var ScaleneGUI = (() => {
  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 __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };
  var __export = (target2, all) => {
    for (var name4 in all)
      __defProp(target2, name4, { get: all[name4], enumerable: true });
  };
  var __copyProps = (to, from, except, desc) => {
    if (from && typeof from === "object" || typeof from === "function") {
      for (let key2 of __getOwnPropNames(from))
        if (!__hasOwnProp.call(to, key2) && key2 !== except)
          __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
    }
    return to;
  };
  var __toESM = (mod, isNodeMode, target2) => (target2 = 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(target2, "default", { value: mod, enumerable: true }) : target2,
    mod
  ));
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

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

  // node_modules/ieee754/index.js
  var require_ieee754 = __commonJS({
    "node_modules/ieee754/index.js"(exports2) {
      exports2.read = function(buffer, offset4, isLE, mLen, nBytes) {
        var e4, m4;
        var eLen = nBytes * 8 - mLen - 1;
        var eMax = (1 << eLen) - 1;
        var eBias = eMax >> 1;
        var nBits = -7;
        var i2 = isLE ? nBytes - 1 : 0;
        var d2 = isLE ? -1 : 1;
        var s2 = buffer[offset4 + i2];
        i2 += d2;
        e4 = s2 & (1 << -nBits) - 1;
        s2 >>= -nBits;
        nBits += eLen;
        for (; nBits > 0; e4 = e4 * 256 + buffer[offset4 + i2], i2 += d2, nBits -= 8) {
        }
        m4 = e4 & (1 << -nBits) - 1;
        e4 >>= -nBits;
        nBits += mLen;
        for (; nBits > 0; m4 = m4 * 256 + buffer[offset4 + i2], i2 += d2, nBits -= 8) {
        }
        if (e4 === 0) {
          e4 = 1 - eBias;
        } else if (e4 === eMax) {
          return m4 ? NaN : (s2 ? -1 : 1) * Infinity;
        } else {
          m4 = m4 + Math.pow(2, mLen);
          e4 = e4 - eBias;
        }
        return (s2 ? -1 : 1) * m4 * Math.pow(2, e4 - mLen);
      };
      exports2.write = function(buffer, value3, offset4, isLE, mLen, nBytes) {
        var e4, m4, c4;
        var eLen = nBytes * 8 - mLen - 1;
        var eMax = (1 << eLen) - 1;
        var eBias = eMax >> 1;
        var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
        var i2 = isLE ? 0 : nBytes - 1;
        var d2 = isLE ? 1 : -1;
        var s2 = value3 < 0 || value3 === 0 && 1 / value3 < 0 ? 1 : 0;
        value3 = Math.abs(value3);
        if (isNaN(value3) || value3 === Infinity) {
          m4 = isNaN(value3) ? 1 : 0;
          e4 = eMax;
        } else {
          e4 = Math.floor(Math.log(value3) / Math.LN2);
          if (value3 * (c4 = Math.pow(2, -e4)) < 1) {
            e4--;
            c4 *= 2;
          }
          if (e4 + eBias >= 1) {
            value3 += rt / c4;
          } else {
            value3 += rt * Math.pow(2, 1 - eBias);
          }
          if (value3 * c4 >= 2) {
            e4++;
            c4 /= 2;
          }
          if (e4 + eBias >= eMax) {
            m4 = 0;
            e4 = eMax;
          } else if (e4 + eBias >= 1) {
            m4 = (value3 * c4 - 1) * Math.pow(2, mLen);
            e4 = e4 + eBias;
          } else {
            m4 = value3 * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
            e4 = 0;
          }
        }
        for (; mLen >= 8; buffer[offset4 + i2] = m4 & 255, i2 += d2, m4 /= 256, mLen -= 8) {
        }
        e4 = e4 << mLen | m4;
        eLen += mLen;
        for (; eLen > 0; buffer[offset4 + i2] = e4 & 255, i2 += d2, e4 /= 256, eLen -= 8) {
        }
        buffer[offset4 + i2 - d2] |= s2 * 128;
      };
    }
  });

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

  // node_modules/bowser/es5.js
  var require_es5 = __commonJS({
    "node_modules/bowser/es5.js"(exports2, module5) {
      !function(e4, t4) {
        "object" == typeof exports2 && "object" == typeof module5 ? module5.exports = t4() : "function" == typeof define && define.amd ? define([], t4) : "object" == typeof exports2 ? exports2.bowser = t4() : e4.bowser = t4();
      }(exports2, function() {
        return function(e4) {
          var t4 = {};
          function r2(i2) {
            if (t4[i2]) return t4[i2].exports;
            var n2 = t4[i2] = { i: i2, l: false, exports: {} };
            return e4[i2].call(n2.exports, n2, n2.exports, r2), n2.l = true, n2.exports;
          }
          return r2.m = e4, r2.c = t4, r2.d = function(e6, t5, i2) {
            r2.o(e6, t5) || Object.defineProperty(e6, t5, { enumerable: true, get: i2 });
          }, r2.r = function(e6) {
            "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e6, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e6, "__esModule", { value: true });
          }, r2.t = function(e6, t5) {
            if (1 & t5 && (e6 = r2(e6)), 8 & t5) return e6;
            if (4 & t5 && "object" == typeof e6 && e6 && e6.__esModule) return e6;
            var i2 = /* @__PURE__ */ Object.create(null);
            if (r2.r(i2), Object.defineProperty(i2, "default", { enumerable: true, value: e6 }), 2 & t5 && "string" != typeof e6) for (var n2 in e6) r2.d(i2, n2, function(t6) {
              return e6[t6];
            }.bind(null, n2));
            return i2;
          }, r2.n = function(e6) {
            var t5 = e6 && e6.__esModule ? function() {
              return e6.default;
            } : function() {
              return e6;
            };
            return r2.d(t5, "a", t5), t5;
          }, r2.o = function(e6, t5) {
            return Object.prototype.hasOwnProperty.call(e6, t5);
          }, r2.p = "", r2(r2.s = 90);
        }({ 17: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2 = r2(18), n2 = function() {
            function e6() {
            }
            return e6.getFirstMatch = function(e7, t5) {
              var r3 = t5.match(e7);
              return r3 && r3.length > 0 && r3[1] || "";
            }, e6.getSecondMatch = function(e7, t5) {
              var r3 = t5.match(e7);
              return r3 && r3.length > 1 && r3[2] || "";
            }, e6.matchAndReturnConst = function(e7, t5, r3) {
              if (e7.test(t5)) return r3;
            }, e6.getWindowsVersionName = function(e7) {
              switch (e7) {
                case "NT":
                  return "NT";
                case "XP":
                  return "XP";
                case "NT 5.0":
                  return "2000";
                case "NT 5.1":
                  return "XP";
                case "NT 5.2":
                  return "2003";
                case "NT 6.0":
                  return "Vista";
                case "NT 6.1":
                  return "7";
                case "NT 6.2":
                  return "8";
                case "NT 6.3":
                  return "8.1";
                case "NT 10.0":
                  return "10";
                default:
                  return;
              }
            }, e6.getMacOSVersionName = function(e7) {
              var t5 = e7.split(".").splice(0, 2).map(function(e8) {
                return parseInt(e8, 10) || 0;
              });
              if (t5.push(0), 10 === t5[0]) switch (t5[1]) {
                case 5:
                  return "Leopard";
                case 6:
                  return "Snow Leopard";
                case 7:
                  return "Lion";
                case 8:
                  return "Mountain Lion";
                case 9:
                  return "Mavericks";
                case 10:
                  return "Yosemite";
                case 11:
                  return "El Capitan";
                case 12:
                  return "Sierra";
                case 13:
                  return "High Sierra";
                case 14:
                  return "Mojave";
                case 15:
                  return "Catalina";
                default:
                  return;
              }
            }, e6.getAndroidVersionName = function(e7) {
              var t5 = e7.split(".").splice(0, 2).map(function(e8) {
                return parseInt(e8, 10) || 0;
              });
              if (t5.push(0), !(1 === t5[0] && t5[1] < 5)) return 1 === t5[0] && t5[1] < 6 ? "Cupcake" : 1 === t5[0] && t5[1] >= 6 ? "Donut" : 2 === t5[0] && t5[1] < 2 ? "Eclair" : 2 === t5[0] && 2 === t5[1] ? "Froyo" : 2 === t5[0] && t5[1] > 2 ? "Gingerbread" : 3 === t5[0] ? "Honeycomb" : 4 === t5[0] && t5[1] < 1 ? "Ice Cream Sandwich" : 4 === t5[0] && t5[1] < 4 ? "Jelly Bean" : 4 === t5[0] && t5[1] >= 4 ? "KitKat" : 5 === t5[0] ? "Lollipop" : 6 === t5[0] ? "Marshmallow" : 7 === t5[0] ? "Nougat" : 8 === t5[0] ? "Oreo" : 9 === t5[0] ? "Pie" : void 0;
            }, e6.getVersionPrecision = function(e7) {
              return e7.split(".").length;
            }, e6.compareVersions = function(t5, r3, i3) {
              void 0 === i3 && (i3 = false);
              var n3 = e6.getVersionPrecision(t5), s2 = e6.getVersionPrecision(r3), a4 = Math.max(n3, s2), o2 = 0, u5 = e6.map([t5, r3], function(t6) {
                var r4 = a4 - e6.getVersionPrecision(t6), i4 = t6 + new Array(r4 + 1).join(".0");
                return e6.map(i4.split("."), function(e7) {
                  return new Array(20 - e7.length).join("0") + e7;
                }).reverse();
              });
              for (i3 && (o2 = a4 - Math.min(n3, s2)), a4 -= 1; a4 >= o2; ) {
                if (u5[0][a4] > u5[1][a4]) return 1;
                if (u5[0][a4] === u5[1][a4]) {
                  if (a4 === o2) return 0;
                  a4 -= 1;
                } else if (u5[0][a4] < u5[1][a4]) return -1;
              }
            }, e6.map = function(e7, t5) {
              var r3, i3 = [];
              if (Array.prototype.map) return Array.prototype.map.call(e7, t5);
              for (r3 = 0; r3 < e7.length; r3 += 1) i3.push(t5(e7[r3]));
              return i3;
            }, e6.find = function(e7, t5) {
              var r3, i3;
              if (Array.prototype.find) return Array.prototype.find.call(e7, t5);
              for (r3 = 0, i3 = e7.length; r3 < i3; r3 += 1) {
                var n3 = e7[r3];
                if (t5(n3, r3)) return n3;
              }
            }, e6.assign = function(e7) {
              for (var t5, r3, i3 = e7, n3 = arguments.length, s2 = new Array(n3 > 1 ? n3 - 1 : 0), a4 = 1; a4 < n3; a4++) s2[a4 - 1] = arguments[a4];
              if (Object.assign) return Object.assign.apply(Object, [e7].concat(s2));
              var o2 = function() {
                var e8 = s2[t5];
                "object" == typeof e8 && null !== e8 && Object.keys(e8).forEach(function(t6) {
                  i3[t6] = e8[t6];
                });
              };
              for (t5 = 0, r3 = s2.length; t5 < r3; t5 += 1) o2();
              return e7;
            }, e6.getBrowserAlias = function(e7) {
              return i2.BROWSER_ALIASES_MAP[e7];
            }, e6.getBrowserTypeByAlias = function(e7) {
              return i2.BROWSER_MAP[e7] || "";
            }, e6;
          }();
          t4.default = n2, e4.exports = t4.default;
        }, 18: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.ENGINE_MAP = t4.OS_MAP = t4.PLATFORMS_MAP = t4.BROWSER_MAP = t4.BROWSER_ALIASES_MAP = void 0;
          t4.BROWSER_ALIASES_MAP = { "Amazon Silk": "amazon_silk", "Android Browser": "android", Bada: "bada", BlackBerry: "blackberry", Chrome: "chrome", Chromium: "chromium", Electron: "electron", Epiphany: "epiphany", Firefox: "firefox", Focus: "focus", Generic: "generic", "Google Search": "google_search", Googlebot: "googlebot", "Internet Explorer": "ie", "K-Meleon": "k_meleon", Maxthon: "maxthon", "Microsoft Edge": "edge", "MZ Browser": "mz", "NAVER Whale Browser": "naver", Opera: "opera", "Opera Coast": "opera_coast", "Pale Moon": "pale_moon", PhantomJS: "phantomjs", Puffin: "puffin", QupZilla: "qupzilla", QQ: "qq", QQLite: "qqlite", Safari: "safari", Sailfish: "sailfish", "Samsung Internet for Android": "samsung_internet", SeaMonkey: "seamonkey", Sleipnir: "sleipnir", Swing: "swing", Tizen: "tizen", "UC Browser": "uc", Vivaldi: "vivaldi", "WebOS Browser": "webos", WeChat: "wechat", "Yandex Browser": "yandex", Roku: "roku" };
          t4.BROWSER_MAP = { amazon_silk: "Amazon Silk", android: "Android Browser", bada: "Bada", blackberry: "BlackBerry", chrome: "Chrome", chromium: "Chromium", electron: "Electron", epiphany: "Epiphany", firefox: "Firefox", focus: "Focus", generic: "Generic", googlebot: "Googlebot", google_search: "Google Search", ie: "Internet Explorer", k_meleon: "K-Meleon", maxthon: "Maxthon", edge: "Microsoft Edge", mz: "MZ Browser", naver: "NAVER Whale Browser", opera: "Opera", opera_coast: "Opera Coast", pale_moon: "Pale Moon", phantomjs: "PhantomJS", puffin: "Puffin", qupzilla: "QupZilla", qq: "QQ Browser", qqlite: "QQ Browser Lite", safari: "Safari", sailfish: "Sailfish", samsung_internet: "Samsung Internet for Android", seamonkey: "SeaMonkey", sleipnir: "Sleipnir", swing: "Swing", tizen: "Tizen", uc: "UC Browser", vivaldi: "Vivaldi", webos: "WebOS Browser", wechat: "WeChat", yandex: "Yandex Browser" };
          t4.PLATFORMS_MAP = { tablet: "tablet", mobile: "mobile", desktop: "desktop", tv: "tv", bot: "bot" };
          t4.OS_MAP = { WindowsPhone: "Windows Phone", Windows: "Windows", MacOS: "macOS", iOS: "iOS", Android: "Android", WebOS: "WebOS", BlackBerry: "BlackBerry", Bada: "Bada", Tizen: "Tizen", Linux: "Linux", ChromeOS: "Chrome OS", PlayStation4: "PlayStation 4", Roku: "Roku" };
          t4.ENGINE_MAP = { EdgeHTML: "EdgeHTML", Blink: "Blink", Trident: "Trident", Presto: "Presto", Gecko: "Gecko", WebKit: "WebKit" };
        }, 90: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2, n2 = (i2 = r2(91)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18);
          function a4(e6, t5) {
            for (var r3 = 0; r3 < t5.length; r3++) {
              var i3 = t5[r3];
              i3.enumerable = i3.enumerable || false, i3.configurable = true, "value" in i3 && (i3.writable = true), Object.defineProperty(e6, i3.key, i3);
            }
          }
          var o2 = function() {
            function e6() {
            }
            var t5, r3, i3;
            return e6.getParser = function(e7, t6) {
              if (void 0 === t6 && (t6 = false), "string" != typeof e7) throw new Error("UserAgent should be a string");
              return new n2.default(e7, t6);
            }, e6.parse = function(e7) {
              return new n2.default(e7).getResult();
            }, t5 = e6, i3 = [{ key: "BROWSER_MAP", get: function() {
              return s2.BROWSER_MAP;
            } }, { key: "ENGINE_MAP", get: function() {
              return s2.ENGINE_MAP;
            } }, { key: "OS_MAP", get: function() {
              return s2.OS_MAP;
            } }, { key: "PLATFORMS_MAP", get: function() {
              return s2.PLATFORMS_MAP;
            } }], (r3 = null) && a4(t5.prototype, r3), i3 && a4(t5, i3), e6;
          }();
          t4.default = o2, e4.exports = t4.default;
        }, 91: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2 = u5(r2(92)), n2 = u5(r2(93)), s2 = u5(r2(94)), a4 = u5(r2(95)), o2 = u5(r2(17));
          function u5(e6) {
            return e6 && e6.__esModule ? e6 : { default: e6 };
          }
          var d2 = function() {
            function e6(e7, t6) {
              if (void 0 === t6 && (t6 = false), null == e7 || "" === e7) throw new Error("UserAgent parameter can't be empty");
              this._ua = e7, this.parsedResult = {}, true !== t6 && this.parse();
            }
            var t5 = e6.prototype;
            return t5.getUA = function() {
              return this._ua;
            }, t5.test = function(e7) {
              return e7.test(this._ua);
            }, t5.parseBrowser = function() {
              var e7 = this;
              this.parsedResult.browser = {};
              var t6 = o2.default.find(i2.default, function(t7) {
                if ("function" == typeof t7.test) return t7.test(e7);
                if (Array.isArray(t7.test)) return t7.test.some(function(t8) {
                  return e7.test(t8);
                });
                throw new Error("Browser's test function is not valid");
              });
              return t6 && (this.parsedResult.browser = t6.describe(this.getUA())), this.parsedResult.browser;
            }, t5.getBrowser = function() {
              return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser();
            }, t5.getBrowserName = function(e7) {
              return e7 ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || "";
            }, t5.getBrowserVersion = function() {
              return this.getBrowser().version;
            }, t5.getOS = function() {
              return this.parsedResult.os ? this.parsedResult.os : this.parseOS();
            }, t5.parseOS = function() {
              var e7 = this;
              this.parsedResult.os = {};
              var t6 = o2.default.find(n2.default, function(t7) {
                if ("function" == typeof t7.test) return t7.test(e7);
                if (Array.isArray(t7.test)) return t7.test.some(function(t8) {
                  return e7.test(t8);
                });
                throw new Error("Browser's test function is not valid");
              });
              return t6 && (this.parsedResult.os = t6.describe(this.getUA())), this.parsedResult.os;
            }, t5.getOSName = function(e7) {
              var t6 = this.getOS().name;
              return e7 ? String(t6).toLowerCase() || "" : t6 || "";
            }, t5.getOSVersion = function() {
              return this.getOS().version;
            }, t5.getPlatform = function() {
              return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform();
            }, t5.getPlatformType = function(e7) {
              void 0 === e7 && (e7 = false);
              var t6 = this.getPlatform().type;
              return e7 ? String(t6).toLowerCase() || "" : t6 || "";
            }, t5.parsePlatform = function() {
              var e7 = this;
              this.parsedResult.platform = {};
              var t6 = o2.default.find(s2.default, function(t7) {
                if ("function" == typeof t7.test) return t7.test(e7);
                if (Array.isArray(t7.test)) return t7.test.some(function(t8) {
                  return e7.test(t8);
                });
                throw new Error("Browser's test function is not valid");
              });
              return t6 && (this.parsedResult.platform = t6.describe(this.getUA())), this.parsedResult.platform;
            }, t5.getEngine = function() {
              return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine();
            }, t5.getEngineName = function(e7) {
              return e7 ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || "";
            }, t5.parseEngine = function() {
              var e7 = this;
              this.parsedResult.engine = {};
              var t6 = o2.default.find(a4.default, function(t7) {
                if ("function" == typeof t7.test) return t7.test(e7);
                if (Array.isArray(t7.test)) return t7.test.some(function(t8) {
                  return e7.test(t8);
                });
                throw new Error("Browser's test function is not valid");
              });
              return t6 && (this.parsedResult.engine = t6.describe(this.getUA())), this.parsedResult.engine;
            }, t5.parse = function() {
              return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(), this;
            }, t5.getResult = function() {
              return o2.default.assign({}, this.parsedResult);
            }, t5.satisfies = function(e7) {
              var t6 = this, r3 = {}, i3 = 0, n3 = {}, s3 = 0;
              if (Object.keys(e7).forEach(function(t7) {
                var a6 = e7[t7];
                "string" == typeof a6 ? (n3[t7] = a6, s3 += 1) : "object" == typeof a6 && (r3[t7] = a6, i3 += 1);
              }), i3 > 0) {
                var a5 = Object.keys(r3), u6 = o2.default.find(a5, function(e8) {
                  return t6.isOS(e8);
                });
                if (u6) {
                  var d3 = this.satisfies(r3[u6]);
                  if (void 0 !== d3) return d3;
                }
                var c4 = o2.default.find(a5, function(e8) {
                  return t6.isPlatform(e8);
                });
                if (c4) {
                  var f2 = this.satisfies(r3[c4]);
                  if (void 0 !== f2) return f2;
                }
              }
              if (s3 > 0) {
                var l2 = Object.keys(n3), h3 = o2.default.find(l2, function(e8) {
                  return t6.isBrowser(e8, true);
                });
                if (void 0 !== h3) return this.compareVersion(n3[h3]);
              }
            }, t5.isBrowser = function(e7, t6) {
              void 0 === t6 && (t6 = false);
              var r3 = this.getBrowserName().toLowerCase(), i3 = e7.toLowerCase(), n3 = o2.default.getBrowserTypeByAlias(i3);
              return t6 && n3 && (i3 = n3.toLowerCase()), i3 === r3;
            }, t5.compareVersion = function(e7) {
              var t6 = [0], r3 = e7, i3 = false, n3 = this.getBrowserVersion();
              if ("string" == typeof n3) return ">" === e7[0] || "<" === e7[0] ? (r3 = e7.substr(1), "=" === e7[1] ? (i3 = true, r3 = e7.substr(2)) : t6 = [], ">" === e7[0] ? t6.push(1) : t6.push(-1)) : "=" === e7[0] ? r3 = e7.substr(1) : "~" === e7[0] && (i3 = true, r3 = e7.substr(1)), t6.indexOf(o2.default.compareVersions(n3, r3, i3)) > -1;
            }, t5.isOS = function(e7) {
              return this.getOSName(true) === String(e7).toLowerCase();
            }, t5.isPlatform = function(e7) {
              return this.getPlatformType(true) === String(e7).toLowerCase();
            }, t5.isEngine = function(e7) {
              return this.getEngineName(true) === String(e7).toLowerCase();
            }, t5.is = function(e7, t6) {
              return void 0 === t6 && (t6 = false), this.isBrowser(e7, t6) || this.isOS(e7) || this.isPlatform(e7);
            }, t5.some = function(e7) {
              var t6 = this;
              return void 0 === e7 && (e7 = []), e7.some(function(e8) {
                return t6.is(e8);
              });
            }, e6;
          }();
          t4.default = d2, e4.exports = t4.default;
        }, 92: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 };
          var s2 = /version\/(\d+(\.?_?\d+)+)/i, a4 = [{ test: [/googlebot/i], describe: function(e6) {
            var t5 = { name: "Googlebot" }, r3 = n2.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/opera/i], describe: function(e6) {
            var t5 = { name: "Opera" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/opr\/|opios/i], describe: function(e6) {
            var t5 = { name: "Opera" }, r3 = n2.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/SamsungBrowser/i], describe: function(e6) {
            var t5 = { name: "Samsung Internet for Android" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/Whale/i], describe: function(e6) {
            var t5 = { name: "NAVER Whale Browser" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/PaleMoon/i], describe: function(e6) {
            var t5 = { name: "Pale Moon" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/MZBrowser/i], describe: function(e6) {
            var t5 = { name: "MZ Browser" }, r3 = n2.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/focus/i], describe: function(e6) {
            var t5 = { name: "Focus" }, r3 = n2.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/swing/i], describe: function(e6) {
            var t5 = { name: "Swing" }, r3 = n2.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/coast/i], describe: function(e6) {
            var t5 = { name: "Opera Coast" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/opt\/\d+(?:.?_?\d+)+/i], describe: function(e6) {
            var t5 = { name: "Opera Touch" }, r3 = n2.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/yabrowser/i], describe: function(e6) {
            var t5 = { name: "Yandex Browser" }, r3 = n2.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/ucbrowser/i], describe: function(e6) {
            var t5 = { name: "UC Browser" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/Maxthon|mxios/i], describe: function(e6) {
            var t5 = { name: "Maxthon" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/epiphany/i], describe: function(e6) {
            var t5 = { name: "Epiphany" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/puffin/i], describe: function(e6) {
            var t5 = { name: "Puffin" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/sleipnir/i], describe: function(e6) {
            var t5 = { name: "Sleipnir" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/k-meleon/i], describe: function(e6) {
            var t5 = { name: "K-Meleon" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/micromessenger/i], describe: function(e6) {
            var t5 = { name: "WeChat" }, r3 = n2.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/qqbrowser/i], describe: function(e6) {
            var t5 = { name: /qqbrowserlite/i.test(e6) ? "QQ Browser Lite" : "QQ Browser" }, r3 = n2.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/msie|trident/i], describe: function(e6) {
            var t5 = { name: "Internet Explorer" }, r3 = n2.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/\sedg\//i], describe: function(e6) {
            var t5 = { name: "Microsoft Edge" }, r3 = n2.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/edg([ea]|ios)/i], describe: function(e6) {
            var t5 = { name: "Microsoft Edge" }, r3 = n2.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/vivaldi/i], describe: function(e6) {
            var t5 = { name: "Vivaldi" }, r3 = n2.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/seamonkey/i], describe: function(e6) {
            var t5 = { name: "SeaMonkey" }, r3 = n2.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/sailfish/i], describe: function(e6) {
            var t5 = { name: "Sailfish" }, r3 = n2.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/silk/i], describe: function(e6) {
            var t5 = { name: "Amazon Silk" }, r3 = n2.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/phantom/i], describe: function(e6) {
            var t5 = { name: "PhantomJS" }, r3 = n2.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/slimerjs/i], describe: function(e6) {
            var t5 = { name: "SlimerJS" }, r3 = n2.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e6) {
            var t5 = { name: "BlackBerry" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/(web|hpw)[o0]s/i], describe: function(e6) {
            var t5 = { name: "WebOS Browser" }, r3 = n2.default.getFirstMatch(s2, e6) || n2.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/bada/i], describe: function(e6) {
            var t5 = { name: "Bada" }, r3 = n2.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/tizen/i], describe: function(e6) {
            var t5 = { name: "Tizen" }, r3 = n2.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/qupzilla/i], describe: function(e6) {
            var t5 = { name: "QupZilla" }, r3 = n2.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/firefox|iceweasel|fxios/i], describe: function(e6) {
            var t5 = { name: "Firefox" }, r3 = n2.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/electron/i], describe: function(e6) {
            var t5 = { name: "Electron" }, r3 = n2.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/MiuiBrowser/i], describe: function(e6) {
            var t5 = { name: "Miui" }, r3 = n2.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/chromium/i], describe: function(e6) {
            var t5 = { name: "Chromium" }, r3 = n2.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, e6) || n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/chrome|crios|crmo/i], describe: function(e6) {
            var t5 = { name: "Chrome" }, r3 = n2.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/GSA/i], describe: function(e6) {
            var t5 = { name: "Google Search" }, r3 = n2.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: function(e6) {
            var t5 = !e6.test(/like android/i), r3 = e6.test(/android/i);
            return t5 && r3;
          }, describe: function(e6) {
            var t5 = { name: "Android Browser" }, r3 = n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/playstation 4/i], describe: function(e6) {
            var t5 = { name: "PlayStation 4" }, r3 = n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/safari|applewebkit/i], describe: function(e6) {
            var t5 = { name: "Safari" }, r3 = n2.default.getFirstMatch(s2, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/.*/i], describe: function(e6) {
            var t5 = -1 !== e6.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /;
            return { name: n2.default.getFirstMatch(t5, e6), version: n2.default.getSecondMatch(t5, e6) };
          } }];
          t4.default = a4, e4.exports = t4.default;
        }, 93: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18);
          var a4 = [{ test: [/Roku\/DVP/], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, e6);
            return { name: s2.OS_MAP.Roku, version: t5 };
          } }, { test: [/windows phone/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, e6);
            return { name: s2.OS_MAP.WindowsPhone, version: t5 };
          } }, { test: [/windows /i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, e6), r3 = n2.default.getWindowsVersionName(t5);
            return { name: s2.OS_MAP.Windows, version: t5, versionName: r3 };
          } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function(e6) {
            var t5 = { name: s2.OS_MAP.iOS }, r3 = n2.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/macintosh/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, e6).replace(/[_\s]/g, "."), r3 = n2.default.getMacOSVersionName(t5), i3 = { name: s2.OS_MAP.MacOS, version: t5 };
            return r3 && (i3.versionName = r3), i3;
          } }, { test: [/(ipod|iphone|ipad)/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, e6).replace(/[_\s]/g, ".");
            return { name: s2.OS_MAP.iOS, version: t5 };
          } }, { test: function(e6) {
            var t5 = !e6.test(/like android/i), r3 = e6.test(/android/i);
            return t5 && r3;
          }, describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, e6), r3 = n2.default.getAndroidVersionName(t5), i3 = { name: s2.OS_MAP.Android, version: t5 };
            return r3 && (i3.versionName = r3), i3;
          } }, { test: [/(web|hpw)[o0]s/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, e6), r3 = { name: s2.OS_MAP.WebOS };
            return t5 && t5.length && (r3.version = t5), r3;
          } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, e6) || n2.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, e6) || n2.default.getFirstMatch(/\bbb(\d+)/i, e6);
            return { name: s2.OS_MAP.BlackBerry, version: t5 };
          } }, { test: [/bada/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, e6);
            return { name: s2.OS_MAP.Bada, version: t5 };
          } }, { test: [/tizen/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, e6);
            return { name: s2.OS_MAP.Tizen, version: t5 };
          } }, { test: [/linux/i], describe: function() {
            return { name: s2.OS_MAP.Linux };
          } }, { test: [/CrOS/], describe: function() {
            return { name: s2.OS_MAP.ChromeOS };
          } }, { test: [/PlayStation 4/], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, e6);
            return { name: s2.OS_MAP.PlayStation4, version: t5 };
          } }];
          t4.default = a4, e4.exports = t4.default;
        }, 94: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18);
          var a4 = [{ test: [/googlebot/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.bot, vendor: "Google" };
          } }, { test: [/huawei/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/(can-l01)/i, e6) && "Nova", r3 = { type: s2.PLATFORMS_MAP.mobile, vendor: "Huawei" };
            return t5 && (r3.model = t5), r3;
          } }, { test: [/nexus\s*(?:7|8|9|10).*/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet, vendor: "Nexus" };
          } }, { test: [/ipad/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
          } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" };
          } }, { test: [/kftt build/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet, vendor: "Amazon", model: "Kindle Fire HD 7" };
          } }, { test: [/silk/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet, vendor: "Amazon" };
          } }, { test: [/tablet(?! pc)/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet };
          } }, { test: function(e6) {
            var t5 = e6.test(/ipod|iphone/i), r3 = e6.test(/like (ipod|iphone)/i);
            return t5 && !r3;
          }, describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/(ipod|iphone)/i, e6);
            return { type: s2.PLATFORMS_MAP.mobile, vendor: "Apple", model: t5 };
          } }, { test: [/nexus\s*[0-6].*/i, /galaxy nexus/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile, vendor: "Nexus" };
          } }, { test: [/Nokia/i], describe: function(e6) {
            var t5 = n2.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i, e6), r3 = { type: s2.PLATFORMS_MAP.mobile, vendor: "Nokia" };
            return t5 && (r3.model = t5), r3;
          } }, { test: [/[^-]mobi/i], describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile };
          } }, { test: function(e6) {
            return "blackberry" === e6.getBrowserName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile, vendor: "BlackBerry" };
          } }, { test: function(e6) {
            return "bada" === e6.getBrowserName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile };
          } }, { test: function(e6) {
            return "windows phone" === e6.getBrowserName();
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile, vendor: "Microsoft" };
          } }, { test: function(e6) {
            var t5 = Number(String(e6.getOSVersion()).split(".")[0]);
            return "android" === e6.getOSName(true) && t5 >= 3;
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.tablet };
          } }, { test: function(e6) {
            return "android" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.mobile };
          } }, { test: function(e6) {
            return "macos" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.desktop, vendor: "Apple" };
          } }, { test: function(e6) {
            return "windows" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.desktop };
          } }, { test: function(e6) {
            return "linux" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.desktop };
          } }, { test: function(e6) {
            return "playstation 4" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.tv };
          } }, { test: function(e6) {
            return "roku" === e6.getOSName(true);
          }, describe: function() {
            return { type: s2.PLATFORMS_MAP.tv };
          } }];
          t4.default = a4, e4.exports = t4.default;
        }, 95: function(e4, t4, r2) {
          "use strict";
          t4.__esModule = true, t4.default = void 0;
          var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18);
          var a4 = [{ test: function(e6) {
            return "microsoft edge" === e6.getBrowserName(true);
          }, describe: function(e6) {
            if (/\sedg\//i.test(e6)) return { name: s2.ENGINE_MAP.Blink };
            var t5 = n2.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, e6);
            return { name: s2.ENGINE_MAP.EdgeHTML, version: t5 };
          } }, { test: [/trident/i], describe: function(e6) {
            var t5 = { name: s2.ENGINE_MAP.Trident }, r3 = n2.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: function(e6) {
            return e6.test(/presto/i);
          }, describe: function(e6) {
            var t5 = { name: s2.ENGINE_MAP.Presto }, r3 = n2.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: function(e6) {
            var t5 = e6.test(/gecko/i), r3 = e6.test(/like gecko/i);
            return t5 && !r3;
          }, describe: function(e6) {
            var t5 = { name: s2.ENGINE_MAP.Gecko }, r3 = n2.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }, { test: [/(apple)?webkit\/537\.36/i], describe: function() {
            return { name: s2.ENGINE_MAP.Blink };
          } }, { test: [/(apple)?webkit/i], describe: function(e6) {
            var t5 = { name: s2.ENGINE_MAP.WebKit }, r3 = n2.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, e6);
            return r3 && (t5.version = r3), t5;
          } }];
          t4.default = a4, e4.exports = t4.default;
        } });
      });
    }
  });

  // scalene-gui.ts
  var scalene_gui_exports = {};
  __export(scalene_gui_exports, {
    applyFileDisplayMode: () => applyFileDisplayMode,
    collapseAll: () => collapseAll,
    expandAll: () => expandAll,
    load: () => load3,
    loadDemo: () => loadDemo,
    loadFetch: () => loadFetch,
    loadFile: () => loadFile,
    onFileDisplayModeChange: () => onFileDisplayModeChange,
    proposeOptimizationLine: () => proposeOptimizationLine,
    proposeOptimizationRegion: () => proposeOptimizationRegion,
    refreshGeminiModels: () => refreshGeminiModels,
    refreshOpenAIModels: () => refreshOpenAIModels,
    toggleAdvanced: () => toggleAdvanced,
    toggleDisplay: () => toggleDisplay,
    togglePassword: () => togglePassword,
    toggleReduced: () => toggleReduced,
    toggleServiceFields: () => toggleServiceFields,
    vsNavigate: () => vsNavigate
  });
  var import_buffer3 = __toESM(require_buffer());

  // node_modules/json-stringify-pretty-compact/index.js
  var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g;
  function stringify(passedObj, options = {}) {
    const indent = JSON.stringify(
      [1],
      void 0,
      options.indent === void 0 ? 2 : options.indent
    ).slice(2, -3);
    const maxLength = indent === "" ? Infinity : options.maxLength === void 0 ? 80 : options.maxLength;
    let { replacer: replacer2 } = options;
    return function _stringify(obj, currentIndent, reserved) {
      if (obj && typeof obj.toJSON === "function") {
        obj = obj.toJSON();
      }
      const string = JSON.stringify(obj, replacer2);
      if (string === void 0) {
        return string;
      }
      const length3 = maxLength - currentIndent.length - reserved;
      if (string.length <= length3) {
        const prettified = string.replace(
          stringOrChar,
          (match3, stringLiteral) => {
            return stringLiteral || `${match3} `;
          }
        );
        if (prettified.length <= length3) {
          return prettified;
        }
      }
      if (replacer2 != null) {
        obj = JSON.parse(string);
        replacer2 = void 0;
      }
      if (typeof obj === "object" && obj !== null) {
        const nextIndent = currentIndent + indent;
        const items = [];
        let index4 = 0;
        let start;
        let end;
        if (Array.isArray(obj)) {
          start = "[";
          end = "]";
          const { length: length4 } = obj;
          for (; index4 < length4; index4++) {
            items.push(
              _stringify(obj[index4], nextIndent, index4 === length4 - 1 ? 0 : 1) || "null"
            );
          }
        } else {
          start = "{";
          end = "}";
          const keys4 = Object.keys(obj);
          const { length: length4 } = keys4;
          for (; index4 < length4; index4++) {
            const key2 = keys4[index4];
            const keyPart = `${JSON.stringify(key2)}: `;
            const value3 = _stringify(
              obj[key2],
              nextIndent,
              keyPart.length + (index4 === length4 - 1 ? 0 : 1)
            );
            if (value3 !== void 0) {
              items.push(keyPart + value3);
            }
          }
        }
        if (items.length > 0) {
          return [start, indent + items.join(`,
${nextIndent}`), end].join(
            `
${currentIndent}`
          );
        }
      }
      return string;
    }(passedObj, "", 0);
  }

  // node_modules/vega/build/vega.module.js
  var vega_module_exports = {};
  __export(vega_module_exports, {
    Bounds: () => Bounds,
    CanvasHandler: () => CanvasHandler,
    CanvasRenderer: () => CanvasRenderer,
    DATE: () => DATE,
    DAY: () => DAY,
    DAYOFYEAR: () => DAYOFYEAR,
    Dataflow: () => Dataflow,
    Debug: () => Debug,
    Error: () => Error$1,
    EventStream: () => EventStream,
    Gradient: () => Gradient,
    GroupItem: () => GroupItem,
    HOURS: () => HOURS,
    Handler: () => Handler,
    HybridHandler: () => HybridHandler,
    HybridRenderer: () => HybridRenderer,
    Info: () => Info,
    Item: () => Item,
    MILLISECONDS: () => MILLISECONDS,
    MINUTES: () => MINUTES,
    MONTH: () => MONTH,
    Marks: () => Marks,
    MultiPulse: () => MultiPulse,
    None: () => None,
    Operator: () => Operator,
    Parameters: () => Parameters,
    Pulse: () => Pulse,
    QUARTER: () => QUARTER,
    RenderType: () => RenderType,
    Renderer: () => Renderer,
    ResourceLoader: () => ResourceLoader,
    SECONDS: () => SECONDS,
    SVGHandler: () => SVGHandler,
    SVGRenderer: () => SVGRenderer,
    SVGStringRenderer: () => SVGStringRenderer,
    Scenegraph: () => Scenegraph,
    TIME_UNITS: () => TIME_UNITS,
    Transform: () => Transform,
    View: () => View,
    WEEK: () => WEEK,
    Warn: () => Warn,
    YEAR: () => YEAR,
    accessor: () => accessor,
    accessorFields: () => accessorFields,
    accessorName: () => accessorName,
    array: () => array,
    ascending: () => ascending,
    bandwidthNRD: () => estimateBandwidth,
    bin: () => bin2,
    bootstrapCI: () => bootstrapCI,
    boundClip: () => boundClip,
    boundContext: () => boundContext,
    boundItem: () => boundItem,
    boundMark: () => boundMark,
    boundStroke: () => boundStroke,
    changeset: () => changeset,
    clampRange: () => clampRange,
    codegenExpression: () => codegen,
    compare: () => compare,
    constant: () => constant,
    cumulativeLogNormal: () => cumulativeLogNormal,
    cumulativeNormal: () => cumulativeNormal,
    cumulativeUniform: () => cumulativeUniform,
    dayofyear: () => dayofyear,
    debounce: () => debounce,
    defaultLocale: () => defaultLocale3,
    definition: () => definition,
    densityLogNormal: () => densityLogNormal,
    densityNormal: () => densityNormal,
    densityUniform: () => densityUniform,
    domChild: () => domChild,
    domClear: () => domClear,
    domCreate: () => domCreate,
    domFind: () => domFind,
    dotbin: () => dotbin,
    error: () => error,
    expressionFunction: () => expressionFunction,
    extend: () => extend,
    extent: () => extent,
    extentIndex: () => extentIndex,
    falsy: () => falsy,
    fastmap: () => fastmap,
    field: () => field,
    flush: () => flush,
    font: () => font,
    fontFamily: () => fontFamily,
    fontSize: () => fontSize,
    format: () => format2,
    formatLocale: () => numberFormatDefaultLocale,
    formats: () => formats,
    hasOwnProperty: () => has,
    id: () => id,
    identity: () => identity,
    inferType: () => inferType,
    inferTypes: () => inferTypes,
    ingest: () => ingest$1,
    inherits: () => inherits,
    inrange: () => inrange,
    interpolate: () => interpolate,
    interpolateColors: () => interpolateColors,
    interpolateRange: () => interpolateRange,
    intersect: () => intersect2,
    intersectBoxLine: () => intersectBoxLine,
    intersectPath: () => intersectPath,
    intersectPoint: () => intersectPoint,
    intersectRule: () => intersectRule,
    isArray: () => isArray,
    isBoolean: () => isBoolean,
    isDate: () => isDate,
    isFunction: () => isFunction,
    isIterable: () => isIterable,
    isNumber: () => isNumber,
    isObject: () => isObject,
    isRegExp: () => isRegExp,
    isString: () => isString,
    isTuple: () => isTuple,
    key: () => key,
    lerp: () => lerp,
    lineHeight: () => lineHeight,
    loader: () => loader,
    locale: () => locale3,
    logger: () => logger,
    lruCache: () => lruCache,
    markup: () => markup,
    merge: () => merge,
    mergeConfig: () => mergeConfig,
    multiLineOffset: () => multiLineOffset,
    one: () => one,
    pad: () => pad,
    panLinear: () => panLinear,
    panLog: () => panLog,
    panPow: () => panPow,
    panSymlog: () => panSymlog,
    parse: () => parse6,
    parseExpression: () => parser,
    parseSelector: () => eventSelector,
    path: () => path,
    pathCurves: () => curves,
    pathEqual: () => pathEqual,
    pathParse: () => parse4,
    pathRectangle: () => vg_rect,
    pathRender: () => pathRender,
    pathSymbols: () => symbols2,
    pathTrail: () => vg_trail,
    peek: () => peek,
    point: () => point6,
    projection: () => projection2,
    quantileLogNormal: () => quantileLogNormal,
    quantileNormal: () => quantileNormal,
    quantileUniform: () => quantileUniform,
    quantiles: () => quantiles,
    quantizeInterpolator: () => quantizeInterpolator,
    quarter: () => quarter,
    quartiles: () => quartiles,
    random: () => random,
    randomInteger: () => integer,
    randomKDE: () => kde,
    randomLCG: () => lcg,
    randomLogNormal: () => lognormal,
    randomMixture: () => mixture,
    randomNormal: () => gaussian,
    randomUniform: () => uniform,
    read: () => read,
    regressionConstant: () => constant2,
    regressionExp: () => exp2,
    regressionLinear: () => linear,
    regressionLoess: () => loess,
    regressionLog: () => log2,
    regressionPoly: () => poly,
    regressionPow: () => pow2,
    regressionQuad: () => quad,
    renderModule: () => renderModule,
    repeat: () => repeat,
    resetDefaultLocale: () => resetDefaultLocale,
    resetSVGClipId: () => resetSVGClipId,
    resetSVGDefIds: () => resetSVGDefIds,
    responseType: () => responseType,
    runtimeContext: () => context2,
    sampleCurve: () => sampleCurve,
    sampleLogNormal: () => sampleLogNormal,
    sampleNormal: () => sampleNormal,
    sampleUniform: () => sampleUniform,
    scale: () => scale,
    sceneEqual: () => sceneEqual,
    sceneFromJSON: () => sceneFromJSON,
    scenePickVisit: () => pickVisit,
    sceneToJSON: () => sceneToJSON,
    sceneVisit: () => visit,
    sceneZOrder: () => zorder,
    scheme: () => scheme,
    serializeXML: () => serializeXML,
    setHybridRendererOptions: () => setHybridRendererOptions,
    setRandom: () => setRandom,
    span: () => span,
    splitAccessPath: () => splitAccessPath,
    stringValue: () => $,
    textMetrics: () => textMetrics,
    timeBin: () => bin,
    timeFloor: () => timeFloor,
    timeFormatLocale: () => timeFormatDefaultLocale,
    timeInterval: () => timeInterval2,
    timeOffset: () => timeOffset,
    timeSequence: () => timeSequence,
    timeUnitSpecifier: () => timeUnitSpecifier,
    timeUnits: () => timeUnits,
    toBoolean: () => toBoolean,
    toDate: () => toDate,
    toNumber: () => toNumber,
    toSet: () => toSet,
    toString: () => toString,
    transform: () => transform,
    transforms: () => transforms,
    truncate: () => truncate,
    truthy: () => truthy,
    tupleid: () => tupleid,
    typeParsers: () => typeParsers,
    utcFloor: () => utcFloor,
    utcInterval: () => utcInterval,
    utcOffset: () => utcOffset,
    utcSequence: () => utcSequence,
    utcdayofyear: () => utcdayofyear,
    utcquarter: () => utcquarter,
    utcweek: () => utcweek,
    version: () => version,
    visitArray: () => visitArray,
    week: () => week,
    writeConfig: () => writeConfig,
    zero: () => zero,
    zoomLinear: () => zoomLinear,
    zoomLog: () => zoomLog,
    zoomPow: () => zoomPow,
    zoomSymlog: () => zoomSymlog
  });

  // node_modules/vega-util/build/vega-util.module.js
  function accessor(fn, fields, name4) {
    fn.fields = fields || [];
    fn.fname = name4;
    return fn;
  }
  function accessorName(fn) {
    return fn == null ? null : fn.fname;
  }
  function accessorFields(fn) {
    return fn == null ? null : fn.fields;
  }
  function getter(path3) {
    return path3.length === 1 ? get1(path3[0]) : getN(path3);
  }
  var get1 = (field3) => function(obj) {
    return obj[field3];
  };
  var getN = (path3) => {
    const len = path3.length;
    return function(obj) {
      for (let i2 = 0; i2 < len; ++i2) {
        obj = obj[path3[i2]];
      }
      return obj;
    };
  };
  function error(message) {
    throw Error(message);
  }
  function splitAccessPath(p2) {
    const path3 = [], n2 = p2.length;
    let q2 = null, b3 = 0, s2 = "", i2, j2, c4;
    p2 = p2 + "";
    function push() {
      path3.push(s2 + p2.substring(i2, j2));
      s2 = "";
      i2 = j2 + 1;
    }
    for (i2 = j2 = 0; j2 < n2; ++j2) {
      c4 = p2[j2];
      if (c4 === "\\") {
        s2 += p2.substring(i2, j2++);
        i2 = j2;
      } else if (c4 === q2) {
        push();
        q2 = null;
        b3 = -1;
      } else if (q2) {
        continue;
      } else if (i2 === b3 && c4 === '"') {
        i2 = j2 + 1;
        q2 = c4;
      } else if (i2 === b3 && c4 === "'") {
        i2 = j2 + 1;
        q2 = c4;
      } else if (c4 === "." && !b3) {
        if (j2 > i2) {
          push();
        } else {
          i2 = j2 + 1;
        }
      } else if (c4 === "[") {
        if (j2 > i2) push();
        b3 = i2 = j2 + 1;
      } else if (c4 === "]") {
        if (!b3) error("Access path missing open bracket: " + p2);
        if (b3 > 0) push();
        b3 = 0;
        i2 = j2 + 1;
      }
    }
    if (b3) error("Access path missing closing bracket: " + p2);
    if (q2) error("Access path missing closing quote: " + p2);
    if (j2 > i2) {
      j2++;
      push();
    }
    return path3;
  }
  function field(field3, name4, opt) {
    const path3 = splitAccessPath(field3);
    field3 = path3.length === 1 ? path3[0] : field3;
    return accessor((opt && opt.get || getter)(path3), [field3], name4 || field3);
  }
  var id = field("id");
  var identity = accessor((_) => _, [], "identity");
  var zero = accessor(() => 0, [], "zero");
  var one = accessor(() => 1, [], "one");
  var truthy = accessor(() => true, [], "true");
  var falsy = accessor(() => false, [], "false");
  function log$1(method2, level, input) {
    const args = [level].concat([].slice.call(input));
    console[method2].apply(console, args);
  }
  var None = 0;
  var Error$1 = 1;
  var Warn = 2;
  var Info = 3;
  var Debug = 4;
  function logger(_, method2) {
    let handler = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : log$1;
    let level = _ || None;
    return {
      level(_2) {
        if (arguments.length) {
          level = +_2;
          return this;
        } else {
          return level;
        }
      },
      error() {
        if (level >= Error$1) handler(method2 || "error", "ERROR", arguments);
        return this;
      },
      warn() {
        if (level >= Warn) handler(method2 || "warn", "WARN", arguments);
        return this;
      },
      info() {
        if (level >= Info) handler(method2 || "log", "INFO", arguments);
        return this;
      },
      debug() {
        if (level >= Debug) handler(method2 || "log", "DEBUG", arguments);
        return this;
      }
    };
  }
  var isArray = Array.isArray;
  function isObject(_) {
    return _ === Object(_);
  }
  var isLegalKey = (key2) => key2 !== "__proto__";
  function mergeConfig() {
    for (var _len = arguments.length, configs = new Array(_len), _key = 0; _key < _len; _key++) {
      configs[_key] = arguments[_key];
    }
    return configs.reduce((out, source4) => {
      for (const key2 in source4) {
        if (key2 === "signals") {
          out.signals = mergeNamed(out.signals, source4.signals);
        } else {
          const r2 = key2 === "legend" ? {
            layout: 1
          } : key2 === "style" ? true : null;
          writeConfig(out, key2, source4[key2], r2);
        }
      }
      return out;
    }, {});
  }
  function writeConfig(output3, key2, value3, recurse2) {
    if (!isLegalKey(key2)) return;
    let k2, o2;
    if (isObject(value3) && !isArray(value3)) {
      o2 = isObject(output3[key2]) ? output3[key2] : output3[key2] = {};
      for (k2 in value3) {
        if (recurse2 && (recurse2 === true || recurse2[k2])) {
          writeConfig(o2, k2, value3[k2]);
        } else if (isLegalKey(k2)) {
          o2[k2] = value3[k2];
        }
      }
    } else {
      output3[key2] = value3;
    }
  }
  function mergeNamed(a4, b3) {
    if (a4 == null) return b3;
    const map4 = {}, out = [];
    function add6(_) {
      if (!map4[_.name]) {
        map4[_.name] = 1;
        out.push(_);
      }
    }
    b3.forEach(add6);
    a4.forEach(add6);
    return out;
  }
  function peek(array4) {
    return array4[array4.length - 1];
  }
  function toNumber(_) {
    return _ == null || _ === "" ? null : +_;
  }
  var exp = (sign3) => (x5) => sign3 * Math.exp(x5);
  var log = (sign3) => (x5) => Math.log(sign3 * x5);
  var symlog = (c4) => (x5) => Math.sign(x5) * Math.log1p(Math.abs(x5 / c4));
  var symexp = (c4) => (x5) => Math.sign(x5) * Math.expm1(Math.abs(x5)) * c4;
  var pow = (exponent) => (x5) => x5 < 0 ? -Math.pow(-x5, exponent) : Math.pow(x5, exponent);
  function pan(domain4, delta, lift, ground) {
    const d0 = lift(domain4[0]), d1 = lift(peek(domain4)), dd = (d1 - d0) * delta;
    return [ground(d0 - dd), ground(d1 - dd)];
  }
  function panLinear(domain4, delta) {
    return pan(domain4, delta, toNumber, identity);
  }
  function panLog(domain4, delta) {
    var sign3 = Math.sign(domain4[0]);
    return pan(domain4, delta, log(sign3), exp(sign3));
  }
  function panPow(domain4, delta, exponent) {
    return pan(domain4, delta, pow(exponent), pow(1 / exponent));
  }
  function panSymlog(domain4, delta, constant3) {
    return pan(domain4, delta, symlog(constant3), symexp(constant3));
  }
  function zoom(domain4, anchor, scale7, lift, ground) {
    const d0 = lift(domain4[0]), d1 = lift(peek(domain4)), da2 = anchor != null ? lift(anchor) : (d0 + d1) / 2;
    return [ground(da2 + (d0 - da2) * scale7), ground(da2 + (d1 - da2) * scale7)];
  }
  function zoomLinear(domain4, anchor, scale7) {
    return zoom(domain4, anchor, scale7, toNumber, identity);
  }
  function zoomLog(domain4, anchor, scale7) {
    const sign3 = Math.sign(domain4[0]);
    return zoom(domain4, anchor, scale7, log(sign3), exp(sign3));
  }
  function zoomPow(domain4, anchor, scale7, exponent) {
    return zoom(domain4, anchor, scale7, pow(exponent), pow(1 / exponent));
  }
  function zoomSymlog(domain4, anchor, scale7, constant3) {
    return zoom(domain4, anchor, scale7, symlog(constant3), symexp(constant3));
  }
  function quarter(date2) {
    return 1 + ~~(new Date(date2).getMonth() / 3);
  }
  function utcquarter(date2) {
    return 1 + ~~(new Date(date2).getUTCMonth() / 3);
  }
  function array(_) {
    return _ != null ? isArray(_) ? _ : [_] : [];
  }
  function clampRange(range7, min4, max4) {
    let lo = range7[0], hi = range7[1], span2;
    if (hi < lo) {
      span2 = hi;
      hi = lo;
      lo = span2;
    }
    span2 = hi - lo;
    return span2 >= max4 - min4 ? [min4, max4] : [lo = Math.min(Math.max(lo, min4), max4 - span2), lo + span2];
  }
  function isFunction(_) {
    return typeof _ === "function";
  }
  var DESCENDING = "descending";
  function compare(fields, orders, opt) {
    opt = opt || {};
    orders = array(orders) || [];
    const ord = [], get6 = [], fmap = {}, gen = opt.comparator || comparator;
    array(fields).forEach((f2, i2) => {
      if (f2 == null) return;
      ord.push(orders[i2] === DESCENDING ? -1 : 1);
      get6.push(f2 = isFunction(f2) ? f2 : field(f2, null, opt));
      (accessorFields(f2) || []).forEach((_) => fmap[_] = 1);
    });
    return get6.length === 0 ? null : accessor(gen(get6, ord), Object.keys(fmap));
  }
  var ascending = (u5, v3) => (u5 < v3 || u5 == null) && v3 != null ? -1 : (u5 > v3 || v3 == null) && u5 != null ? 1 : (v3 = v3 instanceof Date ? +v3 : v3, u5 = u5 instanceof Date ? +u5 : u5) !== u5 && v3 === v3 ? -1 : v3 !== v3 && u5 === u5 ? 1 : 0;
  var comparator = (fields, orders) => fields.length === 1 ? compare1(fields[0], orders[0]) : compareN(fields, orders, fields.length);
  var compare1 = (field3, order) => function(a4, b3) {
    return ascending(field3(a4), field3(b3)) * order;
  };
  var compareN = (fields, orders, n2) => {
    orders.push(0);
    return function(a4, b3) {
      let f2, c4 = 0, i2 = -1;
      while (c4 === 0 && ++i2 < n2) {
        f2 = fields[i2];
        c4 = ascending(f2(a4), f2(b3));
      }
      return c4 * orders[i2];
    };
  };
  function constant(_) {
    return isFunction(_) ? _ : () => _;
  }
  function debounce(delay, handler) {
    let tid;
    return (e4) => {
      if (tid) clearTimeout(tid);
      tid = setTimeout(() => (handler(e4), tid = null), delay);
    };
  }
  function extend(_) {
    for (let x5, k2, i2 = 1, len = arguments.length; i2 < len; ++i2) {
      x5 = arguments[i2];
      for (k2 in x5) {
        _[k2] = x5[k2];
      }
    }
    return _;
  }
  function extent(array4, f2) {
    let i2 = 0, n2, v3, min4, max4;
    if (array4 && (n2 = array4.length)) {
      if (f2 == null) {
        for (v3 = array4[i2]; i2 < n2 && (v3 == null || v3 !== v3); v3 = array4[++i2]) ;
        min4 = max4 = v3;
        for (; i2 < n2; ++i2) {
          v3 = array4[i2];
          if (v3 != null) {
            if (v3 < min4) min4 = v3;
            if (v3 > max4) max4 = v3;
          }
        }
      } else {
        for (v3 = f2(array4[i2]); i2 < n2 && (v3 == null || v3 !== v3); v3 = f2(array4[++i2])) ;
        min4 = max4 = v3;
        for (; i2 < n2; ++i2) {
          v3 = f2(array4[i2]);
          if (v3 != null) {
            if (v3 < min4) min4 = v3;
            if (v3 > max4) max4 = v3;
          }
        }
      }
    }
    return [min4, max4];
  }
  function extentIndex(array4, f2) {
    const n2 = array4.length;
    let i2 = -1, a4, b3, c4, u5, v3;
    if (f2 == null) {
      while (++i2 < n2) {
        b3 = array4[i2];
        if (b3 != null && b3 >= b3) {
          a4 = c4 = b3;
          break;
        }
      }
      if (i2 === n2) return [-1, -1];
      u5 = v3 = i2;
      while (++i2 < n2) {
        b3 = array4[i2];
        if (b3 != null) {
          if (a4 > b3) {
            a4 = b3;
            u5 = i2;
          }
          if (c4 < b3) {
            c4 = b3;
            v3 = i2;
          }
        }
      }
    } else {
      while (++i2 < n2) {
        b3 = f2(array4[i2], i2, array4);
        if (b3 != null && b3 >= b3) {
          a4 = c4 = b3;
          break;
        }
      }
      if (i2 === n2) return [-1, -1];
      u5 = v3 = i2;
      while (++i2 < n2) {
        b3 = f2(array4[i2], i2, array4);
        if (b3 != null) {
          if (a4 > b3) {
            a4 = b3;
            u5 = i2;
          }
          if (c4 < b3) {
            c4 = b3;
            v3 = i2;
          }
        }
      }
    }
    return [u5, v3];
  }
  function has(object2, property2) {
    return Object.hasOwn(object2, property2);
  }
  var NULL = {};
  function fastmap(input) {
    let obj = {}, test2;
    function has$1(key2) {
      return has(obj, key2) && obj[key2] !== NULL;
    }
    const map4 = {
      size: 0,
      empty: 0,
      object: obj,
      has: has$1,
      get(key2) {
        return has$1(key2) ? obj[key2] : void 0;
      },
      set(key2, value3) {
        if (!has$1(key2)) {
          ++map4.size;
          if (obj[key2] === NULL) --map4.empty;
        }
        obj[key2] = value3;
        return this;
      },
      delete(key2) {
        if (has$1(key2)) {
          --map4.size;
          ++map4.empty;
          obj[key2] = NULL;
        }
        return this;
      },
      clear() {
        map4.size = map4.empty = 0;
        map4.object = obj = {};
      },
      test(_) {
        if (arguments.length) {
          test2 = _;
          return map4;
        } else {
          return test2;
        }
      },
      clean() {
        const next = {};
        let size = 0;
        for (const key2 in obj) {
          const value3 = obj[key2];
          if (value3 !== NULL && (!test2 || !test2(value3))) {
            next[key2] = value3;
            ++size;
          }
        }
        map4.size = size;
        map4.empty = 0;
        map4.object = obj = next;
      }
    };
    if (input) Object.keys(input).forEach((key2) => {
      map4.set(key2, input[key2]);
    });
    return map4;
  }
  function flush(range7, value3, threshold2, left, right, center) {
    if (!threshold2 && threshold2 !== 0) return center;
    const t4 = +threshold2;
    let a4 = range7[0], b3 = peek(range7), l2;
    if (b3 < a4) {
      l2 = a4;
      a4 = b3;
      b3 = l2;
    }
    l2 = Math.abs(value3 - a4);
    const r2 = Math.abs(b3 - value3);
    return l2 < r2 && l2 <= t4 ? left : r2 <= t4 ? right : center;
  }
  function inherits(child, parent, members) {
    const proto = child.prototype = Object.create(parent.prototype);
    Object.defineProperty(proto, "constructor", {
      value: child,
      writable: true,
      enumerable: true,
      configurable: true
    });
    return extend(proto, members);
  }
  function inrange(value3, range7, left, right) {
    let r0 = range7[0], r1 = range7[range7.length - 1], t4;
    if (r0 > r1) {
      t4 = r0;
      r0 = r1;
      r1 = t4;
    }
    left = left === void 0 || left;
    right = right === void 0 || right;
    return (left ? r0 <= value3 : r0 < value3) && (right ? value3 <= r1 : value3 < r1);
  }
  function isBoolean(_) {
    return typeof _ === "boolean";
  }
  function isDate(_) {
    return Object.prototype.toString.call(_) === "[object Date]";
  }
  function isIterable(_) {
    return _ && isFunction(_[Symbol.iterator]);
  }
  function isNumber(_) {
    return typeof _ === "number";
  }
  function isRegExp(_) {
    return Object.prototype.toString.call(_) === "[object RegExp]";
  }
  function isString(_) {
    return typeof _ === "string";
  }
  function key(fields, flat, opt) {
    if (fields) {
      fields = flat ? array(fields).map((f2) => f2.replace(/\\(.)/g, "$1")) : array(fields);
    }
    const len = fields && fields.length, gen = opt && opt.get || getter, map4 = (f2) => gen(flat ? [f2] : splitAccessPath(f2));
    let fn;
    if (!len) {
      fn = function() {
        return "";
      };
    } else if (len === 1) {
      const get6 = map4(fields[0]);
      fn = function(_) {
        return "" + get6(_);
      };
    } else {
      const get6 = fields.map(map4);
      fn = function(_) {
        let s2 = "" + get6[0](_), i2 = 0;
        while (++i2 < len) s2 += "|" + get6[i2](_);
        return s2;
      };
    }
    return accessor(fn, fields, "key");
  }
  function lerp(array4, frac) {
    const lo = array4[0], hi = peek(array4), f2 = +frac;
    return !f2 ? lo : f2 === 1 ? hi : lo + f2 * (hi - lo);
  }
  var DEFAULT_MAX_SIZE = 1e4;
  function lruCache(maxsize) {
    maxsize = +maxsize || DEFAULT_MAX_SIZE;
    let curr, prev, size;
    const clear2 = () => {
      curr = {};
      prev = {};
      size = 0;
    };
    const update3 = (key2, value3) => {
      if (++size > maxsize) {
        prev = curr;
        curr = {};
        size = 1;
      }
      return curr[key2] = value3;
    };
    clear2();
    return {
      clear: clear2,
      has: (key2) => has(curr, key2) || has(prev, key2),
      get: (key2) => has(curr, key2) ? curr[key2] : has(prev, key2) ? update3(key2, prev[key2]) : void 0,
      set: (key2, value3) => has(curr, key2) ? curr[key2] = value3 : update3(key2, value3)
    };
  }
  function merge(compare4, array0, array1, output3) {
    const n0 = array0.length, n1 = array1.length;
    if (!n1) return array0;
    if (!n0) return array1;
    const merged = output3 || new array0.constructor(n0 + n1);
    let i0 = 0, i1 = 0, i2 = 0;
    for (; i0 < n0 && i1 < n1; ++i2) {
      merged[i2] = compare4(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++];
    }
    for (; i0 < n0; ++i0, ++i2) {
      merged[i2] = array0[i0];
    }
    for (; i1 < n1; ++i1, ++i2) {
      merged[i2] = array1[i1];
    }
    return merged;
  }
  function repeat(str, reps) {
    let s2 = "";
    while (--reps >= 0) s2 += str;
    return s2;
  }
  function pad(str, length3, padchar, align2) {
    const c4 = padchar || " ", s2 = str + "", n2 = length3 - s2.length;
    return n2 <= 0 ? s2 : align2 === "left" ? repeat(c4, n2) + s2 : align2 === "center" ? repeat(c4, ~~(n2 / 2)) + s2 + repeat(c4, Math.ceil(n2 / 2)) : s2 + repeat(c4, n2);
  }
  function span(array4) {
    return array4 && peek(array4) - array4[0] || 0;
  }
  function $(x5) {
    return isArray(x5) ? "[" + x5.map($) + "]" : isObject(x5) || isString(x5) ? (
      // Output valid JSON and JS source strings.
      // See http://timelessrepo.com/json-isnt-a-javascript-subset
      JSON.stringify(x5).replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
    ) : x5;
  }
  function toBoolean(_) {
    return _ == null || _ === "" ? null : !_ || _ === "false" || _ === "0" ? false : !!_;
  }
  var defaultParser = (_) => isNumber(_) ? _ : isDate(_) ? _ : Date.parse(_);
  function toDate(_, parser4) {
    parser4 = parser4 || defaultParser;
    return _ == null || _ === "" ? null : parser4(_);
  }
  function toString(_) {
    return _ == null || _ === "" ? null : _ + "";
  }
  function toSet(_) {
    const s2 = {}, n2 = _.length;
    for (let i2 = 0; i2 < n2; ++i2) s2[_[i2]] = true;
    return s2;
  }
  function truncate(str, length3, align2, ellipsis) {
    const e4 = ellipsis != null ? ellipsis : "\u2026", s2 = str + "", n2 = s2.length, l2 = Math.max(0, length3 - e4.length);
    return n2 <= length3 ? s2 : align2 === "left" ? e4 + s2.slice(n2 - l2) : align2 === "center" ? s2.slice(0, Math.ceil(l2 / 2)) + e4 + s2.slice(n2 - ~~(l2 / 2)) : s2.slice(0, l2) + e4;
  }
  function visitArray(array4, filter3, visitor) {
    if (array4) {
      if (filter3) {
        const n2 = array4.length;
        for (let i2 = 0; i2 < n2; ++i2) {
          const t4 = filter3(array4[i2]);
          if (t4) visitor(t4, i2, array4);
        }
      } else {
        array4.forEach(visitor);
      }
    }
  }

  // node_modules/d3-dsv/src/dsv.js
  var EOL = {};
  var EOF = {};
  var QUOTE = 34;
  var NEWLINE = 10;
  var RETURN = 13;
  function objectConverter(columns2) {
    return new Function("d", "return {" + columns2.map(function(name4, i2) {
      return JSON.stringify(name4) + ": d[" + i2 + '] || ""';
    }).join(",") + "}");
  }
  function customConverter(columns2, f2) {
    var object2 = objectConverter(columns2);
    return function(row, i2) {
      return f2(object2(row), i2, columns2);
    };
  }
  function inferColumns(rows) {
    var columnSet = /* @__PURE__ */ Object.create(null), columns2 = [];
    rows.forEach(function(row) {
      for (var column in row) {
        if (!(column in columnSet)) {
          columns2.push(columnSet[column] = column);
        }
      }
    });
    return columns2;
  }
  function pad2(value3, width2) {
    var s2 = value3 + "", length3 = s2.length;
    return length3 < width2 ? new Array(width2 - length3 + 1).join(0) + s2 : s2;
  }
  function formatYear(year) {
    return year < 0 ? "-" + pad2(-year, 6) : year > 9999 ? "+" + pad2(year, 6) : pad2(year, 4);
  }
  function formatDate(date2) {
    var hours = date2.getUTCHours(), minutes = date2.getUTCMinutes(), seconds2 = date2.getUTCSeconds(), milliseconds2 = date2.getUTCMilliseconds();
    return isNaN(date2) ? "Invalid Date" : formatYear(date2.getUTCFullYear(), 4) + "-" + pad2(date2.getUTCMonth() + 1, 2) + "-" + pad2(date2.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 parse7(text4, f2) {
      var convert, columns2, rows = parseRows(text4, function(row, i2) {
        if (convert) return convert(row, i2 - 1);
        columns2 = row, convert = f2 ? customConverter(row, f2) : objectConverter(row);
      });
      rows.columns = columns2 || [];
      return rows;
    }
    function parseRows(text4, f2) {
      var rows = [], N = text4.length, I = 0, n2 = 0, t4, eof = N <= 0, eol = false;
      if (text4.charCodeAt(N - 1) === NEWLINE) --N;
      if (text4.charCodeAt(N - 1) === RETURN) --N;
      function token() {
        if (eof) return EOF;
        if (eol) return eol = false, EOL;
        var i2, j2 = I, c4;
        if (text4.charCodeAt(j2) === QUOTE) {
          while (I++ < N && text4.charCodeAt(I) !== QUOTE || text4.charCodeAt(++I) === QUOTE) ;
          if ((i2 = I) >= N) eof = true;
          else if ((c4 = text4.charCodeAt(I++)) === NEWLINE) eol = true;
          else if (c4 === RETURN) {
            eol = true;
            if (text4.charCodeAt(I) === NEWLINE) ++I;
          }
          return text4.slice(j2 + 1, i2 - 1).replace(/""/g, '"');
        }
        while (I < N) {
          if ((c4 = text4.charCodeAt(i2 = I++)) === NEWLINE) eol = true;
          else if (c4 === RETURN) {
            eol = true;
            if (text4.charCodeAt(I) === NEWLINE) ++I;
          } else if (c4 !== DELIMITER) continue;
          return text4.slice(j2, i2);
        }
        return eof = true, text4.slice(j2, N);
      }
      while ((t4 = token()) !== EOF) {
        var row = [];
        while (t4 !== EOL && t4 !== EOF) row.push(t4), t4 = token();
        if (f2 && (row = f2(row, n2++)) == null) continue;
        rows.push(row);
      }
      return rows;
    }
    function preformatBody(rows, columns2) {
      return rows.map(function(row) {
        return columns2.map(function(column) {
          return formatValue4(row[column]);
        }).join(delimiter);
      });
    }
    function format5(rows, columns2) {
      if (columns2 == null) columns2 = inferColumns(rows);
      return [columns2.map(formatValue4).join(delimiter)].concat(preformatBody(rows, columns2)).join("\n");
    }
    function formatBody(rows, columns2) {
      if (columns2 == null) columns2 = inferColumns(rows);
      return preformatBody(rows, columns2).join("\n");
    }
    function formatRows(rows) {
      return rows.map(formatRow).join("\n");
    }
    function formatRow(row) {
      return row.map(formatValue4).join(delimiter);
    }
    function formatValue4(value3) {
      return value3 == null ? "" : value3 instanceof Date ? formatDate(value3) : reFormat.test(value3 += "") ? '"' + value3.replace(/"/g, '""') + '"' : value3;
    }
    return {
      parse: parse7,
      parseRows,
      format: format5,
      formatBody,
      formatRows,
      formatRow,
      formatValue: formatValue4
    };
  }

  // node_modules/topojson-client/src/identity.js
  function identity_default(x5) {
    return x5;
  }

  // node_modules/topojson-client/src/transform.js
  function transform_default(transform4) {
    if (transform4 == null) return identity_default;
    var x06, y06, kx = transform4.scale[0], ky = transform4.scale[1], dx = transform4.translate[0], dy = transform4.translate[1];
    return function(input, i2) {
      if (!i2) x06 = y06 = 0;
      var j2 = 2, n2 = input.length, output3 = new Array(n2);
      output3[0] = (x06 += input[0]) * kx + dx;
      output3[1] = (y06 += input[1]) * ky + dy;
      while (j2 < n2) output3[j2] = input[j2], ++j2;
      return output3;
    };
  }

  // node_modules/topojson-client/src/reverse.js
  function reverse_default(array4, n2) {
    var t4, j2 = array4.length, i2 = j2 - n2;
    while (i2 < --j2) t4 = array4[i2], array4[i2++] = array4[j2], array4[j2] = t4;
  }

  // node_modules/topojson-client/src/feature.js
  function feature_default(topology, o2) {
    if (typeof o2 === "string") o2 = topology.objects[o2];
    return o2.type === "GeometryCollection" ? { type: "FeatureCollection", features: o2.geometries.map(function(o3) {
      return feature(topology, o3);
    }) } : feature(topology, o2);
  }
  function feature(topology, o2) {
    var id2 = o2.id, bbox = o2.bbox, properties = o2.properties == null ? {} : o2.properties, geometry = object(topology, o2);
    return id2 == null && bbox == null ? { type: "Feature", properties, geometry } : bbox == null ? { type: "Feature", id: id2, properties, geometry } : { type: "Feature", id: id2, bbox, properties, geometry };
  }
  function object(topology, o2) {
    var transformPoint = transform_default(topology.transform), arcs = topology.arcs;
    function arc4(i2, points2) {
      if (points2.length) points2.pop();
      for (var a4 = arcs[i2 < 0 ? ~i2 : i2], k2 = 0, n2 = a4.length; k2 < n2; ++k2) {
        points2.push(transformPoint(a4[k2], k2));
      }
      if (i2 < 0) reverse_default(points2, n2);
    }
    function point9(p2) {
      return transformPoint(p2);
    }
    function line4(arcs2) {
      var points2 = [];
      for (var i2 = 0, n2 = arcs2.length; i2 < n2; ++i2) arc4(arcs2[i2], points2);
      if (points2.length < 2) points2.push(points2[0]);
      return points2;
    }
    function ring(arcs2) {
      var points2 = line4(arcs2);
      while (points2.length < 4) points2.push(points2[0]);
      return points2;
    }
    function polygon(arcs2) {
      return arcs2.map(ring);
    }
    function geometry(o3) {
      var type3 = o3.type, coordinates;
      switch (type3) {
        case "GeometryCollection":
          return { type: type3, geometries: o3.geometries.map(geometry) };
        case "Point":
          coordinates = point9(o3.coordinates);
          break;
        case "MultiPoint":
          coordinates = o3.coordinates.map(point9);
          break;
        case "LineString":
          coordinates = line4(o3.arcs);
          break;
        case "MultiLineString":
          coordinates = o3.arcs.map(line4);
          break;
        case "Polygon":
          coordinates = polygon(o3.arcs);
          break;
        case "MultiPolygon":
          coordinates = o3.arcs.map(polygon);
          break;
        default:
          return null;
      }
      return { type: type3, coordinates };
    }
    return geometry(o2);
  }

  // node_modules/topojson-client/src/stitch.js
  function stitch_default(topology, arcs) {
    var stitchedArcs = {}, fragmentByStart = {}, fragmentByEnd = {}, fragments = [], emptyIndex = -1;
    arcs.forEach(function(i2, j2) {
      var arc4 = topology.arcs[i2 < 0 ? ~i2 : i2], t4;
      if (arc4.length < 3 && !arc4[1][0] && !arc4[1][1]) {
        t4 = arcs[++emptyIndex], arcs[emptyIndex] = i2, arcs[j2] = t4;
      }
    });
    arcs.forEach(function(i2) {
      var e4 = ends(i2), start = e4[0], end = e4[1], f2, g2;
      if (f2 = fragmentByEnd[start]) {
        delete fragmentByEnd[f2.end];
        f2.push(i2);
        f2.end = end;
        if (g2 = fragmentByStart[end]) {
          delete fragmentByStart[g2.start];
          var fg = g2 === f2 ? f2 : f2.concat(g2);
          fragmentByStart[fg.start = f2.start] = fragmentByEnd[fg.end = g2.end] = fg;
        } else {
          fragmentByStart[f2.start] = fragmentByEnd[f2.end] = f2;
        }
      } else if (f2 = fragmentByStart[end]) {
        delete fragmentByStart[f2.start];
        f2.unshift(i2);
        f2.start = start;
        if (g2 = fragmentByEnd[start]) {
          delete fragmentByEnd[g2.end];
          var gf = g2 === f2 ? f2 : g2.concat(f2);
          fragmentByStart[gf.start = g2.start] = fragmentByEnd[gf.end = f2.end] = gf;
        } else {
          fragmentByStart[f2.start] = fragmentByEnd[f2.end] = f2;
        }
      } else {
        f2 = [i2];
        fragmentByStart[f2.start = start] = fragmentByEnd[f2.end = end] = f2;
      }
    });
    function ends(i2) {
      var arc4 = topology.arcs[i2 < 0 ? ~i2 : i2], p02 = arc4[0], p1;
      if (topology.transform) p1 = [0, 0], arc4.forEach(function(dp) {
        p1[0] += dp[0], p1[1] += dp[1];
      });
      else p1 = arc4[arc4.length - 1];
      return i2 < 0 ? [p1, p02] : [p02, p1];
    }
    function flush2(fragmentByEnd2, fragmentByStart2) {
      for (var k2 in fragmentByEnd2) {
        var f2 = fragmentByEnd2[k2];
        delete fragmentByStart2[f2.start];
        delete f2.start;
        delete f2.end;
        f2.forEach(function(i2) {
          stitchedArcs[i2 < 0 ? ~i2 : i2] = 1;
        });
        fragments.push(f2);
      }
    }
    flush2(fragmentByEnd, fragmentByStart);
    flush2(fragmentByStart, fragmentByEnd);
    arcs.forEach(function(i2) {
      if (!stitchedArcs[i2 < 0 ? ~i2 : i2]) fragments.push([i2]);
    });
    return fragments;
  }

  // node_modules/topojson-client/src/mesh.js
  function mesh_default(topology) {
    return object(topology, meshArcs.apply(this, arguments));
  }
  function meshArcs(topology, object2, filter3) {
    var arcs, i2, n2;
    if (arguments.length > 1) arcs = extractArcs(topology, object2, filter3);
    else for (i2 = 0, arcs = new Array(n2 = topology.arcs.length); i2 < n2; ++i2) arcs[i2] = i2;
    return { type: "MultiLineString", arcs: stitch_default(topology, arcs) };
  }
  function extractArcs(topology, object2, filter3) {
    var arcs = [], geomsByArc = [], geom;
    function extract0(i2) {
      var j2 = i2 < 0 ? ~i2 : i2;
      (geomsByArc[j2] || (geomsByArc[j2] = [])).push({ i: i2, g: geom });
    }
    function extract1(arcs2) {
      arcs2.forEach(extract0);
    }
    function extract2(arcs2) {
      arcs2.forEach(extract1);
    }
    function extract3(arcs2) {
      arcs2.forEach(extract2);
    }
    function geometry(o2) {
      switch (geom = o2, o2.type) {
        case "GeometryCollection":
          o2.geometries.forEach(geometry);
          break;
        case "LineString":
          extract1(o2.arcs);
          break;
        case "MultiLineString":
        case "Polygon":
          extract2(o2.arcs);
          break;
        case "MultiPolygon":
          extract3(o2.arcs);
          break;
      }
    }
    geometry(object2);
    geomsByArc.forEach(filter3 == null ? function(geoms) {
      arcs.push(geoms[0].i);
    } : function(geoms) {
      if (filter3(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i);
    });
    return arcs;
  }

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

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

  // node_modules/d3-array/src/bisector.js
  function bisector(f2) {
    let compare12, compare22, delta;
    if (f2.length !== 2) {
      compare12 = ascending2;
      compare22 = (d2, x5) => ascending2(f2(d2), x5);
      delta = (d2, x5) => f2(d2) - x5;
    } else {
      compare12 = f2 === ascending2 || f2 === descending ? f2 : zero2;
      compare22 = f2;
      delta = f2;
    }
    function left(a4, x5, lo = 0, hi = a4.length) {
      if (lo < hi) {
        if (compare12(x5, x5) !== 0) return hi;
        do {
          const mid = lo + hi >>> 1;
          if (compare22(a4[mid], x5) < 0) lo = mid + 1;
          else hi = mid;
        } while (lo < hi);
      }
      return lo;
    }
    function right(a4, x5, lo = 0, hi = a4.length) {
      if (lo < hi) {
        if (compare12(x5, x5) !== 0) return hi;
        do {
          const mid = lo + hi >>> 1;
          if (compare22(a4[mid], x5) <= 0) lo = mid + 1;
          else hi = mid;
        } while (lo < hi);
      }
      return lo;
    }
    function center(a4, x5, lo = 0, hi = a4.length) {
      const i2 = left(a4, x5, lo, hi - 1);
      return i2 > lo && delta(a4[i2 - 1], x5) > -delta(a4[i2], x5) ? i2 - 1 : i2;
    }
    return { left, center, right };
  }
  function zero2() {
    return 0;
  }

  // node_modules/d3-array/src/number.js
  function number(x5) {
    return x5 === null ? NaN : +x5;
  }
  function* numbers(values4, valueof) {
    if (valueof === void 0) {
      for (let value3 of values4) {
        if (value3 != null && (value3 = +value3) >= value3) {
          yield value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if ((value3 = valueof(value3, ++index4, values4)) != null && (value3 = +value3) >= value3) {
          yield value3;
        }
      }
    }
  }

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

  // node_modules/d3-array/src/variance.js
  function variance(values4, valueof) {
    let count2 = 0;
    let delta;
    let mean2 = 0;
    let sum3 = 0;
    if (valueof === void 0) {
      for (let value3 of values4) {
        if (value3 != null && (value3 = +value3) >= value3) {
          delta = value3 - mean2;
          mean2 += delta / ++count2;
          sum3 += delta * (value3 - mean2);
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if ((value3 = valueof(value3, ++index4, values4)) != null && (value3 = +value3) >= value3) {
          delta = value3 - mean2;
          mean2 += delta / ++count2;
          sum3 += delta * (value3 - mean2);
        }
      }
    }
    if (count2 > 1) return sum3 / (count2 - 1);
  }

  // node_modules/d3-array/src/deviation.js
  function deviation(values4, valueof) {
    const v3 = variance(values4, valueof);
    return v3 ? Math.sqrt(v3) : v3;
  }

  // node_modules/d3-array/src/fsum.js
  var Adder = class {
    constructor() {
      this._partials = new Float64Array(32);
      this._n = 0;
    }
    add(x5) {
      const p2 = this._partials;
      let i2 = 0;
      for (let j2 = 0; j2 < this._n && j2 < 32; j2++) {
        const y5 = p2[j2], hi = x5 + y5, lo = Math.abs(x5) < Math.abs(y5) ? x5 - (hi - y5) : y5 - (hi - x5);
        if (lo) p2[i2++] = lo;
        x5 = hi;
      }
      p2[i2] = x5;
      this._n = i2 + 1;
      return this;
    }
    valueOf() {
      const p2 = this._partials;
      let n2 = this._n, x5, y5, lo, hi = 0;
      if (n2 > 0) {
        hi = p2[--n2];
        while (n2 > 0) {
          x5 = hi;
          y5 = p2[--n2];
          hi = x5 + y5;
          lo = y5 - (hi - x5);
          if (lo) break;
        }
        if (n2 > 0 && (lo < 0 && p2[n2 - 1] < 0 || lo > 0 && p2[n2 - 1] > 0)) {
          y5 = lo * 2;
          x5 = hi + y5;
          if (y5 == x5 - hi) hi = x5;
        }
      }
      return hi;
    }
  };

  // node_modules/internmap/src/index.js
  var InternMap = class extends Map {
    constructor(entries3, key2 = keyof) {
      super();
      Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
      if (entries3 != null) for (const [key3, value3] of entries3) this.set(key3, value3);
    }
    get(key2) {
      return super.get(intern_get(this, key2));
    }
    has(key2) {
      return super.has(intern_get(this, key2));
    }
    set(key2, value3) {
      return super.set(intern_set(this, key2), value3);
    }
    delete(key2) {
      return super.delete(intern_delete(this, key2));
    }
  };
  var InternSet = class extends Set {
    constructor(values4, key2 = keyof) {
      super();
      Object.defineProperties(this, { _intern: { value: /* @__PURE__ */ new Map() }, _key: { value: key2 } });
      if (values4 != null) for (const value3 of values4) this.add(value3);
    }
    has(value3) {
      return super.has(intern_get(this, value3));
    }
    add(value3) {
      return super.add(intern_set(this, value3));
    }
    delete(value3) {
      return super.delete(intern_delete(this, value3));
    }
  };
  function intern_get({ _intern, _key }, value3) {
    const key2 = _key(value3);
    return _intern.has(key2) ? _intern.get(key2) : value3;
  }
  function intern_set({ _intern, _key }, value3) {
    const key2 = _key(value3);
    if (_intern.has(key2)) return _intern.get(key2);
    _intern.set(key2, value3);
    return value3;
  }
  function intern_delete({ _intern, _key }, value3) {
    const key2 = _key(value3);
    if (_intern.has(key2)) {
      value3 = _intern.get(key2);
      _intern.delete(key2);
    }
    return value3;
  }
  function keyof(value3) {
    return value3 !== null && typeof value3 === "object" ? value3.valueOf() : value3;
  }

  // node_modules/d3-array/src/permute.js
  function permute(source4, keys4) {
    return Array.from(keys4, (key2) => source4[key2]);
  }

  // node_modules/d3-array/src/sort.js
  function compareDefined(compare4 = ascending2) {
    if (compare4 === ascending2) return ascendingDefined;
    if (typeof compare4 !== "function") throw new TypeError("compare is not a function");
    return (a4, b3) => {
      const x5 = compare4(a4, b3);
      if (x5 || x5 === 0) return x5;
      return (compare4(b3, b3) === 0) - (compare4(a4, a4) === 0);
    };
  }
  function ascendingDefined(a4, b3) {
    return (a4 == null || !(a4 >= a4)) - (b3 == null || !(b3 >= b3)) || (a4 < b3 ? -1 : a4 > b3 ? 1 : 0);
  }

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

  // node_modules/d3-array/src/max.js
  function max(values4, valueof) {
    let max4;
    if (valueof === void 0) {
      for (const value3 of values4) {
        if (value3 != null && (max4 < value3 || max4 === void 0 && value3 >= value3)) {
          max4 = value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if ((value3 = valueof(value3, ++index4, values4)) != null && (max4 < value3 || max4 === void 0 && value3 >= value3)) {
          max4 = value3;
        }
      }
    }
    return max4;
  }

  // node_modules/d3-array/src/min.js
  function min(values4, valueof) {
    let min4;
    if (valueof === void 0) {
      for (const value3 of values4) {
        if (value3 != null && (min4 > value3 || min4 === void 0 && value3 >= value3)) {
          min4 = value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if ((value3 = valueof(value3, ++index4, values4)) != null && (min4 > value3 || min4 === void 0 && value3 >= value3)) {
          min4 = value3;
        }
      }
    }
    return min4;
  }

  // node_modules/d3-array/src/quickselect.js
  function quickselect(array4, k2, left = 0, right = Infinity, compare4) {
    k2 = Math.floor(k2);
    left = Math.floor(Math.max(0, left));
    right = Math.floor(Math.min(array4.length - 1, right));
    if (!(left <= k2 && k2 <= right)) return array4;
    compare4 = compare4 === void 0 ? ascendingDefined : compareDefined(compare4);
    while (right > left) {
      if (right - left > 600) {
        const n2 = right - left + 1;
        const m4 = k2 - left + 1;
        const z = Math.log(n2);
        const s2 = 0.5 * Math.exp(2 * z / 3);
        const sd = 0.5 * Math.sqrt(z * s2 * (n2 - s2) / n2) * (m4 - n2 / 2 < 0 ? -1 : 1);
        const newLeft = Math.max(left, Math.floor(k2 - m4 * s2 / n2 + sd));
        const newRight = Math.min(right, Math.floor(k2 + (n2 - m4) * s2 / n2 + sd));
        quickselect(array4, k2, newLeft, newRight, compare4);
      }
      const t4 = array4[k2];
      let i2 = left;
      let j2 = right;
      swap(array4, left, k2);
      if (compare4(array4[right], t4) > 0) swap(array4, left, right);
      while (i2 < j2) {
        swap(array4, i2, j2), ++i2, --j2;
        while (compare4(array4[i2], t4) < 0) ++i2;
        while (compare4(array4[j2], t4) > 0) --j2;
      }
      if (compare4(array4[left], t4) === 0) swap(array4, left, j2);
      else ++j2, swap(array4, j2, right);
      if (j2 <= k2) left = j2 + 1;
      if (k2 <= j2) right = j2 - 1;
    }
    return array4;
  }
  function swap(array4, i2, j2) {
    const t4 = array4[i2];
    array4[i2] = array4[j2];
    array4[j2] = t4;
  }

  // node_modules/d3-array/src/quantile.js
  function quantile(values4, p2, valueof) {
    values4 = Float64Array.from(numbers(values4, valueof));
    if (!(n2 = values4.length) || isNaN(p2 = +p2)) return;
    if (p2 <= 0 || n2 < 2) return min(values4);
    if (p2 >= 1) return max(values4);
    var n2, i2 = (n2 - 1) * p2, i0 = Math.floor(i2), value0 = max(quickselect(values4, i0).subarray(0, i0 + 1)), value1 = min(values4.subarray(i0 + 1));
    return value0 + (value1 - value0) * (i2 - i0);
  }
  function quantileSorted(values4, p2, valueof = number) {
    if (!(n2 = values4.length) || isNaN(p2 = +p2)) return;
    if (p2 <= 0 || n2 < 2) return +valueof(values4[0], 0, values4);
    if (p2 >= 1) return +valueof(values4[n2 - 1], n2 - 1, values4);
    var n2, i2 = (n2 - 1) * p2, i0 = Math.floor(i2), value0 = +valueof(values4[i0], i0, values4), value1 = +valueof(values4[i0 + 1], i0 + 1, values4);
    return value0 + (value1 - value0) * (i2 - i0);
  }

  // node_modules/d3-array/src/mean.js
  function mean(values4, valueof) {
    let count2 = 0;
    let sum3 = 0;
    if (valueof === void 0) {
      for (let value3 of values4) {
        if (value3 != null && (value3 = +value3) >= value3) {
          ++count2, sum3 += value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if ((value3 = valueof(value3, ++index4, values4)) != null && (value3 = +value3) >= value3) {
          ++count2, sum3 += value3;
        }
      }
    }
    if (count2) return sum3 / count2;
  }

  // node_modules/d3-array/src/median.js
  function median(values4, valueof) {
    return quantile(values4, 0.5, valueof);
  }

  // node_modules/d3-array/src/merge.js
  function* flatten(arrays) {
    for (const array4 of arrays) {
      yield* array4;
    }
  }
  function merge2(arrays) {
    return Array.from(flatten(arrays));
  }

  // node_modules/d3-array/src/range.js
  function range(start, stop2, step) {
    start = +start, stop2 = +stop2, step = (n2 = arguments.length) < 2 ? (stop2 = start, start = 0, 1) : n2 < 3 ? 1 : +step;
    var i2 = -1, n2 = Math.max(0, Math.ceil((stop2 - start) / step)) | 0, range7 = new Array(n2);
    while (++i2 < n2) {
      range7[i2] = start + i2 * step;
    }
    return range7;
  }

  // node_modules/d3-array/src/sum.js
  function sum(values4, valueof) {
    let sum3 = 0;
    if (valueof === void 0) {
      for (let value3 of values4) {
        if (value3 = +value3) {
          sum3 += value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        if (value3 = +valueof(value3, ++index4, values4)) {
          sum3 += value3;
        }
      }
    }
    return sum3;
  }

  // node_modules/d3-array/src/intersection.js
  function intersection(values4, ...others) {
    values4 = new InternSet(values4);
    others = others.map(set);
    out: for (const value3 of values4) {
      for (const other of others) {
        if (!other.has(value3)) {
          values4.delete(value3);
          continue out;
        }
      }
    }
    return values4;
  }
  function set(values4) {
    return values4 instanceof InternSet ? values4 : new InternSet(values4);
  }

  // node_modules/d3-array/src/union.js
  function union(...others) {
    const set7 = new InternSet();
    for (const other of others) {
      for (const o2 of other) {
        set7.add(o2);
      }
    }
    return set7;
  }

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

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

  // node_modules/d3-format/src/formatGroup.js
  function formatGroup_default(grouping, thousands) {
    return function(value3, width2) {
      var i2 = value3.length, t4 = [], j2 = 0, g2 = grouping[0], length3 = 0;
      while (i2 > 0 && g2 > 0) {
        if (length3 + g2 + 1 > width2) g2 = Math.max(1, width2 - length3);
        t4.push(value3.substring(i2 -= g2, i2 + g2));
        if ((length3 += g2 + 1) > width2) break;
        g2 = grouping[j2 = (j2 + 1) % grouping.length];
      }
      return t4.reverse().join(thousands);
    };
  }

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

  // node_modules/d3-format/src/formatSpecifier.js
  var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
  function formatSpecifier(specifier) {
    if (!(match3 = re.exec(specifier))) throw new Error("invalid format: " + specifier);
    var match3;
    return new FormatSpecifier({
      fill: match3[1],
      align: match3[2],
      sign: match3[3],
      symbol: match3[4],
      zero: match3[5],
      width: match3[6],
      comma: match3[7],
      precision: match3[8] && match3[8].slice(1),
      trim: match3[9],
      type: match3[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, i2 = 1, i0 = -1, i1; i2 < n2; ++i2) {
      switch (s2[i2]) {
        case ".":
          i0 = i1 = i2;
          break;
        case "0":
          if (i0 === 0) i0 = i2;
          i1 = i2;
          break;
        default:
          if (!+s2[i2]) 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(x5, p2) {
    var d2 = formatDecimalParts(x5, p2);
    if (!d2) return x5 + "";
    var coefficient = d2[0], exponent = d2[1], i2 = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n2 = coefficient.length;
    return i2 === n2 ? coefficient : i2 > n2 ? coefficient + new Array(i2 - n2 + 1).join("0") : i2 > 0 ? coefficient.slice(0, i2) + "." + coefficient.slice(i2) : "0." + new Array(1 - i2).join("0") + formatDecimalParts(x5, Math.max(0, p2 + i2 - 1))[0];
  }

  // node_modules/d3-format/src/formatRounded.js
  function formatRounded_default(x5, p2) {
    var d2 = formatDecimalParts(x5, p2);
    if (!d2) return x5 + "";
    var coefficient = d2[0], exponent = d2[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 = {
    "%": (x5, p2) => (x5 * 100).toFixed(p2),
    "b": (x5) => Math.round(x5).toString(2),
    "c": (x5) => x5 + "",
    "d": formatDecimal_default,
    "e": (x5, p2) => x5.toExponential(p2),
    "f": (x5, p2) => x5.toFixed(p2),
    "g": (x5, p2) => x5.toPrecision(p2),
    "o": (x5) => Math.round(x5).toString(8),
    "p": (x5, p2) => formatRounded_default(x5 * 100, p2),
    "r": formatRounded_default,
    "s": formatPrefixAuto_default,
    "X": (x5) => Math.round(x5).toString(16).toUpperCase(),
    "x": (x5) => Math.round(x5).toString(16)
  };

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

  // 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(locale4) {
    var group2 = locale4.grouping === void 0 || locale4.thousands === void 0 ? identity_default2 : formatGroup_default(map.call(locale4.grouping, Number), locale4.thousands + ""), currencyPrefix = locale4.currency === void 0 ? "" : locale4.currency[0] + "", currencySuffix = locale4.currency === void 0 ? "" : locale4.currency[1] + "", decimal = locale4.decimal === void 0 ? "." : locale4.decimal + "", numerals = locale4.numerals === void 0 ? identity_default2 : formatNumerals_default(map.call(locale4.numerals, String)), percent = locale4.percent === void 0 ? "%" : locale4.percent + "", minus = locale4.minus === void 0 ? "\u2212" : locale4.minus + "", nan = locale4.nan === void 0 ? "NaN" : locale4.nan + "";
    function newFormat(specifier) {
      specifier = formatSpecifier(specifier);
      var fill2 = specifier.fill, align2 = specifier.align, sign3 = specifier.sign, symbol2 = specifier.symbol, zero6 = specifier.zero, width2 = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type3 = specifier.type;
      if (type3 === "n") comma = true, type3 = "g";
      else if (!formatTypes_default[type3]) precision === void 0 && (precision = 12), trim = true, type3 = "g";
      if (zero6 || fill2 === "0" && align2 === "=") zero6 = true, fill2 = "0", align2 = "=";
      var prefix = symbol2 === "$" ? currencyPrefix : symbol2 === "#" && /[boxX]/.test(type3) ? "0" + type3.toLowerCase() : "", suffix = symbol2 === "$" ? currencySuffix : /[%p]/.test(type3) ? percent : "";
      var formatType = formatTypes_default[type3], maybeSuffix = /[defgprs%]/.test(type3);
      precision = precision === void 0 ? 6 : /[gprs]/.test(type3) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
      function format5(value3) {
        var valuePrefix = prefix, valueSuffix = suffix, i2, n2, c4;
        if (type3 === "c") {
          valueSuffix = formatType(value3) + valueSuffix;
          value3 = "";
        } else {
          value3 = +value3;
          var valueNegative = value3 < 0 || 1 / value3 < 0;
          value3 = isNaN(value3) ? nan : formatType(Math.abs(value3), precision);
          if (trim) value3 = formatTrim_default(value3);
          if (valueNegative && +value3 === 0 && sign3 !== "+") valueNegative = false;
          valuePrefix = (valueNegative ? sign3 === "(" ? sign3 : minus : sign3 === "-" || sign3 === "(" ? "" : sign3) + valuePrefix;
          valueSuffix = (type3 === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign3 === "(" ? ")" : "");
          if (maybeSuffix) {
            i2 = -1, n2 = value3.length;
            while (++i2 < n2) {
              if (c4 = value3.charCodeAt(i2), 48 > c4 || c4 > 57) {
                valueSuffix = (c4 === 46 ? decimal + value3.slice(i2 + 1) : value3.slice(i2)) + valueSuffix;
                value3 = value3.slice(0, i2);
                break;
              }
            }
          }
        }
        if (comma && !zero6) value3 = group2(value3, Infinity);
        var length3 = valuePrefix.length + value3.length + valueSuffix.length, padding3 = length3 < width2 ? new Array(width2 - length3 + 1).join(fill2) : "";
        if (comma && zero6) value3 = group2(padding3 + value3, padding3.length ? width2 - valueSuffix.length : Infinity), padding3 = "";
        switch (align2) {
          case "<":
            value3 = valuePrefix + value3 + valueSuffix + padding3;
            break;
          case "=":
            value3 = valuePrefix + padding3 + value3 + valueSuffix;
            break;
          case "^":
            value3 = padding3.slice(0, length3 = padding3.length >> 1) + valuePrefix + value3 + valueSuffix + padding3.slice(length3);
            break;
          default:
            value3 = padding3 + valuePrefix + value3 + valueSuffix;
            break;
        }
        return numerals(value3);
      }
      format5.toString = function() {
        return specifier + "";
      };
      return format5;
    }
    function formatPrefix2(specifier, value3) {
      var f2 = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e4 = Math.max(-8, Math.min(8, Math.floor(exponent_default(value3) / 3))) * 3, k2 = Math.pow(10, -e4), prefix = prefixes[8 + e4 / 3];
      return function(value4) {
        return f2(k2 * value4) + prefix;
      };
    }
    return {
      format: newFormat,
      formatPrefix: formatPrefix2
    };
  }

  // node_modules/d3-format/src/defaultLocale.js
  var locale;
  var format;
  var formatPrefix;
  defaultLocale({
    thousands: ",",
    grouping: [3],
    currency: ["$", ""]
  });
  function defaultLocale(definition3) {
    locale = locale_default(definition3);
    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, value3) {
    return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent_default(value3) / 3))) * 3 - exponent_default(Math.abs(step)));
  }

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

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

  // node_modules/d3-time/src/millisecond.js
  var millisecond = timeInterval(() => {
  }, (date2, step) => {
    date2.setTime(+date2 + step);
  }, (start, end) => {
    return end - start;
  });
  millisecond.every = (k2) => {
    k2 = Math.floor(k2);
    if (!isFinite(k2) || !(k2 > 0)) return null;
    if (!(k2 > 1)) return millisecond;
    return timeInterval((date2) => {
      date2.setTime(Math.floor(date2 / k2) * k2);
    }, (date2, step) => {
      date2.setTime(+date2 + step * k2);
    }, (start, end) => {
      return (end - start) / k2;
    });
  };
  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((date2) => {
    date2.setTime(date2 - date2.getMilliseconds());
  }, (date2, step) => {
    date2.setTime(+date2 + step * durationSecond);
  }, (start, end) => {
    return (end - start) / durationSecond;
  }, (date2) => {
    return date2.getUTCSeconds();
  });
  var seconds = second.range;

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

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

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

  // node_modules/d3-time/src/week.js
  function timeWeekday(i2) {
    return timeInterval((date2) => {
      date2.setDate(date2.getDate() - (date2.getDay() + 7 - i2) % 7);
      date2.setHours(0, 0, 0, 0);
    }, (date2, step) => {
      date2.setDate(date2.getDate() + step * 7);
    }, (start, end) => {
      return (end - start - (end.getTimezoneOffset() - start.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(i2) {
    return timeInterval((date2) => {
      date2.setUTCDate(date2.getUTCDate() - (date2.getUTCDay() + 7 - i2) % 7);
      date2.setUTCHours(0, 0, 0, 0);
    }, (date2, step) => {
      date2.setUTCDate(date2.getUTCDate() + step * 7);
    }, (start, end) => {
      return (end - start) / durationWeek;
    });
  }
  var utcSunday = utcWeekday(0);
  var utcMonday = utcWeekday(1);
  var utcTuesday = utcWeekday(2);
  var utcWednesday = utcWeekday(3);
  var utcThursday = utcWeekday(4);
  var utcFriday = utcWeekday(5);
  var utcSaturday = utcWeekday(6);
  var utcSundays = utcSunday.range;
  var utcMondays = utcMonday.range;
  var utcTuesdays = utcTuesday.range;
  var utcWednesdays = utcWednesday.range;
  var utcThursdays = utcThursday.range;
  var utcFridays = utcFriday.range;
  var utcSaturdays = utcSaturday.range;

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

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

  // node_modules/d3-time/src/ticks.js
  function ticker(year, month, week2, 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],
      [week2, 1, durationWeek],
      [month, 1, durationMonth],
      [month, 3, 3 * durationMonth],
      [year, 1, durationYear]
    ];
    function ticks2(start, stop2, count2) {
      const reverse3 = stop2 < start;
      if (reverse3) [start, stop2] = [stop2, start];
      const interval3 = count2 && typeof count2.range === "function" ? count2 : tickInterval(start, stop2, count2);
      const ticks3 = interval3 ? interval3.range(start, +stop2 + 1) : [];
      return reverse3 ? ticks3.reverse() : ticks3;
    }
    function tickInterval(start, stop2, count2) {
      const target2 = Math.abs(stop2 - start) / count2;
      const i2 = bisector(([, , step2]) => step2).right(tickIntervals, target2);
      if (i2 === tickIntervals.length) return year.every(tickStep(start / durationYear, stop2 / durationYear, count2));
      if (i2 === 0) return millisecond.every(Math.max(tickStep(start, stop2, count2), 1));
      const [t4, step] = tickIntervals[target2 / tickIntervals[i2 - 1][2] < tickIntervals[i2][2] / target2 ? i2 - 1 : i2];
      return t4.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/vega-time/build/vega-time.module.js
  var YEAR = "year";
  var QUARTER = "quarter";
  var MONTH = "month";
  var WEEK = "week";
  var DATE = "date";
  var DAY = "day";
  var DAYOFYEAR = "dayofyear";
  var HOURS = "hours";
  var MINUTES = "minutes";
  var SECONDS = "seconds";
  var MILLISECONDS = "milliseconds";
  var TIME_UNITS = [YEAR, QUARTER, MONTH, WEEK, DATE, DAY, DAYOFYEAR, HOURS, MINUTES, SECONDS, MILLISECONDS];
  var UNITS = TIME_UNITS.reduce((o2, u5, i2) => (o2[u5] = 1 + i2, o2), {});
  function timeUnits(units) {
    const u5 = array(units).slice(), m4 = {};
    if (!u5.length) error("Missing time unit.");
    u5.forEach((unit2) => {
      if (has(UNITS, unit2)) {
        m4[unit2] = 1;
      } else {
        error(`Invalid time unit: ${unit2}.`);
      }
    });
    const numTypes = (m4[WEEK] || m4[DAY] ? 1 : 0) + (m4[QUARTER] || m4[MONTH] || m4[DATE] ? 1 : 0) + (m4[DAYOFYEAR] ? 1 : 0);
    if (numTypes > 1) {
      error(`Incompatible time units: ${units}`);
    }
    u5.sort((a4, b3) => UNITS[a4] - UNITS[b3]);
    return u5;
  }
  var defaultSpecifiers = {
    [YEAR]: "%Y ",
    [QUARTER]: "Q%q ",
    [MONTH]: "%b ",
    [DATE]: "%d ",
    [WEEK]: "W%U ",
    [DAY]: "%a ",
    [DAYOFYEAR]: "%j ",
    [HOURS]: "%H:00",
    [MINUTES]: "00:%M",
    [SECONDS]: ":%S",
    [MILLISECONDS]: ".%L",
    [`${YEAR}-${MONTH}`]: "%Y-%m ",
    [`${YEAR}-${MONTH}-${DATE}`]: "%Y-%m-%d ",
    [`${HOURS}-${MINUTES}`]: "%H:%M"
  };
  function timeUnitSpecifier(units, specifiers) {
    const s2 = extend({}, defaultSpecifiers, specifiers), u5 = timeUnits(units), n2 = u5.length;
    let fmt = "", start = 0, end, key2;
    for (start = 0; start < n2; ) {
      for (end = u5.length; end > start; --end) {
        key2 = u5.slice(start, end).join("-");
        if (s2[key2] != null) {
          fmt += s2[key2];
          start = end;
          break;
        }
      }
    }
    return fmt.trim();
  }
  var t02 = /* @__PURE__ */ new Date();
  function localYear(y5) {
    t02.setFullYear(y5);
    t02.setMonth(0);
    t02.setDate(1);
    t02.setHours(0, 0, 0, 0);
    return t02;
  }
  function dayofyear(d2) {
    return localDayOfYear(new Date(d2));
  }
  function week(d2) {
    return localWeekNum(new Date(d2));
  }
  function localDayOfYear(d2) {
    return timeDay.count(localYear(d2.getFullYear()) - 1, d2);
  }
  function localWeekNum(d2) {
    return timeSunday.count(localYear(d2.getFullYear()) - 1, d2);
  }
  function localFirst(y5) {
    return localYear(y5).getDay();
  }
  function localDate(y5, m4, d2, H, M2, S, L) {
    if (0 <= y5 && y5 < 100) {
      const date2 = new Date(-1, m4, d2, H, M2, S, L);
      date2.setFullYear(y5);
      return date2;
    }
    return new Date(y5, m4, d2, H, M2, S, L);
  }
  function utcdayofyear(d2) {
    return utcDayOfYear(new Date(d2));
  }
  function utcweek(d2) {
    return utcWeekNum(new Date(d2));
  }
  function utcDayOfYear(d2) {
    const y5 = Date.UTC(d2.getUTCFullYear(), 0, 1);
    return utcDay.count(y5 - 1, d2);
  }
  function utcWeekNum(d2) {
    const y5 = Date.UTC(d2.getUTCFullYear(), 0, 1);
    return utcSunday.count(y5 - 1, d2);
  }
  function utcFirst(y5) {
    t02.setTime(Date.UTC(y5, 0, 1));
    return t02.getUTCDay();
  }
  function utcDate(y5, m4, d2, H, M2, S, L) {
    if (0 <= y5 && y5 < 100) {
      const date2 = new Date(Date.UTC(-1, m4, d2, H, M2, S, L));
      date2.setUTCFullYear(d2.y);
      return date2;
    }
    return new Date(Date.UTC(y5, m4, d2, H, M2, S, L));
  }
  function floor(units, step, get6, inv, newDate2) {
    const s2 = step || 1, b3 = peek(units), _ = (unit2, p2, key2) => {
      key2 = key2 || unit2;
      return getUnit(get6[key2], inv[key2], unit2 === b3 && s2, p2);
    };
    const t4 = /* @__PURE__ */ new Date(), u5 = toSet(units), y5 = u5[YEAR] ? _(YEAR) : constant(2012), m4 = u5[MONTH] ? _(MONTH) : u5[QUARTER] ? _(QUARTER) : zero, d2 = u5[WEEK] && u5[DAY] ? _(DAY, 1, WEEK + DAY) : u5[WEEK] ? _(WEEK, 1) : u5[DAY] ? _(DAY, 1) : u5[DATE] ? _(DATE, 1) : u5[DAYOFYEAR] ? _(DAYOFYEAR, 1) : one, H = u5[HOURS] ? _(HOURS) : zero, M2 = u5[MINUTES] ? _(MINUTES) : zero, S = u5[SECONDS] ? _(SECONDS) : zero, L = u5[MILLISECONDS] ? _(MILLISECONDS) : zero;
    return function(v3) {
      t4.setTime(+v3);
      const year = y5(t4);
      return newDate2(year, m4(t4), d2(t4, year), H(t4), M2(t4), S(t4), L(t4));
    };
  }
  function getUnit(f2, inv, step, phase) {
    const u5 = step <= 1 ? f2 : phase ? (d2, y5) => phase + step * Math.floor((f2(d2, y5) - phase) / step) : (d2, y5) => step * Math.floor(f2(d2, y5) / step);
    return inv ? (d2, y5) => inv(u5(d2, y5), y5) : u5;
  }
  function weekday(week2, day, firstDay) {
    return day + week2 * 7 - (firstDay + 6) % 7;
  }
  var localGet = {
    [YEAR]: (d2) => d2.getFullYear(),
    [QUARTER]: (d2) => Math.floor(d2.getMonth() / 3),
    [MONTH]: (d2) => d2.getMonth(),
    [DATE]: (d2) => d2.getDate(),
    [HOURS]: (d2) => d2.getHours(),
    [MINUTES]: (d2) => d2.getMinutes(),
    [SECONDS]: (d2) => d2.getSeconds(),
    [MILLISECONDS]: (d2) => d2.getMilliseconds(),
    [DAYOFYEAR]: (d2) => localDayOfYear(d2),
    [WEEK]: (d2) => localWeekNum(d2),
    [WEEK + DAY]: (d2, y5) => weekday(localWeekNum(d2), d2.getDay(), localFirst(y5)),
    [DAY]: (d2, y5) => weekday(1, d2.getDay(), localFirst(y5))
  };
  var localInv = {
    [QUARTER]: (q2) => 3 * q2,
    [WEEK]: (w3, y5) => weekday(w3, 0, localFirst(y5))
  };
  function timeFloor(units, step) {
    return floor(units, step || 1, localGet, localInv, localDate);
  }
  var utcGet = {
    [YEAR]: (d2) => d2.getUTCFullYear(),
    [QUARTER]: (d2) => Math.floor(d2.getUTCMonth() / 3),
    [MONTH]: (d2) => d2.getUTCMonth(),
    [DATE]: (d2) => d2.getUTCDate(),
    [HOURS]: (d2) => d2.getUTCHours(),
    [MINUTES]: (d2) => d2.getUTCMinutes(),
    [SECONDS]: (d2) => d2.getUTCSeconds(),
    [MILLISECONDS]: (d2) => d2.getUTCMilliseconds(),
    [DAYOFYEAR]: (d2) => utcDayOfYear(d2),
    [WEEK]: (d2) => utcWeekNum(d2),
    [DAY]: (d2, y5) => weekday(1, d2.getUTCDay(), utcFirst(y5)),
    [WEEK + DAY]: (d2, y5) => weekday(utcWeekNum(d2), d2.getUTCDay(), utcFirst(y5))
  };
  var utcInv = {
    [QUARTER]: (q2) => 3 * q2,
    [WEEK]: (w3, y5) => weekday(w3, 0, utcFirst(y5))
  };
  function utcFloor(units, step) {
    return floor(units, step || 1, utcGet, utcInv, utcDate);
  }
  var timeIntervals = {
    [YEAR]: timeYear,
    [QUARTER]: timeMonth.every(3),
    [MONTH]: timeMonth,
    [WEEK]: timeSunday,
    [DATE]: timeDay,
    [DAY]: timeDay,
    [DAYOFYEAR]: timeDay,
    [HOURS]: timeHour,
    [MINUTES]: timeMinute,
    [SECONDS]: second,
    [MILLISECONDS]: millisecond
  };
  var utcIntervals = {
    [YEAR]: utcYear,
    [QUARTER]: utcMonth.every(3),
    [MONTH]: utcMonth,
    [WEEK]: utcSunday,
    [DATE]: utcDay,
    [DAY]: utcDay,
    [DAYOFYEAR]: utcDay,
    [HOURS]: utcHour,
    [MINUTES]: utcMinute,
    [SECONDS]: second,
    [MILLISECONDS]: millisecond
  };
  function timeInterval2(unit2) {
    return timeIntervals[unit2];
  }
  function utcInterval(unit2) {
    return utcIntervals[unit2];
  }
  function offset(ival, date2, step) {
    return ival ? ival.offset(date2, step) : void 0;
  }
  function timeOffset(unit2, date2, step) {
    return offset(timeInterval2(unit2), date2, step);
  }
  function utcOffset(unit2, date2, step) {
    return offset(utcInterval(unit2), date2, step);
  }
  function sequence(ival, start, stop2, step) {
    return ival ? ival.range(start, stop2, step) : void 0;
  }
  function timeSequence(unit2, start, stop2, step) {
    return sequence(timeInterval2(unit2), start, stop2, step);
  }
  function utcSequence(unit2, start, stop2, step) {
    return sequence(utcInterval(unit2), start, stop2, step);
  }
  var durationSecond2 = 1e3;
  var durationMinute2 = durationSecond2 * 60;
  var durationHour2 = durationMinute2 * 60;
  var durationDay2 = durationHour2 * 24;
  var durationWeek2 = durationDay2 * 7;
  var durationMonth2 = durationDay2 * 30;
  var durationYear2 = durationDay2 * 365;
  var Milli = [YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS];
  var Seconds = Milli.slice(0, -1);
  var Minutes = Seconds.slice(0, -1);
  var Hours = Minutes.slice(0, -1);
  var Day = Hours.slice(0, -1);
  var Week = [YEAR, WEEK];
  var Month = [YEAR, MONTH];
  var Year = [YEAR];
  var intervals = [[Seconds, 1, durationSecond2], [Seconds, 5, 5 * durationSecond2], [Seconds, 15, 15 * durationSecond2], [Seconds, 30, 30 * durationSecond2], [Minutes, 1, durationMinute2], [Minutes, 5, 5 * durationMinute2], [Minutes, 15, 15 * durationMinute2], [Minutes, 30, 30 * durationMinute2], [Hours, 1, durationHour2], [Hours, 3, 3 * durationHour2], [Hours, 6, 6 * durationHour2], [Hours, 12, 12 * durationHour2], [Day, 1, durationDay2], [Week, 1, durationWeek2], [Month, 1, durationMonth2], [Month, 3, 3 * durationMonth2], [Year, 1, durationYear2]];
  function bin(opt) {
    const ext = opt.extent, max4 = opt.maxbins || 40, target2 = Math.abs(span(ext)) / max4;
    let i2 = bisector((i3) => i3[2]).right(intervals, target2), units, step;
    if (i2 === intervals.length) {
      units = Year, step = tickStep(ext[0] / durationYear2, ext[1] / durationYear2, max4);
    } else if (i2) {
      i2 = intervals[target2 / intervals[i2 - 1][2] < intervals[i2][2] / target2 ? i2 - 1 : i2];
      units = i2[0];
      step = i2[1];
    } else {
      units = Milli;
      step = Math.max(tickStep(ext[0], ext[1], max4), 1);
    }
    return {
      units,
      step
    };
  }

  // node_modules/d3-time-format/src/locale.js
  function localDate2(d2) {
    if (0 <= d2.y && d2.y < 100) {
      var date2 = new Date(-1, d2.m, d2.d, d2.H, d2.M, d2.S, d2.L);
      date2.setFullYear(d2.y);
      return date2;
    }
    return new Date(d2.y, d2.m, d2.d, d2.H, d2.M, d2.S, d2.L);
  }
  function utcDate2(d2) {
    if (0 <= d2.y && d2.y < 100) {
      var date2 = new Date(Date.UTC(-1, d2.m, d2.d, d2.H, d2.M, d2.S, d2.L));
      date2.setUTCFullYear(d2.y);
      return date2;
    }
    return new Date(Date.UTC(d2.y, d2.m, d2.d, d2.H, d2.M, d2.S, d2.L));
  }
  function newDate(y5, m4, d2) {
    return { y: y5, m: m4, d: d2, H: 0, M: 0, S: 0, L: 0 };
  }
  function formatLocale(locale4) {
    var locale_dateTime = locale4.dateTime, locale_date = locale4.date, locale_time = locale4.time, locale_periods = locale4.periods, locale_weekdays = locale4.days, locale_shortWeekdays = locale4.shortDays, locale_months = locale4.months, locale_shortMonths = locale4.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 formats3 = {
      "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": formatYear2,
      "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
    };
    formats3.x = newFormat(locale_date, formats3);
    formats3.X = newFormat(locale_time, formats3);
    formats3.c = newFormat(locale_dateTime, formats3);
    utcFormats.x = newFormat(locale_date, utcFormats);
    utcFormats.X = newFormat(locale_time, utcFormats);
    utcFormats.c = newFormat(locale_dateTime, utcFormats);
    function newFormat(specifier, formats4) {
      return function(date2) {
        var string = [], i2 = -1, j2 = 0, n2 = specifier.length, c4, pad4, format5;
        if (!(date2 instanceof Date)) date2 = /* @__PURE__ */ new Date(+date2);
        while (++i2 < n2) {
          if (specifier.charCodeAt(i2) === 37) {
            string.push(specifier.slice(j2, i2));
            if ((pad4 = pads[c4 = specifier.charAt(++i2)]) != null) c4 = specifier.charAt(++i2);
            else pad4 = c4 === "e" ? " " : "0";
            if (format5 = formats4[c4]) c4 = format5(date2, pad4);
            string.push(c4);
            j2 = i2 + 1;
          }
        }
        string.push(specifier.slice(j2, i2));
        return string.join("");
      };
    }
    function newParse(specifier, Z) {
      return function(string) {
        var d2 = newDate(1900, void 0, 1), i2 = parseSpecifier(d2, specifier, string += "", 0), week2, day;
        if (i2 != string.length) return null;
        if ("Q" in d2) return new Date(d2.Q);
        if ("s" in d2) return new Date(d2.s * 1e3 + ("L" in d2 ? d2.L : 0));
        if (Z && !("Z" in d2)) d2.Z = 0;
        if ("p" in d2) d2.H = d2.H % 12 + d2.p * 12;
        if (d2.m === void 0) d2.m = "q" in d2 ? d2.q : 0;
        if ("V" in d2) {
          if (d2.V < 1 || d2.V > 53) return null;
          if (!("w" in d2)) d2.w = 1;
          if ("Z" in d2) {
            week2 = utcDate2(newDate(d2.y, 0, 1)), day = week2.getUTCDay();
            week2 = day > 4 || day === 0 ? utcMonday.ceil(week2) : utcMonday(week2);
            week2 = utcDay.offset(week2, (d2.V - 1) * 7);
            d2.y = week2.getUTCFullYear();
            d2.m = week2.getUTCMonth();
            d2.d = week2.getUTCDate() + (d2.w + 6) % 7;
          } else {
            week2 = localDate2(newDate(d2.y, 0, 1)), day = week2.getDay();
            week2 = day > 4 || day === 0 ? timeMonday.ceil(week2) : timeMonday(week2);
            week2 = timeDay.offset(week2, (d2.V - 1) * 7);
            d2.y = week2.getFullYear();
            d2.m = week2.getMonth();
            d2.d = week2.getDate() + (d2.w + 6) % 7;
          }
        } else if ("W" in d2 || "U" in d2) {
          if (!("w" in d2)) d2.w = "u" in d2 ? d2.u % 7 : "W" in d2 ? 1 : 0;
          day = "Z" in d2 ? utcDate2(newDate(d2.y, 0, 1)).getUTCDay() : localDate2(newDate(d2.y, 0, 1)).getDay();
          d2.m = 0;
          d2.d = "W" in d2 ? (d2.w + 6) % 7 + d2.W * 7 - (day + 5) % 7 : d2.w + d2.U * 7 - (day + 6) % 7;
        }
        if ("Z" in d2) {
          d2.H += d2.Z / 100 | 0;
          d2.M += d2.Z % 100;
          return utcDate2(d2);
        }
        return localDate2(d2);
      };
    }
    function parseSpecifier(d2, specifier, string, j2) {
      var i2 = 0, n2 = specifier.length, m4 = string.length, c4, parse7;
      while (i2 < n2) {
        if (j2 >= m4) return -1;
        c4 = specifier.charCodeAt(i2++);
        if (c4 === 37) {
          c4 = specifier.charAt(i2++);
          parse7 = parses[c4 in pads ? specifier.charAt(i2++) : c4];
          if (!parse7 || (j2 = parse7(d2, string, j2)) < 0) return -1;
        } else if (c4 != string.charCodeAt(j2++)) {
          return -1;
        }
      }
      return j2;
    }
    function parsePeriod(d2, string, i2) {
      var n2 = periodRe.exec(string.slice(i2));
      return n2 ? (d2.p = periodLookup.get(n2[0].toLowerCase()), i2 + n2[0].length) : -1;
    }
    function parseShortWeekday(d2, string, i2) {
      var n2 = shortWeekdayRe.exec(string.slice(i2));
      return n2 ? (d2.w = shortWeekdayLookup.get(n2[0].toLowerCase()), i2 + n2[0].length) : -1;
    }
    function parseWeekday(d2, string, i2) {
      var n2 = weekdayRe.exec(string.slice(i2));
      return n2 ? (d2.w = weekdayLookup.get(n2[0].toLowerCase()), i2 + n2[0].length) : -1;
    }
    function parseShortMonth(d2, string, i2) {
      var n2 = shortMonthRe.exec(string.slice(i2));
      return n2 ? (d2.m = shortMonthLookup.get(n2[0].toLowerCase()), i2 + n2[0].length) : -1;
    }
    function parseMonth(d2, string, i2) {
      var n2 = monthRe.exec(string.slice(i2));
      return n2 ? (d2.m = monthLookup.get(n2[0].toLowerCase()), i2 + n2[0].length) : -1;
    }
    function parseLocaleDateTime(d2, string, i2) {
      return parseSpecifier(d2, locale_dateTime, string, i2);
    }
    function parseLocaleDate(d2, string, i2) {
      return parseSpecifier(d2, locale_date, string, i2);
    }
    function parseLocaleTime(d2, string, i2) {
      return parseSpecifier(d2, locale_time, string, i2);
    }
    function formatShortWeekday(d2) {
      return locale_shortWeekdays[d2.getDay()];
    }
    function formatWeekday(d2) {
      return locale_weekdays[d2.getDay()];
    }
    function formatShortMonth(d2) {
      return locale_shortMonths[d2.getMonth()];
    }
    function formatMonth(d2) {
      return locale_months[d2.getMonth()];
    }
    function formatPeriod(d2) {
      return locale_periods[+(d2.getHours() >= 12)];
    }
    function formatQuarter(d2) {
      return 1 + ~~(d2.getMonth() / 3);
    }
    function formatUTCShortWeekday(d2) {
      return locale_shortWeekdays[d2.getUTCDay()];
    }
    function formatUTCWeekday(d2) {
      return locale_weekdays[d2.getUTCDay()];
    }
    function formatUTCShortMonth(d2) {
      return locale_shortMonths[d2.getUTCMonth()];
    }
    function formatUTCMonth(d2) {
      return locale_months[d2.getUTCMonth()];
    }
    function formatUTCPeriod(d2) {
      return locale_periods[+(d2.getUTCHours() >= 12)];
    }
    function formatUTCQuarter(d2) {
      return 1 + ~~(d2.getUTCMonth() / 3);
    }
    return {
      format: function(specifier) {
        var f2 = newFormat(specifier += "", formats3);
        f2.toString = function() {
          return specifier;
        };
        return f2;
      },
      parse: function(specifier) {
        var p2 = newParse(specifier += "", false);
        p2.toString = function() {
          return specifier;
        };
        return p2;
      },
      utcFormat: function(specifier) {
        var f2 = newFormat(specifier += "", utcFormats);
        f2.toString = function() {
          return specifier;
        };
        return f2;
      },
      utcParse: function(specifier) {
        var p2 = newParse(specifier += "", true);
        p2.toString = function() {
          return specifier;
        };
        return p2;
      }
    };
  }
  var pads = { "-": "", "_": " ", "0": "0" };
  var numberRe = /^\s*\d+/;
  var percentRe = /^%/;
  var requoteRe = /[\\^$*+?|[\]().{}]/g;
  function pad3(value3, fill2, width2) {
    var sign3 = value3 < 0 ? "-" : "", string = (sign3 ? -value3 : value3) + "", length3 = string.length;
    return sign3 + (length3 < width2 ? new Array(width2 - length3 + 1).join(fill2) + string : string);
  }
  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((name4, i2) => [name4.toLowerCase(), i2]));
  }
  function parseWeekdayNumberSunday(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 1));
    return n2 ? (d2.w = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseWeekdayNumberMonday(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 1));
    return n2 ? (d2.u = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseWeekNumberSunday(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.U = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseWeekNumberISO(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.V = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseWeekNumberMonday(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.W = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseFullYear(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 4));
    return n2 ? (d2.y = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseYear(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.y = +n2[0] + (+n2[0] > 68 ? 1900 : 2e3), i2 + n2[0].length) : -1;
  }
  function parseZone(d2, string, i2) {
    var n2 = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i2, i2 + 6));
    return n2 ? (d2.Z = n2[1] ? 0 : -(n2[2] + (n2[3] || "00")), i2 + n2[0].length) : -1;
  }
  function parseQuarter(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 1));
    return n2 ? (d2.q = n2[0] * 3 - 3, i2 + n2[0].length) : -1;
  }
  function parseMonthNumber(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.m = n2[0] - 1, i2 + n2[0].length) : -1;
  }
  function parseDayOfMonth(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.d = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseDayOfYear(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 3));
    return n2 ? (d2.m = 0, d2.d = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseHour24(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.H = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseMinutes(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.M = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseSeconds(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 2));
    return n2 ? (d2.S = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseMilliseconds(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 3));
    return n2 ? (d2.L = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseMicroseconds(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2, i2 + 6));
    return n2 ? (d2.L = Math.floor(n2[0] / 1e3), i2 + n2[0].length) : -1;
  }
  function parseLiteralPercent(d2, string, i2) {
    var n2 = percentRe.exec(string.slice(i2, i2 + 1));
    return n2 ? i2 + n2[0].length : -1;
  }
  function parseUnixTimestamp(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2));
    return n2 ? (d2.Q = +n2[0], i2 + n2[0].length) : -1;
  }
  function parseUnixTimestampSeconds(d2, string, i2) {
    var n2 = numberRe.exec(string.slice(i2));
    return n2 ? (d2.s = +n2[0], i2 + n2[0].length) : -1;
  }
  function formatDayOfMonth(d2, p2) {
    return pad3(d2.getDate(), p2, 2);
  }
  function formatHour24(d2, p2) {
    return pad3(d2.getHours(), p2, 2);
  }
  function formatHour12(d2, p2) {
    return pad3(d2.getHours() % 12 || 12, p2, 2);
  }
  function formatDayOfYear(d2, p2) {
    return pad3(1 + timeDay.count(timeYear(d2), d2), p2, 3);
  }
  function formatMilliseconds(d2, p2) {
    return pad3(d2.getMilliseconds(), p2, 3);
  }
  function formatMicroseconds(d2, p2) {
    return formatMilliseconds(d2, p2) + "000";
  }
  function formatMonthNumber(d2, p2) {
    return pad3(d2.getMonth() + 1, p2, 2);
  }
  function formatMinutes(d2, p2) {
    return pad3(d2.getMinutes(), p2, 2);
  }
  function formatSeconds(d2, p2) {
    return pad3(d2.getSeconds(), p2, 2);
  }
  function formatWeekdayNumberMonday(d2) {
    var day = d2.getDay();
    return day === 0 ? 7 : day;
  }
  function formatWeekNumberSunday(d2, p2) {
    return pad3(timeSunday.count(timeYear(d2) - 1, d2), p2, 2);
  }
  function dISO(d2) {
    var day = d2.getDay();
    return day >= 4 || day === 0 ? timeThursday(d2) : timeThursday.ceil(d2);
  }
  function formatWeekNumberISO(d2, p2) {
    d2 = dISO(d2);
    return pad3(timeThursday.count(timeYear(d2), d2) + (timeYear(d2).getDay() === 4), p2, 2);
  }
  function formatWeekdayNumberSunday(d2) {
    return d2.getDay();
  }
  function formatWeekNumberMonday(d2, p2) {
    return pad3(timeMonday.count(timeYear(d2) - 1, d2), p2, 2);
  }
  function formatYear2(d2, p2) {
    return pad3(d2.getFullYear() % 100, p2, 2);
  }
  function formatYearISO(d2, p2) {
    d2 = dISO(d2);
    return pad3(d2.getFullYear() % 100, p2, 2);
  }
  function formatFullYear(d2, p2) {
    return pad3(d2.getFullYear() % 1e4, p2, 4);
  }
  function formatFullYearISO(d2, p2) {
    var day = d2.getDay();
    d2 = day >= 4 || day === 0 ? timeThursday(d2) : timeThursday.ceil(d2);
    return pad3(d2.getFullYear() % 1e4, p2, 4);
  }
  function formatZone(d2) {
    var z = d2.getTimezoneOffset();
    return (z > 0 ? "-" : (z *= -1, "+")) + pad3(z / 60 | 0, "0", 2) + pad3(z % 60, "0", 2);
  }
  function formatUTCDayOfMonth(d2, p2) {
    return pad3(d2.getUTCDate(), p2, 2);
  }
  function formatUTCHour24(d2, p2) {
    return pad3(d2.getUTCHours(), p2, 2);
  }
  function formatUTCHour12(d2, p2) {
    return pad3(d2.getUTCHours() % 12 || 12, p2, 2);
  }
  function formatUTCDayOfYear(d2, p2) {
    return pad3(1 + utcDay.count(utcYear(d2), d2), p2, 3);
  }
  function formatUTCMilliseconds(d2, p2) {
    return pad3(d2.getUTCMilliseconds(), p2, 3);
  }
  function formatUTCMicroseconds(d2, p2) {
    return formatUTCMilliseconds(d2, p2) + "000";
  }
  function formatUTCMonthNumber(d2, p2) {
    return pad3(d2.getUTCMonth() + 1, p2, 2);
  }
  function formatUTCMinutes(d2, p2) {
    return pad3(d2.getUTCMinutes(), p2, 2);
  }
  function formatUTCSeconds(d2, p2) {
    return pad3(d2.getUTCSeconds(), p2, 2);
  }
  function formatUTCWeekdayNumberMonday(d2) {
    var dow = d2.getUTCDay();
    return dow === 0 ? 7 : dow;
  }
  function formatUTCWeekNumberSunday(d2, p2) {
    return pad3(utcSunday.count(utcYear(d2) - 1, d2), p2, 2);
  }
  function UTCdISO(d2) {
    var day = d2.getUTCDay();
    return day >= 4 || day === 0 ? utcThursday(d2) : utcThursday.ceil(d2);
  }
  function formatUTCWeekNumberISO(d2, p2) {
    d2 = UTCdISO(d2);
    return pad3(utcThursday.count(utcYear(d2), d2) + (utcYear(d2).getUTCDay() === 4), p2, 2);
  }
  function formatUTCWeekdayNumberSunday(d2) {
    return d2.getUTCDay();
  }
  function formatUTCWeekNumberMonday(d2, p2) {
    return pad3(utcMonday.count(utcYear(d2) - 1, d2), p2, 2);
  }
  function formatUTCYear(d2, p2) {
    return pad3(d2.getUTCFullYear() % 100, p2, 2);
  }
  function formatUTCYearISO(d2, p2) {
    d2 = UTCdISO(d2);
    return pad3(d2.getUTCFullYear() % 100, p2, 2);
  }
  function formatUTCFullYear(d2, p2) {
    return pad3(d2.getUTCFullYear() % 1e4, p2, 4);
  }
  function formatUTCFullYearISO(d2, p2) {
    var day = d2.getUTCDay();
    d2 = day >= 4 || day === 0 ? utcThursday(d2) : utcThursday.ceil(d2);
    return pad3(d2.getUTCFullYear() % 1e4, p2, 4);
  }
  function formatUTCZone() {
    return "+0000";
  }
  function formatLiteralPercent() {
    return "%";
  }
  function formatUnixTimestamp(d2) {
    return +d2;
  }
  function formatUnixTimestampSeconds(d2) {
    return Math.floor(+d2 / 1e3);
  }

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

  // node_modules/vega-format/build/vega-format.module.js
  function memoize(method2) {
    const cache3 = {};
    return (spec) => cache3[spec] || (cache3[spec] = method2(spec));
  }
  function trimZeroes(numberFormat2, decimalChar) {
    return (x5) => {
      const str = numberFormat2(x5), dec = str.indexOf(decimalChar);
      if (dec < 0) return str;
      let idx = rightmostDigit(str, dec);
      const end = idx < str.length ? str.slice(idx) : "";
      while (--idx > dec) if (str[idx] !== "0") {
        ++idx;
        break;
      }
      return str.slice(0, idx) + end;
    };
  }
  function rightmostDigit(str, dec) {
    let i2 = str.lastIndexOf("e"), c4;
    if (i2 > 0) return i2;
    for (i2 = str.length; --i2 > dec; ) {
      c4 = str.charCodeAt(i2);
      if (c4 >= 48 && c4 <= 57) return i2 + 1;
    }
  }
  function numberLocale(locale4) {
    const format5 = memoize(locale4.format), formatPrefix2 = locale4.formatPrefix;
    return {
      format: format5,
      formatPrefix: formatPrefix2,
      formatFloat(spec) {
        const s2 = formatSpecifier(spec || ",");
        if (s2.precision == null) {
          s2.precision = 12;
          switch (s2.type) {
            case "%":
              s2.precision -= 2;
              break;
            case "e":
              s2.precision -= 1;
              break;
          }
          return trimZeroes(
            format5(s2),
            // number format
            format5(".1f")(1)[1]
            // decimal point character
          );
        } else {
          return format5(s2);
        }
      },
      formatSpan(start, stop2, count2, specifier) {
        specifier = formatSpecifier(specifier == null ? ",f" : specifier);
        const step = tickStep(start, stop2, count2), value3 = Math.max(Math.abs(start), Math.abs(stop2));
        let precision;
        if (specifier.precision == null) {
          switch (specifier.type) {
            case "s": {
              if (!isNaN(precision = precisionPrefix_default(step, value3))) {
                specifier.precision = precision;
              }
              return formatPrefix2(specifier, value3);
            }
            case "":
            case "e":
            case "g":
            case "p":
            case "r": {
              if (!isNaN(precision = precisionRound_default(step, value3))) {
                specifier.precision = precision - (specifier.type === "e");
              }
              break;
            }
            case "f":
            case "%": {
              if (!isNaN(precision = precisionFixed_default(step))) {
                specifier.precision = precision - (specifier.type === "%") * 2;
              }
              break;
            }
          }
        }
        return format5(specifier);
      }
    };
  }
  var defaultNumberLocale;
  resetNumberFormatDefaultLocale();
  function resetNumberFormatDefaultLocale() {
    return defaultNumberLocale = numberLocale({
      format,
      formatPrefix
    });
  }
  function numberFormatLocale(definition3) {
    return numberLocale(locale_default(definition3));
  }
  function numberFormatDefaultLocale(definition3) {
    return arguments.length ? defaultNumberLocale = numberFormatLocale(definition3) : defaultNumberLocale;
  }
  function timeMultiFormat(format5, interval3, spec) {
    spec = spec || {};
    if (!isObject(spec)) {
      error(`Invalid time multi-format specifier: ${spec}`);
    }
    const second2 = interval3(SECONDS), minute = interval3(MINUTES), hour = interval3(HOURS), day = interval3(DATE), week2 = interval3(WEEK), month = interval3(MONTH), quarter2 = interval3(QUARTER), year = interval3(YEAR), L = format5(spec[MILLISECONDS] || ".%L"), S = format5(spec[SECONDS] || ":%S"), M2 = format5(spec[MINUTES] || "%I:%M"), H = format5(spec[HOURS] || "%I %p"), d2 = format5(spec[DATE] || spec[DAY] || "%a %d"), w3 = format5(spec[WEEK] || "%b %d"), m4 = format5(spec[MONTH] || "%B"), q2 = format5(spec[QUARTER] || "%B"), y5 = format5(spec[YEAR] || "%Y");
    return (date2) => (second2(date2) < date2 ? L : minute(date2) < date2 ? S : hour(date2) < date2 ? M2 : day(date2) < date2 ? H : month(date2) < date2 ? week2(date2) < date2 ? d2 : w3 : year(date2) < date2 ? quarter2(date2) < date2 ? m4 : q2 : y5)(date2);
  }
  function timeLocale(locale4) {
    const timeFormat4 = memoize(locale4.format), utcFormat3 = memoize(locale4.utcFormat);
    return {
      timeFormat: (spec) => isString(spec) ? timeFormat4(spec) : timeMultiFormat(timeFormat4, timeInterval2, spec),
      utcFormat: (spec) => isString(spec) ? utcFormat3(spec) : timeMultiFormat(utcFormat3, utcInterval, spec),
      timeParse: memoize(locale4.parse),
      utcParse: memoize(locale4.utcParse)
    };
  }
  var defaultTimeLocale;
  resetTimeFormatDefaultLocale();
  function resetTimeFormatDefaultLocale() {
    return defaultTimeLocale = timeLocale({
      format: timeFormat,
      parse: timeParse,
      utcFormat,
      utcParse
    });
  }
  function timeFormatLocale(definition3) {
    return timeLocale(formatLocale(definition3));
  }
  function timeFormatDefaultLocale(definition3) {
    return arguments.length ? defaultTimeLocale = timeFormatLocale(definition3) : defaultTimeLocale;
  }
  var createLocale = (number8, time3) => extend({}, number8, time3);
  function locale3(numberSpec, timeSpec) {
    const number8 = numberSpec ? numberFormatLocale(numberSpec) : numberFormatDefaultLocale();
    const time3 = timeSpec ? timeFormatLocale(timeSpec) : timeFormatDefaultLocale();
    return createLocale(number8, time3);
  }
  function defaultLocale3(numberSpec, timeSpec) {
    const args = arguments.length;
    if (args && args !== 2) {
      error("defaultLocale expects either zero or two arguments.");
    }
    return args ? createLocale(numberFormatDefaultLocale(numberSpec), timeFormatDefaultLocale(timeSpec)) : createLocale(numberFormatDefaultLocale(), timeFormatDefaultLocale());
  }
  function resetDefaultLocale() {
    resetNumberFormatDefaultLocale();
    resetTimeFormatDefaultLocale();
    return defaultLocale3();
  }

  // node_modules/vega-loader/build/vega-loader.browser.module.js
  var protocol_re = /^(data:|([A-Za-z]+:)?\/\/)/;
  var allowed_re = /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
  var whitespace_re = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g;
  var fileProtocol = "file://";
  function loaderFactory(fetch2, fs) {
    return (options) => ({
      options: options || {},
      sanitize,
      load,
      fileAccess: false,
      file: fileLoader(fs),
      http: httpLoader(fetch2)
    });
  }
  async function load(uri, options) {
    const opt = await this.sanitize(uri, options), url = opt.href;
    return opt.localFile ? this.file(url) : this.http(url, options);
  }
  async function sanitize(uri, options) {
    options = extend({}, this.options, options);
    const fileAccess = this.fileAccess, result = {
      href: null
    };
    let isFile, loadFile2, base;
    const isAllowed = allowed_re.test(uri.replace(whitespace_re, ""));
    if (uri == null || typeof uri !== "string" || !isAllowed) {
      error("Sanitize failure, invalid URI: " + $(uri));
    }
    const hasProtocol = protocol_re.test(uri);
    if ((base = options.baseURL) && !hasProtocol) {
      if (!uri.startsWith("/") && !base.endsWith("/")) {
        uri = "/" + uri;
      }
      uri = base + uri;
    }
    loadFile2 = (isFile = uri.startsWith(fileProtocol)) || options.mode === "file" || options.mode !== "http" && !hasProtocol && fileAccess;
    if (isFile) {
      uri = uri.slice(fileProtocol.length);
    } else if (uri.startsWith("//")) {
      if (options.defaultProtocol === "file") {
        uri = uri.slice(2);
        loadFile2 = true;
      } else {
        uri = (options.defaultProtocol || "http") + ":" + uri;
      }
    }
    Object.defineProperty(result, "localFile", {
      value: !!loadFile2
    });
    result.href = uri;
    if (options.target) {
      result.target = options.target + "";
    }
    if (options.rel) {
      result.rel = options.rel + "";
    }
    if (options.context === "image" && options.crossOrigin) {
      result.crossOrigin = options.crossOrigin + "";
    }
    return result;
  }
  function fileLoader(fs) {
    return fs ? (filename) => new Promise((accept, reject) => {
      fs.readFile(filename, (error3, data3) => {
        if (error3) reject(error3);
        else accept(data3);
      });
    }) : fileReject;
  }
  async function fileReject() {
    error("No file system access.");
  }
  function httpLoader(fetch2) {
    return fetch2 ? async function(url, options) {
      const opt = extend({}, this.options.http, options), type3 = options && options.response, response = await fetch2(url, opt);
      return !response.ok ? error(response.status + "" + response.statusText) : isFunction(response[type3]) ? response[type3]() : response.text();
    } : httpReject;
  }
  async function httpReject() {
    error("No HTTP fetch method available.");
  }
  var isValid = (_) => _ != null && _ === _;
  var isBoolean2 = (_) => _ === "true" || _ === "false" || _ === true || _ === false;
  var isDate2 = (_) => !Number.isNaN(Date.parse(_));
  var isNumber2 = (_) => !Number.isNaN(+_) && !(_ instanceof Date);
  var isInteger = (_) => isNumber2(_) && Number.isInteger(+_);
  var typeParsers = {
    boolean: toBoolean,
    integer: toNumber,
    number: toNumber,
    date: toDate,
    string: toString,
    unknown: identity
  };
  var typeTests = [isBoolean2, isInteger, isNumber2, isDate2];
  var typeList = ["boolean", "integer", "number", "date"];
  function inferType(values4, field3) {
    if (!values4 || !values4.length) return "unknown";
    const n2 = values4.length, m4 = typeTests.length, a4 = typeTests.map((_, i2) => i2 + 1);
    for (let i2 = 0, t4 = 0, j2, value3; i2 < n2; ++i2) {
      value3 = field3 ? values4[i2][field3] : values4[i2];
      for (j2 = 0; j2 < m4; ++j2) {
        if (a4[j2] && isValid(value3) && !typeTests[j2](value3)) {
          a4[j2] = 0;
          ++t4;
          if (t4 === typeTests.length) return "string";
        }
      }
    }
    return typeList[a4.reduce((u5, v3) => u5 === 0 ? v3 : u5, 0) - 1];
  }
  function inferTypes(data3, fields) {
    return fields.reduce((types4, field3) => {
      types4[field3] = inferType(data3, field3);
      return types4;
    }, {});
  }
  function delimitedFormat(delimiter) {
    const parse7 = function(data3, format5) {
      const delim = {
        delimiter
      };
      return dsv(data3, format5 ? extend(format5, delim) : delim);
    };
    parse7.responseType = "text";
    return parse7;
  }
  function dsv(data3, format5) {
    if (format5.header) {
      data3 = format5.header.map($).join(format5.delimiter) + "\n" + data3;
    }
    return dsv_default(format5.delimiter).parse(data3 + "");
  }
  dsv.responseType = "text";
  function isBuffer(_) {
    return typeof Buffer === "function" && isFunction(Buffer.isBuffer) ? Buffer.isBuffer(_) : false;
  }
  function json(data3, format5) {
    const prop = format5 && format5.property ? field(format5.property) : identity;
    return isObject(data3) && !isBuffer(data3) ? parseJSON(prop(data3), format5) : prop(JSON.parse(data3));
  }
  json.responseType = "json";
  function parseJSON(data3, format5) {
    if (!isArray(data3) && isIterable(data3)) {
      data3 = [...data3];
    }
    return format5 && format5.copy ? JSON.parse(JSON.stringify(data3)) : data3;
  }
  var filters = {
    interior: (a4, b3) => a4 !== b3,
    exterior: (a4, b3) => a4 === b3
  };
  function topojson(data3, format5) {
    let method2, object2, property2, filter3;
    data3 = json(data3, format5);
    if (format5 && format5.feature) {
      method2 = feature_default;
      property2 = format5.feature;
    } else if (format5 && format5.mesh) {
      method2 = mesh_default;
      property2 = format5.mesh;
      filter3 = filters[format5.filter];
    } else {
      error("Missing TopoJSON feature or mesh parameter.");
    }
    object2 = (object2 = data3.objects[property2]) ? method2(data3, object2, filter3) : error("Invalid TopoJSON object: " + property2);
    return object2 && object2.features || [object2];
  }
  topojson.responseType = "json";
  var format2 = {
    dsv,
    csv: delimitedFormat(","),
    tsv: delimitedFormat("	"),
    json,
    topojson
  };
  function formats(name4, reader) {
    if (arguments.length > 1) {
      format2[name4] = reader;
      return this;
    } else {
      return has(format2, name4) ? format2[name4] : null;
    }
  }
  function responseType(type3) {
    const f2 = formats(type3);
    return f2 && f2.responseType || "text";
  }
  function read(data3, schema, timeParser, utcParser) {
    schema = schema || {};
    const reader = formats(schema.type || "json");
    if (!reader) error("Unknown data format type: " + schema.type);
    data3 = reader(data3, schema);
    if (schema.parse) parse(data3, schema.parse, timeParser, utcParser);
    if (has(data3, "columns")) delete data3.columns;
    return data3;
  }
  function parse(data3, types4, timeParser, utcParser) {
    if (!data3.length) return;
    const locale4 = timeFormatDefaultLocale();
    timeParser = timeParser || locale4.timeParse;
    utcParser = utcParser || locale4.utcParse;
    let fields = data3.columns || Object.keys(data3[0]), datum2, field3, i2, j2, n2, m4;
    if (types4 === "auto") types4 = inferTypes(data3, fields);
    fields = Object.keys(types4);
    const parsers = fields.map((field4) => {
      const type3 = types4[field4];
      let parts, pattern;
      if (type3 && (type3.startsWith("date:") || type3.startsWith("utc:"))) {
        parts = type3.split(/:(.+)?/, 2);
        pattern = parts[1];
        if (pattern[0] === "'" && pattern[pattern.length - 1] === "'" || pattern[0] === '"' && pattern[pattern.length - 1] === '"') {
          pattern = pattern.slice(1, -1);
        }
        const parse7 = parts[0] === "utc" ? utcParser : timeParser;
        return parse7(pattern);
      }
      if (!typeParsers[type3]) {
        throw Error("Illegal format pattern: " + field4 + ":" + type3);
      }
      return typeParsers[type3];
    });
    for (i2 = 0, n2 = data3.length, m4 = fields.length; i2 < n2; ++i2) {
      datum2 = data3[i2];
      for (j2 = 0; j2 < m4; ++j2) {
        field3 = fields[j2];
        datum2[field3] = parsers[j2](datum2[field3]);
      }
    }
  }
  var loader = loaderFactory(
    typeof fetch !== "undefined" && fetch,
    // use built-in fetch API
    null
    // no file system access
  );

  // node_modules/vega-dataflow/build/vega-dataflow.module.js
  function UniqueList(idFunc) {
    const $2 = idFunc || identity, list = [], ids = {};
    list.add = (_) => {
      const id2 = $2(_);
      if (!ids[id2]) {
        ids[id2] = 1;
        list.push(_);
      }
      return list;
    };
    list.remove = (_) => {
      const id2 = $2(_);
      if (ids[id2]) {
        ids[id2] = 0;
        const idx = list.indexOf(_);
        if (idx >= 0) list.splice(idx, 1);
      }
      return list;
    };
    return list;
  }
  async function asyncCallback(df, callback) {
    try {
      await callback(df);
    } catch (err) {
      df.error(err);
    }
  }
  var TUPLE_ID_KEY = Symbol("vega_id");
  var TUPLE_ID = 1;
  function isTuple(t4) {
    return !!(t4 && tupleid(t4));
  }
  function tupleid(t4) {
    return t4[TUPLE_ID_KEY];
  }
  function setid(t4, id2) {
    t4[TUPLE_ID_KEY] = id2;
    return t4;
  }
  function ingest$1(datum2) {
    const t4 = datum2 === Object(datum2) ? datum2 : {
      data: datum2
    };
    return tupleid(t4) ? t4 : setid(t4, TUPLE_ID++);
  }
  function derive(t4) {
    return rederive(t4, ingest$1({}));
  }
  function rederive(t4, d2) {
    for (const k2 in t4) d2[k2] = t4[k2];
    return d2;
  }
  function replace(t4, d2) {
    return setid(d2, tupleid(t4));
  }
  function stableCompare(cmp, f2) {
    return !cmp ? null : f2 ? (a4, b3) => cmp(a4, b3) || tupleid(f2(a4)) - tupleid(f2(b3)) : (a4, b3) => cmp(a4, b3) || tupleid(a4) - tupleid(b3);
  }
  function isChangeSet(v3) {
    return v3 && v3.constructor === changeset;
  }
  function changeset() {
    const add6 = [], rem2 = [], mod = [], remp = [], modp = [];
    let clean = null, reflow2 = false;
    return {
      constructor: changeset,
      insert(t4) {
        const d2 = array(t4), n2 = d2.length;
        for (let i2 = 0; i2 < n2; ++i2) add6.push(d2[i2]);
        return this;
      },
      remove(t4) {
        const a4 = isFunction(t4) ? remp : rem2, d2 = array(t4), n2 = d2.length;
        for (let i2 = 0; i2 < n2; ++i2) a4.push(d2[i2]);
        return this;
      },
      modify(t4, field3, value3) {
        const m4 = {
          field: field3,
          value: constant(value3)
        };
        if (isFunction(t4)) {
          m4.filter = t4;
          modp.push(m4);
        } else {
          m4.tuple = t4;
          mod.push(m4);
        }
        return this;
      },
      encode(t4, set7) {
        if (isFunction(t4)) modp.push({
          filter: t4,
          field: set7
        });
        else mod.push({
          tuple: t4,
          field: set7
        });
        return this;
      },
      clean(value3) {
        clean = value3;
        return this;
      },
      reflow() {
        reflow2 = true;
        return this;
      },
      pulse(pulse2, tuples) {
        const cur = {}, out = {};
        let i2, n2, m4, f2, t4, id2;
        for (i2 = 0, n2 = tuples.length; i2 < n2; ++i2) {
          cur[tupleid(tuples[i2])] = 1;
        }
        for (i2 = 0, n2 = rem2.length; i2 < n2; ++i2) {
          t4 = rem2[i2];
          cur[tupleid(t4)] = -1;
        }
        for (i2 = 0, n2 = remp.length; i2 < n2; ++i2) {
          f2 = remp[i2];
          tuples.forEach((t5) => {
            if (f2(t5)) cur[tupleid(t5)] = -1;
          });
        }
        for (i2 = 0, n2 = add6.length; i2 < n2; ++i2) {
          t4 = add6[i2];
          id2 = tupleid(t4);
          if (cur[id2]) {
            cur[id2] = 1;
          } else {
            pulse2.add.push(ingest$1(add6[i2]));
          }
        }
        for (i2 = 0, n2 = tuples.length; i2 < n2; ++i2) {
          t4 = tuples[i2];
          if (cur[tupleid(t4)] < 0) pulse2.rem.push(t4);
        }
        function modify2(t5, f3, v3) {
          if (v3) {
            t5[f3] = v3(t5);
          } else {
            pulse2.encode = f3;
          }
          if (!reflow2) out[tupleid(t5)] = t5;
        }
        for (i2 = 0, n2 = mod.length; i2 < n2; ++i2) {
          m4 = mod[i2];
          t4 = m4.tuple;
          f2 = m4.field;
          id2 = cur[tupleid(t4)];
          if (id2 > 0) {
            modify2(t4, f2, m4.value);
            pulse2.modifies(f2);
          }
        }
        for (i2 = 0, n2 = modp.length; i2 < n2; ++i2) {
          m4 = modp[i2];
          f2 = m4.filter;
          tuples.forEach((t5) => {
            if (f2(t5) && cur[tupleid(t5)] > 0) {
              modify2(t5, m4.field, m4.value);
            }
          });
          pulse2.modifies(m4.field);
        }
        if (reflow2) {
          pulse2.mod = rem2.length || remp.length ? tuples.filter((t5) => cur[tupleid(t5)] > 0) : tuples.slice();
        } else {
          for (id2 in out) pulse2.mod.push(out[id2]);
        }
        if (clean || clean == null && (rem2.length || remp.length)) {
          pulse2.clean(true);
        }
        return pulse2;
      }
    };
  }
  var CACHE = "_:mod:_";
  function Parameters() {
    Object.defineProperty(this, CACHE, {
      writable: true,
      value: {}
    });
  }
  Parameters.prototype = {
    /**
     * Set a parameter value. If the parameter value changes, the parameter
     * will be recorded as modified.
     * @param {string} name - The parameter name.
     * @param {number} index - The index into an array-value parameter. Ignored if
     *   the argument is undefined, null or less than zero.
     * @param {*} value - The parameter value to set.
     * @param {boolean} [force=false] - If true, records the parameter as modified
     *   even if the value is unchanged.
     * @return {Parameters} - This parameter object.
     */
    set(name4, index4, value3, force) {
      const o2 = this, v3 = o2[name4], mod = o2[CACHE];
      if (index4 != null && index4 >= 0) {
        if (v3[index4] !== value3 || force) {
          v3[index4] = value3;
          mod[index4 + ":" + name4] = -1;
          mod[name4] = -1;
        }
      } else if (v3 !== value3 || force) {
        o2[name4] = value3;
        mod[name4] = isArray(value3) ? 1 + value3.length : -1;
      }
      return o2;
    },
    /**
     * Tests if one or more parameters has been modified. If invoked with no
     * arguments, returns true if any parameter value has changed. If the first
     * argument is array, returns trues if any parameter name in the array has
     * changed. Otherwise, tests if the given name and optional array index has
     * changed.
     * @param {string} name - The parameter name to test.
     * @param {number} [index=undefined] - The parameter array index to test.
     * @return {boolean} - Returns true if a queried parameter was modified.
     */
    modified(name4, index4) {
      const mod = this[CACHE];
      if (!arguments.length) {
        for (const k2 in mod) {
          if (mod[k2]) return true;
        }
        return false;
      } else if (isArray(name4)) {
        for (let k2 = 0; k2 < name4.length; ++k2) {
          if (mod[name4[k2]]) return true;
        }
        return false;
      }
      return index4 != null && index4 >= 0 ? index4 + 1 < mod[name4] || !!mod[index4 + ":" + name4] : !!mod[name4];
    },
    /**
     * Clears the modification records. After calling this method,
     * all parameters are considered unmodified.
     */
    clear() {
      this[CACHE] = {};
      return this;
    }
  };
  var OP_ID = 0;
  var PULSE = "pulse";
  var NO_PARAMS = new Parameters();
  var SKIP$1 = 1;
  var MODIFIED = 2;
  function Operator(init2, update3, params2, react) {
    this.id = ++OP_ID;
    this.value = init2;
    this.stamp = -1;
    this.rank = -1;
    this.qrank = -1;
    this.flags = 0;
    if (update3) {
      this._update = update3;
    }
    if (params2) this.parameters(params2, react);
  }
  function flag(bit) {
    return function(state) {
      const f2 = this.flags;
      if (arguments.length === 0) return !!(f2 & bit);
      this.flags = state ? f2 | bit : f2 & ~bit;
      return this;
    };
  }
  Operator.prototype = {
    /**
     * Returns a list of target operators dependent on this operator.
     * If this list does not exist, it is created and then returned.
     * @return {UniqueList}
     */
    targets() {
      return this._targets || (this._targets = UniqueList(id));
    },
    /**
     * Sets the value of this operator.
     * @param {*} value - the value to set.
     * @return {Number} Returns 1 if the operator value has changed
     *   according to strict equality, returns 0 otherwise.
     */
    set(value3) {
      if (this.value !== value3) {
        this.value = value3;
        return 1;
      } else {
        return 0;
      }
    },
    /**
     * Indicates that operator evaluation should be skipped on the next pulse.
     * This operator will still propagate incoming pulses, but its update function
     * will not be invoked. The skip flag is reset after every pulse, so calling
     * this method will affect processing of the next pulse only.
     */
    skip: flag(SKIP$1),
    /**
     * Indicates that this operator's value has been modified on its most recent
     * pulse. Normally modification is checked via strict equality; however, in
     * some cases it is more efficient to update the internal state of an object.
     * In those cases, the modified flag can be used to trigger propagation. Once
     * set, the modification flag persists across pulses until unset. The flag can
     * be used with the last timestamp to test if a modification is recent.
     */
    modified: flag(MODIFIED),
    /**
     * Sets the parameters for this operator. The parameter values are analyzed for
     * operator instances. If found, this operator will be added as a dependency
     * of the parameterizing operator. Operator values are dynamically marshalled
     * from each operator parameter prior to evaluation. If a parameter value is
     * an array, the array will also be searched for Operator instances. However,
     * the search does not recurse into sub-arrays or object properties.
     * @param {object} params - A hash of operator parameters.
     * @param {boolean} [react=true] - A flag indicating if this operator should
     *   automatically update (react) when parameter values change. In other words,
     *   this flag determines if the operator registers itself as a listener on
     *   any upstream operators included in the parameters.
     * @param {boolean} [initonly=false] - A flag indicating if this operator
     *   should calculate an update only upon its initial evaluation, then
     *   deregister dependencies and suppress all future update invocations.
     * @return {Operator[]} - An array of upstream dependencies.
     */
    parameters(params2, react, initonly) {
      react = react !== false;
      const argval = this._argval = this._argval || new Parameters(), argops = this._argops = this._argops || [], deps = [];
      let name4, value3, n2, i2;
      const add6 = (name5, index4, value4) => {
        if (value4 instanceof Operator) {
          if (value4 !== this) {
            if (react) value4.targets().add(this);
            deps.push(value4);
          }
          argops.push({
            op: value4,
            name: name5,
            index: index4
          });
        } else {
          argval.set(name5, index4, value4);
        }
      };
      for (name4 in params2) {
        value3 = params2[name4];
        if (name4 === PULSE) {
          array(value3).forEach((op) => {
            if (!(op instanceof Operator)) {
              error("Pulse parameters must be operator instances.");
            } else if (op !== this) {
              op.targets().add(this);
              deps.push(op);
            }
          });
          this.source = value3;
        } else if (isArray(value3)) {
          argval.set(name4, -1, Array(n2 = value3.length));
          for (i2 = 0; i2 < n2; ++i2) add6(name4, i2, value3[i2]);
        } else {
          add6(name4, -1, value3);
        }
      }
      this.marshall().clear();
      if (initonly) argops.initonly = true;
      return deps;
    },
    /**
     * Internal method for marshalling parameter values.
     * Visits each operator dependency to pull the latest value.
     * @return {Parameters} A Parameters object to pass to the update function.
     */
    marshall(stamp) {
      const argval = this._argval || NO_PARAMS, argops = this._argops;
      let item, i2, op, mod;
      if (argops) {
        const n2 = argops.length;
        for (i2 = 0; i2 < n2; ++i2) {
          item = argops[i2];
          op = item.op;
          mod = op.modified() && op.stamp === stamp;
          argval.set(item.name, item.index, op.value, mod);
        }
        if (argops.initonly) {
          for (i2 = 0; i2 < n2; ++i2) {
            item = argops[i2];
            item.op.targets().remove(this);
          }
          this._argops = null;
          this._update = null;
        }
      }
      return argval;
    },
    /**
     * Detach this operator from the dataflow.
     * Unregisters listeners on upstream dependencies.
     */
    detach() {
      const argops = this._argops;
      let i2, n2, item, op;
      if (argops) {
        for (i2 = 0, n2 = argops.length; i2 < n2; ++i2) {
          item = argops[i2];
          op = item.op;
          if (op._targets) {
            op._targets.remove(this);
          }
        }
      }
      this.pulse = null;
      this.source = null;
    },
    /**
     * Delegate method to perform operator processing.
     * Subclasses can override this method to perform custom processing.
     * By default, it marshalls parameters and calls the update function
     * if that function is defined. If the update function does not
     * change the operator value then StopPropagation is returned.
     * If no update function is defined, this method does nothing.
     * @param {Pulse} pulse - the current dataflow pulse.
     * @return The output pulse or StopPropagation. A falsy return value
     *   (including undefined) will let the input pulse pass through.
     */
    evaluate(pulse2) {
      const update3 = this._update;
      if (update3) {
        const params2 = this.marshall(pulse2.stamp), v3 = update3.call(this, params2, pulse2);
        params2.clear();
        if (v3 !== this.value) {
          this.value = v3;
        } else if (!this.modified()) {
          return pulse2.StopPropagation;
        }
      }
    },
    /**
     * Run this operator for the current pulse. If this operator has already
     * been run at (or after) the pulse timestamp, returns StopPropagation.
     * Internally, this method calls {@link evaluate} to perform processing.
     * If {@link evaluate} returns a falsy value, the input pulse is returned.
     * This method should NOT be overridden, instead overrride {@link evaluate}.
     * @param {Pulse} pulse - the current dataflow pulse.
     * @return the output pulse for this operator (or StopPropagation)
     */
    run(pulse2) {
      if (pulse2.stamp < this.stamp) return pulse2.StopPropagation;
      let rv;
      if (this.skip()) {
        this.skip(false);
        rv = 0;
      } else {
        rv = this.evaluate(pulse2);
      }
      return this.pulse = rv || pulse2;
    }
  };
  function add(init2, update3, params2, react) {
    let shift = 1, op;
    if (init2 instanceof Operator) {
      op = init2;
    } else if (init2 && init2.prototype instanceof Operator) {
      op = new init2();
    } else if (isFunction(init2)) {
      op = new Operator(null, init2);
    } else {
      shift = 0;
      op = new Operator(init2, update3);
    }
    this.rank(op);
    if (shift) {
      react = params2;
      params2 = update3;
    }
    if (params2) this.connect(op, op.parameters(params2, react));
    this.touch(op);
    return op;
  }
  function connect(target2, sources) {
    const targetRank = target2.rank, n2 = sources.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      if (targetRank < sources[i2].rank) {
        this.rerank(target2);
        return;
      }
    }
  }
  var STREAM_ID = 0;
  function EventStream(filter3, apply3, receive) {
    this.id = ++STREAM_ID;
    this.value = null;
    if (receive) this.receive = receive;
    if (filter3) this._filter = filter3;
    if (apply3) this._apply = apply3;
  }
  function stream(filter3, apply3, receive) {
    return new EventStream(filter3, apply3, receive);
  }
  EventStream.prototype = {
    _filter: truthy,
    _apply: identity,
    targets() {
      return this._targets || (this._targets = UniqueList(id));
    },
    consume(_) {
      if (!arguments.length) return !!this._consume;
      this._consume = !!_;
      return this;
    },
    receive(evt) {
      if (this._filter(evt)) {
        const val = this.value = this._apply(evt), trg = this._targets, n2 = trg ? trg.length : 0;
        for (let i2 = 0; i2 < n2; ++i2) trg[i2].receive(val);
        if (this._consume) {
          evt.preventDefault();
          evt.stopPropagation();
        }
      }
    },
    filter(filter3) {
      const s2 = stream(filter3);
      this.targets().add(s2);
      return s2;
    },
    apply(apply3) {
      const s2 = stream(null, apply3);
      this.targets().add(s2);
      return s2;
    },
    merge() {
      const s2 = stream();
      this.targets().add(s2);
      for (let i2 = 0, n2 = arguments.length; i2 < n2; ++i2) {
        arguments[i2].targets().add(s2);
      }
      return s2;
    },
    throttle(pause) {
      let t4 = -1;
      return this.filter(() => {
        const now2 = Date.now();
        if (now2 - t4 > pause) {
          t4 = now2;
          return 1;
        } else {
          return 0;
        }
      });
    },
    debounce(delay) {
      const s2 = stream();
      this.targets().add(stream(null, null, debounce(delay, (e4) => {
        const df = e4.dataflow;
        s2.receive(e4);
        if (df && df.run) df.run();
      })));
      return s2;
    },
    between(a4, b3) {
      let active = false;
      a4.targets().add(stream(null, null, () => active = true));
      b3.targets().add(stream(null, null, () => active = false));
      return this.filter(() => active);
    },
    detach() {
      this._filter = truthy;
      this._targets = null;
    }
  };
  function events(source4, type3, filter3, apply3) {
    const df = this, s2 = stream(filter3, apply3), send = function(e4) {
      e4.dataflow = df;
      try {
        s2.receive(e4);
      } catch (error3) {
        df.error(error3);
      } finally {
        df.run();
      }
    };
    let sources;
    if (typeof source4 === "string" && typeof document !== "undefined") {
      sources = document.querySelectorAll(source4);
    } else {
      sources = array(source4);
    }
    const n2 = sources.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      sources[i2].addEventListener(type3, send);
    }
    return s2;
  }
  function parse2(data3, format5) {
    const locale4 = this.locale();
    return read(data3, format5, locale4.timeParse, locale4.utcParse);
  }
  function ingest(target2, data3, format5) {
    data3 = this.parse(data3, format5);
    return this.pulse(target2, this.changeset().insert(data3));
  }
  async function request(url, format5) {
    const df = this;
    let status = 0, data3;
    try {
      data3 = await df.loader().load(url, {
        context: "dataflow",
        response: responseType(format5 && format5.type)
      });
      try {
        data3 = df.parse(data3, format5);
      } catch (err) {
        status = -2;
        df.warn("Data ingestion failed", url, err);
      }
    } catch (err) {
      status = -1;
      df.warn("Loading failed", url, err);
    }
    return {
      data: data3,
      status
    };
  }
  async function preload(target2, url, format5) {
    const df = this, pending = df._pending || loadPending(df);
    pending.requests += 1;
    const res = await df.request(url, format5);
    df.pulse(target2, df.changeset().remove(truthy).insert(res.data || []));
    pending.done();
    return res;
  }
  function loadPending(df) {
    let accept;
    const pending = new Promise((a4) => accept = a4);
    pending.requests = 0;
    pending.done = () => {
      if (--pending.requests === 0) {
        df._pending = null;
        accept(df);
      }
    };
    return df._pending = pending;
  }
  var SKIP = {
    skip: true
  };
  function on(source4, target2, update3, params2, options) {
    const fn = source4 instanceof Operator ? onOperator : onStream;
    fn(this, source4, target2, update3, params2, options);
    return this;
  }
  function onStream(df, stream2, target2, update3, params2, options) {
    const opt = extend({}, options, SKIP);
    let func, op;
    if (!isFunction(target2)) target2 = constant(target2);
    if (update3 === void 0) {
      func = (e4) => df.touch(target2(e4));
    } else if (isFunction(update3)) {
      op = new Operator(null, update3, params2, false);
      func = (e4) => {
        op.evaluate(e4);
        const t4 = target2(e4), v3 = op.value;
        isChangeSet(v3) ? df.pulse(t4, v3, options) : df.update(t4, v3, opt);
      };
    } else {
      func = (e4) => df.update(target2(e4), update3, opt);
    }
    stream2.apply(func);
  }
  function onOperator(df, source4, target2, update3, params2, options) {
    if (update3 === void 0) {
      source4.targets().add(target2);
    } else {
      const opt = options || {}, op = new Operator(null, updater(target2, update3), params2, false);
      op.modified(opt.force);
      op.rank = source4.rank;
      source4.targets().add(op);
      if (target2) {
        op.skip(true);
        op.value = target2.value;
        op.targets().add(target2);
        df.connect(target2, [op]);
      }
    }
  }
  function updater(target2, update3) {
    update3 = isFunction(update3) ? update3 : constant(update3);
    return target2 ? function(_, pulse2) {
      const value3 = update3(_, pulse2);
      if (!target2.skip()) {
        target2.skip(value3 !== this.value).value = value3;
      }
      return value3;
    } : update3;
  }
  function rank(op) {
    op.rank = ++this._rank;
  }
  function rerank(op) {
    const queue = [op];
    let cur, list, i2;
    while (queue.length) {
      this.rank(cur = queue.pop());
      if (list = cur._targets) {
        for (i2 = list.length; --i2 >= 0; ) {
          queue.push(cur = list[i2]);
          if (cur === op) error("Cycle detected in dataflow graph.");
        }
      }
    }
  }
  var StopPropagation = {};
  var ADD = 1 << 0;
  var REM = 1 << 1;
  var MOD = 1 << 2;
  var ADD_REM = ADD | REM;
  var ADD_MOD = ADD | MOD;
  var ALL = ADD | REM | MOD;
  var REFLOW = 1 << 3;
  var SOURCE = 1 << 4;
  var NO_SOURCE = 1 << 5;
  var NO_FIELDS = 1 << 6;
  function Pulse(dataflow, stamp, encode2) {
    this.dataflow = dataflow;
    this.stamp = stamp == null ? -1 : stamp;
    this.add = [];
    this.rem = [];
    this.mod = [];
    this.fields = null;
    this.encode = encode2 || null;
  }
  function materialize(data3, filter3) {
    const out = [];
    visitArray(data3, filter3, (_) => out.push(_));
    return out;
  }
  function filter(pulse2, flags) {
    const map4 = {};
    pulse2.visit(flags, (t4) => {
      map4[tupleid(t4)] = 1;
    });
    return (t4) => map4[tupleid(t4)] ? null : t4;
  }
  function addFilter(a4, b3) {
    return a4 ? (t4, i2) => a4(t4, i2) && b3(t4, i2) : b3;
  }
  Pulse.prototype = {
    /**
     * Sentinel value indicating pulse propagation should stop.
     */
    StopPropagation,
    /**
     * Boolean flag indicating ADD (added) tuples.
     */
    ADD,
    /**
     * Boolean flag indicating REM (removed) tuples.
     */
    REM,
    /**
     * Boolean flag indicating MOD (modified) tuples.
     */
    MOD,
    /**
     * Boolean flag indicating ADD (added) and REM (removed) tuples.
     */
    ADD_REM,
    /**
     * Boolean flag indicating ADD (added) and MOD (modified) tuples.
     */
    ADD_MOD,
    /**
     * Boolean flag indicating ADD, REM and MOD tuples.
     */
    ALL,
    /**
     * Boolean flag indicating all tuples in a data source
     * except for the ADD, REM and MOD tuples.
     */
    REFLOW,
    /**
     * Boolean flag indicating a 'pass-through' to a
     * backing data source, ignoring ADD, REM and MOD tuples.
     */
    SOURCE,
    /**
     * Boolean flag indicating that source data should be
     * suppressed when creating a forked pulse.
     */
    NO_SOURCE,
    /**
     * Boolean flag indicating that field modifications should be
     * suppressed when creating a forked pulse.
     */
    NO_FIELDS,
    /**
     * Creates a new pulse based on the values of this pulse.
     * The dataflow, time stamp and field modification values are copied over.
     * By default, new empty ADD, REM and MOD arrays are created.
     * @param {number} flags - Integer of boolean flags indicating which (if any)
     *   tuple arrays should be copied to the new pulse. The supported flag values
     *   are ADD, REM and MOD. Array references are copied directly: new array
     *   instances are not created.
     * @return {Pulse} - The forked pulse instance.
     * @see init
     */
    fork(flags) {
      return new Pulse(this.dataflow).init(this, flags);
    },
    /**
     * Creates a copy of this pulse with new materialized array
     * instances for the ADD, REM, MOD, and SOURCE arrays.
     * The dataflow, time stamp and field modification values are copied over.
     * @return {Pulse} - The cloned pulse instance.
     * @see init
     */
    clone() {
      const p2 = this.fork(ALL);
      p2.add = p2.add.slice();
      p2.rem = p2.rem.slice();
      p2.mod = p2.mod.slice();
      if (p2.source) p2.source = p2.source.slice();
      return p2.materialize(ALL | SOURCE);
    },
    /**
     * Returns a pulse that adds all tuples from a backing source. This is
     * useful for cases where operators are added to a dataflow after an
     * upstream data pipeline has already been processed, ensuring that
     * new operators can observe all tuples within a stream.
     * @return {Pulse} - A pulse instance with all source tuples included
     *   in the add array. If the current pulse already has all source
     *   tuples in its add array, it is returned directly. If the current
     *   pulse does not have a backing source, it is returned directly.
     */
    addAll() {
      let p2 = this;
      const reuse = !p2.source || p2.add === p2.rem || !p2.rem.length && p2.source.length === p2.add.length;
      if (reuse) {
        return p2;
      } else {
        p2 = new Pulse(this.dataflow).init(this);
        p2.add = p2.source;
        p2.rem = [];
        return p2;
      }
    },
    /**
     * Initialize this pulse based on the values of another pulse. This method
     * is used internally by {@link fork} to initialize a new forked tuple.
     * The dataflow, time stamp and field modification values are copied over.
     * By default, new empty ADD, REM and MOD arrays are created.
     * @param {Pulse} src - The source pulse to copy from.
     * @param {number} flags - Integer of boolean flags indicating which (if any)
     *   tuple arrays should be copied to the new pulse. The supported flag values
     *   are ADD, REM and MOD. Array references are copied directly: new array
     *   instances are not created. By default, source data arrays are copied
     *   to the new pulse. Use the NO_SOURCE flag to enforce a null source.
     * @return {Pulse} - Returns this Pulse instance.
     */
    init(src, flags) {
      const p2 = this;
      p2.stamp = src.stamp;
      p2.encode = src.encode;
      if (src.fields && !(flags & NO_FIELDS)) {
        p2.fields = src.fields;
      }
      if (flags & ADD) {
        p2.addF = src.addF;
        p2.add = src.add;
      } else {
        p2.addF = null;
        p2.add = [];
      }
      if (flags & REM) {
        p2.remF = src.remF;
        p2.rem = src.rem;
      } else {
        p2.remF = null;
        p2.rem = [];
      }
      if (flags & MOD) {
        p2.modF = src.modF;
        p2.mod = src.mod;
      } else {
        p2.modF = null;
        p2.mod = [];
      }
      if (flags & NO_SOURCE) {
        p2.srcF = null;
        p2.source = null;
      } else {
        p2.srcF = src.srcF;
        p2.source = src.source;
        if (src.cleans) p2.cleans = src.cleans;
      }
      return p2;
    },
    /**
     * Schedules a function to run after pulse propagation completes.
     * @param {function} func - The function to run.
     */
    runAfter(func) {
      this.dataflow.runAfter(func);
    },
    /**
     * Indicates if tuples have been added, removed or modified.
     * @param {number} [flags] - The tuple types (ADD, REM or MOD) to query.
     *   Defaults to ALL, returning true if any tuple type has changed.
     * @return {boolean} - Returns true if one or more queried tuple types have
     *   changed, false otherwise.
     */
    changed(flags) {
      const f2 = flags || ALL;
      return f2 & ADD && this.add.length || f2 & REM && this.rem.length || f2 & MOD && this.mod.length;
    },
    /**
     * Forces a "reflow" of tuple values, such that all tuples in the backing
     * source are added to the MOD set, unless already present in the ADD set.
     * @param {boolean} [fork=false] - If true, returns a forked copy of this
     *   pulse, and invokes reflow on that derived pulse.
     * @return {Pulse} - The reflowed pulse instance.
     */
    reflow(fork) {
      if (fork) return this.fork(ALL).reflow();
      const len = this.add.length, src = this.source && this.source.length;
      if (src && src !== len) {
        this.mod = this.source;
        if (len) this.filter(MOD, filter(this, ADD));
      }
      return this;
    },
    /**
     * Get/set metadata to pulse requesting garbage collection
     * to reclaim currently unused resources.
     */
    clean(value3) {
      if (arguments.length) {
        this.cleans = !!value3;
        return this;
      } else {
        return this.cleans;
      }
    },
    /**
     * Marks one or more data field names as modified to assist dependency
     * tracking and incremental processing by transform operators.
     * @param {string|Array<string>} _ - The field(s) to mark as modified.
     * @return {Pulse} - This pulse instance.
     */
    modifies(_) {
      const hash2 = this.fields || (this.fields = {});
      if (isArray(_)) {
        _.forEach((f2) => hash2[f2] = true);
      } else {
        hash2[_] = true;
      }
      return this;
    },
    /**
     * Checks if one or more data fields have been modified during this pulse
     * propagation timestamp.
     * @param {string|Array<string>} _ - The field(s) to check for modified.
     * @param {boolean} nomod - If true, will check the modified flag even if
     *   no mod tuples exist. If false (default), mod tuples must be present.
     * @return {boolean} - Returns true if any of the provided fields has been
     *   marked as modified, false otherwise.
     */
    modified(_, nomod) {
      const fields = this.fields;
      return !((nomod || this.mod.length) && fields) ? false : !arguments.length ? !!fields : isArray(_) ? _.some((f2) => fields[f2]) : fields[_];
    },
    /**
     * Adds a filter function to one more tuple sets. Filters are applied to
     * backing tuple arrays, to determine the actual set of tuples considered
     * added, removed or modified. They can be used to delay materialization of
     * a tuple set in order to avoid expensive array copies. In addition, the
     * filter functions can serve as value transformers: unlike standard predicate
     * function (which return boolean values), Pulse filters should return the
     * actual tuple value to process. If a tuple set is already filtered, the
     * new filter function will be appended into a conjuntive ('and') query.
     * @param {number} flags - Flags indicating the tuple set(s) to filter.
     * @param {function(*):object} filter - Filter function that will be applied
     *   to the tuple set array, and should return a data tuple if the value
     *   should be included in the tuple set, and falsy (or null) otherwise.
     * @return {Pulse} - Returns this pulse instance.
     */
    filter(flags, filter3) {
      const p2 = this;
      if (flags & ADD) p2.addF = addFilter(p2.addF, filter3);
      if (flags & REM) p2.remF = addFilter(p2.remF, filter3);
      if (flags & MOD) p2.modF = addFilter(p2.modF, filter3);
      if (flags & SOURCE) p2.srcF = addFilter(p2.srcF, filter3);
      return p2;
    },
    /**
     * Materialize one or more tuple sets in this pulse. If the tuple set(s) have
     * a registered filter function, it will be applied and the tuple set(s) will
     * be replaced with materialized tuple arrays.
     * @param {number} flags - Flags indicating the tuple set(s) to materialize.
     * @return {Pulse} - Returns this pulse instance.
     */
    materialize(flags) {
      flags = flags || ALL;
      const p2 = this;
      if (flags & ADD && p2.addF) {
        p2.add = materialize(p2.add, p2.addF);
        p2.addF = null;
      }
      if (flags & REM && p2.remF) {
        p2.rem = materialize(p2.rem, p2.remF);
        p2.remF = null;
      }
      if (flags & MOD && p2.modF) {
        p2.mod = materialize(p2.mod, p2.modF);
        p2.modF = null;
      }
      if (flags & SOURCE && p2.srcF) {
        p2.source = p2.source.filter(p2.srcF);
        p2.srcF = null;
      }
      return p2;
    },
    /**
     * Visit one or more tuple sets in this pulse.
     * @param {number} flags - Flags indicating the tuple set(s) to visit.
     *   Legal values are ADD, REM, MOD and SOURCE (if a backing data source
     *   has been set).
     * @param {function(object):*} - Visitor function invoked per-tuple.
     * @return {Pulse} - Returns this pulse instance.
     */
    visit(flags, visitor) {
      const p2 = this, v3 = visitor;
      if (flags & SOURCE) {
        visitArray(p2.source, p2.srcF, v3);
        return p2;
      }
      if (flags & ADD) visitArray(p2.add, p2.addF, v3);
      if (flags & REM) visitArray(p2.rem, p2.remF, v3);
      if (flags & MOD) visitArray(p2.mod, p2.modF, v3);
      const src = p2.source;
      if (flags & REFLOW && src) {
        const sum3 = p2.add.length + p2.mod.length;
        if (sum3 === src.length) ;
        else if (sum3) {
          visitArray(src, filter(p2, ADD_MOD), v3);
        } else {
          visitArray(src, p2.srcF, v3);
        }
      }
      return p2;
    }
  };
  function MultiPulse(dataflow, stamp, pulses, encode2) {
    const p2 = this;
    let c4 = 0;
    this.dataflow = dataflow;
    this.stamp = stamp;
    this.fields = null;
    this.encode = encode2 || null;
    this.pulses = pulses;
    for (const pulse2 of pulses) {
      if (pulse2.stamp !== stamp) continue;
      if (pulse2.fields) {
        const hash2 = p2.fields || (p2.fields = {});
        for (const f2 in pulse2.fields) {
          hash2[f2] = 1;
        }
      }
      if (pulse2.changed(p2.ADD)) c4 |= p2.ADD;
      if (pulse2.changed(p2.REM)) c4 |= p2.REM;
      if (pulse2.changed(p2.MOD)) c4 |= p2.MOD;
    }
    this.changes = c4;
  }
  inherits(MultiPulse, Pulse, {
    /**
     * Creates a new pulse based on the values of this pulse.
     * The dataflow, time stamp and field modification values are copied over.
     * @return {Pulse}
     */
    fork(flags) {
      const p2 = new Pulse(this.dataflow).init(this, flags & this.NO_FIELDS);
      if (flags !== void 0) {
        if (flags & p2.ADD) this.visit(p2.ADD, (t4) => p2.add.push(t4));
        if (flags & p2.REM) this.visit(p2.REM, (t4) => p2.rem.push(t4));
        if (flags & p2.MOD) this.visit(p2.MOD, (t4) => p2.mod.push(t4));
      }
      return p2;
    },
    changed(flags) {
      return this.changes & flags;
    },
    modified(_) {
      const p2 = this, fields = p2.fields;
      return !(fields && p2.changes & p2.MOD) ? 0 : isArray(_) ? _.some((f2) => fields[f2]) : fields[_];
    },
    filter() {
      error("MultiPulse does not support filtering.");
    },
    materialize() {
      error("MultiPulse does not support materialization.");
    },
    visit(flags, visitor) {
      const p2 = this, pulses = p2.pulses, n2 = pulses.length;
      let i2 = 0;
      if (flags & p2.SOURCE) {
        for (; i2 < n2; ++i2) {
          pulses[i2].visit(flags, visitor);
        }
      } else {
        for (; i2 < n2; ++i2) {
          if (pulses[i2].stamp === p2.stamp) {
            pulses[i2].visit(flags, visitor);
          }
        }
      }
      return p2;
    }
  });
  async function evaluate(encode2, prerun, postrun) {
    const df = this, async = [];
    if (df._pulse) return reentrant(df);
    if (df._pending) await df._pending;
    if (prerun) await asyncCallback(df, prerun);
    if (!df._touched.length) {
      df.debug("Dataflow invoked, but nothing to do.");
      return df;
    }
    const stamp = ++df._clock;
    df._pulse = new Pulse(df, stamp, encode2);
    df._touched.forEach((op2) => df._enqueue(op2, true));
    df._touched = UniqueList(id);
    let count2 = 0, op, next, error3;
    try {
      while (df._heap.size() > 0) {
        op = df._heap.pop();
        if (op.rank !== op.qrank) {
          df._enqueue(op, true);
          continue;
        }
        next = op.run(df._getPulse(op, encode2));
        if (next.then) {
          next = await next;
        } else if (next.async) {
          async.push(next.async);
          next = StopPropagation;
        }
        if (next !== StopPropagation) {
          if (op._targets) op._targets.forEach((op2) => df._enqueue(op2));
        }
        ++count2;
      }
    } catch (err) {
      df._heap.clear();
      error3 = err;
    }
    df._input = {};
    df._pulse = null;
    df.debug(`Pulse ${stamp}: ${count2} operators`);
    if (error3) {
      df._postrun = [];
      df.error(error3);
    }
    if (df._postrun.length) {
      const pr = df._postrun.sort((a4, b3) => b3.priority - a4.priority);
      df._postrun = [];
      for (let i2 = 0; i2 < pr.length; ++i2) {
        await asyncCallback(df, pr[i2].callback);
      }
    }
    if (postrun) await asyncCallback(df, postrun);
    if (async.length) {
      Promise.all(async).then((cb) => df.runAsync(null, () => {
        cb.forEach((f2) => {
          try {
            f2(df);
          } catch (err) {
            df.error(err);
          }
        });
      }));
    }
    return df;
  }
  async function runAsync(encode2, prerun, postrun) {
    while (this._running) await this._running;
    const clear2 = () => this._running = null;
    (this._running = this.evaluate(encode2, prerun, postrun)).then(clear2, clear2);
    return this._running;
  }
  function run(encode2, prerun, postrun) {
    return this._pulse ? reentrant(this) : (this.evaluate(encode2, prerun, postrun), this);
  }
  function runAfter(callback, enqueue2, priority) {
    if (this._pulse || enqueue2) {
      this._postrun.push({
        priority: priority || 0,
        callback
      });
    } else {
      try {
        callback(this);
      } catch (err) {
        this.error(err);
      }
    }
  }
  function reentrant(df) {
    df.error("Dataflow already running. Use runAsync() to chain invocations.");
    return df;
  }
  function enqueue(op, force) {
    const q2 = op.stamp < this._clock;
    if (q2) op.stamp = this._clock;
    if (q2 || force) {
      op.qrank = op.rank;
      this._heap.push(op);
    }
  }
  function getPulse(op, encode2) {
    const s2 = op.source, stamp = this._clock;
    return s2 && isArray(s2) ? new MultiPulse(this, stamp, s2.map((_) => _.pulse), encode2) : this._input[op.id] || singlePulse(this._pulse, s2 && s2.pulse);
  }
  function singlePulse(p2, s2) {
    if (s2 && s2.stamp === p2.stamp) {
      return s2;
    }
    p2 = p2.fork();
    if (s2 && s2 !== StopPropagation) {
      p2.source = s2.source;
    }
    return p2;
  }
  var NO_OPT = {
    skip: false,
    force: false
  };
  function touch(op, options) {
    const opt = options || NO_OPT;
    if (this._pulse) {
      this._enqueue(op);
    } else {
      this._touched.add(op);
    }
    if (opt.skip) op.skip(true);
    return this;
  }
  function update(op, value3, options) {
    const opt = options || NO_OPT;
    if (op.set(value3) || opt.force) {
      this.touch(op, opt);
    }
    return this;
  }
  function pulse(op, changeset2, options) {
    this.touch(op, options || NO_OPT);
    const p2 = new Pulse(this, this._clock + (this._pulse ? 0 : 1)), t4 = op.pulse && op.pulse.source || [];
    p2.target = op;
    this._input[op.id] = changeset2.pulse(p2, t4);
    return this;
  }
  function Heap(cmp) {
    let nodes = [];
    return {
      clear: () => nodes = [],
      size: () => nodes.length,
      peek: () => nodes[0],
      push: (x5) => {
        nodes.push(x5);
        return siftdown(nodes, 0, nodes.length - 1, cmp);
      },
      pop: () => {
        const last = nodes.pop();
        let item;
        if (nodes.length) {
          item = nodes[0];
          nodes[0] = last;
          siftup(nodes, 0, cmp);
        } else {
          item = last;
        }
        return item;
      }
    };
  }
  function siftdown(array4, start, idx, cmp) {
    let parent, pidx;
    const item = array4[idx];
    while (idx > start) {
      pidx = idx - 1 >> 1;
      parent = array4[pidx];
      if (cmp(item, parent) < 0) {
        array4[idx] = parent;
        idx = pidx;
        continue;
      }
      break;
    }
    return array4[idx] = item;
  }
  function siftup(array4, idx, cmp) {
    const start = idx, end = array4.length, item = array4[idx];
    let cidx = (idx << 1) + 1, ridx;
    while (cidx < end) {
      ridx = cidx + 1;
      if (ridx < end && cmp(array4[cidx], array4[ridx]) >= 0) {
        cidx = ridx;
      }
      array4[idx] = array4[cidx];
      idx = cidx;
      cidx = (idx << 1) + 1;
    }
    array4[idx] = item;
    return siftdown(array4, start, idx, cmp);
  }
  function Dataflow() {
    this.logger(logger());
    this.logLevel(Error$1);
    this._clock = 0;
    this._rank = 0;
    this._locale = defaultLocale3();
    try {
      this._loader = loader();
    } catch (e4) {
    }
    this._touched = UniqueList(id);
    this._input = {};
    this._pulse = null;
    this._heap = Heap((a4, b3) => a4.qrank - b3.qrank);
    this._postrun = [];
  }
  function logMethod(method2) {
    return function() {
      return this._log[method2].apply(this, arguments);
    };
  }
  Dataflow.prototype = {
    /**
     * The current timestamp of this dataflow. This value reflects the
     * timestamp of the previous dataflow run. The dataflow is initialized
     * with a stamp value of 0. The initial run of the dataflow will have
     * a timestap of 1, and so on. This value will match the
     * {@link Pulse.stamp} property.
     * @return {number} - The current timestamp value.
     */
    stamp() {
      return this._clock;
    },
    /**
     * Gets or sets the loader instance to use for data file loading. A
     * loader object must provide a "load" method for loading files and a
     * "sanitize" method for checking URL/filename validity. Both methods
     * should accept a URI and options hash as arguments, and return a Promise
     * that resolves to the loaded file contents (load) or a hash containing
     * sanitized URI data with the sanitized url assigned to the "href" property
     * (sanitize).
     * @param {object} _ - The loader instance to use.
     * @return {object|Dataflow} - If no arguments are provided, returns
     *   the current loader instance. Otherwise returns this Dataflow instance.
     */
    loader(_) {
      if (arguments.length) {
        this._loader = _;
        return this;
      } else {
        return this._loader;
      }
    },
    /**
     * Gets or sets the locale instance to use for formatting and parsing
     * string values. The locale object should be provided by the
     * vega-format library, and include methods such as format, timeFormat,
     * utcFormat, timeParse, and utcParse.
     * @param {object} _ - The locale instance to use.
     * @return {object|Dataflow} - If no arguments are provided, returns
     *   the current locale instance. Otherwise returns this Dataflow instance.
     */
    locale(_) {
      if (arguments.length) {
        this._locale = _;
        return this;
      } else {
        return this._locale;
      }
    },
    /**
     * Get or set the logger instance used to log messages. If no arguments are
     * provided, returns the current logger instance. Otherwise, sets the logger
     * and return this Dataflow instance. Provided loggers must support the full
     * API of logger objects generated by the vega-util logger method. Note that
     * by default the log level of the new logger will be used; use the logLevel
     * method to adjust the log level as needed.
     */
    logger(logger3) {
      if (arguments.length) {
        this._log = logger3;
        return this;
      } else {
        return this._log;
      }
    },
    /**
     * Logs an error message. By default, logged messages are written to console
     * output. The message will only be logged if the current log level is high
     * enough to permit error messages.
     */
    error: logMethod("error"),
    /**
     * Logs a warning message. By default, logged messages are written to console
     * output. The message will only be logged if the current log level is high
     * enough to permit warning messages.
     */
    warn: logMethod("warn"),
    /**
     * Logs a information message. By default, logged messages are written to
     * console output. The message will only be logged if the current log level is
     * high enough to permit information messages.
     */
    info: logMethod("info"),
    /**
     * Logs a debug message. By default, logged messages are written to console
     * output. The message will only be logged if the current log level is high
     * enough to permit debug messages.
     */
    debug: logMethod("debug"),
    /**
     * Get or set the current log level. If an argument is provided, it
     * will be used as the new log level.
     * @param {number} [level] - Should be one of None, Warn, Info
     * @return {number} - The current log level.
     */
    logLevel: logMethod("level"),
    /**
     * Empty entry threshold for garbage cleaning. Map data structures will
     * perform cleaning once the number of empty entries exceeds this value.
     */
    cleanThreshold: 1e4,
    // OPERATOR REGISTRATION
    add,
    connect,
    rank,
    rerank,
    // OPERATOR UPDATES
    pulse,
    touch,
    update,
    changeset,
    // DATA LOADING
    ingest,
    parse: parse2,
    preload,
    request,
    // EVENT HANDLING
    events,
    on,
    // PULSE PROPAGATION
    evaluate,
    run,
    runAsync,
    runAfter,
    _enqueue: enqueue,
    _getPulse: getPulse
  };
  function Transform(init2, params2) {
    Operator.call(this, init2, null, params2);
  }
  inherits(Transform, Operator, {
    /**
     * Overrides {@link Operator.evaluate} for transform operators.
     * Internally, this method calls {@link evaluate} to perform processing.
     * If {@link evaluate} returns a falsy value, the input pulse is returned.
     * This method should NOT be overridden, instead overrride {@link evaluate}.
     * @param {Pulse} pulse - the current dataflow pulse.
     * @return the output pulse for this operator (or StopPropagation)
     */
    run(pulse2) {
      if (pulse2.stamp < this.stamp) return pulse2.StopPropagation;
      let rv;
      if (this.skip()) {
        this.skip(false);
      } else {
        rv = this.evaluate(pulse2);
      }
      rv = rv || pulse2;
      if (rv.then) {
        rv = rv.then((_) => this.pulse = _);
      } else if (rv !== pulse2.StopPropagation) {
        this.pulse = rv;
      }
      return rv;
    },
    /**
     * Overrides {@link Operator.evaluate} for transform operators.
     * Marshalls parameter values and then invokes {@link transform}.
     * @param {Pulse} pulse - the current dataflow pulse.
     * @return {Pulse} The output pulse (or StopPropagation). A falsy return
         value (including undefined) will let the input pulse pass through.
    */
    evaluate(pulse2) {
      const params2 = this.marshall(pulse2.stamp), out = this.transform(params2, pulse2);
      params2.clear();
      return out;
    },
    /**
     * Process incoming pulses.
     * Subclasses should override this method to implement transforms.
     * @param {Parameters} _ - The operator parameter values.
     * @param {Pulse} pulse - The current dataflow pulse.
     * @return {Pulse} The output pulse (or StopPropagation). A falsy return
     *   value (including undefined) will let the input pulse pass through.
     */
    transform() {
    }
  });
  var transforms = {};
  function definition(type3) {
    const t4 = transform(type3);
    return t4 && t4.Definition || null;
  }
  function transform(type3) {
    type3 = type3 && type3.toLowerCase();
    return has(transforms, type3) ? transforms[type3] : null;
  }

  // node_modules/vega-transforms/build/vega-transforms.module.js
  var vega_transforms_module_exports = {};
  __export(vega_transforms_module_exports, {
    aggregate: () => Aggregate,
    bin: () => Bin,
    collect: () => Collect,
    compare: () => Compare,
    countpattern: () => CountPattern,
    cross: () => Cross,
    density: () => Density,
    dotbin: () => DotBin,
    expression: () => Expression,
    extent: () => Extent,
    facet: () => Facet,
    field: () => Field,
    filter: () => Filter,
    flatten: () => Flatten,
    fold: () => Fold,
    formula: () => Formula,
    generate: () => Generate,
    impute: () => Impute,
    joinaggregate: () => JoinAggregate,
    kde: () => KDE,
    key: () => Key,
    load: () => Load,
    lookup: () => Lookup,
    multiextent: () => MultiExtent,
    multivalues: () => MultiValues,
    params: () => Params,
    pivot: () => Pivot,
    prefacet: () => PreFacet,
    project: () => Project,
    proxy: () => Proxy2,
    quantile: () => Quantile,
    relay: () => Relay,
    sample: () => Sample,
    sequence: () => Sequence,
    sieve: () => Sieve,
    subflow: () => Subflow,
    timeunit: () => TimeUnit,
    tupleindex: () => TupleIndex,
    values: () => Values,
    window: () => Window
  });

  // node_modules/vega-statistics/build/vega-statistics.module.js
  function* numbers2(values4, valueof) {
    if (valueof == null) {
      for (let value3 of values4) {
        if (value3 != null && value3 !== "" && (value3 = +value3) >= value3) {
          yield value3;
        }
      }
    } else {
      let index4 = -1;
      for (let value3 of values4) {
        value3 = valueof(value3, ++index4, values4);
        if (value3 != null && value3 !== "" && (value3 = +value3) >= value3) {
          yield value3;
        }
      }
    }
  }
  function quantiles(array4, p2, f2) {
    const values4 = Float64Array.from(numbers2(array4, f2));
    values4.sort(ascending2);
    return p2.map((_) => quantileSorted(values4, _));
  }
  function quartiles(array4, f2) {
    return quantiles(array4, [0.25, 0.5, 0.75], f2);
  }
  function estimateBandwidth(array4, f2) {
    const n2 = array4.length, d2 = deviation(array4, f2), q2 = quartiles(array4, f2), h3 = (q2[2] - q2[0]) / 1.34, v3 = Math.min(d2, h3) || d2 || Math.abs(q2[0]) || 1;
    return 1.06 * v3 * Math.pow(n2, -0.2);
  }
  function bin2(_) {
    const maxb = _.maxbins || 20, base = _.base || 10, logb = Math.log(base), div = _.divide || [5, 2];
    let min4 = _.extent[0], max4 = _.extent[1], step, level, minstep, v3, i2, n2;
    const span2 = _.span || max4 - min4 || Math.abs(min4) || 1;
    if (_.step) {
      step = _.step;
    } else if (_.steps) {
      v3 = span2 / maxb;
      for (i2 = 0, n2 = _.steps.length; i2 < n2 && _.steps[i2] < v3; ++i2) ;
      step = _.steps[Math.max(0, i2 - 1)];
    } else {
      level = Math.ceil(Math.log(maxb) / logb);
      minstep = _.minstep || 0;
      step = Math.max(minstep, Math.pow(base, Math.round(Math.log(span2) / logb) - level));
      while (Math.ceil(span2 / step) > maxb) {
        step *= base;
      }
      for (i2 = 0, n2 = div.length; i2 < n2; ++i2) {
        v3 = step / div[i2];
        if (v3 >= minstep && span2 / v3 <= maxb) step = v3;
      }
    }
    v3 = Math.log(step);
    const precision = v3 >= 0 ? 0 : ~~(-v3 / logb) + 1, eps = Math.pow(base, -precision - 1);
    if (_.nice || _.nice === void 0) {
      v3 = Math.floor(min4 / step + eps) * step;
      min4 = min4 < v3 ? v3 - step : v3;
      max4 = Math.ceil(max4 / step) * step;
    }
    return {
      start: min4,
      stop: max4 === min4 ? min4 + step : max4,
      step
    };
  }
  var random = Math.random;
  function setRandom(r2) {
    random = r2;
  }
  function bootstrapCI(array4, samples, alpha, f2) {
    if (!array4.length) return [void 0, void 0];
    const values4 = Float64Array.from(numbers2(array4, f2)), n2 = values4.length, m4 = samples;
    let a4, i2, j2, mu;
    for (j2 = 0, mu = Array(m4); j2 < m4; ++j2) {
      for (a4 = 0, i2 = 0; i2 < n2; ++i2) {
        a4 += values4[~~(random() * n2)];
      }
      mu[j2] = a4 / n2;
    }
    mu.sort(ascending2);
    return [quantile(mu, alpha / 2), quantile(mu, 1 - alpha / 2)];
  }
  function dotbin(array4, step, smooth, f2) {
    f2 = f2 || ((_) => _);
    const n2 = array4.length, v3 = new Float64Array(n2);
    let i2 = 0, j2 = 1, a4 = f2(array4[0]), b3 = a4, w3 = a4 + step, x5;
    for (; j2 < n2; ++j2) {
      x5 = f2(array4[j2]);
      if (x5 >= w3) {
        b3 = (a4 + b3) / 2;
        for (; i2 < j2; ++i2) v3[i2] = b3;
        w3 = x5 + step;
        a4 = x5;
      }
      b3 = x5;
    }
    b3 = (a4 + b3) / 2;
    for (; i2 < j2; ++i2) v3[i2] = b3;
    return smooth ? smoothing(v3, step + step / 4) : v3;
  }
  function smoothing(v3, thresh) {
    const n2 = v3.length;
    let a4 = 0, b3 = 1, c4, d2;
    while (v3[a4] === v3[b3]) ++b3;
    while (b3 < n2) {
      c4 = b3 + 1;
      while (v3[b3] === v3[c4]) ++c4;
      if (v3[b3] - v3[b3 - 1] < thresh) {
        d2 = b3 + (a4 + c4 - b3 - b3 >> 1);
        while (d2 < b3) v3[d2++] = v3[b3];
        while (d2 > b3) v3[d2--] = v3[a4];
      }
      a4 = b3;
      b3 = c4;
    }
    return v3;
  }
  function lcg(seed) {
    return function() {
      seed = (1103515245 * seed + 12345) % 2147483647;
      return seed / 2147483647;
    };
  }
  function integer(min4, max4) {
    if (max4 == null) {
      max4 = min4;
      min4 = 0;
    }
    let a4, b3, d2;
    const dist2 = {
      min(_) {
        if (arguments.length) {
          a4 = _ || 0;
          d2 = b3 - a4;
          return dist2;
        } else {
          return a4;
        }
      },
      max(_) {
        if (arguments.length) {
          b3 = _ || 0;
          d2 = b3 - a4;
          return dist2;
        } else {
          return b3;
        }
      },
      sample() {
        return a4 + Math.floor(d2 * random());
      },
      pdf(x5) {
        return x5 === Math.floor(x5) && x5 >= a4 && x5 < b3 ? 1 / d2 : 0;
      },
      cdf(x5) {
        const v3 = Math.floor(x5);
        return v3 < a4 ? 0 : v3 >= b3 ? 1 : (v3 - a4 + 1) / d2;
      },
      icdf(p2) {
        return p2 >= 0 && p2 <= 1 ? a4 - 1 + Math.floor(p2 * d2) : NaN;
      }
    };
    return dist2.min(min4).max(max4);
  }
  var SQRT2PI = Math.sqrt(2 * Math.PI);
  var SQRT2 = Math.SQRT2;
  var nextSample = NaN;
  function sampleNormal(mean2, stdev) {
    mean2 = mean2 || 0;
    stdev = stdev == null ? 1 : stdev;
    let x5 = 0, y5 = 0, rds, c4;
    if (nextSample === nextSample) {
      x5 = nextSample;
      nextSample = NaN;
    } else {
      do {
        x5 = random() * 2 - 1;
        y5 = random() * 2 - 1;
        rds = x5 * x5 + y5 * y5;
      } while (rds === 0 || rds > 1);
      c4 = Math.sqrt(-2 * Math.log(rds) / rds);
      x5 *= c4;
      nextSample = y5 * c4;
    }
    return mean2 + x5 * stdev;
  }
  function densityNormal(value3, mean2, stdev) {
    stdev = stdev == null ? 1 : stdev;
    const z = (value3 - (mean2 || 0)) / stdev;
    return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI);
  }
  function cumulativeNormal(value3, mean2, stdev) {
    mean2 = mean2 || 0;
    stdev = stdev == null ? 1 : stdev;
    const z = (value3 - mean2) / stdev, Z = Math.abs(z);
    let cd2;
    if (Z > 37) {
      cd2 = 0;
    } else {
      const exp4 = Math.exp(-Z * Z / 2);
      let sum3;
      if (Z < 7.07106781186547) {
        sum3 = 0.0352624965998911 * Z + 0.700383064443688;
        sum3 = sum3 * Z + 6.37396220353165;
        sum3 = sum3 * Z + 33.912866078383;
        sum3 = sum3 * Z + 112.079291497871;
        sum3 = sum3 * Z + 221.213596169931;
        sum3 = sum3 * Z + 220.206867912376;
        cd2 = exp4 * sum3;
        sum3 = 0.0883883476483184 * Z + 1.75566716318264;
        sum3 = sum3 * Z + 16.064177579207;
        sum3 = sum3 * Z + 86.7807322029461;
        sum3 = sum3 * Z + 296.564248779674;
        sum3 = sum3 * Z + 637.333633378831;
        sum3 = sum3 * Z + 793.826512519948;
        sum3 = sum3 * Z + 440.413735824752;
        cd2 = cd2 / sum3;
      } else {
        sum3 = Z + 0.65;
        sum3 = Z + 4 / sum3;
        sum3 = Z + 3 / sum3;
        sum3 = Z + 2 / sum3;
        sum3 = Z + 1 / sum3;
        cd2 = exp4 / sum3 / 2.506628274631;
      }
    }
    return z > 0 ? 1 - cd2 : cd2;
  }
  function quantileNormal(p2, mean2, stdev) {
    if (p2 < 0 || p2 > 1) return NaN;
    return (mean2 || 0) + (stdev == null ? 1 : stdev) * SQRT2 * erfinv(2 * p2 - 1);
  }
  function erfinv(x5) {
    let w3 = -Math.log((1 - x5) * (1 + x5)), p2;
    if (w3 < 6.25) {
      w3 -= 3.125;
      p2 = -364441206401782e-35;
      p2 = -16850591381820166e-35 + p2 * w3;
      p2 = 128584807152564e-32 + p2 * w3;
      p2 = 11157877678025181e-33 + p2 * w3;
      p2 = -1333171662854621e-31 + p2 * w3;
      p2 = 20972767875968562e-33 + p2 * w3;
      p2 = 6637638134358324e-30 + p2 * w3;
      p2 = -4054566272975207e-29 + p2 * w3;
      p2 = -8151934197605472e-29 + p2 * w3;
      p2 = 26335093153082323e-28 + p2 * w3;
      p2 = -12975133253453532e-27 + p2 * w3;
      p2 = -5415412054294628e-26 + p2 * w3;
      p2 = 10512122733215323e-25 + p2 * w3;
      p2 = -4112633980346984e-24 + p2 * w3;
      p2 = -29070369957882005e-24 + p2 * w3;
      p2 = 42347877827932404e-23 + p2 * w3;
      p2 = -13654692000834679e-22 + p2 * w3;
      p2 = -13882523362786469e-21 + p2 * w3;
      p2 = 18673420803405714e-20 + p2 * w3;
      p2 = -740702534166267e-18 + p2 * w3;
      p2 = -0.006033670871430149 + p2 * w3;
      p2 = 0.24015818242558962 + p2 * w3;
      p2 = 1.6536545626831027 + p2 * w3;
    } else if (w3 < 16) {
      w3 = Math.sqrt(w3) - 3.25;
      p2 = 22137376921775787e-25;
      p2 = 9075656193888539e-23 + p2 * w3;
      p2 = -27517406297064545e-23 + p2 * w3;
      p2 = 18239629214389228e-24 + p2 * w3;
      p2 = 15027403968909828e-22 + p2 * w3;
      p2 = -4013867526981546e-21 + p2 * w3;
      p2 = 29234449089955446e-22 + p2 * w3;
      p2 = 12475304481671779e-21 + p2 * w3;
      p2 = -47318229009055734e-21 + p2 * w3;
      p2 = 6828485145957318e-20 + p2 * w3;
      p2 = 24031110387097894e-21 + p2 * w3;
      p2 = -3550375203628475e-19 + p2 * w3;
      p2 = 9532893797373805e-19 + p2 * w3;
      p2 = -0.0016882755560235047 + p2 * w3;
      p2 = 0.002491442096107851 + p2 * w3;
      p2 = -0.003751208507569241 + p2 * w3;
      p2 = 0.005370914553590064 + p2 * w3;
      p2 = 1.0052589676941592 + p2 * w3;
      p2 = 3.0838856104922208 + p2 * w3;
    } else if (Number.isFinite(w3)) {
      w3 = Math.sqrt(w3) - 5;
      p2 = -27109920616438573e-27;
      p2 = -2555641816996525e-25 + p2 * w3;
      p2 = 15076572693500548e-25 + p2 * w3;
      p2 = -3789465440126737e-24 + p2 * w3;
      p2 = 761570120807834e-23 + p2 * w3;
      p2 = -1496002662714924e-23 + p2 * w3;
      p2 = 2914795345090108e-23 + p2 * w3;
      p2 = -6771199775845234e-23 + p2 * w3;
      p2 = 22900482228026655e-23 + p2 * w3;
      p2 = -99298272942317e-20 + p2 * w3;
      p2 = 4526062597223154e-21 + p2 * w3;
      p2 = -1968177810553167e-20 + p2 * w3;
      p2 = 7599527703001776e-20 + p2 * w3;
      p2 = -21503011930044477e-20 + p2 * w3;
      p2 = -13871931833623122e-20 + p2 * w3;
      p2 = 1.0103004648645344 + p2 * w3;
      p2 = 4.849906401408584 + p2 * w3;
    } else {
      p2 = Infinity;
    }
    return p2 * x5;
  }
  function gaussian(mean2, stdev) {
    let mu, sigma;
    const dist2 = {
      mean(_) {
        if (arguments.length) {
          mu = _ || 0;
          return dist2;
        } else {
          return mu;
        }
      },
      stdev(_) {
        if (arguments.length) {
          sigma = _ == null ? 1 : _;
          return dist2;
        } else {
          return sigma;
        }
      },
      sample: () => sampleNormal(mu, sigma),
      pdf: (value3) => densityNormal(value3, mu, sigma),
      cdf: (value3) => cumulativeNormal(value3, mu, sigma),
      icdf: (p2) => quantileNormal(p2, mu, sigma)
    };
    return dist2.mean(mean2).stdev(stdev);
  }
  function kde(support, bandwidth2) {
    const kernel = gaussian();
    let n2 = 0;
    const dist2 = {
      data(_) {
        if (arguments.length) {
          support = _;
          n2 = _ ? _.length : 0;
          return dist2.bandwidth(bandwidth2);
        } else {
          return support;
        }
      },
      bandwidth(_) {
        if (!arguments.length) return bandwidth2;
        bandwidth2 = _;
        if (!bandwidth2 && support) bandwidth2 = estimateBandwidth(support);
        return dist2;
      },
      sample() {
        return support[~~(random() * n2)] + bandwidth2 * kernel.sample();
      },
      pdf(x5) {
        let y5 = 0, i2 = 0;
        for (; i2 < n2; ++i2) {
          y5 += kernel.pdf((x5 - support[i2]) / bandwidth2);
        }
        return y5 / bandwidth2 / n2;
      },
      cdf(x5) {
        let y5 = 0, i2 = 0;
        for (; i2 < n2; ++i2) {
          y5 += kernel.cdf((x5 - support[i2]) / bandwidth2);
        }
        return y5 / n2;
      },
      icdf() {
        throw Error("KDE icdf not supported.");
      }
    };
    return dist2.data(support);
  }
  function sampleLogNormal(mean2, stdev) {
    mean2 = mean2 || 0;
    stdev = stdev == null ? 1 : stdev;
    return Math.exp(mean2 + sampleNormal() * stdev);
  }
  function densityLogNormal(value3, mean2, stdev) {
    if (value3 <= 0) return 0;
    mean2 = mean2 || 0;
    stdev = stdev == null ? 1 : stdev;
    const z = (Math.log(value3) - mean2) / stdev;
    return Math.exp(-0.5 * z * z) / (stdev * SQRT2PI * value3);
  }
  function cumulativeLogNormal(value3, mean2, stdev) {
    return cumulativeNormal(Math.log(value3), mean2, stdev);
  }
  function quantileLogNormal(p2, mean2, stdev) {
    return Math.exp(quantileNormal(p2, mean2, stdev));
  }
  function lognormal(mean2, stdev) {
    let mu, sigma;
    const dist2 = {
      mean(_) {
        if (arguments.length) {
          mu = _ || 0;
          return dist2;
        } else {
          return mu;
        }
      },
      stdev(_) {
        if (arguments.length) {
          sigma = _ == null ? 1 : _;
          return dist2;
        } else {
          return sigma;
        }
      },
      sample: () => sampleLogNormal(mu, sigma),
      pdf: (value3) => densityLogNormal(value3, mu, sigma),
      cdf: (value3) => cumulativeLogNormal(value3, mu, sigma),
      icdf: (p2) => quantileLogNormal(p2, mu, sigma)
    };
    return dist2.mean(mean2).stdev(stdev);
  }
  function mixture(dists, weights) {
    let m4 = 0, w3;
    function normalize4(x5) {
      const w4 = [];
      let sum3 = 0, i2;
      for (i2 = 0; i2 < m4; ++i2) {
        sum3 += w4[i2] = x5[i2] == null ? 1 : +x5[i2];
      }
      for (i2 = 0; i2 < m4; ++i2) {
        w4[i2] /= sum3;
      }
      return w4;
    }
    const dist2 = {
      weights(_) {
        if (arguments.length) {
          w3 = normalize4(weights = _ || []);
          return dist2;
        }
        return weights;
      },
      distributions(_) {
        if (arguments.length) {
          if (_) {
            m4 = _.length;
            dists = _;
          } else {
            m4 = 0;
            dists = [];
          }
          return dist2.weights(weights);
        }
        return dists;
      },
      sample() {
        const r2 = random();
        let d2 = dists[m4 - 1], v3 = w3[0], i2 = 0;
        for (; i2 < m4 - 1; v3 += w3[++i2]) {
          if (r2 < v3) {
            d2 = dists[i2];
            break;
          }
        }
        return d2.sample();
      },
      pdf(x5) {
        let p2 = 0, i2 = 0;
        for (; i2 < m4; ++i2) {
          p2 += w3[i2] * dists[i2].pdf(x5);
        }
        return p2;
      },
      cdf(x5) {
        let p2 = 0, i2 = 0;
        for (; i2 < m4; ++i2) {
          p2 += w3[i2] * dists[i2].cdf(x5);
        }
        return p2;
      },
      icdf() {
        throw Error("Mixture icdf not supported.");
      }
    };
    return dist2.distributions(dists).weights(weights);
  }
  function sampleUniform(min4, max4) {
    if (max4 == null) {
      max4 = min4 == null ? 1 : min4;
      min4 = 0;
    }
    return min4 + (max4 - min4) * random();
  }
  function densityUniform(value3, min4, max4) {
    if (max4 == null) {
      max4 = min4 == null ? 1 : min4;
      min4 = 0;
    }
    return value3 >= min4 && value3 <= max4 ? 1 / (max4 - min4) : 0;
  }
  function cumulativeUniform(value3, min4, max4) {
    if (max4 == null) {
      max4 = min4 == null ? 1 : min4;
      min4 = 0;
    }
    return value3 < min4 ? 0 : value3 > max4 ? 1 : (value3 - min4) / (max4 - min4);
  }
  function quantileUniform(p2, min4, max4) {
    if (max4 == null) {
      max4 = min4 == null ? 1 : min4;
      min4 = 0;
    }
    return p2 >= 0 && p2 <= 1 ? min4 + p2 * (max4 - min4) : NaN;
  }
  function uniform(min4, max4) {
    let a4, b3;
    const dist2 = {
      min(_) {
        if (arguments.length) {
          a4 = _ || 0;
          return dist2;
        } else {
          return a4;
        }
      },
      max(_) {
        if (arguments.length) {
          b3 = _ == null ? 1 : _;
          return dist2;
        } else {
          return b3;
        }
      },
      sample: () => sampleUniform(a4, b3),
      pdf: (value3) => densityUniform(value3, a4, b3),
      cdf: (value3) => cumulativeUniform(value3, a4, b3),
      icdf: (p2) => quantileUniform(p2, a4, b3)
    };
    if (max4 == null) {
      max4 = min4 == null ? 1 : min4;
      min4 = 0;
    }
    return dist2.min(min4).max(max4);
  }
  function constant2(data3, x5, y5) {
    let mean2 = 0, n2 = 0;
    for (const d2 of data3) {
      const val = y5(d2);
      if (x5(d2) == null || val == null || isNaN(val)) continue;
      mean2 += (val - mean2) / ++n2;
    }
    return {
      coef: [mean2],
      predict: () => mean2,
      rSquared: 0
    };
  }
  function ols(uX, uY, uXY, uX2) {
    const delta = uX2 - uX * uX, slope = Math.abs(delta) < 1e-24 ? 0 : (uXY - uX * uY) / delta, intercept = uY - slope * uX;
    return [intercept, slope];
  }
  function points(data3, x5, y5, sort3) {
    data3 = data3.filter((d3) => {
      let u5 = x5(d3), v3 = y5(d3);
      return u5 != null && (u5 = +u5) >= u5 && v3 != null && (v3 = +v3) >= v3;
    });
    if (sort3) {
      data3.sort((a4, b3) => x5(a4) - x5(b3));
    }
    const n2 = data3.length, X4 = new Float64Array(n2), Y4 = new Float64Array(n2);
    let i2 = 0, ux = 0, uy = 0, xv, yv, d2;
    for (d2 of data3) {
      X4[i2] = xv = +x5(d2);
      Y4[i2] = yv = +y5(d2);
      ++i2;
      ux += (xv - ux) / i2;
      uy += (yv - uy) / i2;
    }
    for (i2 = 0; i2 < n2; ++i2) {
      X4[i2] -= ux;
      Y4[i2] -= uy;
    }
    return [X4, Y4, ux, uy];
  }
  function visitPoints(data3, x5, y5, callback) {
    let i2 = -1, u5, v3;
    for (const d2 of data3) {
      u5 = x5(d2);
      v3 = y5(d2);
      if (u5 != null && (u5 = +u5) >= u5 && v3 != null && (v3 = +v3) >= v3) {
        callback(u5, v3, ++i2);
      }
    }
  }
  function rSquared(data3, x5, y5, uY, predict) {
    let SSE = 0, SST = 0;
    visitPoints(data3, x5, y5, (dx, dy) => {
      const sse = dy - predict(dx), sst = dy - uY;
      SSE += sse * sse;
      SST += sst * sst;
    });
    return 1 - SSE / SST;
  }
  function linear(data3, x5, y5) {
    let X4 = 0, Y4 = 0, XY = 0, X24 = 0, n2 = 0;
    visitPoints(data3, x5, y5, (dx, dy) => {
      ++n2;
      X4 += (dx - X4) / n2;
      Y4 += (dy - Y4) / n2;
      XY += (dx * dy - XY) / n2;
      X24 += (dx * dx - X24) / n2;
    });
    const coef = ols(X4, Y4, XY, X24), predict = (x6) => coef[0] + coef[1] * x6;
    return {
      coef,
      predict,
      rSquared: rSquared(data3, x5, y5, Y4, predict)
    };
  }
  function log2(data3, x5, y5) {
    let X4 = 0, Y4 = 0, XY = 0, X24 = 0, n2 = 0;
    visitPoints(data3, x5, y5, (dx, dy) => {
      ++n2;
      dx = Math.log(dx);
      X4 += (dx - X4) / n2;
      Y4 += (dy - Y4) / n2;
      XY += (dx * dy - XY) / n2;
      X24 += (dx * dx - X24) / n2;
    });
    const coef = ols(X4, Y4, XY, X24), predict = (x6) => coef[0] + coef[1] * Math.log(x6);
    return {
      coef,
      predict,
      rSquared: rSquared(data3, x5, y5, Y4, predict)
    };
  }
  function exp2(data3, x5, y5) {
    const [xv, yv, ux, uy] = points(data3, x5, y5);
    let YL = 0, XY = 0, XYL = 0, X2Y = 0, n2 = 0, dx, ly2, xy;
    visitPoints(data3, x5, y5, (_, dy) => {
      dx = xv[n2++];
      ly2 = Math.log(dy);
      xy = dx * dy;
      YL += (dy * ly2 - YL) / n2;
      XY += (xy - XY) / n2;
      XYL += (xy * ly2 - XYL) / n2;
      X2Y += (dx * xy - X2Y) / n2;
    });
    const [c0, c1] = ols(XY / uy, YL / uy, XYL / uy, X2Y / uy), predict = (x6) => Math.exp(c0 + c1 * (x6 - ux));
    return {
      coef: [Math.exp(c0 - c1 * ux), c1],
      predict,
      rSquared: rSquared(data3, x5, y5, uy, predict)
    };
  }
  function pow2(data3, x5, y5) {
    let X4 = 0, Y4 = 0, XY = 0, X24 = 0, YS = 0, n2 = 0;
    visitPoints(data3, x5, y5, (dx, dy) => {
      const lx2 = Math.log(dx), ly2 = Math.log(dy);
      ++n2;
      X4 += (lx2 - X4) / n2;
      Y4 += (ly2 - Y4) / n2;
      XY += (lx2 * ly2 - XY) / n2;
      X24 += (lx2 * lx2 - X24) / n2;
      YS += (dy - YS) / n2;
    });
    const coef = ols(X4, Y4, XY, X24), predict = (x6) => coef[0] * Math.pow(x6, coef[1]);
    coef[0] = Math.exp(coef[0]);
    return {
      coef,
      predict,
      rSquared: rSquared(data3, x5, y5, YS, predict)
    };
  }
  function quad(data3, x5, y5) {
    const [xv, yv, ux, uy] = points(data3, x5, y5), n2 = xv.length;
    let X24 = 0, X32 = 0, X4 = 0, XY = 0, X2Y = 0, i2, dx, dy, x22;
    for (i2 = 0; i2 < n2; ) {
      dx = xv[i2];
      dy = yv[i2++];
      x22 = dx * dx;
      X24 += (x22 - X24) / i2;
      X32 += (x22 * dx - X32) / i2;
      X4 += (x22 * x22 - X4) / i2;
      XY += (dx * dy - XY) / i2;
      X2Y += (x22 * dy - X2Y) / i2;
    }
    const X2X2 = X4 - X24 * X24, d2 = X24 * X2X2 - X32 * X32, a4 = (X2Y * X24 - XY * X32) / d2, b3 = (XY * X2X2 - X2Y * X32) / d2, c4 = -a4 * X24, predict = (x6) => {
      x6 = x6 - ux;
      return a4 * x6 * x6 + b3 * x6 + c4 + uy;
    };
    return {
      coef: [c4 - b3 * ux + a4 * ux * ux + uy, b3 - 2 * a4 * ux, a4],
      predict,
      rSquared: rSquared(data3, x5, y5, uy, predict)
    };
  }
  function poly(data3, x5, y5, order) {
    if (order === 0) return constant2(data3, x5, y5);
    if (order === 1) return linear(data3, x5, y5);
    if (order === 2) return quad(data3, x5, y5);
    const [xv, yv, ux, uy] = points(data3, x5, y5), n2 = xv.length, lhs = [], rhs = [], k2 = order + 1;
    let i2, j2, l2, v3, c4;
    for (i2 = 0; i2 < k2; ++i2) {
      for (l2 = 0, v3 = 0; l2 < n2; ++l2) {
        v3 += Math.pow(xv[l2], i2) * yv[l2];
      }
      lhs.push(v3);
      c4 = new Float64Array(k2);
      for (j2 = 0; j2 < k2; ++j2) {
        for (l2 = 0, v3 = 0; l2 < n2; ++l2) {
          v3 += Math.pow(xv[l2], i2 + j2);
        }
        c4[j2] = v3;
      }
      rhs.push(c4);
    }
    rhs.push(lhs);
    const coef = gaussianElimination(rhs), predict = (x6) => {
      x6 -= ux;
      let y6 = uy + coef[0] + coef[1] * x6 + coef[2] * x6 * x6;
      for (i2 = 3; i2 < k2; ++i2) y6 += coef[i2] * Math.pow(x6, i2);
      return y6;
    };
    return {
      coef: uncenter(k2, coef, -ux, uy),
      predict,
      rSquared: rSquared(data3, x5, y5, uy, predict)
    };
  }
  function uncenter(k2, a4, x5, y5) {
    const z = Array(k2);
    let i2, j2, v3, c4;
    for (i2 = 0; i2 < k2; ++i2) z[i2] = 0;
    for (i2 = k2 - 1; i2 >= 0; --i2) {
      v3 = a4[i2];
      c4 = 1;
      z[i2] += v3;
      for (j2 = 1; j2 <= i2; ++j2) {
        c4 *= (i2 + 1 - j2) / j2;
        z[i2 - j2] += v3 * Math.pow(x5, j2) * c4;
      }
    }
    z[0] += y5;
    return z;
  }
  function gaussianElimination(matrix) {
    const n2 = matrix.length - 1, coef = [];
    let i2, j2, k2, r2, t4;
    for (i2 = 0; i2 < n2; ++i2) {
      r2 = i2;
      for (j2 = i2 + 1; j2 < n2; ++j2) {
        if (Math.abs(matrix[i2][j2]) > Math.abs(matrix[i2][r2])) {
          r2 = j2;
        }
      }
      for (k2 = i2; k2 < n2 + 1; ++k2) {
        t4 = matrix[k2][i2];
        matrix[k2][i2] = matrix[k2][r2];
        matrix[k2][r2] = t4;
      }
      for (j2 = i2 + 1; j2 < n2; ++j2) {
        for (k2 = n2; k2 >= i2; k2--) {
          matrix[k2][j2] -= matrix[k2][i2] * matrix[i2][j2] / matrix[i2][i2];
        }
      }
    }
    for (j2 = n2 - 1; j2 >= 0; --j2) {
      t4 = 0;
      for (k2 = j2 + 1; k2 < n2; ++k2) {
        t4 += matrix[k2][j2] * coef[k2];
      }
      coef[j2] = (matrix[n2][j2] - t4) / matrix[j2][j2];
    }
    return coef;
  }
  var maxiters = 2;
  var epsilon = 1e-12;
  function loess(data3, x5, y5, bandwidth2) {
    const [xv, yv, ux, uy] = points(data3, x5, y5, true), n2 = xv.length, bw = Math.max(2, ~~(bandwidth2 * n2)), yhat = new Float64Array(n2), residuals = new Float64Array(n2), robustWeights = new Float64Array(n2).fill(1);
    for (let iter = -1; ++iter <= maxiters; ) {
      const interval3 = [0, bw - 1];
      for (let i2 = 0; i2 < n2; ++i2) {
        const dx = xv[i2], i0 = interval3[0], i1 = interval3[1], edge = dx - xv[i0] > xv[i1] - dx ? i0 : i1;
        let W = 0, X4 = 0, Y4 = 0, XY = 0, X24 = 0;
        const denom = 1 / Math.abs(xv[edge] - dx || 1);
        for (let k2 = i0; k2 <= i1; ++k2) {
          const xk = xv[k2], yk = yv[k2], w3 = tricube(Math.abs(dx - xk) * denom) * robustWeights[k2], xkw = xk * w3;
          W += w3;
          X4 += xkw;
          Y4 += yk * w3;
          XY += yk * xkw;
          X24 += xk * xkw;
        }
        const [a4, b3] = ols(X4 / W, Y4 / W, XY / W, X24 / W);
        yhat[i2] = a4 + b3 * dx;
        residuals[i2] = Math.abs(yv[i2] - yhat[i2]);
        updateInterval(xv, i2 + 1, interval3);
      }
      if (iter === maxiters) {
        break;
      }
      const medianResidual = median(residuals);
      if (Math.abs(medianResidual) < epsilon) break;
      for (let i2 = 0, arg, w3; i2 < n2; ++i2) {
        arg = residuals[i2] / (6 * medianResidual);
        robustWeights[i2] = arg >= 1 ? epsilon : (w3 = 1 - arg * arg) * w3;
      }
    }
    return output(xv, yhat, ux, uy);
  }
  function tricube(x5) {
    return (x5 = 1 - x5 * x5 * x5) * x5 * x5;
  }
  function updateInterval(xv, i2, interval3) {
    const val = xv[i2];
    let left = interval3[0], right = interval3[1] + 1;
    if (right >= xv.length) return;
    while (i2 > left && xv[right] - val <= val - xv[left]) {
      interval3[0] = ++left;
      interval3[1] = right;
      ++right;
    }
  }
  function output(xv, yhat, ux, uy) {
    const n2 = xv.length, out = [];
    let i2 = 0, cnt = 0, prev = [], v3;
    for (; i2 < n2; ++i2) {
      v3 = xv[i2] + ux;
      if (prev[0] === v3) {
        prev[1] += (yhat[i2] - prev[1]) / ++cnt;
      } else {
        cnt = 0;
        prev[1] += uy;
        prev = [v3, yhat[i2]];
        out.push(prev);
      }
    }
    prev[1] += uy;
    return out;
  }
  var MIN_RADIANS = 0.5 * Math.PI / 180;
  function sampleCurve(f2, extent2, minSteps, maxSteps) {
    minSteps = minSteps || 25;
    maxSteps = Math.max(minSteps, maxSteps || 200);
    const point9 = (x5) => [x5, f2(x5)], minX = extent2[0], maxX = extent2[1], span2 = maxX - minX, stop2 = span2 / maxSteps, prev = [point9(minX)], next = [];
    if (minSteps === maxSteps) {
      for (let i2 = 1; i2 < maxSteps; ++i2) {
        prev.push(point9(minX + i2 / minSteps * span2));
      }
      prev.push(point9(maxX));
      return prev;
    } else {
      next.push(point9(maxX));
      for (let i2 = minSteps; --i2 > 0; ) {
        next.push(point9(minX + i2 / minSteps * span2));
      }
    }
    let p02 = prev[0];
    let p1 = next[next.length - 1];
    const sx = 1 / span2;
    const sy = scaleY(p02[1], next);
    while (p1) {
      const pm = point9((p02[0] + p1[0]) / 2);
      const dx = pm[0] - p02[0] >= stop2;
      if (dx && angleDelta(p02, pm, p1, sx, sy) > MIN_RADIANS) {
        next.push(pm);
      } else {
        p02 = p1;
        prev.push(p1);
        next.pop();
      }
      p1 = next[next.length - 1];
    }
    return prev;
  }
  function scaleY(init2, points2) {
    let ymin = init2;
    let ymax = init2;
    const n2 = points2.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      const y5 = points2[i2][1];
      if (y5 < ymin) ymin = y5;
      if (y5 > ymax) ymax = y5;
    }
    return 1 / (ymax - ymin);
  }
  function angleDelta(p2, q2, r2, sx, sy) {
    const a0 = Math.atan2(sy * (r2[1] - p2[1]), sx * (r2[0] - p2[0])), a1 = Math.atan2(sy * (q2[1] - p2[1]), sx * (q2[0] - p2[0]));
    return Math.abs(a0 - a1);
  }

  // node_modules/vega-transforms/build/vega-transforms.module.js
  function multikey(f2) {
    return (x5) => {
      const n2 = f2.length;
      let i2 = 1, k2 = String(f2[0](x5));
      for (; i2 < n2; ++i2) {
        k2 += "|" + f2[i2](x5);
      }
      return k2;
    };
  }
  function groupkey(fields) {
    return !fields || !fields.length ? function() {
      return "";
    } : fields.length === 1 ? fields[0] : multikey(fields);
  }
  function measureName(op, field3, as) {
    return as || op + (!field3 ? "" : "_" + field3);
  }
  var noop = () => {
  };
  var base_op = {
    init: noop,
    add: noop,
    rem: noop,
    idx: 0
  };
  var AggregateOps = {
    values: {
      init: (m4) => m4.cell.store = true,
      value: (m4) => m4.cell.data.values(),
      idx: -1
    },
    count: {
      value: (m4) => m4.cell.num
    },
    __count__: {
      value: (m4) => m4.missing + m4.valid
    },
    missing: {
      value: (m4) => m4.missing
    },
    valid: {
      value: (m4) => m4.valid
    },
    sum: {
      init: (m4) => m4.sum = 0,
      value: (m4) => m4.valid ? m4.sum : void 0,
      add: (m4, v3) => m4.sum += +v3,
      rem: (m4, v3) => m4.sum -= v3
    },
    product: {
      init: (m4) => m4.product = 1,
      value: (m4) => m4.valid ? m4.product : void 0,
      add: (m4, v3) => m4.product *= v3,
      rem: (m4, v3) => m4.product /= v3
    },
    mean: {
      init: (m4) => m4.mean = 0,
      value: (m4) => m4.valid ? m4.mean : void 0,
      add: (m4, v3) => (m4.mean_d = v3 - m4.mean, m4.mean += m4.mean_d / m4.valid),
      rem: (m4, v3) => (m4.mean_d = v3 - m4.mean, m4.mean -= m4.valid ? m4.mean_d / m4.valid : m4.mean)
    },
    average: {
      value: (m4) => m4.valid ? m4.mean : void 0,
      req: ["mean"],
      idx: 1
    },
    variance: {
      init: (m4) => m4.dev = 0,
      value: (m4) => m4.valid > 1 ? m4.dev / (m4.valid - 1) : void 0,
      add: (m4, v3) => m4.dev += m4.mean_d * (v3 - m4.mean),
      rem: (m4, v3) => m4.dev -= m4.mean_d * (v3 - m4.mean),
      req: ["mean"],
      idx: 1
    },
    variancep: {
      value: (m4) => m4.valid > 1 ? m4.dev / m4.valid : void 0,
      req: ["variance"],
      idx: 2
    },
    stdev: {
      value: (m4) => m4.valid > 1 ? Math.sqrt(m4.dev / (m4.valid - 1)) : void 0,
      req: ["variance"],
      idx: 2
    },
    stdevp: {
      value: (m4) => m4.valid > 1 ? Math.sqrt(m4.dev / m4.valid) : void 0,
      req: ["variance"],
      idx: 2
    },
    stderr: {
      value: (m4) => m4.valid > 1 ? Math.sqrt(m4.dev / (m4.valid * (m4.valid - 1))) : void 0,
      req: ["variance"],
      idx: 2
    },
    distinct: {
      value: (m4) => m4.cell.data.distinct(m4.get),
      req: ["values"],
      idx: 3
    },
    ci0: {
      value: (m4) => m4.cell.data.ci0(m4.get),
      req: ["values"],
      idx: 3
    },
    ci1: {
      value: (m4) => m4.cell.data.ci1(m4.get),
      req: ["values"],
      idx: 3
    },
    median: {
      value: (m4) => m4.cell.data.q2(m4.get),
      req: ["values"],
      idx: 3
    },
    q1: {
      value: (m4) => m4.cell.data.q1(m4.get),
      req: ["values"],
      idx: 3
    },
    q3: {
      value: (m4) => m4.cell.data.q3(m4.get),
      req: ["values"],
      idx: 3
    },
    min: {
      init: (m4) => m4.min = void 0,
      value: (m4) => m4.min = Number.isNaN(m4.min) ? m4.cell.data.min(m4.get) : m4.min,
      add: (m4, v3) => {
        if (v3 < m4.min || m4.min === void 0) m4.min = v3;
      },
      rem: (m4, v3) => {
        if (v3 <= m4.min) m4.min = NaN;
      },
      req: ["values"],
      idx: 4
    },
    max: {
      init: (m4) => m4.max = void 0,
      value: (m4) => m4.max = Number.isNaN(m4.max) ? m4.cell.data.max(m4.get) : m4.max,
      add: (m4, v3) => {
        if (v3 > m4.max || m4.max === void 0) m4.max = v3;
      },
      rem: (m4, v3) => {
        if (v3 >= m4.max) m4.max = NaN;
      },
      req: ["values"],
      idx: 4
    },
    argmin: {
      init: (m4) => m4.argmin = void 0,
      value: (m4) => m4.argmin || m4.cell.data.argmin(m4.get),
      add: (m4, v3, t4) => {
        if (v3 < m4.min) m4.argmin = t4;
      },
      rem: (m4, v3) => {
        if (v3 <= m4.min) m4.argmin = void 0;
      },
      req: ["min", "values"],
      idx: 3
    },
    argmax: {
      init: (m4) => m4.argmax = void 0,
      value: (m4) => m4.argmax || m4.cell.data.argmax(m4.get),
      add: (m4, v3, t4) => {
        if (v3 > m4.max) m4.argmax = t4;
      },
      rem: (m4, v3) => {
        if (v3 >= m4.max) m4.argmax = void 0;
      },
      req: ["max", "values"],
      idx: 3
    },
    exponential: {
      init: (m4, r2) => {
        m4.exp = 0;
        m4.exp_r = r2;
      },
      value: (m4) => m4.valid ? m4.exp * (1 - m4.exp_r) / (1 - m4.exp_r ** m4.valid) : void 0,
      add: (m4, v3) => m4.exp = m4.exp_r * m4.exp + v3,
      rem: (m4, v3) => m4.exp = (m4.exp - v3 / m4.exp_r ** (m4.valid - 1)) / m4.exp_r
    },
    exponentialb: {
      value: (m4) => m4.valid ? m4.exp * (1 - m4.exp_r) : void 0,
      req: ["exponential"],
      idx: 1
    }
  };
  var ValidAggregateOps = Object.keys(AggregateOps).filter((d2) => d2 !== "__count__");
  function measure(key2, value3) {
    return (out, aggregate_param) => extend({
      name: key2,
      aggregate_param,
      out: out || key2
    }, base_op, value3);
  }
  [...ValidAggregateOps, "__count__"].forEach((key2) => {
    AggregateOps[key2] = measure(key2, AggregateOps[key2]);
  });
  function createMeasure(op, param2, name4) {
    return AggregateOps[op](name4, param2);
  }
  function compareIndex(a4, b3) {
    return a4.idx - b3.idx;
  }
  function resolve(agg) {
    const map4 = {};
    agg.forEach((a4) => map4[a4.name] = a4);
    const getreqs = (a4) => {
      if (!a4.req) return;
      a4.req.forEach((key2) => {
        if (!map4[key2]) getreqs(map4[key2] = AggregateOps[key2]());
      });
    };
    agg.forEach(getreqs);
    return Object.values(map4).sort(compareIndex);
  }
  function init() {
    this.valid = 0;
    this.missing = 0;
    this._ops.forEach((op) => op.aggregate_param == null ? op.init(this) : op.init(this, op.aggregate_param));
  }
  function add2(v3, t4) {
    if (v3 == null || v3 === "") {
      ++this.missing;
      return;
    }
    if (v3 !== v3) return;
    ++this.valid;
    this._ops.forEach((op) => op.add(this, v3, t4));
  }
  function rem(v3, t4) {
    if (v3 == null || v3 === "") {
      --this.missing;
      return;
    }
    if (v3 !== v3) return;
    --this.valid;
    this._ops.forEach((op) => op.rem(this, v3, t4));
  }
  function set2(t4) {
    this._out.forEach((op) => t4[op.out] = op.value(this));
    return t4;
  }
  function compileMeasures(agg, field3) {
    const get6 = field3 || identity, ops2 = resolve(agg), out = agg.slice().sort(compareIndex);
    function ctr(cell2) {
      this._ops = ops2;
      this._out = out;
      this.cell = cell2;
      this.init();
    }
    ctr.prototype.init = init;
    ctr.prototype.add = add2;
    ctr.prototype.rem = rem;
    ctr.prototype.set = set2;
    ctr.prototype.get = get6;
    ctr.fields = agg.map((op) => op.out);
    return ctr;
  }
  function TupleStore(key2) {
    this._key = key2 ? field(key2) : tupleid;
    this.reset();
  }
  var prototype$1 = TupleStore.prototype;
  prototype$1.reset = function() {
    this._add = [];
    this._rem = [];
    this._ext = null;
    this._get = null;
    this._q = null;
  };
  prototype$1.add = function(v3) {
    this._add.push(v3);
  };
  prototype$1.rem = function(v3) {
    this._rem.push(v3);
  };
  prototype$1.values = function() {
    this._get = null;
    if (this._rem.length === 0) return this._add;
    const a4 = this._add, r2 = this._rem, k2 = this._key, n2 = a4.length, m4 = r2.length, x5 = Array(n2 - m4), map4 = {};
    let i2, j2, v3;
    for (i2 = 0; i2 < m4; ++i2) {
      map4[k2(r2[i2])] = 1;
    }
    for (i2 = 0, j2 = 0; i2 < n2; ++i2) {
      if (map4[k2(v3 = a4[i2])]) {
        map4[k2(v3)] = 0;
      } else {
        x5[j2++] = v3;
      }
    }
    this._rem = [];
    return this._add = x5;
  };
  prototype$1.distinct = function(get6) {
    const v3 = this.values(), map4 = {};
    let n2 = v3.length, count2 = 0, s2;
    while (--n2 >= 0) {
      s2 = get6(v3[n2]) + "";
      if (!has(map4, s2)) {
        map4[s2] = 1;
        ++count2;
      }
    }
    return count2;
  };
  prototype$1.extent = function(get6) {
    if (this._get !== get6 || !this._ext) {
      const v3 = this.values(), i2 = extentIndex(v3, get6);
      this._ext = [v3[i2[0]], v3[i2[1]]];
      this._get = get6;
    }
    return this._ext;
  };
  prototype$1.argmin = function(get6) {
    return this.extent(get6)[0] || {};
  };
  prototype$1.argmax = function(get6) {
    return this.extent(get6)[1] || {};
  };
  prototype$1.min = function(get6) {
    const m4 = this.extent(get6)[0];
    return m4 != null ? get6(m4) : void 0;
  };
  prototype$1.max = function(get6) {
    const m4 = this.extent(get6)[1];
    return m4 != null ? get6(m4) : void 0;
  };
  prototype$1.quartile = function(get6) {
    if (this._get !== get6 || !this._q) {
      this._q = quartiles(this.values(), get6);
      this._get = get6;
    }
    return this._q;
  };
  prototype$1.q1 = function(get6) {
    return this.quartile(get6)[0];
  };
  prototype$1.q2 = function(get6) {
    return this.quartile(get6)[1];
  };
  prototype$1.q3 = function(get6) {
    return this.quartile(get6)[2];
  };
  prototype$1.ci = function(get6) {
    if (this._get !== get6 || !this._ci) {
      this._ci = bootstrapCI(this.values(), 1e3, 0.05, get6);
      this._get = get6;
    }
    return this._ci;
  };
  prototype$1.ci0 = function(get6) {
    return this.ci(get6)[0];
  };
  prototype$1.ci1 = function(get6) {
    return this.ci(get6)[1];
  };
  function Aggregate(params2) {
    Transform.call(this, null, params2);
    this._adds = [];
    this._mods = [];
    this._alen = 0;
    this._mlen = 0;
    this._drop = true;
    this._cross = false;
    this._dims = [];
    this._dnames = [];
    this._measures = [];
    this._countOnly = false;
    this._counts = null;
    this._prev = null;
    this._inputs = null;
    this._outputs = null;
  }
  Aggregate.Definition = {
    "type": "Aggregate",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "ops",
      "type": "enum",
      "array": true,
      "values": ValidAggregateOps
    }, {
      "name": "aggregate_params",
      "type": "number",
      "null": true,
      "array": true
    }, {
      "name": "fields",
      "type": "field",
      "null": true,
      "array": true
    }, {
      "name": "as",
      "type": "string",
      "null": true,
      "array": true
    }, {
      "name": "drop",
      "type": "boolean",
      "default": true
    }, {
      "name": "cross",
      "type": "boolean",
      "default": false
    }, {
      "name": "key",
      "type": "field"
    }]
  };
  inherits(Aggregate, Transform, {
    transform(_, pulse2) {
      const aggr = this, out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), mod = _.modified();
      aggr.stamp = out.stamp;
      if (aggr.value && (mod || pulse2.modified(aggr._inputs, true))) {
        aggr._prev = aggr.value;
        aggr.value = mod ? aggr.init(_) : /* @__PURE__ */ Object.create(null);
        pulse2.visit(pulse2.SOURCE, (t4) => aggr.add(t4));
      } else {
        aggr.value = aggr.value || aggr.init(_);
        pulse2.visit(pulse2.REM, (t4) => aggr.rem(t4));
        pulse2.visit(pulse2.ADD, (t4) => aggr.add(t4));
      }
      out.modifies(aggr._outputs);
      aggr._drop = _.drop !== false;
      if (_.cross && aggr._dims.length > 1) {
        aggr._drop = false;
        aggr.cross();
      }
      if (pulse2.clean() && aggr._drop) {
        out.clean(true).runAfter(() => this.clean());
      }
      return aggr.changes(out);
    },
    cross() {
      const aggr = this, curr = aggr.value, dims = aggr._dnames, vals2 = dims.map(() => ({})), n2 = dims.length;
      function collect2(cells) {
        let key2, i2, t4, v3;
        for (key2 in cells) {
          t4 = cells[key2].tuple;
          for (i2 = 0; i2 < n2; ++i2) {
            vals2[i2][v3 = t4[dims[i2]]] = v3;
          }
        }
      }
      collect2(aggr._prev);
      collect2(curr);
      function generate3(base, tuple, index4) {
        const name4 = dims[index4], v3 = vals2[index4++];
        for (const k2 in v3) {
          const key2 = base ? base + "|" + k2 : k2;
          tuple[name4] = v3[k2];
          if (index4 < n2) generate3(key2, tuple, index4);
          else if (!curr[key2]) aggr.cell(key2, tuple);
        }
      }
      generate3("", {}, 0);
    },
    init(_) {
      const inputs = this._inputs = [], outputs = this._outputs = [], inputMap = {};
      function inputVisit(get6) {
        const fields2 = array(accessorFields(get6)), n3 = fields2.length;
        let i3 = 0, f2;
        for (; i3 < n3; ++i3) {
          if (!inputMap[f2 = fields2[i3]]) {
            inputMap[f2] = 1;
            inputs.push(f2);
          }
        }
      }
      this._dims = array(_.groupby);
      this._dnames = this._dims.map((d2) => {
        const dname = accessorName(d2);
        inputVisit(d2);
        outputs.push(dname);
        return dname;
      });
      this.cellkey = _.key ? _.key : groupkey(this._dims);
      this._countOnly = true;
      this._counts = [];
      this._measures = [];
      const fields = _.fields || [null], ops2 = _.ops || ["count"], aggregate_params = _.aggregate_params || [null], as = _.as || [], n2 = fields.length, map4 = {};
      let field3, op, aggregate_param, m4, mname, outname, i2;
      if (n2 !== ops2.length) {
        error("Unmatched number of fields and aggregate ops.");
      }
      for (i2 = 0; i2 < n2; ++i2) {
        field3 = fields[i2];
        op = ops2[i2];
        aggregate_param = aggregate_params[i2] || null;
        if (field3 == null && op !== "count") {
          error("Null aggregate field specified.");
        }
        mname = accessorName(field3);
        outname = measureName(op, mname, as[i2]);
        outputs.push(outname);
        if (op === "count") {
          this._counts.push(outname);
          continue;
        }
        m4 = map4[mname];
        if (!m4) {
          inputVisit(field3);
          m4 = map4[mname] = [];
          m4.field = field3;
          this._measures.push(m4);
        }
        if (op !== "count") this._countOnly = false;
        m4.push(createMeasure(op, aggregate_param, outname));
      }
      this._measures = this._measures.map((m5) => compileMeasures(m5, m5.field));
      return /* @__PURE__ */ Object.create(null);
    },
    // -- Cell Management -----
    cellkey: groupkey(),
    cell(key2, t4) {
      let cell2 = this.value[key2];
      if (!cell2) {
        cell2 = this.value[key2] = this.newcell(key2, t4);
        this._adds[this._alen++] = cell2;
      } else if (cell2.num === 0 && this._drop && cell2.stamp < this.stamp) {
        cell2.stamp = this.stamp;
        this._adds[this._alen++] = cell2;
      } else if (cell2.stamp < this.stamp) {
        cell2.stamp = this.stamp;
        this._mods[this._mlen++] = cell2;
      }
      return cell2;
    },
    newcell(key2, t4) {
      const cell2 = {
        key: key2,
        num: 0,
        agg: null,
        tuple: this.newtuple(t4, this._prev && this._prev[key2]),
        stamp: this.stamp,
        store: false
      };
      if (!this._countOnly) {
        const measures = this._measures, n2 = measures.length;
        cell2.agg = Array(n2);
        for (let i2 = 0; i2 < n2; ++i2) {
          cell2.agg[i2] = new measures[i2](cell2);
        }
      }
      if (cell2.store) {
        cell2.data = new TupleStore();
      }
      return cell2;
    },
    newtuple(t4, p2) {
      const names = this._dnames, dims = this._dims, n2 = dims.length, x5 = {};
      for (let i2 = 0; i2 < n2; ++i2) {
        x5[names[i2]] = dims[i2](t4);
      }
      return p2 ? replace(p2.tuple, x5) : ingest$1(x5);
    },
    clean() {
      const cells = this.value;
      for (const key2 in cells) {
        if (cells[key2].num === 0) {
          delete cells[key2];
        }
      }
    },
    // -- Process Tuples -----
    add(t4) {
      const key2 = this.cellkey(t4), cell2 = this.cell(key2, t4);
      cell2.num += 1;
      if (this._countOnly) return;
      if (cell2.store) cell2.data.add(t4);
      const agg = cell2.agg;
      for (let i2 = 0, n2 = agg.length; i2 < n2; ++i2) {
        agg[i2].add(agg[i2].get(t4), t4);
      }
    },
    rem(t4) {
      const key2 = this.cellkey(t4), cell2 = this.cell(key2, t4);
      cell2.num -= 1;
      if (this._countOnly) return;
      if (cell2.store) cell2.data.rem(t4);
      const agg = cell2.agg;
      for (let i2 = 0, n2 = agg.length; i2 < n2; ++i2) {
        agg[i2].rem(agg[i2].get(t4), t4);
      }
    },
    celltuple(cell2) {
      const tuple = cell2.tuple, counts = this._counts;
      if (cell2.store) {
        cell2.data.values();
      }
      for (let i2 = 0, n2 = counts.length; i2 < n2; ++i2) {
        tuple[counts[i2]] = cell2.num;
      }
      if (!this._countOnly) {
        const agg = cell2.agg;
        for (let i2 = 0, n2 = agg.length; i2 < n2; ++i2) {
          agg[i2].set(tuple);
        }
      }
      return tuple;
    },
    changes(out) {
      const adds = this._adds, mods = this._mods, prev = this._prev, drop = this._drop, add6 = out.add, rem2 = out.rem, mod = out.mod;
      let cell2, key2, i2, n2;
      if (prev) for (key2 in prev) {
        cell2 = prev[key2];
        if (!drop || cell2.num) rem2.push(cell2.tuple);
      }
      for (i2 = 0, n2 = this._alen; i2 < n2; ++i2) {
        add6.push(this.celltuple(adds[i2]));
        adds[i2] = null;
      }
      for (i2 = 0, n2 = this._mlen; i2 < n2; ++i2) {
        cell2 = mods[i2];
        (cell2.num === 0 && drop ? rem2 : mod).push(this.celltuple(cell2));
        mods[i2] = null;
      }
      this._alen = this._mlen = 0;
      this._prev = null;
      return out;
    }
  });
  var EPSILON$1 = 1e-14;
  function Bin(params2) {
    Transform.call(this, null, params2);
  }
  Bin.Definition = {
    "type": "Bin",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "interval",
      "type": "boolean",
      "default": true
    }, {
      "name": "anchor",
      "type": "number"
    }, {
      "name": "maxbins",
      "type": "number",
      "default": 20
    }, {
      "name": "base",
      "type": "number",
      "default": 10
    }, {
      "name": "divide",
      "type": "number",
      "array": true,
      "default": [5, 2]
    }, {
      "name": "extent",
      "type": "number",
      "array": true,
      "length": 2,
      "required": true
    }, {
      "name": "span",
      "type": "number"
    }, {
      "name": "step",
      "type": "number"
    }, {
      "name": "steps",
      "type": "number",
      "array": true
    }, {
      "name": "minstep",
      "type": "number",
      "default": 0
    }, {
      "name": "nice",
      "type": "boolean",
      "default": true
    }, {
      "name": "name",
      "type": "string"
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["bin0", "bin1"]
    }]
  };
  inherits(Bin, Transform, {
    transform(_, pulse2) {
      const band2 = _.interval !== false, bins2 = this._bins(_), start = bins2.start, step = bins2.step, as = _.as || ["bin0", "bin1"], b0 = as[0], b1 = as[1];
      let flag2;
      if (_.modified()) {
        pulse2 = pulse2.reflow(true);
        flag2 = pulse2.SOURCE;
      } else {
        flag2 = pulse2.modified(accessorFields(_.field)) ? pulse2.ADD_MOD : pulse2.ADD;
      }
      pulse2.visit(flag2, band2 ? (t4) => {
        const v3 = bins2(t4);
        t4[b0] = v3;
        t4[b1] = v3 == null ? null : start + step * (1 + (v3 - start) / step);
      } : (t4) => t4[b0] = bins2(t4));
      return pulse2.modifies(band2 ? as : b0);
    },
    _bins(_) {
      if (this.value && !_.modified()) {
        return this.value;
      }
      const field3 = _.field, bins2 = bin2(_), step = bins2.step;
      let start = bins2.start, stop2 = start + Math.ceil((bins2.stop - start) / step) * step, a4, d2;
      if ((a4 = _.anchor) != null) {
        d2 = a4 - (start + step * Math.floor((a4 - start) / step));
        start += d2;
        stop2 += d2;
      }
      const f2 = function(t4) {
        let v3 = toNumber(field3(t4));
        return v3 == null ? null : v3 < start ? -Infinity : v3 > stop2 ? Infinity : (v3 = Math.max(start, Math.min(v3, stop2 - step)), start + step * Math.floor(EPSILON$1 + (v3 - start) / step));
      };
      f2.start = start;
      f2.stop = bins2.stop;
      f2.step = step;
      return this.value = accessor(f2, accessorFields(field3), _.name || "bin_" + accessorName(field3));
    }
  });
  function SortedList(idFunc, source4, input) {
    const $2 = idFunc;
    let data3 = source4 || [], add6 = input || [], rem2 = {}, cnt = 0;
    return {
      add: (t4) => add6.push(t4),
      remove: (t4) => rem2[$2(t4)] = ++cnt,
      size: () => data3.length,
      data: (compare4, resort) => {
        if (cnt) {
          data3 = data3.filter((t4) => !rem2[$2(t4)]);
          rem2 = {};
          cnt = 0;
        }
        if (resort && compare4) {
          data3.sort(compare4);
        }
        if (add6.length) {
          data3 = compare4 ? merge(compare4, data3, add6.sort(compare4)) : data3.concat(add6);
          add6 = [];
        }
        return data3;
      }
    };
  }
  function Collect(params2) {
    Transform.call(this, [], params2);
  }
  Collect.Definition = {
    "type": "Collect",
    "metadata": {
      "source": true
    },
    "params": [{
      "name": "sort",
      "type": "compare"
    }]
  };
  inherits(Collect, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.ALL), list = SortedList(tupleid, this.value, out.materialize(out.ADD).add), sort3 = _.sort, mod = pulse2.changed() || sort3 && (_.modified("sort") || pulse2.modified(sort3.fields));
      out.visit(out.REM, list.remove);
      this.modified(mod);
      this.value = out.source = list.data(stableCompare(sort3), mod);
      if (pulse2.source && pulse2.source.root) {
        this.value.root = pulse2.source.root;
      }
      return out;
    }
  });
  function Compare(params2) {
    Operator.call(this, null, update$5, params2);
  }
  inherits(Compare, Operator);
  function update$5(_) {
    return this.value && !_.modified() ? this.value : compare(_.fields, _.orders);
  }
  function CountPattern(params2) {
    Transform.call(this, null, params2);
  }
  CountPattern.Definition = {
    "type": "CountPattern",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "case",
      "type": "enum",
      "values": ["upper", "lower", "mixed"],
      "default": "mixed"
    }, {
      "name": "pattern",
      "type": "string",
      "default": '[\\w"]+'
    }, {
      "name": "stopwords",
      "type": "string",
      "default": ""
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["text", "count"]
    }]
  };
  function tokenize(text4, tcase, match3) {
    switch (tcase) {
      case "upper":
        text4 = text4.toUpperCase();
        break;
      case "lower":
        text4 = text4.toLowerCase();
        break;
    }
    return text4.match(match3);
  }
  inherits(CountPattern, Transform, {
    transform(_, pulse2) {
      const process2 = (update3) => (tuple) => {
        var tokens = tokenize(get6(tuple), _.case, match3) || [], t4;
        for (var i2 = 0, n2 = tokens.length; i2 < n2; ++i2) {
          if (!stop2.test(t4 = tokens[i2])) update3(t4);
        }
      };
      const init2 = this._parameterCheck(_, pulse2), counts = this._counts, match3 = this._match, stop2 = this._stop, get6 = _.field, as = _.as || ["text", "count"], add6 = process2((t4) => counts[t4] = 1 + (counts[t4] || 0)), rem2 = process2((t4) => counts[t4] -= 1);
      if (init2) {
        pulse2.visit(pulse2.SOURCE, add6);
      } else {
        pulse2.visit(pulse2.ADD, add6);
        pulse2.visit(pulse2.REM, rem2);
      }
      return this._finish(pulse2, as);
    },
    _parameterCheck(_, pulse2) {
      let init2 = false;
      if (_.modified("stopwords") || !this._stop) {
        this._stop = new RegExp("^" + (_.stopwords || "") + "$", "i");
        init2 = true;
      }
      if (_.modified("pattern") || !this._match) {
        this._match = new RegExp(_.pattern || "[\\w']+", "g");
        init2 = true;
      }
      if (_.modified("field") || pulse2.modified(_.field.fields)) {
        init2 = true;
      }
      if (init2) this._counts = {};
      return init2;
    },
    _finish(pulse2, as) {
      const counts = this._counts, tuples = this._tuples || (this._tuples = {}), text4 = as[0], count2 = as[1], out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
      let w3, t4, c4;
      for (w3 in counts) {
        t4 = tuples[w3];
        c4 = counts[w3] || 0;
        if (!t4 && c4) {
          tuples[w3] = t4 = ingest$1({});
          t4[text4] = w3;
          t4[count2] = c4;
          out.add.push(t4);
        } else if (c4 === 0) {
          if (t4) out.rem.push(t4);
          counts[w3] = null;
          tuples[w3] = null;
        } else if (t4[count2] !== c4) {
          t4[count2] = c4;
          out.mod.push(t4);
        }
      }
      return out.modifies(as);
    }
  });
  function Cross(params2) {
    Transform.call(this, null, params2);
  }
  Cross.Definition = {
    "type": "Cross",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "filter",
      "type": "expr"
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["a", "b"]
    }]
  };
  inherits(Cross, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE), as = _.as || ["a", "b"], a4 = as[0], b3 = as[1], reset3 = !this.value || pulse2.changed(pulse2.ADD_REM) || _.modified("as") || _.modified("filter");
      let data3 = this.value;
      if (reset3) {
        if (data3) out.rem = data3;
        data3 = pulse2.materialize(pulse2.SOURCE).source;
        out.add = this.value = cross(data3, a4, b3, _.filter || truthy);
      } else {
        out.mod = data3;
      }
      out.source = this.value;
      return out.modifies(as);
    }
  });
  function cross(input, a4, b3, filter3) {
    var data3 = [], t4 = {}, n2 = input.length, i2 = 0, j2, left;
    for (; i2 < n2; ++i2) {
      t4[a4] = left = input[i2];
      for (j2 = 0; j2 < n2; ++j2) {
        t4[b3] = input[j2];
        if (filter3(t4)) {
          data3.push(ingest$1(t4));
          t4 = {};
          t4[a4] = left;
        }
      }
    }
    return data3;
  }
  var Distributions = {
    kde,
    mixture,
    normal: gaussian,
    lognormal,
    uniform
  };
  var DISTRIBUTIONS = "distributions";
  var FUNCTION = "function";
  var FIELD = "field";
  function parse3(def2, data3) {
    const func = def2[FUNCTION];
    if (!has(Distributions, func)) {
      error("Unknown distribution function: " + func);
    }
    const d2 = Distributions[func]();
    for (const name4 in def2) {
      if (name4 === FIELD) {
        d2.data((def2.from || data3()).map(def2[name4]));
      } else if (name4 === DISTRIBUTIONS) {
        d2[name4](def2[name4].map((_) => parse3(_, data3)));
      } else if (typeof d2[name4] === FUNCTION) {
        d2[name4](def2[name4]);
      }
    }
    return d2;
  }
  function Density(params2) {
    Transform.call(this, null, params2);
  }
  var distributions = [{
    "key": {
      "function": "normal"
    },
    "params": [{
      "name": "mean",
      "type": "number",
      "default": 0
    }, {
      "name": "stdev",
      "type": "number",
      "default": 1
    }]
  }, {
    "key": {
      "function": "lognormal"
    },
    "params": [{
      "name": "mean",
      "type": "number",
      "default": 0
    }, {
      "name": "stdev",
      "type": "number",
      "default": 1
    }]
  }, {
    "key": {
      "function": "uniform"
    },
    "params": [{
      "name": "min",
      "type": "number",
      "default": 0
    }, {
      "name": "max",
      "type": "number",
      "default": 1
    }]
  }, {
    "key": {
      "function": "kde"
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "from",
      "type": "data"
    }, {
      "name": "bandwidth",
      "type": "number",
      "default": 0
    }]
  }];
  var mixture2 = {
    "key": {
      "function": "mixture"
    },
    "params": [{
      "name": "distributions",
      "type": "param",
      "array": true,
      "params": distributions
    }, {
      "name": "weights",
      "type": "number",
      "array": true
    }]
  };
  Density.Definition = {
    "type": "Density",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "extent",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "steps",
      "type": "number"
    }, {
      "name": "minsteps",
      "type": "number",
      "default": 25
    }, {
      "name": "maxsteps",
      "type": "number",
      "default": 200
    }, {
      "name": "method",
      "type": "string",
      "default": "pdf",
      "values": ["pdf", "cdf"]
    }, {
      "name": "distribution",
      "type": "param",
      "params": distributions.concat(mixture2)
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "default": ["value", "density"]
    }]
  };
  inherits(Density, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
      if (!this.value || pulse2.changed() || _.modified()) {
        const dist2 = parse3(_.distribution, source(pulse2)), minsteps = _.steps || _.minsteps || 25, maxsteps = _.steps || _.maxsteps || 200;
        let method2 = _.method || "pdf";
        if (method2 !== "pdf" && method2 !== "cdf") {
          error("Invalid density method: " + method2);
        }
        if (!_.extent && !dist2.data) {
          error("Missing density extent parameter.");
        }
        method2 = dist2[method2];
        const as = _.as || ["value", "density"], domain4 = _.extent || extent(dist2.data()), values4 = sampleCurve(method2, domain4, minsteps, maxsteps).map((v3) => {
          const tuple = {};
          tuple[as[0]] = v3[0];
          tuple[as[1]] = v3[1];
          return ingest$1(tuple);
        });
        if (this.value) out.rem = this.value;
        this.value = out.add = out.source = values4;
      }
      return out;
    }
  });
  function source(pulse2) {
    return () => pulse2.materialize(pulse2.SOURCE).source;
  }
  function fieldNames(fields, as) {
    if (!fields) return null;
    return fields.map((f2, i2) => as[i2] || accessorName(f2));
  }
  function partition$1(data3, groupby, field3) {
    const groups = [], get6 = (f2) => f2(t4);
    let map4, i2, n2, t4, k2, g2;
    if (groupby == null) {
      groups.push(data3.map(field3));
    } else {
      for (map4 = {}, i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
        t4 = data3[i2];
        k2 = groupby.map(get6);
        g2 = map4[k2];
        if (!g2) {
          map4[k2] = g2 = [];
          g2.dims = k2;
          groups.push(g2);
        }
        g2.push(field3(t4));
      }
    }
    return groups;
  }
  var Output = "bin";
  function DotBin(params2) {
    Transform.call(this, null, params2);
  }
  DotBin.Definition = {
    "type": "DotBin",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "step",
      "type": "number"
    }, {
      "name": "smooth",
      "type": "boolean",
      "default": false
    }, {
      "name": "as",
      "type": "string",
      "default": Output
    }]
  };
  var autostep = (data3, field3) => span(extent(data3, field3)) / 30;
  inherits(DotBin, Transform, {
    transform(_, pulse2) {
      if (this.value && !(_.modified() || pulse2.changed())) {
        return pulse2;
      }
      const source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition$1(pulse2.source, _.groupby, identity), smooth = _.smooth || false, field3 = _.field, step = _.step || autostep(source4, field3), sort3 = stableCompare((a4, b3) => field3(a4) - field3(b3)), as = _.as || Output, n2 = groups.length;
      let min4 = Infinity, max4 = -Infinity, i2 = 0, j2;
      for (; i2 < n2; ++i2) {
        const g2 = groups[i2].sort(sort3);
        j2 = -1;
        for (const v3 of dotbin(g2, step, smooth, field3)) {
          if (v3 < min4) min4 = v3;
          if (v3 > max4) max4 = v3;
          g2[++j2][as] = v3;
        }
      }
      this.value = {
        start: min4,
        stop: max4,
        step
      };
      return pulse2.reflow(true).modifies(as);
    }
  });
  function Expression(params2) {
    Operator.call(this, null, update$4, params2);
    this.modified(true);
  }
  inherits(Expression, Operator);
  function update$4(_) {
    const expr2 = _.expr;
    return this.value && !_.modified("expr") ? this.value : accessor((datum2) => expr2(datum2, _), accessorFields(expr2), accessorName(expr2));
  }
  function Extent(params2) {
    Transform.call(this, [void 0, void 0], params2);
  }
  Extent.Definition = {
    "type": "Extent",
    "metadata": {},
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }]
  };
  inherits(Extent, Transform, {
    transform(_, pulse2) {
      const extent2 = this.value, field3 = _.field, mod = pulse2.changed() || pulse2.modified(field3.fields) || _.modified("field");
      let min4 = extent2[0], max4 = extent2[1];
      if (mod || min4 == null) {
        min4 = Infinity;
        max4 = -Infinity;
      }
      pulse2.visit(mod ? pulse2.SOURCE : pulse2.ADD, (t4) => {
        const v3 = toNumber(field3(t4));
        if (v3 != null) {
          if (v3 < min4) min4 = v3;
          if (v3 > max4) max4 = v3;
        }
      });
      if (!Number.isFinite(min4) || !Number.isFinite(max4)) {
        let name4 = accessorName(field3);
        if (name4) name4 = ` for field "${name4}"`;
        pulse2.dataflow.warn(`Infinite extent${name4}: [${min4}, ${max4}]`);
        min4 = max4 = void 0;
      }
      this.value = [min4, max4];
    }
  });
  function Subflow(pulse2, parent) {
    Operator.call(this, pulse2);
    this.parent = parent;
    this.count = 0;
  }
  inherits(Subflow, Operator, {
    /**
     * Routes pulses from this subflow to a target transform.
     * @param {Transform} target - A transform that receives the subflow of tuples.
     */
    connect(target2) {
      this.detachSubflow = target2.detachSubflow;
      this.targets().add(target2);
      return target2.source = this;
    },
    /**
     * Add an 'add' tuple to the subflow pulse.
     * @param {Tuple} t - The tuple being added.
     */
    add(t4) {
      this.count += 1;
      this.value.add.push(t4);
    },
    /**
     * Add a 'rem' tuple to the subflow pulse.
     * @param {Tuple} t - The tuple being removed.
     */
    rem(t4) {
      this.count -= 1;
      this.value.rem.push(t4);
    },
    /**
     * Add a 'mod' tuple to the subflow pulse.
     * @param {Tuple} t - The tuple being modified.
     */
    mod(t4) {
      this.value.mod.push(t4);
    },
    /**
     * Re-initialize this operator's pulse value.
     * @param {Pulse} pulse - The pulse to copy from.
     * @see Pulse.init
     */
    init(pulse2) {
      this.value.init(pulse2, pulse2.NO_SOURCE);
    },
    /**
     * Evaluate this operator. This method overrides the
     * default behavior to simply return the contained pulse value.
     * @return {Pulse}
     */
    evaluate() {
      return this.value;
    }
  });
  function Facet(params2) {
    Transform.call(this, {}, params2);
    this._keys = fastmap();
    const a4 = this._targets = [];
    a4.active = 0;
    a4.forEach = (f2) => {
      for (let i2 = 0, n2 = a4.active; i2 < n2; ++i2) {
        f2(a4[i2], i2, a4);
      }
    };
  }
  inherits(Facet, Transform, {
    activate(flow) {
      this._targets[this._targets.active++] = flow;
    },
    // parent argument provided by PreFacet subclass
    subflow(key2, flow, pulse2, parent) {
      const flows = this.value;
      let sf = has(flows, key2) && flows[key2], df, p2;
      if (!sf) {
        p2 = parent || (p2 = this._group[key2]) && p2.tuple;
        df = pulse2.dataflow;
        sf = new Subflow(pulse2.fork(pulse2.NO_SOURCE), this);
        df.add(sf).connect(flow(df, key2, p2));
        flows[key2] = sf;
        this.activate(sf);
      } else if (sf.value.stamp < pulse2.stamp) {
        sf.init(pulse2);
        this.activate(sf);
      }
      return sf;
    },
    clean() {
      const flows = this.value;
      let detached = 0;
      for (const key2 in flows) {
        if (flows[key2].count === 0) {
          const detach = flows[key2].detachSubflow;
          if (detach) detach();
          delete flows[key2];
          ++detached;
        }
      }
      if (detached) {
        const active = this._targets.filter((sf) => sf && sf.count > 0);
        this.initTargets(active);
      }
    },
    initTargets(act) {
      const a4 = this._targets, n2 = a4.length, m4 = act ? act.length : 0;
      let i2 = 0;
      for (; i2 < m4; ++i2) {
        a4[i2] = act[i2];
      }
      for (; i2 < n2 && a4[i2] != null; ++i2) {
        a4[i2] = null;
      }
      a4.active = m4;
    },
    transform(_, pulse2) {
      const df = pulse2.dataflow, key2 = _.key, flow = _.subflow, cache3 = this._keys, rekey = _.modified("key"), subflow = (key3) => this.subflow(key3, flow, pulse2);
      this._group = _.group || {};
      this.initTargets();
      pulse2.visit(pulse2.REM, (t4) => {
        const id2 = tupleid(t4), k2 = cache3.get(id2);
        if (k2 !== void 0) {
          cache3.delete(id2);
          subflow(k2).rem(t4);
        }
      });
      pulse2.visit(pulse2.ADD, (t4) => {
        const k2 = key2(t4);
        cache3.set(tupleid(t4), k2);
        subflow(k2).add(t4);
      });
      if (rekey || pulse2.modified(key2.fields)) {
        pulse2.visit(pulse2.MOD, (t4) => {
          const id2 = tupleid(t4), k0 = cache3.get(id2), k1 = key2(t4);
          if (k0 === k1) {
            subflow(k1).mod(t4);
          } else {
            cache3.set(id2, k1);
            subflow(k0).rem(t4);
            subflow(k1).add(t4);
          }
        });
      } else if (pulse2.changed(pulse2.MOD)) {
        pulse2.visit(pulse2.MOD, (t4) => {
          subflow(cache3.get(tupleid(t4))).mod(t4);
        });
      }
      if (rekey) {
        pulse2.visit(pulse2.REFLOW, (t4) => {
          const id2 = tupleid(t4), k0 = cache3.get(id2), k1 = key2(t4);
          if (k0 !== k1) {
            cache3.set(id2, k1);
            subflow(k0).rem(t4);
            subflow(k1).add(t4);
          }
        });
      }
      if (pulse2.clean()) {
        df.runAfter(() => {
          this.clean();
          cache3.clean();
        });
      } else if (cache3.empty > df.cleanThreshold) {
        df.runAfter(cache3.clean);
      }
      return pulse2;
    }
  });
  function Field(params2) {
    Operator.call(this, null, update$3, params2);
  }
  inherits(Field, Operator);
  function update$3(_) {
    return this.value && !_.modified() ? this.value : isArray(_.name) ? array(_.name).map((f2) => field(f2)) : field(_.name, _.as);
  }
  function Filter(params2) {
    Transform.call(this, fastmap(), params2);
  }
  Filter.Definition = {
    "type": "Filter",
    "metadata": {
      "changes": true
    },
    "params": [{
      "name": "expr",
      "type": "expr",
      "required": true
    }]
  };
  inherits(Filter, Transform, {
    transform(_, pulse2) {
      const df = pulse2.dataflow, cache3 = this.value, output3 = pulse2.fork(), add6 = output3.add, rem2 = output3.rem, mod = output3.mod, test2 = _.expr;
      let isMod = true;
      pulse2.visit(pulse2.REM, (t4) => {
        const id2 = tupleid(t4);
        if (!cache3.has(id2)) rem2.push(t4);
        else cache3.delete(id2);
      });
      pulse2.visit(pulse2.ADD, (t4) => {
        if (test2(t4, _)) add6.push(t4);
        else cache3.set(tupleid(t4), 1);
      });
      function revisit(t4) {
        const id2 = tupleid(t4), b3 = test2(t4, _), s2 = cache3.get(id2);
        if (b3 && s2) {
          cache3.delete(id2);
          add6.push(t4);
        } else if (!b3 && !s2) {
          cache3.set(id2, 1);
          rem2.push(t4);
        } else if (isMod && b3 && !s2) {
          mod.push(t4);
        }
      }
      pulse2.visit(pulse2.MOD, revisit);
      if (_.modified()) {
        isMod = false;
        pulse2.visit(pulse2.REFLOW, revisit);
      }
      if (cache3.empty > df.cleanThreshold) df.runAfter(cache3.clean);
      return output3;
    }
  });
  function Flatten(params2) {
    Transform.call(this, [], params2);
  }
  Flatten.Definition = {
    "type": "Flatten",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "fields",
      "type": "field",
      "array": true,
      "required": true
    }, {
      "name": "index",
      "type": "string"
    }, {
      "name": "as",
      "type": "string",
      "array": true
    }]
  };
  inherits(Flatten, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE), fields = _.fields, as = fieldNames(fields, _.as || []), index4 = _.index || null, m4 = as.length;
      out.rem = this.value;
      pulse2.visit(pulse2.SOURCE, (t4) => {
        const arrays = fields.map((f2) => f2(t4)), maxlen = arrays.reduce((l2, a4) => Math.max(l2, a4.length), 0);
        let i2 = 0, j2, d2, v3;
        for (; i2 < maxlen; ++i2) {
          d2 = derive(t4);
          for (j2 = 0; j2 < m4; ++j2) {
            d2[as[j2]] = (v3 = arrays[j2][i2]) == null ? null : v3;
          }
          if (index4) {
            d2[index4] = i2;
          }
          out.add.push(d2);
        }
      });
      this.value = out.source = out.add;
      if (index4) out.modifies(index4);
      return out.modifies(as);
    }
  });
  function Fold(params2) {
    Transform.call(this, [], params2);
  }
  Fold.Definition = {
    "type": "Fold",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "fields",
      "type": "field",
      "array": true,
      "required": true
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["key", "value"]
    }]
  };
  inherits(Fold, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE), fields = _.fields, fnames = fields.map(accessorName), as = _.as || ["key", "value"], k2 = as[0], v3 = as[1], n2 = fields.length;
      out.rem = this.value;
      pulse2.visit(pulse2.SOURCE, (t4) => {
        for (let i2 = 0, d2; i2 < n2; ++i2) {
          d2 = derive(t4);
          d2[k2] = fnames[i2];
          d2[v3] = fields[i2](t4);
          out.add.push(d2);
        }
      });
      this.value = out.source = out.add;
      return out.modifies(as);
    }
  });
  function Formula(params2) {
    Transform.call(this, null, params2);
  }
  Formula.Definition = {
    "type": "Formula",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "expr",
      "type": "expr",
      "required": true
    }, {
      "name": "as",
      "type": "string",
      "required": true
    }, {
      "name": "initonly",
      "type": "boolean"
    }]
  };
  inherits(Formula, Transform, {
    transform(_, pulse2) {
      const func = _.expr, as = _.as, mod = _.modified(), flag2 = _.initonly ? pulse2.ADD : mod ? pulse2.SOURCE : pulse2.modified(func.fields) || pulse2.modified(as) ? pulse2.ADD_MOD : pulse2.ADD;
      if (mod) {
        pulse2 = pulse2.materialize().reflow(true);
      }
      if (!_.initonly) {
        pulse2.modifies(as);
      }
      return pulse2.visit(flag2, (t4) => t4[as] = func(t4, _));
    }
  });
  function Generate(params2) {
    Transform.call(this, [], params2);
  }
  inherits(Generate, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.ALL), gen = _.generator;
      let data3 = this.value, num = _.size - data3.length, add6, rem2, t4;
      if (num > 0) {
        for (add6 = []; --num >= 0; ) {
          add6.push(t4 = ingest$1(gen(_)));
          data3.push(t4);
        }
        out.add = out.add.length ? out.materialize(out.ADD).add.concat(add6) : add6;
      } else {
        rem2 = data3.slice(0, -num);
        out.rem = out.rem.length ? out.materialize(out.REM).rem.concat(rem2) : rem2;
        data3 = data3.slice(-num);
      }
      out.source = this.value = data3;
      return out;
    }
  });
  var Methods = {
    value: "value",
    median,
    mean,
    min,
    max
  };
  var Empty = [];
  function Impute(params2) {
    Transform.call(this, [], params2);
  }
  Impute.Definition = {
    "type": "Impute",
    "metadata": {
      "changes": true
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "key",
      "type": "field",
      "required": true
    }, {
      "name": "keyvals",
      "array": true
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "method",
      "type": "enum",
      "default": "value",
      "values": ["value", "mean", "median", "max", "min"]
    }, {
      "name": "value",
      "default": 0
    }]
  };
  function getValue(_) {
    var m4 = _.method || Methods.value, v3;
    if (Methods[m4] == null) {
      error("Unrecognized imputation method: " + m4);
    } else if (m4 === Methods.value) {
      v3 = _.value !== void 0 ? _.value : 0;
      return () => v3;
    } else {
      return Methods[m4];
    }
  }
  function getField(_) {
    const f2 = _.field;
    return (t4) => t4 ? f2(t4) : NaN;
  }
  inherits(Impute, Transform, {
    transform(_, pulse2) {
      var out = pulse2.fork(pulse2.ALL), impute = getValue(_), field3 = getField(_), fName = accessorName(_.field), kName = accessorName(_.key), gNames = (_.groupby || []).map(accessorName), groups = partition(pulse2.source, _.groupby, _.key, _.keyvals), curr = [], prev = this.value, m4 = groups.domain.length, group2, value3, gVals, kVal, g2, i2, j2, l2, n2, t4;
      for (g2 = 0, l2 = groups.length; g2 < l2; ++g2) {
        group2 = groups[g2];
        gVals = group2.values;
        value3 = NaN;
        for (j2 = 0; j2 < m4; ++j2) {
          if (group2[j2] != null) continue;
          kVal = groups.domain[j2];
          t4 = {
            _impute: true
          };
          for (i2 = 0, n2 = gVals.length; i2 < n2; ++i2) t4[gNames[i2]] = gVals[i2];
          t4[kName] = kVal;
          t4[fName] = Number.isNaN(value3) ? value3 = impute(group2, field3) : value3;
          curr.push(ingest$1(t4));
        }
      }
      if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr);
      if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev);
      this.value = curr;
      return out;
    }
  });
  function partition(data3, groupby, key2, keyvals) {
    var get6 = (f2) => f2(t4), groups = [], domain4 = keyvals ? keyvals.slice() : [], kMap = {}, gMap = {}, gVals, gKey, group2, i2, j2, k2, n2, t4;
    domain4.forEach((k3, i3) => kMap[k3] = i3 + 1);
    for (i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
      t4 = data3[i2];
      k2 = key2(t4);
      j2 = kMap[k2] || (kMap[k2] = domain4.push(k2));
      gKey = (gVals = groupby ? groupby.map(get6) : Empty) + "";
      if (!(group2 = gMap[gKey])) {
        group2 = gMap[gKey] = [];
        groups.push(group2);
        group2.values = gVals;
      }
      group2[j2 - 1] = t4;
    }
    groups.domain = domain4;
    return groups;
  }
  function JoinAggregate(params2) {
    Aggregate.call(this, params2);
  }
  JoinAggregate.Definition = {
    "type": "JoinAggregate",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "fields",
      "type": "field",
      "null": true,
      "array": true
    }, {
      "name": "ops",
      "type": "enum",
      "array": true,
      "values": ValidAggregateOps
    }, {
      "name": "as",
      "type": "string",
      "null": true,
      "array": true
    }, {
      "name": "key",
      "type": "field"
    }]
  };
  inherits(JoinAggregate, Aggregate, {
    transform(_, pulse2) {
      const aggr = this, mod = _.modified();
      let cells;
      if (aggr.value && (mod || pulse2.modified(aggr._inputs, true))) {
        cells = aggr.value = mod ? aggr.init(_) : {};
        pulse2.visit(pulse2.SOURCE, (t4) => aggr.add(t4));
      } else {
        cells = aggr.value = aggr.value || this.init(_);
        pulse2.visit(pulse2.REM, (t4) => aggr.rem(t4));
        pulse2.visit(pulse2.ADD, (t4) => aggr.add(t4));
      }
      aggr.changes();
      pulse2.visit(pulse2.SOURCE, (t4) => {
        extend(t4, cells[aggr.cellkey(t4)].tuple);
      });
      return pulse2.reflow(mod).modifies(this._outputs);
    },
    changes() {
      const adds = this._adds, mods = this._mods;
      let i2, n2;
      for (i2 = 0, n2 = this._alen; i2 < n2; ++i2) {
        this.celltuple(adds[i2]);
        adds[i2] = null;
      }
      for (i2 = 0, n2 = this._mlen; i2 < n2; ++i2) {
        this.celltuple(mods[i2]);
        mods[i2] = null;
      }
      this._alen = this._mlen = 0;
    }
  });
  function KDE(params2) {
    Transform.call(this, null, params2);
  }
  KDE.Definition = {
    "type": "KDE",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "cumulative",
      "type": "boolean",
      "default": false
    }, {
      "name": "counts",
      "type": "boolean",
      "default": false
    }, {
      "name": "bandwidth",
      "type": "number",
      "default": 0
    }, {
      "name": "extent",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "resolve",
      "type": "enum",
      "values": ["shared", "independent"],
      "default": "independent"
    }, {
      "name": "steps",
      "type": "number"
    }, {
      "name": "minsteps",
      "type": "number",
      "default": 25
    }, {
      "name": "maxsteps",
      "type": "number",
      "default": 200
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "default": ["value", "density"]
    }]
  };
  inherits(KDE, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
      if (!this.value || pulse2.changed() || _.modified()) {
        const source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition$1(source4, _.groupby, _.field), names = (_.groupby || []).map(accessorName), bandwidth2 = _.bandwidth, method2 = _.cumulative ? "cdf" : "pdf", as = _.as || ["value", "density"], values4 = [];
        let domain4 = _.extent, minsteps = _.steps || _.minsteps || 25, maxsteps = _.steps || _.maxsteps || 200;
        if (method2 !== "pdf" && method2 !== "cdf") {
          error("Invalid density method: " + method2);
        }
        if (_.resolve === "shared") {
          if (!domain4) domain4 = extent(source4, _.field);
          minsteps = maxsteps = _.steps || maxsteps;
        }
        groups.forEach((g2) => {
          const density = kde(g2, bandwidth2)[method2], scale7 = _.counts ? g2.length : 1, local = domain4 || extent(g2);
          sampleCurve(density, local, minsteps, maxsteps).forEach((v3) => {
            const t4 = {};
            for (let i2 = 0; i2 < names.length; ++i2) {
              t4[names[i2]] = g2.dims[i2];
            }
            t4[as[0]] = v3[0];
            t4[as[1]] = v3[1] * scale7;
            values4.push(ingest$1(t4));
          });
        });
        if (this.value) out.rem = this.value;
        this.value = out.add = out.source = values4;
      }
      return out;
    }
  });
  function Key(params2) {
    Operator.call(this, null, update$2, params2);
  }
  inherits(Key, Operator);
  function update$2(_) {
    return this.value && !_.modified() ? this.value : key(_.fields, _.flat);
  }
  function Load(params2) {
    Transform.call(this, [], params2);
    this._pending = null;
  }
  inherits(Load, Transform, {
    transform(_, pulse2) {
      const df = pulse2.dataflow;
      if (this._pending) {
        return output2(this, pulse2, this._pending);
      }
      if (stop(_)) return pulse2.StopPropagation;
      if (_.values) {
        return output2(this, pulse2, df.parse(_.values, _.format));
      } else if (_.async) {
        const p2 = df.request(_.url, _.format).then((res) => {
          this._pending = array(res.data);
          return (df2) => df2.touch(this);
        });
        return {
          async: p2
        };
      } else {
        return df.request(_.url, _.format).then((res) => output2(this, pulse2, array(res.data)));
      }
    }
  });
  function stop(_) {
    return _.modified("async") && !(_.modified("values") || _.modified("url") || _.modified("format"));
  }
  function output2(op, pulse2, data3) {
    data3.forEach(ingest$1);
    const out = pulse2.fork(pulse2.NO_FIELDS & pulse2.NO_SOURCE);
    out.rem = op.value;
    op.value = out.source = out.add = data3;
    op._pending = null;
    if (out.rem.length) out.clean(true);
    return out;
  }
  function Lookup(params2) {
    Transform.call(this, {}, params2);
  }
  Lookup.Definition = {
    "type": "Lookup",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "index",
      "type": "index",
      "params": [{
        "name": "from",
        "type": "data",
        "required": true
      }, {
        "name": "key",
        "type": "field",
        "required": true
      }]
    }, {
      "name": "values",
      "type": "field",
      "array": true
    }, {
      "name": "fields",
      "type": "field",
      "array": true,
      "required": true
    }, {
      "name": "as",
      "type": "string",
      "array": true
    }, {
      "name": "default",
      "default": null
    }]
  };
  inherits(Lookup, Transform, {
    transform(_, pulse2) {
      const keys4 = _.fields, index4 = _.index, values4 = _.values, defaultValue = _.default == null ? null : _.default, reset3 = _.modified(), n2 = keys4.length;
      let flag2 = reset3 ? pulse2.SOURCE : pulse2.ADD, out = pulse2, as = _.as, set7, m4, mods;
      if (values4) {
        m4 = values4.length;
        if (n2 > 1 && !as) {
          error('Multi-field lookup requires explicit "as" parameter.');
        }
        if (as && as.length !== n2 * m4) {
          error('The "as" parameter has too few output field names.');
        }
        as = as || values4.map(accessorName);
        set7 = function(t4) {
          for (var i2 = 0, k2 = 0, j2, v3; i2 < n2; ++i2) {
            v3 = index4.get(keys4[i2](t4));
            if (v3 == null) for (j2 = 0; j2 < m4; ++j2, ++k2) t4[as[k2]] = defaultValue;
            else for (j2 = 0; j2 < m4; ++j2, ++k2) t4[as[k2]] = values4[j2](v3);
          }
        };
      } else {
        if (!as) {
          error("Missing output field names.");
        }
        set7 = function(t4) {
          for (var i2 = 0, v3; i2 < n2; ++i2) {
            v3 = index4.get(keys4[i2](t4));
            t4[as[i2]] = v3 == null ? defaultValue : v3;
          }
        };
      }
      if (reset3) {
        out = pulse2.reflow(true);
      } else {
        mods = keys4.some((k2) => pulse2.modified(k2.fields));
        flag2 |= mods ? pulse2.MOD : 0;
      }
      pulse2.visit(flag2, set7);
      return out.modifies(as);
    }
  });
  function MultiExtent(params2) {
    Operator.call(this, null, update$1, params2);
  }
  inherits(MultiExtent, Operator);
  function update$1(_) {
    if (this.value && !_.modified()) {
      return this.value;
    }
    const ext = _.extents, n2 = ext.length;
    let min4 = Infinity, max4 = -Infinity, i2, e4;
    for (i2 = 0; i2 < n2; ++i2) {
      e4 = ext[i2];
      if (e4[0] < min4) min4 = e4[0];
      if (e4[1] > max4) max4 = e4[1];
    }
    return [min4, max4];
  }
  function MultiValues(params2) {
    Operator.call(this, null, update2, params2);
  }
  inherits(MultiValues, Operator);
  function update2(_) {
    return this.value && !_.modified() ? this.value : _.values.reduce((data3, _2) => data3.concat(_2), []);
  }
  function Params(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Params, Transform, {
    transform(_, pulse2) {
      this.modified(_.modified());
      this.value = _;
      return pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
    }
  });
  function Pivot(params2) {
    Aggregate.call(this, params2);
  }
  Pivot.Definition = {
    "type": "Pivot",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "value",
      "type": "field",
      "required": true
    }, {
      "name": "op",
      "type": "enum",
      "values": ValidAggregateOps,
      "default": "sum"
    }, {
      "name": "limit",
      "type": "number",
      "default": 0
    }, {
      "name": "key",
      "type": "field"
    }]
  };
  inherits(Pivot, Aggregate, {
    _transform: Aggregate.prototype.transform,
    transform(_, pulse2) {
      return this._transform(aggregateParams(_, pulse2), pulse2);
    }
  });
  function aggregateParams(_, pulse2) {
    const key2 = _.field, value3 = _.value, op = (_.op === "count" ? "__count__" : _.op) || "sum", fields = accessorFields(key2).concat(accessorFields(value3)), keys4 = pivotKeys(key2, _.limit || 0, pulse2);
    if (pulse2.changed()) _.set("__pivot__", null, null, true);
    return {
      key: _.key,
      groupby: _.groupby,
      ops: keys4.map(() => op),
      fields: keys4.map((k2) => get(k2, key2, value3, fields)),
      as: keys4.map((k2) => k2 + ""),
      modified: _.modified.bind(_)
    };
  }
  function get(k2, key2, value3, fields) {
    return accessor((d2) => key2(d2) === k2 ? value3(d2) : NaN, fields, k2 + "");
  }
  function pivotKeys(key2, limit, pulse2) {
    const map4 = {}, list = [];
    pulse2.visit(pulse2.SOURCE, (t4) => {
      const k2 = key2(t4);
      if (!map4[k2]) {
        map4[k2] = 1;
        list.push(k2);
      }
    });
    list.sort(ascending);
    return limit ? list.slice(0, limit) : list;
  }
  function PreFacet(params2) {
    Facet.call(this, params2);
  }
  inherits(PreFacet, Facet, {
    transform(_, pulse2) {
      const flow = _.subflow, field3 = _.field, subflow = (t4) => this.subflow(tupleid(t4), flow, pulse2, t4);
      if (_.modified("field") || field3 && pulse2.modified(accessorFields(field3))) {
        error("PreFacet does not support field modification.");
      }
      this.initTargets();
      if (field3) {
        pulse2.visit(pulse2.MOD, (t4) => {
          const sf = subflow(t4);
          field3(t4).forEach((_2) => sf.mod(_2));
        });
        pulse2.visit(pulse2.ADD, (t4) => {
          const sf = subflow(t4);
          field3(t4).forEach((_2) => sf.add(ingest$1(_2)));
        });
        pulse2.visit(pulse2.REM, (t4) => {
          const sf = subflow(t4);
          field3(t4).forEach((_2) => sf.rem(_2));
        });
      } else {
        pulse2.visit(pulse2.MOD, (t4) => subflow(t4).mod(t4));
        pulse2.visit(pulse2.ADD, (t4) => subflow(t4).add(t4));
        pulse2.visit(pulse2.REM, (t4) => subflow(t4).rem(t4));
      }
      if (pulse2.clean()) {
        pulse2.runAfter(() => this.clean());
      }
      return pulse2;
    }
  });
  function Project(params2) {
    Transform.call(this, null, params2);
  }
  Project.Definition = {
    "type": "Project",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "fields",
      "type": "field",
      "array": true
    }, {
      "name": "as",
      "type": "string",
      "null": true,
      "array": true
    }]
  };
  inherits(Project, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE), fields = _.fields, as = fieldNames(_.fields, _.as || []), derive2 = fields ? (s2, t4) => project(s2, t4, fields, as) : rederive;
      let lut;
      if (this.value) {
        lut = this.value;
      } else {
        pulse2 = pulse2.addAll();
        lut = this.value = {};
      }
      pulse2.visit(pulse2.REM, (t4) => {
        const id2 = tupleid(t4);
        out.rem.push(lut[id2]);
        lut[id2] = null;
      });
      pulse2.visit(pulse2.ADD, (t4) => {
        const dt = derive2(t4, ingest$1({}));
        lut[tupleid(t4)] = dt;
        out.add.push(dt);
      });
      pulse2.visit(pulse2.MOD, (t4) => {
        out.mod.push(derive2(t4, lut[tupleid(t4)]));
      });
      return out;
    }
  });
  function project(s2, t4, fields, as) {
    for (let i2 = 0, n2 = fields.length; i2 < n2; ++i2) {
      t4[as[i2]] = fields[i2](s2);
    }
    return t4;
  }
  function Proxy2(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Proxy2, Transform, {
    transform(_, pulse2) {
      this.value = _.value;
      return _.modified("value") ? pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS) : pulse2.StopPropagation;
    }
  });
  function Quantile(params2) {
    Transform.call(this, null, params2);
  }
  Quantile.Definition = {
    "type": "Quantile",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "probs",
      "type": "number",
      "array": true
    }, {
      "name": "step",
      "type": "number",
      "default": 0.01
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "default": ["prob", "value"]
    }]
  };
  var EPSILON = 1e-14;
  inherits(Quantile, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), as = _.as || ["prob", "value"];
      if (this.value && !_.modified() && !pulse2.changed()) {
        out.source = this.value;
        return out;
      }
      const source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition$1(source4, _.groupby, _.field), names = (_.groupby || []).map(accessorName), values4 = [], step = _.step || 0.01, p2 = _.probs || range(step / 2, 1 - EPSILON, step), n2 = p2.length;
      groups.forEach((g2) => {
        const q2 = quantiles(g2, p2);
        for (let i2 = 0; i2 < n2; ++i2) {
          const t4 = {};
          for (let i3 = 0; i3 < names.length; ++i3) {
            t4[names[i3]] = g2.dims[i3];
          }
          t4[as[0]] = p2[i2];
          t4[as[1]] = q2[i2];
          values4.push(ingest$1(t4));
        }
      });
      if (this.value) out.rem = this.value;
      this.value = out.add = out.source = values4;
      return out;
    }
  });
  function Relay(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Relay, Transform, {
    transform(_, pulse2) {
      let out, lut;
      if (this.value) {
        lut = this.value;
      } else {
        out = pulse2 = pulse2.addAll();
        lut = this.value = {};
      }
      if (_.derive) {
        out = pulse2.fork(pulse2.NO_SOURCE);
        pulse2.visit(pulse2.REM, (t4) => {
          const id2 = tupleid(t4);
          out.rem.push(lut[id2]);
          lut[id2] = null;
        });
        pulse2.visit(pulse2.ADD, (t4) => {
          const dt = derive(t4);
          lut[tupleid(t4)] = dt;
          out.add.push(dt);
        });
        pulse2.visit(pulse2.MOD, (t4) => {
          const dt = lut[tupleid(t4)];
          for (const k2 in t4) {
            dt[k2] = t4[k2];
            out.modifies(k2);
          }
          out.mod.push(dt);
        });
      }
      return out;
    }
  });
  function Sample(params2) {
    Transform.call(this, [], params2);
    this.count = 0;
  }
  Sample.Definition = {
    "type": "Sample",
    "metadata": {},
    "params": [{
      "name": "size",
      "type": "number",
      "default": 1e3
    }]
  };
  inherits(Sample, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE), mod = _.modified("size"), num = _.size, map4 = this.value.reduce((m4, t4) => (m4[tupleid(t4)] = 1, m4), {});
      let res = this.value, cnt = this.count, cap = 0;
      function update3(t4) {
        let p2, idx;
        if (res.length < num) {
          res.push(t4);
        } else {
          idx = ~~((cnt + 1) * random());
          if (idx < res.length && idx >= cap) {
            p2 = res[idx];
            if (map4[tupleid(p2)]) out.rem.push(p2);
            res[idx] = t4;
          }
        }
        ++cnt;
      }
      if (pulse2.rem.length) {
        pulse2.visit(pulse2.REM, (t4) => {
          const id2 = tupleid(t4);
          if (map4[id2]) {
            map4[id2] = -1;
            out.rem.push(t4);
          }
          --cnt;
        });
        res = res.filter((t4) => map4[tupleid(t4)] !== -1);
      }
      if ((pulse2.rem.length || mod) && res.length < num && pulse2.source) {
        cap = cnt = res.length;
        pulse2.visit(pulse2.SOURCE, (t4) => {
          if (!map4[tupleid(t4)]) update3(t4);
        });
        cap = -1;
      }
      if (mod && res.length > num) {
        const n2 = res.length - num;
        for (let i2 = 0; i2 < n2; ++i2) {
          map4[tupleid(res[i2])] = -1;
          out.rem.push(res[i2]);
        }
        res = res.slice(n2);
      }
      if (pulse2.mod.length) {
        pulse2.visit(pulse2.MOD, (t4) => {
          if (map4[tupleid(t4)]) out.mod.push(t4);
        });
      }
      if (pulse2.add.length) {
        pulse2.visit(pulse2.ADD, update3);
      }
      if (pulse2.add.length || cap < 0) {
        out.add = res.filter((t4) => !map4[tupleid(t4)]);
      }
      this.count = cnt;
      this.value = out.source = res;
      return out;
    }
  });
  function Sequence(params2) {
    Transform.call(this, null, params2);
  }
  Sequence.Definition = {
    "type": "Sequence",
    "metadata": {
      "generates": true,
      "changes": true
    },
    "params": [{
      "name": "start",
      "type": "number",
      "required": true
    }, {
      "name": "stop",
      "type": "number",
      "required": true
    }, {
      "name": "step",
      "type": "number",
      "default": 1
    }, {
      "name": "as",
      "type": "string",
      "default": "data"
    }]
  };
  inherits(Sequence, Transform, {
    transform(_, pulse2) {
      if (this.value && !_.modified()) return;
      const out = pulse2.materialize().fork(pulse2.MOD), as = _.as || "data";
      out.rem = this.value ? pulse2.rem.concat(this.value) : pulse2.rem;
      this.value = range(_.start, _.stop, _.step || 1).map((v3) => {
        const t4 = {};
        t4[as] = v3;
        return ingest$1(t4);
      });
      out.add = pulse2.add.concat(this.value);
      return out;
    }
  });
  function Sieve(params2) {
    Transform.call(this, null, params2);
    this.modified(true);
  }
  inherits(Sieve, Transform, {
    transform(_, pulse2) {
      this.value = pulse2.source;
      return pulse2.changed() ? pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS) : pulse2.StopPropagation;
    }
  });
  function TimeUnit(params2) {
    Transform.call(this, null, params2);
  }
  var OUTPUT = ["unit0", "unit1"];
  TimeUnit.Definition = {
    "type": "TimeUnit",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field",
      "required": true
    }, {
      "name": "interval",
      "type": "boolean",
      "default": true
    }, {
      "name": "units",
      "type": "enum",
      "values": TIME_UNITS,
      "array": true
    }, {
      "name": "step",
      "type": "number",
      "default": 1
    }, {
      "name": "maxbins",
      "type": "number",
      "default": 40
    }, {
      "name": "extent",
      "type": "date",
      "array": true
    }, {
      "name": "timezone",
      "type": "enum",
      "default": "local",
      "values": ["local", "utc"]
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": OUTPUT
    }]
  };
  inherits(TimeUnit, Transform, {
    transform(_, pulse2) {
      const field3 = _.field, band2 = _.interval !== false, utc = _.timezone === "utc", floor2 = this._floor(_, pulse2), offset4 = (utc ? utcInterval : timeInterval2)(floor2.unit).offset, as = _.as || OUTPUT, u0 = as[0], u1 = as[1], step = floor2.step;
      let min4 = floor2.start || Infinity, max4 = floor2.stop || -Infinity, flag2 = pulse2.ADD;
      if (_.modified() || pulse2.changed(pulse2.REM) || pulse2.modified(accessorFields(field3))) {
        pulse2 = pulse2.reflow(true);
        flag2 = pulse2.SOURCE;
        min4 = Infinity;
        max4 = -Infinity;
      }
      pulse2.visit(flag2, (t4) => {
        const v3 = field3(t4);
        let a4, b3;
        if (v3 == null) {
          t4[u0] = null;
          if (band2) t4[u1] = null;
        } else {
          t4[u0] = a4 = b3 = floor2(v3);
          if (band2) t4[u1] = b3 = offset4(a4, step);
          if (a4 < min4) min4 = a4;
          if (b3 > max4) max4 = b3;
        }
      });
      floor2.start = min4;
      floor2.stop = max4;
      return pulse2.modifies(band2 ? as : u0);
    },
    _floor(_, pulse2) {
      const utc = _.timezone === "utc";
      const {
        units,
        step
      } = _.units ? {
        units: _.units,
        step: _.step || 1
      } : bin({
        extent: _.extent || extent(pulse2.materialize(pulse2.SOURCE).source, _.field),
        maxbins: _.maxbins
      });
      const tunits = timeUnits(units), prev = this.value || {}, floor2 = (utc ? utcFloor : timeFloor)(tunits, step);
      floor2.unit = peek(tunits);
      floor2.units = tunits;
      floor2.step = step;
      floor2.start = prev.start;
      floor2.stop = prev.stop;
      return this.value = floor2;
    }
  });
  function TupleIndex(params2) {
    Transform.call(this, fastmap(), params2);
  }
  inherits(TupleIndex, Transform, {
    transform(_, pulse2) {
      const df = pulse2.dataflow, field3 = _.field, index4 = this.value, set7 = (t4) => index4.set(field3(t4), t4);
      let mod = true;
      if (_.modified("field") || pulse2.modified(field3.fields)) {
        index4.clear();
        pulse2.visit(pulse2.SOURCE, set7);
      } else if (pulse2.changed()) {
        pulse2.visit(pulse2.REM, (t4) => index4.delete(field3(t4)));
        pulse2.visit(pulse2.ADD, set7);
      } else {
        mod = false;
      }
      this.modified(mod);
      if (index4.empty > df.cleanThreshold) df.runAfter(index4.clean);
      return pulse2.fork();
    }
  });
  function Values(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Values, Transform, {
    transform(_, pulse2) {
      const run2 = !this.value || _.modified("field") || _.modified("sort") || pulse2.changed() || _.sort && pulse2.modified(_.sort.fields);
      if (run2) {
        this.value = (_.sort ? pulse2.source.slice().sort(stableCompare(_.sort)) : pulse2.source).map(_.field);
      }
    }
  });
  function WindowOp(op, field3, param2, as) {
    const fn = WindowOps[op](field3, param2);
    return {
      init: fn.init || zero,
      update: function(w3, t4) {
        t4[as] = fn.next(w3);
      }
    };
  }
  var WindowOps = {
    row_number: function() {
      return {
        next: (w3) => w3.index + 1
      };
    },
    rank: function() {
      let rank2;
      return {
        init: () => rank2 = 1,
        next: (w3) => {
          const i2 = w3.index, data3 = w3.data;
          return i2 && w3.compare(data3[i2 - 1], data3[i2]) ? rank2 = i2 + 1 : rank2;
        }
      };
    },
    dense_rank: function() {
      let drank;
      return {
        init: () => drank = 1,
        next: (w3) => {
          const i2 = w3.index, d2 = w3.data;
          return i2 && w3.compare(d2[i2 - 1], d2[i2]) ? ++drank : drank;
        }
      };
    },
    percent_rank: function() {
      const rank2 = WindowOps.rank(), next = rank2.next;
      return {
        init: rank2.init,
        next: (w3) => (next(w3) - 1) / (w3.data.length - 1)
      };
    },
    cume_dist: function() {
      let cume;
      return {
        init: () => cume = 0,
        next: (w3) => {
          const d2 = w3.data, c4 = w3.compare;
          let i2 = w3.index;
          if (cume < i2) {
            while (i2 + 1 < d2.length && !c4(d2[i2], d2[i2 + 1])) ++i2;
            cume = i2;
          }
          return (1 + cume) / d2.length;
        }
      };
    },
    ntile: function(field3, num) {
      num = +num;
      if (!(num > 0)) error("ntile num must be greater than zero.");
      const cume = WindowOps.cume_dist(), next = cume.next;
      return {
        init: cume.init,
        next: (w3) => Math.ceil(num * next(w3))
      };
    },
    lag: function(field3, offset4) {
      offset4 = +offset4 || 1;
      return {
        next: (w3) => {
          const i2 = w3.index - offset4;
          return i2 >= 0 ? field3(w3.data[i2]) : null;
        }
      };
    },
    lead: function(field3, offset4) {
      offset4 = +offset4 || 1;
      return {
        next: (w3) => {
          const i2 = w3.index + offset4, d2 = w3.data;
          return i2 < d2.length ? field3(d2[i2]) : null;
        }
      };
    },
    first_value: function(field3) {
      return {
        next: (w3) => field3(w3.data[w3.i0])
      };
    },
    last_value: function(field3) {
      return {
        next: (w3) => field3(w3.data[w3.i1 - 1])
      };
    },
    nth_value: function(field3, nth) {
      nth = +nth;
      if (!(nth > 0)) error("nth_value nth must be greater than zero.");
      return {
        next: (w3) => {
          const i2 = w3.i0 + (nth - 1);
          return i2 < w3.i1 ? field3(w3.data[i2]) : null;
        }
      };
    },
    prev_value: function(field3) {
      let prev;
      return {
        init: () => prev = null,
        next: (w3) => {
          const v3 = field3(w3.data[w3.index]);
          return v3 != null ? prev = v3 : prev;
        }
      };
    },
    next_value: function(field3) {
      let v3, i2;
      return {
        init: () => (v3 = null, i2 = -1),
        next: (w3) => {
          const d2 = w3.data;
          return w3.index <= i2 ? v3 : (i2 = find(field3, d2, w3.index)) < 0 ? (i2 = d2.length, v3 = null) : v3 = field3(d2[i2]);
        }
      };
    }
  };
  function find(field3, data3, index4) {
    for (let n2 = data3.length; index4 < n2; ++index4) {
      const v3 = field3(data3[index4]);
      if (v3 != null) return index4;
    }
    return -1;
  }
  var ValidWindowOps = Object.keys(WindowOps);
  function WindowState(_) {
    const ops2 = array(_.ops), fields = array(_.fields), params2 = array(_.params), aggregate_params = array(_.aggregate_params), as = array(_.as), outputs = this.outputs = [], windows = this.windows = [], inputs = {}, map4 = {}, counts = [], measures = [];
    let countOnly = true;
    function visitInputs(f2) {
      array(accessorFields(f2)).forEach((_2) => inputs[_2] = 1);
    }
    visitInputs(_.sort);
    ops2.forEach((op, i2) => {
      const field3 = fields[i2], param2 = params2[i2], aggregate_param = aggregate_params[i2] || null, mname = accessorName(field3), name4 = measureName(op, mname, as[i2]);
      visitInputs(field3);
      outputs.push(name4);
      if (has(WindowOps, op)) {
        windows.push(WindowOp(op, field3, param2, name4));
      } else {
        if (field3 == null && op !== "count") {
          error("Null aggregate field specified.");
        }
        if (op === "count") {
          counts.push(name4);
          return;
        }
        countOnly = false;
        let m4 = map4[mname];
        if (!m4) {
          m4 = map4[mname] = [];
          m4.field = field3;
          measures.push(m4);
        }
        m4.push(createMeasure(op, aggregate_param, name4));
      }
    });
    if (counts.length || measures.length) {
      this.cell = cell(measures, counts, countOnly);
    }
    this.inputs = Object.keys(inputs);
  }
  var prototype = WindowState.prototype;
  prototype.init = function() {
    this.windows.forEach((_) => _.init());
    if (this.cell) this.cell.init();
  };
  prototype.update = function(w3, t4) {
    const cell2 = this.cell, wind = this.windows, data3 = w3.data, m4 = wind && wind.length;
    let j2;
    if (cell2) {
      for (j2 = w3.p0; j2 < w3.i0; ++j2) cell2.rem(data3[j2]);
      for (j2 = w3.p1; j2 < w3.i1; ++j2) cell2.add(data3[j2]);
      cell2.set(t4);
    }
    for (j2 = 0; j2 < m4; ++j2) wind[j2].update(w3, t4);
  };
  function cell(measures, counts, countOnly) {
    measures = measures.map((m4) => compileMeasures(m4, m4.field));
    const cell2 = {
      num: 0,
      agg: null,
      store: false,
      count: counts
    };
    if (!countOnly) {
      var n2 = measures.length, a4 = cell2.agg = Array(n2), i2 = 0;
      for (; i2 < n2; ++i2) a4[i2] = new measures[i2](cell2);
    }
    if (cell2.store) {
      var store = cell2.data = new TupleStore();
    }
    cell2.add = function(t4) {
      cell2.num += 1;
      if (countOnly) return;
      if (store) store.add(t4);
      for (let i3 = 0; i3 < n2; ++i3) {
        a4[i3].add(a4[i3].get(t4), t4);
      }
    };
    cell2.rem = function(t4) {
      cell2.num -= 1;
      if (countOnly) return;
      if (store) store.rem(t4);
      for (let i3 = 0; i3 < n2; ++i3) {
        a4[i3].rem(a4[i3].get(t4), t4);
      }
    };
    cell2.set = function(t4) {
      let i3, n3;
      if (store) store.values();
      for (i3 = 0, n3 = counts.length; i3 < n3; ++i3) t4[counts[i3]] = cell2.num;
      if (!countOnly) for (i3 = 0, n3 = a4.length; i3 < n3; ++i3) a4[i3].set(t4);
    };
    cell2.init = function() {
      cell2.num = 0;
      if (store) store.reset();
      for (let i3 = 0; i3 < n2; ++i3) a4[i3].init();
    };
    return cell2;
  }
  function Window(params2) {
    Transform.call(this, {}, params2);
    this._mlen = 0;
    this._mods = [];
  }
  Window.Definition = {
    "type": "Window",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "sort",
      "type": "compare"
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "ops",
      "type": "enum",
      "array": true,
      "values": ValidWindowOps.concat(ValidAggregateOps)
    }, {
      "name": "params",
      "type": "number",
      "null": true,
      "array": true
    }, {
      "name": "aggregate_params",
      "type": "number",
      "null": true,
      "array": true
    }, {
      "name": "fields",
      "type": "field",
      "null": true,
      "array": true
    }, {
      "name": "as",
      "type": "string",
      "null": true,
      "array": true
    }, {
      "name": "frame",
      "type": "number",
      "null": true,
      "array": true,
      "length": 2,
      "default": [null, 0]
    }, {
      "name": "ignorePeers",
      "type": "boolean",
      "default": false
    }]
  };
  inherits(Window, Transform, {
    transform(_, pulse2) {
      this.stamp = pulse2.stamp;
      const mod = _.modified(), cmp = stableCompare(_.sort), key2 = groupkey(_.groupby), group2 = (t4) => this.group(key2(t4));
      let state = this.state;
      if (!state || mod) {
        state = this.state = new WindowState(_);
      }
      if (mod || pulse2.modified(state.inputs)) {
        this.value = {};
        pulse2.visit(pulse2.SOURCE, (t4) => group2(t4).add(t4));
      } else {
        pulse2.visit(pulse2.REM, (t4) => group2(t4).remove(t4));
        pulse2.visit(pulse2.ADD, (t4) => group2(t4).add(t4));
      }
      for (let i2 = 0, n2 = this._mlen; i2 < n2; ++i2) {
        processPartition(this._mods[i2], state, cmp, _);
      }
      this._mlen = 0;
      this._mods = [];
      return pulse2.reflow(mod).modifies(state.outputs);
    },
    group(key2) {
      let group2 = this.value[key2];
      if (!group2) {
        group2 = this.value[key2] = SortedList(tupleid);
        group2.stamp = -1;
      }
      if (group2.stamp < this.stamp) {
        group2.stamp = this.stamp;
        this._mods[this._mlen++] = group2;
      }
      return group2;
    }
  });
  function processPartition(list, state, cmp, _) {
    const sort3 = _.sort, range7 = sort3 && !_.ignorePeers, frame2 = _.frame || [null, 0], data3 = list.data(cmp), n2 = data3.length, b3 = range7 ? bisector(sort3) : null, w3 = {
      i0: 0,
      i1: 0,
      p0: 0,
      p1: 0,
      index: 0,
      data: data3,
      compare: sort3 || constant(-1)
    };
    state.init();
    for (let i2 = 0; i2 < n2; ++i2) {
      setWindow(w3, frame2, i2, n2);
      if (range7) adjustRange(w3, b3);
      state.update(w3, data3[i2]);
    }
  }
  function setWindow(w3, f2, i2, n2) {
    w3.p0 = w3.i0;
    w3.p1 = w3.i1;
    w3.i0 = f2[0] == null ? 0 : Math.max(0, i2 - Math.abs(f2[0]));
    w3.i1 = f2[1] == null ? n2 : Math.min(n2, i2 + Math.abs(f2[1]) + 1);
    w3.index = i2;
  }
  function adjustRange(w3, bisect2) {
    const r0 = w3.i0, r1 = w3.i1 - 1, c4 = w3.compare, d2 = w3.data, n2 = d2.length - 1;
    if (r0 > 0 && !c4(d2[r0], d2[r0 - 1])) w3.i0 = bisect2.left(d2, d2[r0]);
    if (r1 < n2 && !c4(d2[r1], d2[r1 + 1])) w3.i1 = bisect2.right(d2, d2[r1]);
  }

  // node_modules/vega-view-transforms/build/vega-view-transforms.module.js
  var vega_view_transforms_module_exports = {};
  __export(vega_view_transforms_module_exports, {
    bound: () => Bound,
    identifier: () => Identifier,
    mark: () => Mark,
    overlap: () => Overlap,
    render: () => Render,
    viewlayout: () => ViewLayout
  });

  // node_modules/d3-shape/src/constant.js
  function constant_default(x5) {
    return function constant3() {
      return x5;
    };
  }

  // node_modules/d3-shape/src/math.js
  var abs = Math.abs;
  var atan2 = Math.atan2;
  var cos = Math.cos;
  var max2 = Math.max;
  var min2 = Math.min;
  var sin = Math.sin;
  var sqrt = Math.sqrt;
  var epsilon2 = 1e-12;
  var pi = Math.PI;
  var halfPi = pi / 2;
  var tau = 2 * pi;
  function acos(x5) {
    return x5 > 1 ? 0 : x5 < -1 ? pi : Math.acos(x5);
  }
  function asin(x5) {
    return x5 >= 1 ? halfPi : x5 <= -1 ? -halfPi : Math.asin(x5);
  }

  // node_modules/d3-path/src/path.js
  var pi2 = Math.PI;
  var tau2 = 2 * pi2;
  var epsilon3 = 1e-6;
  var tauEpsilon = tau2 - epsilon3;
  function append(strings) {
    this._ += strings[0];
    for (let i2 = 1, n2 = strings.length; i2 < n2; ++i2) {
      this._ += arguments[i2] + strings[i2];
    }
  }
  function appendRound(digits) {
    let d2 = Math.floor(digits);
    if (!(d2 >= 0)) throw new Error(`invalid digits: ${digits}`);
    if (d2 > 15) return append;
    const k2 = 10 ** d2;
    return function(strings) {
      this._ += strings[0];
      for (let i2 = 1, n2 = strings.length; i2 < n2; ++i2) {
        this._ += Math.round(arguments[i2] * k2) / k2 + strings[i2];
      }
    };
  }
  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(x5, y5) {
      this._append`M${this._x0 = this._x1 = +x5},${this._y0 = this._y1 = +y5}`;
    }
    closePath() {
      if (this._x1 !== null) {
        this._x1 = this._x0, this._y1 = this._y0;
        this._append`Z`;
      }
    }
    lineTo(x5, y5) {
      this._append`L${this._x1 = +x5},${this._y1 = +y5}`;
    }
    quadraticCurveTo(x12, y12, x5, y5) {
      this._append`Q${+x12},${+y12},${this._x1 = +x5},${this._y1 = +y5}`;
    }
    bezierCurveTo(x12, y12, x22, y22, x5, y5) {
      this._append`C${+x12},${+y12},${+x22},${+y22},${this._x1 = +x5},${this._y1 = +y5}`;
    }
    arcTo(x12, y12, x22, y22, r2) {
      x12 = +x12, y12 = +y12, x22 = +x22, y22 = +y22, r2 = +r2;
      if (r2 < 0) throw new Error(`negative radius: ${r2}`);
      let x06 = this._x1, y06 = this._y1, x21 = x22 - x12, y21 = y22 - y12, x01 = x06 - x12, y01 = y06 - y12, l01_2 = x01 * x01 + y01 * y01;
      if (this._x1 === null) {
        this._append`M${this._x1 = x12},${this._y1 = y12}`;
      } else if (!(l01_2 > epsilon3)) ;
      else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon3) || !r2) {
        this._append`L${this._x1 = x12},${this._y1 = y12}`;
      } else {
        let x20 = x22 - x06, y20 = y22 - y06, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l2 = r2 * Math.tan((pi2 - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l2 / l01, t21 = l2 / l21;
        if (Math.abs(t01 - 1) > epsilon3) {
          this._append`L${x12 + t01 * x01},${y12 + t01 * y01}`;
        }
        this._append`A${r2},${r2},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x12 + t21 * x21},${this._y1 = y12 + t21 * y21}`;
      }
    }
    arc(x5, y5, r2, a0, a1, ccw) {
      x5 = +x5, y5 = +y5, r2 = +r2, ccw = !!ccw;
      if (r2 < 0) throw new Error(`negative radius: ${r2}`);
      let dx = r2 * Math.cos(a0), dy = r2 * Math.sin(a0), x06 = x5 + dx, y06 = y5 + dy, cw2 = 1 ^ ccw, da2 = ccw ? a0 - a1 : a1 - a0;
      if (this._x1 === null) {
        this._append`M${x06},${y06}`;
      } else if (Math.abs(this._x1 - x06) > epsilon3 || Math.abs(this._y1 - y06) > epsilon3) {
        this._append`L${x06},${y06}`;
      }
      if (!r2) return;
      if (da2 < 0) da2 = da2 % tau2 + tau2;
      if (da2 > tauEpsilon) {
        this._append`A${r2},${r2},0,1,${cw2},${x5 - dx},${y5 - dy}A${r2},${r2},0,1,${cw2},${this._x1 = x06},${this._y1 = y06}`;
      } else if (da2 > epsilon3) {
        this._append`A${r2},${r2},0,${+(da2 >= pi2)},${cw2},${this._x1 = x5 + r2 * Math.cos(a1)},${this._y1 = y5 + r2 * Math.sin(a1)}`;
      }
    }
    rect(x5, y5, w3, h3) {
      this._append`M${this._x0 = this._x1 = +x5},${this._y0 = this._y1 = +y5}h${w3 = +w3}v${+h3}h${-w3}Z`;
    }
    toString() {
      return this._;
    }
  };
  function path() {
    return new Path();
  }
  path.prototype = Path.prototype;

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

  // node_modules/d3-shape/src/arc.js
  function arcInnerRadius(d2) {
    return d2.innerRadius;
  }
  function arcOuterRadius(d2) {
    return d2.outerRadius;
  }
  function arcStartAngle(d2) {
    return d2.startAngle;
  }
  function arcEndAngle(d2) {
    return d2.endAngle;
  }
  function arcPadAngle(d2) {
    return d2 && d2.padAngle;
  }
  function intersect(x06, y06, x12, y12, x22, y22, x32, y32) {
    var x10 = x12 - x06, y10 = y12 - y06, x322 = x32 - x22, y322 = y32 - y22, t4 = y322 * x10 - x322 * y10;
    if (t4 * t4 < epsilon2) return;
    t4 = (x322 * (y06 - y22) - y322 * (x06 - x22)) / t4;
    return [x06 + t4 * x10, y06 + t4 * y10];
  }
  function cornerTangents(x06, y06, x12, y12, r1, rc, cw2) {
    var x01 = x06 - x12, y01 = y06 - y12, lo = (cw2 ? rc : -rc) / sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x06 + ox, y11 = y06 + oy, x10 = x12 + ox, y10 = y12 + oy, x004 = (x11 + x10) / 2, y004 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r2 = r1 - rc, D3 = x11 * y10 - x10 * y11, d3 = (dy < 0 ? -1 : 1) * sqrt(max2(0, r2 * r2 * d2 - D3 * D3)), cx0 = (D3 * dy - dx * d3) / d2, cy0 = (-D3 * dx - dy * d3) / d2, cx1 = (D3 * dy + dx * d3) / d2, cy1 = (-D3 * dx + dy * d3) / d2, dx0 = cx0 - x004, dy0 = cy0 - y004, dx1 = cx1 - x004, dy1 = cy1 - y004;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
    return {
      cx: cx0,
      cy: cy0,
      x01: -ox,
      y01: -oy,
      x11: cx0 * (r1 / r2 - 1),
      y11: cy0 * (r1 / r2 - 1)
    };
  }
  function arc_default() {
    var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant_default(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context3 = null, path3 = withPath(arc4);
    function arc4() {
      var buffer, r2, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da2 = abs(a1 - a0), cw2 = a1 > a0;
      if (!context3) context3 = buffer = path3();
      if (r1 < r0) r2 = r1, r1 = r0, r0 = r2;
      if (!(r1 > epsilon2)) context3.moveTo(0, 0);
      else if (da2 > tau - epsilon2) {
        context3.moveTo(r1 * cos(a0), r1 * sin(a0));
        context3.arc(0, 0, r1, a0, a1, !cw2);
        if (r0 > epsilon2) {
          context3.moveTo(r0 * cos(a1), r0 * sin(a1));
          context3.arc(0, 0, r0, a1, a0, cw2);
        }
      } else {
        var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da2, da1 = da2, ap = padAngle.apply(this, arguments) / 2, rp = ap > epsilon2 && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)), rc = min2(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t04, t13;
        if (rp > epsilon2) {
          var p02 = asin(rp / r0 * sin(ap)), p1 = asin(rp / r1 * sin(ap));
          if ((da0 -= p02 * 2) > epsilon2) p02 *= cw2 ? 1 : -1, a00 += p02, a10 -= p02;
          else da0 = 0, a00 = a10 = (a0 + a1) / 2;
          if ((da1 -= p1 * 2) > epsilon2) p1 *= cw2 ? 1 : -1, a01 += p1, a11 -= p1;
          else da1 = 0, a01 = a11 = (a0 + a1) / 2;
        }
        var x01 = r1 * cos(a01), y01 = r1 * sin(a01), x10 = r0 * cos(a10), y10 = r0 * sin(a10);
        if (rc > epsilon2) {
          var x11 = r1 * cos(a11), y11 = r1 * sin(a11), x004 = r0 * cos(a00), y004 = r0 * sin(a00), oc;
          if (da2 < pi) {
            if (oc = intersect(x01, y01, x004, y004, x11, y11, x10, y10)) {
              var ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2), lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
              rc0 = min2(rc, (r0 - lc) / (kc - 1));
              rc1 = min2(rc, (r1 - lc) / (kc + 1));
            } else {
              rc0 = rc1 = 0;
            }
          }
        }
        if (!(da1 > epsilon2)) context3.moveTo(x01, y01);
        else if (rc1 > epsilon2) {
          t04 = cornerTangents(x004, y004, x01, y01, r1, rc1, cw2);
          t13 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw2);
          context3.moveTo(t04.cx + t04.x01, t04.cy + t04.y01);
          if (rc1 < rc) context3.arc(t04.cx, t04.cy, rc1, atan2(t04.y01, t04.x01), atan2(t13.y01, t13.x01), !cw2);
          else {
            context3.arc(t04.cx, t04.cy, rc1, atan2(t04.y01, t04.x01), atan2(t04.y11, t04.x11), !cw2);
            context3.arc(0, 0, r1, atan2(t04.cy + t04.y11, t04.cx + t04.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), !cw2);
            context3.arc(t13.cx, t13.cy, rc1, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw2);
          }
        } else context3.moveTo(x01, y01), context3.arc(0, 0, r1, a01, a11, !cw2);
        if (!(r0 > epsilon2) || !(da0 > epsilon2)) context3.lineTo(x10, y10);
        else if (rc0 > epsilon2) {
          t04 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw2);
          t13 = cornerTangents(x01, y01, x004, y004, r0, -rc0, cw2);
          context3.lineTo(t04.cx + t04.x01, t04.cy + t04.y01);
          if (rc0 < rc) context3.arc(t04.cx, t04.cy, rc0, atan2(t04.y01, t04.x01), atan2(t13.y01, t13.x01), !cw2);
          else {
            context3.arc(t04.cx, t04.cy, rc0, atan2(t04.y01, t04.x01), atan2(t04.y11, t04.x11), !cw2);
            context3.arc(0, 0, r0, atan2(t04.cy + t04.y11, t04.cx + t04.x11), atan2(t13.cy + t13.y11, t13.cx + t13.x11), cw2);
            context3.arc(t13.cx, t13.cy, rc0, atan2(t13.y11, t13.x11), atan2(t13.y01, t13.x01), !cw2);
          }
        } else context3.arc(0, 0, r0, a10, a00, cw2);
      }
      context3.closePath();
      if (buffer) return context3 = null, buffer + "" || null;
    }
    arc4.centroid = function() {
      var r2 = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a4 = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;
      return [cos(a4) * r2, sin(a4) * r2];
    };
    arc4.innerRadius = function(_) {
      return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant_default(+_), arc4) : innerRadius;
    };
    arc4.outerRadius = function(_) {
      return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant_default(+_), arc4) : outerRadius;
    };
    arc4.cornerRadius = function(_) {
      return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant_default(+_), arc4) : cornerRadius;
    };
    arc4.padRadius = function(_) {
      return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant_default(+_), arc4) : padRadius;
    };
    arc4.startAngle = function(_) {
      return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant_default(+_), arc4) : startAngle;
    };
    arc4.endAngle = function(_) {
      return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant_default(+_), arc4) : endAngle;
    };
    arc4.padAngle = function(_) {
      return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant_default(+_), arc4) : padAngle;
    };
    arc4.context = function(_) {
      return arguments.length ? (context3 = _ == null ? null : _, arc4) : context3;
    };
    return arc4;
  }

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

  // node_modules/d3-shape/src/curve/linear.js
  function Linear(context3) {
    this._context = context3;
  }
  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(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
        // falls through
        default:
          this._context.lineTo(x5, y5);
          break;
      }
    }
  };
  function linear_default(context3) {
    return new Linear(context3);
  }

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

  // node_modules/d3-shape/src/line.js
  function line_default(x5, y5) {
    var defined2 = constant_default(true), context3 = null, curve2 = linear_default, output3 = null, path3 = withPath(line4);
    x5 = typeof x5 === "function" ? x5 : x5 === void 0 ? x : constant_default(x5);
    y5 = typeof y5 === "function" ? y5 : y5 === void 0 ? y : constant_default(y5);
    function line4(data3) {
      var i2, n2 = (data3 = array_default(data3)).length, d2, defined0 = false, buffer;
      if (context3 == null) output3 = curve2(buffer = path3());
      for (i2 = 0; i2 <= n2; ++i2) {
        if (!(i2 < n2 && defined2(d2 = data3[i2], i2, data3)) === defined0) {
          if (defined0 = !defined0) output3.lineStart();
          else output3.lineEnd();
        }
        if (defined0) output3.point(+x5(d2, i2, data3), +y5(d2, i2, data3));
      }
      if (buffer) return output3 = null, buffer + "" || null;
    }
    line4.x = function(_) {
      return arguments.length ? (x5 = typeof _ === "function" ? _ : constant_default(+_), line4) : x5;
    };
    line4.y = function(_) {
      return arguments.length ? (y5 = typeof _ === "function" ? _ : constant_default(+_), line4) : y5;
    };
    line4.defined = function(_) {
      return arguments.length ? (defined2 = typeof _ === "function" ? _ : constant_default(!!_), line4) : defined2;
    };
    line4.curve = function(_) {
      return arguments.length ? (curve2 = _, context3 != null && (output3 = curve2(context3)), line4) : curve2;
    };
    line4.context = function(_) {
      return arguments.length ? (_ == null ? context3 = output3 = null : output3 = curve2(context3 = _), line4) : context3;
    };
    return line4;
  }

  // node_modules/d3-shape/src/area.js
  function area_default(x06, y06, y12) {
    var x12 = null, defined2 = constant_default(true), context3 = null, curve2 = linear_default, output3 = null, path3 = withPath(area4);
    x06 = typeof x06 === "function" ? x06 : x06 === void 0 ? x : constant_default(+x06);
    y06 = typeof y06 === "function" ? y06 : y06 === void 0 ? constant_default(0) : constant_default(+y06);
    y12 = typeof y12 === "function" ? y12 : y12 === void 0 ? y : constant_default(+y12);
    function area4(data3) {
      var i2, j2, k2, n2 = (data3 = array_default(data3)).length, d2, defined0 = false, buffer, x0z = new Array(n2), y0z = new Array(n2);
      if (context3 == null) output3 = curve2(buffer = path3());
      for (i2 = 0; i2 <= n2; ++i2) {
        if (!(i2 < n2 && defined2(d2 = data3[i2], i2, data3)) === defined0) {
          if (defined0 = !defined0) {
            j2 = i2;
            output3.areaStart();
            output3.lineStart();
          } else {
            output3.lineEnd();
            output3.lineStart();
            for (k2 = i2 - 1; k2 >= j2; --k2) {
              output3.point(x0z[k2], y0z[k2]);
            }
            output3.lineEnd();
            output3.areaEnd();
          }
        }
        if (defined0) {
          x0z[i2] = +x06(d2, i2, data3), y0z[i2] = +y06(d2, i2, data3);
          output3.point(x12 ? +x12(d2, i2, data3) : x0z[i2], y12 ? +y12(d2, i2, data3) : y0z[i2]);
        }
      }
      if (buffer) return output3 = null, buffer + "" || null;
    }
    function arealine() {
      return line_default().defined(defined2).curve(curve2).context(context3);
    }
    area4.x = function(_) {
      return arguments.length ? (x06 = typeof _ === "function" ? _ : constant_default(+_), x12 = null, area4) : x06;
    };
    area4.x0 = function(_) {
      return arguments.length ? (x06 = typeof _ === "function" ? _ : constant_default(+_), area4) : x06;
    };
    area4.x1 = function(_) {
      return arguments.length ? (x12 = _ == null ? null : typeof _ === "function" ? _ : constant_default(+_), area4) : x12;
    };
    area4.y = function(_) {
      return arguments.length ? (y06 = typeof _ === "function" ? _ : constant_default(+_), y12 = null, area4) : y06;
    };
    area4.y0 = function(_) {
      return arguments.length ? (y06 = typeof _ === "function" ? _ : constant_default(+_), area4) : y06;
    };
    area4.y1 = function(_) {
      return arguments.length ? (y12 = _ == null ? null : typeof _ === "function" ? _ : constant_default(+_), area4) : y12;
    };
    area4.lineX0 = area4.lineY0 = function() {
      return arealine().x(x06).y(y06);
    };
    area4.lineY1 = function() {
      return arealine().x(x06).y(y12);
    };
    area4.lineX1 = function() {
      return arealine().x(x12).y(y06);
    };
    area4.defined = function(_) {
      return arguments.length ? (defined2 = typeof _ === "function" ? _ : constant_default(!!_), area4) : defined2;
    };
    area4.curve = function(_) {
      return arguments.length ? (curve2 = _, context3 != null && (output3 = curve2(context3)), area4) : curve2;
    };
    area4.context = function(_) {
      return arguments.length ? (_ == null ? context3 = output3 = null : output3 = curve2(context3 = _), area4) : context3;
    };
    return area4;
  }

  // node_modules/d3-shape/src/symbol/circle.js
  var circle_default = {
    draw(context3, size) {
      const r2 = sqrt(size / pi);
      context3.moveTo(r2, 0);
      context3.arc(0, 0, r2, 0, tau);
    }
  };

  // node_modules/d3-shape/src/symbol.js
  function Symbol2(type3, size) {
    let context3 = null, path3 = withPath(symbol2);
    type3 = typeof type3 === "function" ? type3 : constant_default(type3 || circle_default);
    size = typeof size === "function" ? size : constant_default(size === void 0 ? 64 : +size);
    function symbol2() {
      let buffer;
      if (!context3) context3 = buffer = path3();
      type3.apply(this, arguments).draw(context3, +size.apply(this, arguments));
      if (buffer) return context3 = null, buffer + "" || null;
    }
    symbol2.type = function(_) {
      return arguments.length ? (type3 = typeof _ === "function" ? _ : constant_default(_), symbol2) : type3;
    };
    symbol2.size = function(_) {
      return arguments.length ? (size = typeof _ === "function" ? _ : constant_default(+_), symbol2) : size;
    };
    symbol2.context = function(_) {
      return arguments.length ? (context3 = _ == null ? null : _, symbol2) : context3;
    };
    return symbol2;
  }

  // node_modules/d3-shape/src/noop.js
  function noop_default() {
  }

  // node_modules/d3-shape/src/curve/basis.js
  function point(that, x5, y5) {
    that._context.bezierCurveTo(
      (2 * that._x0 + that._x1) / 3,
      (2 * that._y0 + that._y1) / 3,
      (that._x0 + 2 * that._x1) / 3,
      (that._y0 + 2 * that._y1) / 3,
      (that._x0 + 4 * that._x1 + x5) / 6,
      (that._y0 + 4 * that._y1 + y5) / 6
    );
  }
  function Basis(context3) {
    this._context = context3;
  }
  Basis.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._y0 = this._y1 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 3:
          point(this, this._x1, this._y1);
        // falls through
        case 2:
          this._context.lineTo(this._x1, this._y1);
          break;
      }
      if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
          this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6);
        // falls through
        default:
          point(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = x5;
      this._y0 = this._y1, this._y1 = y5;
    }
  };
  function basis_default(context3) {
    return new Basis(context3);
  }

  // node_modules/d3-shape/src/curve/basisClosed.js
  function BasisClosed(context3) {
    this._context = context3;
  }
  BasisClosed.prototype = {
    areaStart: noop_default,
    areaEnd: noop_default,
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 1: {
          this._context.moveTo(this._x2, this._y2);
          this._context.closePath();
          break;
        }
        case 2: {
          this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);
          this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);
          this._context.closePath();
          break;
        }
        case 3: {
          this.point(this._x2, this._y2);
          this.point(this._x3, this._y3);
          this.point(this._x4, this._y4);
          break;
        }
      }
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._x2 = x5, this._y2 = y5;
          break;
        case 1:
          this._point = 2;
          this._x3 = x5, this._y3 = y5;
          break;
        case 2:
          this._point = 3;
          this._x4 = x5, this._y4 = y5;
          this._context.moveTo((this._x0 + 4 * this._x1 + x5) / 6, (this._y0 + 4 * this._y1 + y5) / 6);
          break;
        default:
          point(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = x5;
      this._y0 = this._y1, this._y1 = y5;
    }
  };
  function basisClosed_default(context3) {
    return new BasisClosed(context3);
  }

  // node_modules/d3-shape/src/curve/basisOpen.js
  function BasisOpen(context3) {
    this._context = context3;
  }
  BasisOpen.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._y0 = this._y1 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
          var x06 = (this._x0 + 4 * this._x1 + x5) / 6, y06 = (this._y0 + 4 * this._y1 + y5) / 6;
          this._line ? this._context.lineTo(x06, y06) : this._context.moveTo(x06, y06);
          break;
        case 3:
          this._point = 4;
        // falls through
        default:
          point(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = x5;
      this._y0 = this._y1, this._y1 = y5;
    }
  };
  function basisOpen_default(context3) {
    return new BasisOpen(context3);
  }

  // node_modules/d3-shape/src/curve/bundle.js
  function Bundle(context3, beta) {
    this._basis = new Basis(context3);
    this._beta = beta;
  }
  Bundle.prototype = {
    lineStart: function() {
      this._x = [];
      this._y = [];
      this._basis.lineStart();
    },
    lineEnd: function() {
      var x5 = this._x, y5 = this._y, j2 = x5.length - 1;
      if (j2 > 0) {
        var x06 = x5[0], y06 = y5[0], dx = x5[j2] - x06, dy = y5[j2] - y06, i2 = -1, t4;
        while (++i2 <= j2) {
          t4 = i2 / j2;
          this._basis.point(
            this._beta * x5[i2] + (1 - this._beta) * (x06 + t4 * dx),
            this._beta * y5[i2] + (1 - this._beta) * (y06 + t4 * dy)
          );
        }
      }
      this._x = this._y = null;
      this._basis.lineEnd();
    },
    point: function(x5, y5) {
      this._x.push(+x5);
      this._y.push(+y5);
    }
  };
  var bundle_default = function custom(beta) {
    function bundle2(context3) {
      return beta === 1 ? new Basis(context3) : new Bundle(context3, beta);
    }
    bundle2.beta = function(beta2) {
      return custom(+beta2);
    };
    return bundle2;
  }(0.85);

  // node_modules/d3-shape/src/curve/cardinal.js
  function point2(that, x5, y5) {
    that._context.bezierCurveTo(
      that._x1 + that._k * (that._x2 - that._x0),
      that._y1 + that._k * (that._y2 - that._y0),
      that._x2 + that._k * (that._x1 - x5),
      that._y2 + that._k * (that._y1 - y5),
      that._x2,
      that._y2
    );
  }
  function Cardinal(context3, tension) {
    this._context = context3;
    this._k = (1 - tension) / 6;
  }
  Cardinal.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 2:
          this._context.lineTo(this._x2, this._y2);
          break;
        case 3:
          point2(this, this._x1, this._y1);
          break;
      }
      if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
          this._x1 = x5, this._y1 = y5;
          break;
        case 2:
          this._point = 3;
        // falls through
        default:
          point2(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var cardinal_default = function custom2(tension) {
    function cardinal(context3) {
      return new Cardinal(context3, tension);
    }
    cardinal.tension = function(tension2) {
      return custom2(+tension2);
    };
    return cardinal;
  }(0);

  // node_modules/d3-shape/src/curve/cardinalClosed.js
  function CardinalClosed(context3, tension) {
    this._context = context3;
    this._k = (1 - tension) / 6;
  }
  CardinalClosed.prototype = {
    areaStart: noop_default,
    areaEnd: noop_default,
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 1: {
          this._context.moveTo(this._x3, this._y3);
          this._context.closePath();
          break;
        }
        case 2: {
          this._context.lineTo(this._x3, this._y3);
          this._context.closePath();
          break;
        }
        case 3: {
          this.point(this._x3, this._y3);
          this.point(this._x4, this._y4);
          this.point(this._x5, this._y5);
          break;
        }
      }
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._x3 = x5, this._y3 = y5;
          break;
        case 1:
          this._point = 2;
          this._context.moveTo(this._x4 = x5, this._y4 = y5);
          break;
        case 2:
          this._point = 3;
          this._x5 = x5, this._y5 = y5;
          break;
        default:
          point2(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var cardinalClosed_default = function custom3(tension) {
    function cardinal(context3) {
      return new CardinalClosed(context3, tension);
    }
    cardinal.tension = function(tension2) {
      return custom3(+tension2);
    };
    return cardinal;
  }(0);

  // node_modules/d3-shape/src/curve/cardinalOpen.js
  function CardinalOpen(context3, tension) {
    this._context = context3;
    this._k = (1 - tension) / 6;
  }
  CardinalOpen.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
          this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
          break;
        case 3:
          this._point = 4;
        // falls through
        default:
          point2(this, x5, y5);
          break;
      }
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var cardinalOpen_default = function custom4(tension) {
    function cardinal(context3) {
      return new CardinalOpen(context3, tension);
    }
    cardinal.tension = function(tension2) {
      return custom4(+tension2);
    };
    return cardinal;
  }(0);

  // node_modules/d3-shape/src/curve/catmullRom.js
  function point3(that, x5, y5) {
    var x12 = that._x1, y12 = that._y1, x22 = that._x2, y22 = that._y2;
    if (that._l01_a > epsilon2) {
      var a4 = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a, n2 = 3 * that._l01_a * (that._l01_a + that._l12_a);
      x12 = (x12 * a4 - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n2;
      y12 = (y12 * a4 - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n2;
    }
    if (that._l23_a > epsilon2) {
      var b3 = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a, m4 = 3 * that._l23_a * (that._l23_a + that._l12_a);
      x22 = (x22 * b3 + that._x1 * that._l23_2a - x5 * that._l12_2a) / m4;
      y22 = (y22 * b3 + that._y1 * that._l23_2a - y5 * that._l12_2a) / m4;
    }
    that._context.bezierCurveTo(x12, y12, x22, y22, that._x2, that._y2);
  }
  function CatmullRom(context3, alpha) {
    this._context = context3;
    this._alpha = alpha;
  }
  CatmullRom.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
      this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 2:
          this._context.lineTo(this._x2, this._y2);
          break;
        case 3:
          this.point(this._x2, this._y2);
          break;
      }
      if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      if (this._point) {
        var x23 = this._x2 - x5, y23 = this._y2 - y5;
        this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
      }
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
        // falls through
        default:
          point3(this, x5, y5);
          break;
      }
      this._l01_a = this._l12_a, this._l12_a = this._l23_a;
      this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var catmullRom_default = function custom5(alpha) {
    function catmullRom(context3) {
      return alpha ? new CatmullRom(context3, alpha) : new Cardinal(context3, 0);
    }
    catmullRom.alpha = function(alpha2) {
      return custom5(+alpha2);
    };
    return catmullRom;
  }(0.5);

  // node_modules/d3-shape/src/curve/catmullRomClosed.js
  function CatmullRomClosed(context3, alpha) {
    this._context = context3;
    this._alpha = alpha;
  }
  CatmullRomClosed.prototype = {
    areaStart: noop_default,
    areaEnd: noop_default,
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;
      this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 1: {
          this._context.moveTo(this._x3, this._y3);
          this._context.closePath();
          break;
        }
        case 2: {
          this._context.lineTo(this._x3, this._y3);
          this._context.closePath();
          break;
        }
        case 3: {
          this.point(this._x3, this._y3);
          this.point(this._x4, this._y4);
          this.point(this._x5, this._y5);
          break;
        }
      }
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      if (this._point) {
        var x23 = this._x2 - x5, y23 = this._y2 - y5;
        this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
      }
      switch (this._point) {
        case 0:
          this._point = 1;
          this._x3 = x5, this._y3 = y5;
          break;
        case 1:
          this._point = 2;
          this._context.moveTo(this._x4 = x5, this._y4 = y5);
          break;
        case 2:
          this._point = 3;
          this._x5 = x5, this._y5 = y5;
          break;
        default:
          point3(this, x5, y5);
          break;
      }
      this._l01_a = this._l12_a, this._l12_a = this._l23_a;
      this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var catmullRomClosed_default = function custom6(alpha) {
    function catmullRom(context3) {
      return alpha ? new CatmullRomClosed(context3, alpha) : new CardinalClosed(context3, 0);
    }
    catmullRom.alpha = function(alpha2) {
      return custom6(+alpha2);
    };
    return catmullRom;
  }(0.5);

  // node_modules/d3-shape/src/curve/catmullRomOpen.js
  function CatmullRomOpen(context3, alpha) {
    this._context = context3;
    this._alpha = alpha;
  }
  CatmullRomOpen.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
      this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
    },
    lineEnd: function() {
      if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      if (this._point) {
        var x23 = this._x2 - x5, y23 = this._y2 - y5;
        this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
      }
      switch (this._point) {
        case 0:
          this._point = 1;
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
          this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
          break;
        case 3:
          this._point = 4;
        // falls through
        default:
          point3(this, x5, y5);
          break;
      }
      this._l01_a = this._l12_a, this._l12_a = this._l23_a;
      this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;
      this._x0 = this._x1, this._x1 = this._x2, this._x2 = x5;
      this._y0 = this._y1, this._y1 = this._y2, this._y2 = y5;
    }
  };
  var catmullRomOpen_default = function custom7(alpha) {
    function catmullRom(context3) {
      return alpha ? new CatmullRomOpen(context3, alpha) : new CardinalOpen(context3, 0);
    }
    catmullRom.alpha = function(alpha2) {
      return custom7(+alpha2);
    };
    return catmullRom;
  }(0.5);

  // node_modules/d3-shape/src/curve/linearClosed.js
  function LinearClosed(context3) {
    this._context = context3;
  }
  LinearClosed.prototype = {
    areaStart: noop_default,
    areaEnd: noop_default,
    lineStart: function() {
      this._point = 0;
    },
    lineEnd: function() {
      if (this._point) this._context.closePath();
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      if (this._point) this._context.lineTo(x5, y5);
      else this._point = 1, this._context.moveTo(x5, y5);
    }
  };
  function linearClosed_default(context3) {
    return new LinearClosed(context3);
  }

  // node_modules/d3-shape/src/curve/monotone.js
  function sign(x5) {
    return x5 < 0 ? -1 : 1;
  }
  function slope3(that, x22, y22) {
    var h0 = that._x1 - that._x0, h1 = x22 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y22 - that._y1) / (h1 || h0 < 0 && -0), p2 = (s0 * h1 + s1 * h0) / (h0 + h1);
    return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p2)) || 0;
  }
  function slope2(that, t4) {
    var h3 = that._x1 - that._x0;
    return h3 ? (3 * (that._y1 - that._y0) / h3 - t4) / 2 : t4;
  }
  function point4(that, t04, t13) {
    var x06 = that._x0, y06 = that._y0, x12 = that._x1, y12 = that._y1, dx = (x12 - x06) / 3;
    that._context.bezierCurveTo(x06 + dx, y06 + dx * t04, x12 - dx, y12 - dx * t13, x12, y12);
  }
  function MonotoneX(context3) {
    this._context = context3;
  }
  MonotoneX.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      switch (this._point) {
        case 2:
          this._context.lineTo(this._x1, this._y1);
          break;
        case 3:
          point4(this, this._t0, slope2(this, this._t0));
          break;
      }
      if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
      this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      var t13 = NaN;
      x5 = +x5, y5 = +y5;
      if (x5 === this._x1 && y5 === this._y1) return;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
          break;
        case 2:
          this._point = 3;
          point4(this, slope2(this, t13 = slope3(this, x5, y5)), t13);
          break;
        default:
          point4(this, this._t0, t13 = slope3(this, x5, y5));
          break;
      }
      this._x0 = this._x1, this._x1 = x5;
      this._y0 = this._y1, this._y1 = y5;
      this._t0 = t13;
    }
  };
  function MonotoneY(context3) {
    this._context = new ReflectContext(context3);
  }
  (MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x5, y5) {
    MonotoneX.prototype.point.call(this, y5, x5);
  };
  function ReflectContext(context3) {
    this._context = context3;
  }
  ReflectContext.prototype = {
    moveTo: function(x5, y5) {
      this._context.moveTo(y5, x5);
    },
    closePath: function() {
      this._context.closePath();
    },
    lineTo: function(x5, y5) {
      this._context.lineTo(y5, x5);
    },
    bezierCurveTo: function(x12, y12, x22, y22, x5, y5) {
      this._context.bezierCurveTo(y12, x12, y22, x22, y5, x5);
    }
  };
  function monotoneX(context3) {
    return new MonotoneX(context3);
  }
  function monotoneY(context3) {
    return new MonotoneY(context3);
  }

  // node_modules/d3-shape/src/curve/natural.js
  function Natural(context3) {
    this._context = context3;
  }
  Natural.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x = [];
      this._y = [];
    },
    lineEnd: function() {
      var x5 = this._x, y5 = this._y, n2 = x5.length;
      if (n2) {
        this._line ? this._context.lineTo(x5[0], y5[0]) : this._context.moveTo(x5[0], y5[0]);
        if (n2 === 2) {
          this._context.lineTo(x5[1], y5[1]);
        } else {
          var px2 = controlPoints(x5), py2 = controlPoints(y5);
          for (var i0 = 0, i1 = 1; i1 < n2; ++i0, ++i1) {
            this._context.bezierCurveTo(px2[0][i0], py2[0][i0], px2[1][i0], py2[1][i0], x5[i1], y5[i1]);
          }
        }
      }
      if (this._line || this._line !== 0 && n2 === 1) this._context.closePath();
      this._line = 1 - this._line;
      this._x = this._y = null;
    },
    point: function(x5, y5) {
      this._x.push(+x5);
      this._y.push(+y5);
    }
  };
  function controlPoints(x5) {
    var i2, n2 = x5.length - 1, m4, a4 = new Array(n2), b3 = new Array(n2), r2 = new Array(n2);
    a4[0] = 0, b3[0] = 2, r2[0] = x5[0] + 2 * x5[1];
    for (i2 = 1; i2 < n2 - 1; ++i2) a4[i2] = 1, b3[i2] = 4, r2[i2] = 4 * x5[i2] + 2 * x5[i2 + 1];
    a4[n2 - 1] = 2, b3[n2 - 1] = 7, r2[n2 - 1] = 8 * x5[n2 - 1] + x5[n2];
    for (i2 = 1; i2 < n2; ++i2) m4 = a4[i2] / b3[i2 - 1], b3[i2] -= m4, r2[i2] -= m4 * r2[i2 - 1];
    a4[n2 - 1] = r2[n2 - 1] / b3[n2 - 1];
    for (i2 = n2 - 2; i2 >= 0; --i2) a4[i2] = (r2[i2] - a4[i2 + 1]) / b3[i2];
    b3[n2 - 1] = (x5[n2] + a4[n2 - 1]) / 2;
    for (i2 = 0; i2 < n2 - 1; ++i2) b3[i2] = 2 * x5[i2 + 1] - a4[i2 + 1];
    return [a4, b3];
  }
  function natural_default(context3) {
    return new Natural(context3);
  }

  // node_modules/d3-shape/src/curve/step.js
  function Step(context3, t4) {
    this._context = context3;
    this._t = t4;
  }
  Step.prototype = {
    areaStart: function() {
      this._line = 0;
    },
    areaEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._x = this._y = NaN;
      this._point = 0;
    },
    lineEnd: function() {
      if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);
      if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
      if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;
    },
    point: function(x5, y5) {
      x5 = +x5, y5 = +y5;
      switch (this._point) {
        case 0:
          this._point = 1;
          this._line ? this._context.lineTo(x5, y5) : this._context.moveTo(x5, y5);
          break;
        case 1:
          this._point = 2;
        // falls through
        default: {
          if (this._t <= 0) {
            this._context.lineTo(this._x, y5);
            this._context.lineTo(x5, y5);
          } else {
            var x12 = this._x * (1 - this._t) + x5 * this._t;
            this._context.lineTo(x12, this._y);
            this._context.lineTo(x12, y5);
          }
          break;
        }
      }
      this._x = x5, this._y = y5;
    }
  };
  function step_default(context3) {
    return new Step(context3, 0.5);
  }
  function stepBefore(context3) {
    return new Step(context3, 0);
  }
  function stepAfter(context3) {
    return new Step(context3, 1);
  }

  // node_modules/vega-canvas/build/vega-canvas.browser.module.js
  function domCanvas(w3, h3) {
    if (typeof document !== "undefined" && document.createElement) {
      const c4 = document.createElement("canvas");
      if (c4 && c4.getContext) {
        c4.width = w3;
        c4.height = h3;
        return c4;
      }
    }
    return null;
  }
  var domImage = () => typeof Image !== "undefined" ? Image : null;

  // node_modules/d3-scale/src/init.js
  function initRange(domain4, range7) {
    switch (arguments.length) {
      case 0:
        break;
      case 1:
        this.range(domain4);
        break;
      default:
        this.range(range7).domain(domain4);
        break;
    }
    return this;
  }
  function initInterpolator(domain4, interpolator) {
    switch (arguments.length) {
      case 0:
        break;
      case 1: {
        if (typeof domain4 === "function") this.interpolator(domain4);
        else this.range(domain4);
        break;
      }
      default: {
        this.domain(domain4);
        if (typeof interpolator === "function") this.interpolator(interpolator);
        else this.range(interpolator);
        break;
      }
    }
    return this;
  }

  // node_modules/d3-scale/src/ordinal.js
  var implicit = Symbol("implicit");
  function ordinal() {
    var index4 = new InternMap(), domain4 = [], range7 = [], unknown = implicit;
    function scale7(d2) {
      let i2 = index4.get(d2);
      if (i2 === void 0) {
        if (unknown !== implicit) return unknown;
        index4.set(d2, i2 = domain4.push(d2) - 1);
      }
      return range7[i2 % range7.length];
    }
    scale7.domain = function(_) {
      if (!arguments.length) return domain4.slice();
      domain4 = [], index4 = new InternMap();
      for (const value3 of _) {
        if (index4.has(value3)) continue;
        index4.set(value3, domain4.push(value3) - 1);
      }
      return scale7;
    };
    scale7.range = function(_) {
      return arguments.length ? (range7 = Array.from(_), scale7) : range7.slice();
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    scale7.copy = function() {
      return ordinal(domain4, range7).unknown(unknown);
    };
    initRange.apply(scale7, arguments);
    return scale7;
  }

  // node_modules/d3-interpolate/src/index.js
  var src_exports = {};
  __export(src_exports, {
    interpolate: () => value_default,
    interpolateArray: () => array_default2,
    interpolateBasis: () => basis_default2,
    interpolateBasisClosed: () => basisClosed_default2,
    interpolateCubehelix: () => cubehelix_default,
    interpolateCubehelixLong: () => cubehelixLong,
    interpolateDate: () => date_default,
    interpolateDiscrete: () => discrete_default,
    interpolateHcl: () => hcl_default,
    interpolateHclLong: () => hclLong,
    interpolateHsl: () => hsl_default,
    interpolateHslLong: () => hslLong,
    interpolateHue: () => hue_default,
    interpolateLab: () => lab2,
    interpolateNumber: () => number_default,
    interpolateNumberArray: () => numberArray_default,
    interpolateObject: () => object_default,
    interpolateRgb: () => rgb_default,
    interpolateRgbBasis: () => rgbBasis,
    interpolateRgbBasisClosed: () => rgbBasisClosed,
    interpolateRound: () => round_default,
    interpolateString: () => string_default,
    interpolateTransformCss: () => interpolateTransformCss,
    interpolateTransformSvg: () => interpolateTransformSvg,
    interpolateZoom: () => zoom_default,
    piecewise: () => piecewise,
    quantize: () => quantize_default2
  });

  // node_modules/d3-color/src/define.js
  function define_default(constructor, factory, prototype2) {
    constructor.prototype = factory.prototype = prototype2;
    prototype2.constructor = constructor;
  }
  function extend2(parent, definition3) {
    var prototype2 = Object.create(parent.prototype);
    for (var key2 in definition3) prototype2[key2] = definition3[key2];
    return prototype2;
  }

  // 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(format5) {
    var m4, l2;
    format5 = (format5 + "").trim().toLowerCase();
    return (m4 = reHex.exec(format5)) ? (l2 = m4[1].length, m4 = parseInt(m4[1], 16), l2 === 6 ? rgbn(m4) : l2 === 3 ? new Rgb(m4 >> 8 & 15 | m4 >> 4 & 240, m4 >> 4 & 15 | m4 & 240, (m4 & 15) << 4 | m4 & 15, 1) : l2 === 8 ? rgba(m4 >> 24 & 255, m4 >> 16 & 255, m4 >> 8 & 255, (m4 & 255) / 255) : l2 === 4 ? rgba(m4 >> 12 & 15 | m4 >> 8 & 240, m4 >> 8 & 15 | m4 >> 4 & 240, m4 >> 4 & 15 | m4 & 240, ((m4 & 15) << 4 | m4 & 15) / 255) : null) : (m4 = reRgbInteger.exec(format5)) ? new Rgb(m4[1], m4[2], m4[3], 1) : (m4 = reRgbPercent.exec(format5)) ? new Rgb(m4[1] * 255 / 100, m4[2] * 255 / 100, m4[3] * 255 / 100, 1) : (m4 = reRgbaInteger.exec(format5)) ? rgba(m4[1], m4[2], m4[3], m4[4]) : (m4 = reRgbaPercent.exec(format5)) ? rgba(m4[1] * 255 / 100, m4[2] * 255 / 100, m4[3] * 255 / 100, m4[4]) : (m4 = reHslPercent.exec(format5)) ? hsla(m4[1], m4[2] / 100, m4[3] / 100, 1) : (m4 = reHslaPercent.exec(format5)) ? hsla(m4[1], m4[2] / 100, m4[3] / 100, m4[4]) : named.hasOwnProperty(format5) ? rgbn(named[format5]) : format5 === "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(r2, g2, b3, a4) {
    if (a4 <= 0) r2 = g2 = b3 = NaN;
    return new Rgb(r2, g2, b3, a4);
  }
  function rgbConvert(o2) {
    if (!(o2 instanceof Color)) o2 = color(o2);
    if (!o2) return new Rgb();
    o2 = o2.rgb();
    return new Rgb(o2.r, o2.g, o2.b, o2.opacity);
  }
  function rgb(r2, g2, b3, opacity2) {
    return arguments.length === 1 ? rgbConvert(r2) : new Rgb(r2, g2, b3, opacity2 == null ? 1 : opacity2);
  }
  function Rgb(r2, g2, b3, opacity2) {
    this.r = +r2;
    this.g = +g2;
    this.b = +b3;
    this.opacity = +opacity2;
  }
  define_default(Rgb, rgb, extend2(Color, {
    brighter(k2) {
      k2 = k2 == null ? brighter : Math.pow(brighter, k2);
      return new Rgb(this.r * k2, this.g * k2, this.b * k2, this.opacity);
    },
    darker(k2) {
      k2 = k2 == null ? darker : Math.pow(darker, k2);
      return new Rgb(this.r * k2, this.g * k2, this.b * k2, 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 a4 = clampa(this.opacity);
    return `${a4 === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a4 === 1 ? ")" : `, ${a4})`}`;
  }
  function clampa(opacity2) {
    return isNaN(opacity2) ? 1 : Math.max(0, Math.min(1, opacity2));
  }
  function clampi(value3) {
    return Math.max(0, Math.min(255, Math.round(value3) || 0));
  }
  function hex(value3) {
    value3 = clampi(value3);
    return (value3 < 16 ? "0" : "") + value3.toString(16);
  }
  function hsla(h3, s2, l2, a4) {
    if (a4 <= 0) h3 = s2 = l2 = NaN;
    else if (l2 <= 0 || l2 >= 1) h3 = s2 = NaN;
    else if (s2 <= 0) h3 = NaN;
    return new Hsl(h3, s2, l2, a4);
  }
  function hslConvert(o2) {
    if (o2 instanceof Hsl) return new Hsl(o2.h, o2.s, o2.l, o2.opacity);
    if (!(o2 instanceof Color)) o2 = color(o2);
    if (!o2) return new Hsl();
    if (o2 instanceof Hsl) return o2;
    o2 = o2.rgb();
    var r2 = o2.r / 255, g2 = o2.g / 255, b3 = o2.b / 255, min4 = Math.min(r2, g2, b3), max4 = Math.max(r2, g2, b3), h3 = NaN, s2 = max4 - min4, l2 = (max4 + min4) / 2;
    if (s2) {
      if (r2 === max4) h3 = (g2 - b3) / s2 + (g2 < b3) * 6;
      else if (g2 === max4) h3 = (b3 - r2) / s2 + 2;
      else h3 = (r2 - g2) / s2 + 4;
      s2 /= l2 < 0.5 ? max4 + min4 : 2 - max4 - min4;
      h3 *= 60;
    } else {
      s2 = l2 > 0 && l2 < 1 ? 0 : h3;
    }
    return new Hsl(h3, s2, l2, o2.opacity);
  }
  function hsl(h3, s2, l2, opacity2) {
    return arguments.length === 1 ? hslConvert(h3) : new Hsl(h3, s2, l2, opacity2 == null ? 1 : opacity2);
  }
  function Hsl(h3, s2, l2, opacity2) {
    this.h = +h3;
    this.s = +s2;
    this.l = +l2;
    this.opacity = +opacity2;
  }
  define_default(Hsl, hsl, extend2(Color, {
    brighter(k2) {
      k2 = k2 == null ? brighter : Math.pow(brighter, k2);
      return new Hsl(this.h, this.s, this.l * k2, this.opacity);
    },
    darker(k2) {
      k2 = k2 == null ? darker : Math.pow(darker, k2);
      return new Hsl(this.h, this.s, this.l * k2, this.opacity);
    },
    rgb() {
      var h3 = this.h % 360 + (this.h < 0) * 360, s2 = isNaN(h3) || isNaN(this.s) ? 0 : this.s, l2 = this.l, m22 = l2 + (l2 < 0.5 ? l2 : 1 - l2) * s2, m1 = 2 * l2 - m22;
      return new Rgb(
        hsl2rgb(h3 >= 240 ? h3 - 240 : h3 + 120, m1, m22),
        hsl2rgb(h3, m1, m22),
        hsl2rgb(h3 < 120 ? h3 + 240 : h3 - 120, m1, m22),
        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 a4 = clampa(this.opacity);
      return `${a4 === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a4 === 1 ? ")" : `, ${a4})`}`;
    }
  }));
  function clamph(value3) {
    value3 = (value3 || 0) % 360;
    return value3 < 0 ? value3 + 360 : value3;
  }
  function clampt(value3) {
    return Math.max(0, Math.min(1, value3 || 0));
  }
  function hsl2rgb(h3, m1, m22) {
    return (h3 < 60 ? m1 + (m22 - m1) * h3 / 60 : h3 < 180 ? m22 : h3 < 240 ? m1 + (m22 - m1) * (240 - h3) / 60 : m1) * 255;
  }

  // node_modules/d3-color/src/math.js
  var radians = Math.PI / 180;
  var degrees = 180 / Math.PI;

  // node_modules/d3-color/src/lab.js
  var K = 18;
  var Xn = 0.96422;
  var Yn = 1;
  var Zn = 0.82521;
  var t03 = 4 / 29;
  var t12 = 6 / 29;
  var t2 = 3 * t12 * t12;
  var t3 = t12 * t12 * t12;
  function labConvert(o2) {
    if (o2 instanceof Lab) return new Lab(o2.l, o2.a, o2.b, o2.opacity);
    if (o2 instanceof Hcl) return hcl2lab(o2);
    if (!(o2 instanceof Rgb)) o2 = rgbConvert(o2);
    var r2 = rgb2lrgb(o2.r), g2 = rgb2lrgb(o2.g), b3 = rgb2lrgb(o2.b), y5 = xyz2lab((0.2225045 * r2 + 0.7168786 * g2 + 0.0606169 * b3) / Yn), x5, z;
    if (r2 === g2 && g2 === b3) x5 = z = y5;
    else {
      x5 = xyz2lab((0.4360747 * r2 + 0.3850649 * g2 + 0.1430804 * b3) / Xn);
      z = xyz2lab((0.0139322 * r2 + 0.0971045 * g2 + 0.7141733 * b3) / Zn);
    }
    return new Lab(116 * y5 - 16, 500 * (x5 - y5), 200 * (y5 - z), o2.opacity);
  }
  function lab(l2, a4, b3, opacity2) {
    return arguments.length === 1 ? labConvert(l2) : new Lab(l2, a4, b3, opacity2 == null ? 1 : opacity2);
  }
  function Lab(l2, a4, b3, opacity2) {
    this.l = +l2;
    this.a = +a4;
    this.b = +b3;
    this.opacity = +opacity2;
  }
  define_default(Lab, lab, extend2(Color, {
    brighter(k2) {
      return new Lab(this.l + K * (k2 == null ? 1 : k2), this.a, this.b, this.opacity);
    },
    darker(k2) {
      return new Lab(this.l - K * (k2 == null ? 1 : k2), this.a, this.b, this.opacity);
    },
    rgb() {
      var y5 = (this.l + 16) / 116, x5 = isNaN(this.a) ? y5 : y5 + this.a / 500, z = isNaN(this.b) ? y5 : y5 - this.b / 200;
      x5 = Xn * lab2xyz(x5);
      y5 = Yn * lab2xyz(y5);
      z = Zn * lab2xyz(z);
      return new Rgb(
        lrgb2rgb(3.1338561 * x5 - 1.6168667 * y5 - 0.4906146 * z),
        lrgb2rgb(-0.9787684 * x5 + 1.9161415 * y5 + 0.033454 * z),
        lrgb2rgb(0.0719453 * x5 - 0.2289914 * y5 + 1.4052427 * z),
        this.opacity
      );
    }
  }));
  function xyz2lab(t4) {
    return t4 > t3 ? Math.pow(t4, 1 / 3) : t4 / t2 + t03;
  }
  function lab2xyz(t4) {
    return t4 > t12 ? t4 * t4 * t4 : t2 * (t4 - t03);
  }
  function lrgb2rgb(x5) {
    return 255 * (x5 <= 31308e-7 ? 12.92 * x5 : 1.055 * Math.pow(x5, 1 / 2.4) - 0.055);
  }
  function rgb2lrgb(x5) {
    return (x5 /= 255) <= 0.04045 ? x5 / 12.92 : Math.pow((x5 + 0.055) / 1.055, 2.4);
  }
  function hclConvert(o2) {
    if (o2 instanceof Hcl) return new Hcl(o2.h, o2.c, o2.l, o2.opacity);
    if (!(o2 instanceof Lab)) o2 = labConvert(o2);
    if (o2.a === 0 && o2.b === 0) return new Hcl(NaN, 0 < o2.l && o2.l < 100 ? 0 : NaN, o2.l, o2.opacity);
    var h3 = Math.atan2(o2.b, o2.a) * degrees;
    return new Hcl(h3 < 0 ? h3 + 360 : h3, Math.sqrt(o2.a * o2.a + o2.b * o2.b), o2.l, o2.opacity);
  }
  function hcl(h3, c4, l2, opacity2) {
    return arguments.length === 1 ? hclConvert(h3) : new Hcl(h3, c4, l2, opacity2 == null ? 1 : opacity2);
  }
  function Hcl(h3, c4, l2, opacity2) {
    this.h = +h3;
    this.c = +c4;
    this.l = +l2;
    this.opacity = +opacity2;
  }
  function hcl2lab(o2) {
    if (isNaN(o2.h)) return new Lab(o2.l, 0, 0, o2.opacity);
    var h3 = o2.h * radians;
    return new Lab(o2.l, Math.cos(h3) * o2.c, Math.sin(h3) * o2.c, o2.opacity);
  }
  define_default(Hcl, hcl, extend2(Color, {
    brighter(k2) {
      return new Hcl(this.h, this.c, this.l + K * (k2 == null ? 1 : k2), this.opacity);
    },
    darker(k2) {
      return new Hcl(this.h, this.c, this.l - K * (k2 == null ? 1 : k2), this.opacity);
    },
    rgb() {
      return hcl2lab(this).rgb();
    }
  }));

  // node_modules/d3-color/src/cubehelix.js
  var A = -0.14861;
  var B = 1.78277;
  var C = -0.29227;
  var D = -0.90649;
  var E = 1.97294;
  var ED = E * D;
  var EB = E * B;
  var BC_DA = B * C - D * A;
  function cubehelixConvert(o2) {
    if (o2 instanceof Cubehelix) return new Cubehelix(o2.h, o2.s, o2.l, o2.opacity);
    if (!(o2 instanceof Rgb)) o2 = rgbConvert(o2);
    var r2 = o2.r / 255, g2 = o2.g / 255, b3 = o2.b / 255, l2 = (BC_DA * b3 + ED * r2 - EB * g2) / (BC_DA + ED - EB), bl2 = b3 - l2, k2 = (E * (g2 - l2) - C * bl2) / D, s2 = Math.sqrt(k2 * k2 + bl2 * bl2) / (E * l2 * (1 - l2)), h3 = s2 ? Math.atan2(k2, bl2) * degrees - 120 : NaN;
    return new Cubehelix(h3 < 0 ? h3 + 360 : h3, s2, l2, o2.opacity);
  }
  function cubehelix(h3, s2, l2, opacity2) {
    return arguments.length === 1 ? cubehelixConvert(h3) : new Cubehelix(h3, s2, l2, opacity2 == null ? 1 : opacity2);
  }
  function Cubehelix(h3, s2, l2, opacity2) {
    this.h = +h3;
    this.s = +s2;
    this.l = +l2;
    this.opacity = +opacity2;
  }
  define_default(Cubehelix, cubehelix, extend2(Color, {
    brighter(k2) {
      k2 = k2 == null ? brighter : Math.pow(brighter, k2);
      return new Cubehelix(this.h, this.s, this.l * k2, this.opacity);
    },
    darker(k2) {
      k2 = k2 == null ? darker : Math.pow(darker, k2);
      return new Cubehelix(this.h, this.s, this.l * k2, this.opacity);
    },
    rgb() {
      var h3 = isNaN(this.h) ? 0 : (this.h + 120) * radians, l2 = +this.l, a4 = isNaN(this.s) ? 0 : this.s * l2 * (1 - l2), cosh2 = Math.cos(h3), sinh2 = Math.sin(h3);
      return new Rgb(
        255 * (l2 + a4 * (A * cosh2 + B * sinh2)),
        255 * (l2 + a4 * (C * cosh2 + D * sinh2)),
        255 * (l2 + a4 * (E * cosh2)),
        this.opacity
      );
    }
  }));

  // node_modules/d3-interpolate/src/basis.js
  function basis(t13, v0, v1, v22, v3) {
    var t22 = t13 * t13, t32 = t22 * t13;
    return ((1 - 3 * t13 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t13 + 3 * t22 - 3 * t32) * v22 + t32 * v3) / 6;
  }
  function basis_default2(values4) {
    var n2 = values4.length - 1;
    return function(t4) {
      var i2 = t4 <= 0 ? t4 = 0 : t4 >= 1 ? (t4 = 1, n2 - 1) : Math.floor(t4 * n2), v1 = values4[i2], v22 = values4[i2 + 1], v0 = i2 > 0 ? values4[i2 - 1] : 2 * v1 - v22, v3 = i2 < n2 - 1 ? values4[i2 + 2] : 2 * v22 - v1;
      return basis((t4 - i2 / n2) * n2, v0, v1, v22, v3);
    };
  }

  // node_modules/d3-interpolate/src/basisClosed.js
  function basisClosed_default2(values4) {
    var n2 = values4.length;
    return function(t4) {
      var i2 = Math.floor(((t4 %= 1) < 0 ? ++t4 : t4) * n2), v0 = values4[(i2 + n2 - 1) % n2], v1 = values4[i2 % n2], v22 = values4[(i2 + 1) % n2], v3 = values4[(i2 + 2) % n2];
      return basis((t4 - i2 / n2) * n2, v0, v1, v22, v3);
    };
  }

  // node_modules/d3-interpolate/src/constant.js
  var constant_default2 = (x5) => () => x5;

  // node_modules/d3-interpolate/src/color.js
  function linear2(a4, d2) {
    return function(t4) {
      return a4 + t4 * d2;
    };
  }
  function exponential(a4, b3, y5) {
    return a4 = Math.pow(a4, y5), b3 = Math.pow(b3, y5) - a4, y5 = 1 / y5, function(t4) {
      return Math.pow(a4 + t4 * b3, y5);
    };
  }
  function hue(a4, b3) {
    var d2 = b3 - a4;
    return d2 ? linear2(a4, d2 > 180 || d2 < -180 ? d2 - 360 * Math.round(d2 / 360) : d2) : constant_default2(isNaN(a4) ? b3 : a4);
  }
  function gamma(y5) {
    return (y5 = +y5) === 1 ? nogamma : function(a4, b3) {
      return b3 - a4 ? exponential(a4, b3, y5) : constant_default2(isNaN(a4) ? b3 : a4);
    };
  }
  function nogamma(a4, b3) {
    var d2 = b3 - a4;
    return d2 ? linear2(a4, d2) : constant_default2(isNaN(a4) ? b3 : a4);
  }

  // node_modules/d3-interpolate/src/rgb.js
  var rgb_default = function rgbGamma(y5) {
    var color5 = gamma(y5);
    function rgb2(start, end) {
      var r2 = color5((start = rgb(start)).r, (end = rgb(end)).r), g2 = color5(start.g, end.g), b3 = color5(start.b, end.b), opacity2 = nogamma(start.opacity, end.opacity);
      return function(t4) {
        start.r = r2(t4);
        start.g = g2(t4);
        start.b = b3(t4);
        start.opacity = opacity2(t4);
        return start + "";
      };
    }
    rgb2.gamma = rgbGamma;
    return rgb2;
  }(1);
  function rgbSpline(spline) {
    return function(colors2) {
      var n2 = colors2.length, r2 = new Array(n2), g2 = new Array(n2), b3 = new Array(n2), i2, color5;
      for (i2 = 0; i2 < n2; ++i2) {
        color5 = rgb(colors2[i2]);
        r2[i2] = color5.r || 0;
        g2[i2] = color5.g || 0;
        b3[i2] = color5.b || 0;
      }
      r2 = spline(r2);
      g2 = spline(g2);
      b3 = spline(b3);
      color5.opacity = 1;
      return function(t4) {
        color5.r = r2(t4);
        color5.g = g2(t4);
        color5.b = b3(t4);
        return color5 + "";
      };
    };
  }
  var rgbBasis = rgbSpline(basis_default2);
  var rgbBasisClosed = rgbSpline(basisClosed_default2);

  // node_modules/d3-interpolate/src/numberArray.js
  function numberArray_default(a4, b3) {
    if (!b3) b3 = [];
    var n2 = a4 ? Math.min(b3.length, a4.length) : 0, c4 = b3.slice(), i2;
    return function(t4) {
      for (i2 = 0; i2 < n2; ++i2) c4[i2] = a4[i2] * (1 - t4) + b3[i2] * t4;
      return c4;
    };
  }
  function isNumberArray(x5) {
    return ArrayBuffer.isView(x5) && !(x5 instanceof DataView);
  }

  // node_modules/d3-interpolate/src/array.js
  function array_default2(a4, b3) {
    return (isNumberArray(b3) ? numberArray_default : genericArray)(a4, b3);
  }
  function genericArray(a4, b3) {
    var nb = b3 ? b3.length : 0, na = a4 ? Math.min(nb, a4.length) : 0, x5 = new Array(na), c4 = new Array(nb), i2;
    for (i2 = 0; i2 < na; ++i2) x5[i2] = value_default(a4[i2], b3[i2]);
    for (; i2 < nb; ++i2) c4[i2] = b3[i2];
    return function(t4) {
      for (i2 = 0; i2 < na; ++i2) c4[i2] = x5[i2](t4);
      return c4;
    };
  }

  // node_modules/d3-interpolate/src/date.js
  function date_default(a4, b3) {
    var d2 = /* @__PURE__ */ new Date();
    return a4 = +a4, b3 = +b3, function(t4) {
      return d2.setTime(a4 * (1 - t4) + b3 * t4), d2;
    };
  }

  // node_modules/d3-interpolate/src/number.js
  function number_default(a4, b3) {
    return a4 = +a4, b3 = +b3, function(t4) {
      return a4 * (1 - t4) + b3 * t4;
    };
  }

  // node_modules/d3-interpolate/src/object.js
  function object_default(a4, b3) {
    var i2 = {}, c4 = {}, k2;
    if (a4 === null || typeof a4 !== "object") a4 = {};
    if (b3 === null || typeof b3 !== "object") b3 = {};
    for (k2 in b3) {
      if (k2 in a4) {
        i2[k2] = value_default(a4[k2], b3[k2]);
      } else {
        c4[k2] = b3[k2];
      }
    }
    return function(t4) {
      for (k2 in i2) c4[k2] = i2[k2](t4);
      return c4;
    };
  }

  // node_modules/d3-interpolate/src/string.js
  var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
  var reB = new RegExp(reA.source, "g");
  function zero3(b3) {
    return function() {
      return b3;
    };
  }
  function one2(b3) {
    return function(t4) {
      return b3(t4) + "";
    };
  }
  function string_default(a4, b3) {
    var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i2 = -1, s2 = [], q2 = [];
    a4 = a4 + "", b3 = b3 + "";
    while ((am = reA.exec(a4)) && (bm = reB.exec(b3))) {
      if ((bs = bm.index) > bi) {
        bs = b3.slice(bi, bs);
        if (s2[i2]) s2[i2] += bs;
        else s2[++i2] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s2[i2]) s2[i2] += bm;
        else s2[++i2] = bm;
      } else {
        s2[++i2] = null;
        q2.push({ i: i2, x: number_default(am, bm) });
      }
      bi = reB.lastIndex;
    }
    if (bi < b3.length) {
      bs = b3.slice(bi);
      if (s2[i2]) s2[i2] += bs;
      else s2[++i2] = bs;
    }
    return s2.length < 2 ? q2[0] ? one2(q2[0].x) : zero3(b3) : (b3 = q2.length, function(t4) {
      for (var i3 = 0, o2; i3 < b3; ++i3) s2[(o2 = q2[i3]).i] = o2.x(t4);
      return s2.join("");
    });
  }

  // node_modules/d3-interpolate/src/value.js
  function value_default(a4, b3) {
    var t4 = typeof b3, c4;
    return b3 == null || t4 === "boolean" ? constant_default2(b3) : (t4 === "number" ? number_default : t4 === "string" ? (c4 = color(b3)) ? (b3 = c4, rgb_default) : string_default : b3 instanceof color ? rgb_default : b3 instanceof Date ? date_default : isNumberArray(b3) ? numberArray_default : Array.isArray(b3) ? genericArray : typeof b3.valueOf !== "function" && typeof b3.toString !== "function" || isNaN(b3) ? object_default : number_default)(a4, b3);
  }

  // node_modules/d3-interpolate/src/discrete.js
  function discrete_default(range7) {
    var n2 = range7.length;
    return function(t4) {
      return range7[Math.max(0, Math.min(n2 - 1, Math.floor(t4 * n2)))];
    };
  }

  // node_modules/d3-interpolate/src/hue.js
  function hue_default(a4, b3) {
    var i2 = hue(+a4, +b3);
    return function(t4) {
      var x5 = i2(t4);
      return x5 - 360 * Math.floor(x5 / 360);
    };
  }

  // node_modules/d3-interpolate/src/round.js
  function round_default(a4, b3) {
    return a4 = +a4, b3 = +b3, function(t4) {
      return Math.round(a4 * (1 - t4) + b3 * t4);
    };
  }

  // node_modules/d3-interpolate/src/transform/decompose.js
  var degrees2 = 180 / Math.PI;
  var identity2 = {
    translateX: 0,
    translateY: 0,
    rotate: 0,
    skewX: 0,
    scaleX: 1,
    scaleY: 1
  };
  function decompose_default(a4, b3, c4, d2, e4, f2) {
    var scaleX, scaleY2, skewX;
    if (scaleX = Math.sqrt(a4 * a4 + b3 * b3)) a4 /= scaleX, b3 /= scaleX;
    if (skewX = a4 * c4 + b3 * d2) c4 -= a4 * skewX, d2 -= b3 * skewX;
    if (scaleY2 = Math.sqrt(c4 * c4 + d2 * d2)) c4 /= scaleY2, d2 /= scaleY2, skewX /= scaleY2;
    if (a4 * d2 < b3 * c4) a4 = -a4, b3 = -b3, skewX = -skewX, scaleX = -scaleX;
    return {
      translateX: e4,
      translateY: f2,
      rotate: Math.atan2(b3, a4) * degrees2,
      skewX: Math.atan(skewX) * degrees2,
      scaleX,
      scaleY: scaleY2
    };
  }

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

  // node_modules/d3-interpolate/src/transform/index.js
  function interpolateTransform(parse7, pxComma, pxParen, degParen) {
    function pop(s2) {
      return s2.length ? s2.pop() + " " : "";
    }
    function translate4(xa, ya, xb, yb, s2, q2) {
      if (xa !== xb || ya !== yb) {
        var i2 = s2.push("translate(", null, pxComma, null, pxParen);
        q2.push({ i: i2 - 4, x: number_default(xa, xb) }, { i: i2 - 2, x: number_default(ya, yb) });
      } else if (xb || yb) {
        s2.push("translate(" + xb + pxComma + yb + pxParen);
      }
    }
    function rotate2(a4, b3, s2, q2) {
      if (a4 !== b3) {
        if (a4 - b3 > 180) b3 += 360;
        else if (b3 - a4 > 180) a4 += 360;
        q2.push({ i: s2.push(pop(s2) + "rotate(", null, degParen) - 2, x: number_default(a4, b3) });
      } else if (b3) {
        s2.push(pop(s2) + "rotate(" + b3 + degParen);
      }
    }
    function skewX(a4, b3, s2, q2) {
      if (a4 !== b3) {
        q2.push({ i: s2.push(pop(s2) + "skewX(", null, degParen) - 2, x: number_default(a4, b3) });
      } else if (b3) {
        s2.push(pop(s2) + "skewX(" + b3 + degParen);
      }
    }
    function scale7(xa, ya, xb, yb, s2, q2) {
      if (xa !== xb || ya !== yb) {
        var i2 = s2.push(pop(s2) + "scale(", null, ",", null, ")");
        q2.push({ i: i2 - 4, x: number_default(xa, xb) }, { i: i2 - 2, x: number_default(ya, yb) });
      } else if (xb !== 1 || yb !== 1) {
        s2.push(pop(s2) + "scale(" + xb + "," + yb + ")");
      }
    }
    return function(a4, b3) {
      var s2 = [], q2 = [];
      a4 = parse7(a4), b3 = parse7(b3);
      translate4(a4.translateX, a4.translateY, b3.translateX, b3.translateY, s2, q2);
      rotate2(a4.rotate, b3.rotate, s2, q2);
      skewX(a4.skewX, b3.skewX, s2, q2);
      scale7(a4.scaleX, a4.scaleY, b3.scaleX, b3.scaleY, s2, q2);
      a4 = b3 = null;
      return function(t4) {
        var i2 = -1, n2 = q2.length, o2;
        while (++i2 < n2) s2[(o2 = q2[i2]).i] = o2.x(t4);
        return s2.join("");
      };
    };
  }
  var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)");
  var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")");

  // node_modules/d3-interpolate/src/zoom.js
  var epsilon22 = 1e-12;
  function cosh(x5) {
    return ((x5 = Math.exp(x5)) + 1 / x5) / 2;
  }
  function sinh(x5) {
    return ((x5 = Math.exp(x5)) - 1 / x5) / 2;
  }
  function tanh(x5) {
    return ((x5 = Math.exp(2 * x5)) - 1) / (x5 + 1);
  }
  var zoom_default = function zoomRho(rho, rho2, rho4) {
    function zoom3(p02, p1) {
      var ux0 = p02[0], uy0 = p02[1], w0 = p02[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i2, S;
      if (d2 < epsilon22) {
        S = Math.log(w1 / w0) / rho;
        i2 = function(t4) {
          return [
            ux0 + t4 * dx,
            uy0 + t4 * dy,
            w0 * Math.exp(rho * t4 * S)
          ];
        };
      } else {
        var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
        S = (r1 - r0) / rho;
        i2 = function(t4) {
          var s2 = t4 * S, coshr0 = cosh(r0), u5 = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s2 + r0) - sinh(r0));
          return [
            ux0 + u5 * dx,
            uy0 + u5 * dy,
            w0 * coshr0 / cosh(rho * s2 + r0)
          ];
        };
      }
      i2.duration = S * 1e3 * rho / Math.SQRT2;
      return i2;
    }
    zoom3.rho = function(_) {
      var _1 = Math.max(1e-3, +_), _2 = _1 * _1, _4 = _2 * _2;
      return zoomRho(_1, _2, _4);
    };
    return zoom3;
  }(Math.SQRT2, 2, 4);

  // node_modules/d3-interpolate/src/hsl.js
  function hsl2(hue2) {
    return function(start, end) {
      var h3 = hue2((start = hsl(start)).h, (end = hsl(end)).h), s2 = nogamma(start.s, end.s), l2 = nogamma(start.l, end.l), opacity2 = nogamma(start.opacity, end.opacity);
      return function(t4) {
        start.h = h3(t4);
        start.s = s2(t4);
        start.l = l2(t4);
        start.opacity = opacity2(t4);
        return start + "";
      };
    };
  }
  var hsl_default = hsl2(hue);
  var hslLong = hsl2(nogamma);

  // node_modules/d3-interpolate/src/lab.js
  function lab2(start, end) {
    var l2 = nogamma((start = lab(start)).l, (end = lab(end)).l), a4 = nogamma(start.a, end.a), b3 = nogamma(start.b, end.b), opacity2 = nogamma(start.opacity, end.opacity);
    return function(t4) {
      start.l = l2(t4);
      start.a = a4(t4);
      start.b = b3(t4);
      start.opacity = opacity2(t4);
      return start + "";
    };
  }

  // node_modules/d3-interpolate/src/hcl.js
  function hcl2(hue2) {
    return function(start, end) {
      var h3 = hue2((start = hcl(start)).h, (end = hcl(end)).h), c4 = nogamma(start.c, end.c), l2 = nogamma(start.l, end.l), opacity2 = nogamma(start.opacity, end.opacity);
      return function(t4) {
        start.h = h3(t4);
        start.c = c4(t4);
        start.l = l2(t4);
        start.opacity = opacity2(t4);
        return start + "";
      };
    };
  }
  var hcl_default = hcl2(hue);
  var hclLong = hcl2(nogamma);

  // node_modules/d3-interpolate/src/cubehelix.js
  function cubehelix2(hue2) {
    return function cubehelixGamma(y5) {
      y5 = +y5;
      function cubehelix3(start, end) {
        var h3 = hue2((start = cubehelix(start)).h, (end = cubehelix(end)).h), s2 = nogamma(start.s, end.s), l2 = nogamma(start.l, end.l), opacity2 = nogamma(start.opacity, end.opacity);
        return function(t4) {
          start.h = h3(t4);
          start.s = s2(t4);
          start.l = l2(Math.pow(t4, y5));
          start.opacity = opacity2(t4);
          return start + "";
        };
      }
      cubehelix3.gamma = cubehelixGamma;
      return cubehelix3;
    }(1);
  }
  var cubehelix_default = cubehelix2(hue);
  var cubehelixLong = cubehelix2(nogamma);

  // node_modules/d3-interpolate/src/piecewise.js
  function piecewise(interpolate3, values4) {
    if (values4 === void 0) values4 = interpolate3, interpolate3 = value_default;
    var i2 = 0, n2 = values4.length - 1, v3 = values4[0], I = new Array(n2 < 0 ? 0 : n2);
    while (i2 < n2) I[i2] = interpolate3(v3, v3 = values4[++i2]);
    return function(t4) {
      var i3 = Math.max(0, Math.min(n2 - 1, Math.floor(t4 *= n2)));
      return I[i3](t4 - i3);
    };
  }

  // node_modules/d3-interpolate/src/quantize.js
  function quantize_default2(interpolator, n2) {
    var samples = new Array(n2);
    for (var i2 = 0; i2 < n2; ++i2) samples[i2] = interpolator(i2 / (n2 - 1));
    return samples;
  }

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

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

  // node_modules/d3-scale/src/continuous.js
  var unit = [0, 1];
  function identity3(x5) {
    return x5;
  }
  function normalize(a4, b3) {
    return (b3 -= a4 = +a4) ? function(x5) {
      return (x5 - a4) / b3;
    } : constants(isNaN(b3) ? NaN : 0.5);
  }
  function clamper(a4, b3) {
    var t4;
    if (a4 > b3) t4 = a4, a4 = b3, b3 = t4;
    return function(x5) {
      return Math.max(a4, Math.min(b3, x5));
    };
  }
  function bimap(domain4, range7, interpolate3) {
    var d0 = domain4[0], d1 = domain4[1], r0 = range7[0], r1 = range7[1];
    if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate3(r1, r0);
    else d0 = normalize(d0, d1), r0 = interpolate3(r0, r1);
    return function(x5) {
      return r0(d0(x5));
    };
  }
  function polymap(domain4, range7, interpolate3) {
    var j2 = Math.min(domain4.length, range7.length) - 1, d2 = new Array(j2), r2 = new Array(j2), i2 = -1;
    if (domain4[j2] < domain4[0]) {
      domain4 = domain4.slice().reverse();
      range7 = range7.slice().reverse();
    }
    while (++i2 < j2) {
      d2[i2] = normalize(domain4[i2], domain4[i2 + 1]);
      r2[i2] = interpolate3(range7[i2], range7[i2 + 1]);
    }
    return function(x5) {
      var i3 = bisect_default2(domain4, x5, 1, j2) - 1;
      return r2[i3](d2[i3](x5));
    };
  }
  function copy(source4, target2) {
    return target2.domain(source4.domain()).range(source4.range()).interpolate(source4.interpolate()).clamp(source4.clamp()).unknown(source4.unknown());
  }
  function transformer() {
    var domain4 = unit, range7 = unit, interpolate3 = value_default, transform4, untransform, unknown, clamp2 = identity3, piecewise2, output3, input;
    function rescale() {
      var n2 = Math.min(domain4.length, range7.length);
      if (clamp2 !== identity3) clamp2 = clamper(domain4[0], domain4[n2 - 1]);
      piecewise2 = n2 > 2 ? polymap : bimap;
      output3 = input = null;
      return scale7;
    }
    function scale7(x5) {
      return x5 == null || isNaN(x5 = +x5) ? unknown : (output3 || (output3 = piecewise2(domain4.map(transform4), range7, interpolate3)))(transform4(clamp2(x5)));
    }
    scale7.invert = function(y5) {
      return clamp2(untransform((input || (input = piecewise2(range7, domain4.map(transform4), number_default)))(y5)));
    };
    scale7.domain = function(_) {
      return arguments.length ? (domain4 = Array.from(_, number2), rescale()) : domain4.slice();
    };
    scale7.range = function(_) {
      return arguments.length ? (range7 = Array.from(_), rescale()) : range7.slice();
    };
    scale7.rangeRound = function(_) {
      return range7 = Array.from(_), interpolate3 = round_default, rescale();
    };
    scale7.clamp = function(_) {
      return arguments.length ? (clamp2 = _ ? true : identity3, rescale()) : clamp2 !== identity3;
    };
    scale7.interpolate = function(_) {
      return arguments.length ? (interpolate3 = _, rescale()) : interpolate3;
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    return function(t4, u5) {
      transform4 = t4, untransform = u5;
      return rescale();
    };
  }
  function continuous() {
    return transformer()(identity3, identity3);
  }

  // node_modules/d3-scale/src/tickFormat.js
  function tickFormat(start, stop2, count2, specifier) {
    var step = tickStep(start, stop2, count2), precision;
    specifier = formatSpecifier(specifier == null ? ",f" : specifier);
    switch (specifier.type) {
      case "s": {
        var value3 = Math.max(Math.abs(start), Math.abs(stop2));
        if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value3))) specifier.precision = precision;
        return formatPrefix(specifier, value3);
      }
      case "":
      case "e":
      case "g":
      case "p":
      case "r": {
        if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop2))))) 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(scale7) {
    var domain4 = scale7.domain;
    scale7.ticks = function(count2) {
      var d2 = domain4();
      return ticks(d2[0], d2[d2.length - 1], count2 == null ? 10 : count2);
    };
    scale7.tickFormat = function(count2, specifier) {
      var d2 = domain4();
      return tickFormat(d2[0], d2[d2.length - 1], count2 == null ? 10 : count2, specifier);
    };
    scale7.nice = function(count2) {
      if (count2 == null) count2 = 10;
      var d2 = domain4();
      var i0 = 0;
      var i1 = d2.length - 1;
      var start = d2[i0];
      var stop2 = d2[i1];
      var prestep;
      var step;
      var maxIter = 10;
      if (stop2 < start) {
        step = start, start = stop2, stop2 = step;
        step = i0, i0 = i1, i1 = step;
      }
      while (maxIter-- > 0) {
        step = tickIncrement(start, stop2, count2);
        if (step === prestep) {
          d2[i0] = start;
          d2[i1] = stop2;
          return domain4(d2);
        } else if (step > 0) {
          start = Math.floor(start / step) * step;
          stop2 = Math.ceil(stop2 / step) * step;
        } else if (step < 0) {
          start = Math.ceil(start * step) / step;
          stop2 = Math.floor(stop2 * step) / step;
        } else {
          break;
        }
        prestep = step;
      }
      return scale7;
    };
    return scale7;
  }
  function linear3() {
    var scale7 = continuous();
    scale7.copy = function() {
      return copy(scale7, linear3());
    };
    initRange.apply(scale7, arguments);
    return linearish(scale7);
  }

  // node_modules/d3-scale/src/identity.js
  function identity4(domain4) {
    var unknown;
    function scale7(x5) {
      return x5 == null || isNaN(x5 = +x5) ? unknown : x5;
    }
    scale7.invert = scale7;
    scale7.domain = scale7.range = function(_) {
      return arguments.length ? (domain4 = Array.from(_, number2), scale7) : domain4.slice();
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    scale7.copy = function() {
      return identity4(domain4).unknown(unknown);
    };
    domain4 = arguments.length ? Array.from(domain4, number2) : [0, 1];
    return linearish(scale7);
  }

  // node_modules/d3-scale/src/nice.js
  function nice(domain4, interval3) {
    domain4 = domain4.slice();
    var i0 = 0, i1 = domain4.length - 1, x06 = domain4[i0], x12 = domain4[i1], t4;
    if (x12 < x06) {
      t4 = i0, i0 = i1, i1 = t4;
      t4 = x06, x06 = x12, x12 = t4;
    }
    domain4[i0] = interval3.floor(x06);
    domain4[i1] = interval3.ceil(x12);
    return domain4;
  }

  // node_modules/d3-scale/src/log.js
  function transformLog(x5) {
    return Math.log(x5);
  }
  function transformExp(x5) {
    return Math.exp(x5);
  }
  function transformLogn(x5) {
    return -Math.log(-x5);
  }
  function transformExpn(x5) {
    return -Math.exp(-x5);
  }
  function pow10(x5) {
    return isFinite(x5) ? +("1e" + x5) : x5 < 0 ? 0 : x5;
  }
  function powp(base) {
    return base === 10 ? pow10 : base === Math.E ? Math.exp : (x5) => Math.pow(base, x5);
  }
  function logp(base) {
    return base === Math.E ? Math.log : base === 10 && Math.log10 || base === 2 && Math.log2 || (base = Math.log(base), (x5) => Math.log(x5) / base);
  }
  function reflect(f2) {
    return (x5, k2) => -f2(-x5, k2);
  }
  function loggish(transform4) {
    const scale7 = transform4(transformLog, transformExp);
    const domain4 = scale7.domain;
    let base = 10;
    let logs;
    let pows;
    function rescale() {
      logs = logp(base), pows = powp(base);
      if (domain4()[0] < 0) {
        logs = reflect(logs), pows = reflect(pows);
        transform4(transformLogn, transformExpn);
      } else {
        transform4(transformLog, transformExp);
      }
      return scale7;
    }
    scale7.base = function(_) {
      return arguments.length ? (base = +_, rescale()) : base;
    };
    scale7.domain = function(_) {
      return arguments.length ? (domain4(_), rescale()) : domain4();
    };
    scale7.ticks = (count2) => {
      const d2 = domain4();
      let u5 = d2[0];
      let v3 = d2[d2.length - 1];
      const r2 = v3 < u5;
      if (r2) [u5, v3] = [v3, u5];
      let i2 = logs(u5);
      let j2 = logs(v3);
      let k2;
      let t4;
      const n2 = count2 == null ? 10 : +count2;
      let z = [];
      if (!(base % 1) && j2 - i2 < n2) {
        i2 = Math.floor(i2), j2 = Math.ceil(j2);
        if (u5 > 0) for (; i2 <= j2; ++i2) {
          for (k2 = 1; k2 < base; ++k2) {
            t4 = i2 < 0 ? k2 / pows(-i2) : k2 * pows(i2);
            if (t4 < u5) continue;
            if (t4 > v3) break;
            z.push(t4);
          }
        }
        else for (; i2 <= j2; ++i2) {
          for (k2 = base - 1; k2 >= 1; --k2) {
            t4 = i2 > 0 ? k2 / pows(-i2) : k2 * pows(i2);
            if (t4 < u5) continue;
            if (t4 > v3) break;
            z.push(t4);
          }
        }
        if (z.length * 2 < n2) z = ticks(u5, v3, n2);
      } else {
        z = ticks(i2, j2, Math.min(j2 - i2, n2)).map(pows);
      }
      return r2 ? z.reverse() : z;
    };
    scale7.tickFormat = (count2, specifier) => {
      if (count2 == null) count2 = 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 (count2 === Infinity) return specifier;
      const k2 = Math.max(1, base * count2 / scale7.ticks().length);
      return (d2) => {
        let i2 = d2 / pows(Math.round(logs(d2)));
        if (i2 * base < base - 0.5) i2 *= base;
        return i2 <= k2 ? specifier(d2) : "";
      };
    };
    scale7.nice = () => {
      return domain4(nice(domain4(), {
        floor: (x5) => pows(Math.floor(logs(x5))),
        ceil: (x5) => pows(Math.ceil(logs(x5)))
      }));
    };
    return scale7;
  }
  function log3() {
    const scale7 = loggish(transformer()).domain([1, 10]);
    scale7.copy = () => copy(scale7, log3()).base(scale7.base());
    initRange.apply(scale7, arguments);
    return scale7;
  }

  // node_modules/d3-scale/src/symlog.js
  function transformSymlog(c4) {
    return function(x5) {
      return Math.sign(x5) * Math.log1p(Math.abs(x5 / c4));
    };
  }
  function transformSymexp(c4) {
    return function(x5) {
      return Math.sign(x5) * Math.expm1(Math.abs(x5)) * c4;
    };
  }
  function symlogish(transform4) {
    var c4 = 1, scale7 = transform4(transformSymlog(c4), transformSymexp(c4));
    scale7.constant = function(_) {
      return arguments.length ? transform4(transformSymlog(c4 = +_), transformSymexp(c4)) : c4;
    };
    return linearish(scale7);
  }
  function symlog2() {
    var scale7 = symlogish(transformer());
    scale7.copy = function() {
      return copy(scale7, symlog2()).constant(scale7.constant());
    };
    return initRange.apply(scale7, arguments);
  }

  // node_modules/d3-scale/src/pow.js
  function transformPow(exponent) {
    return function(x5) {
      return x5 < 0 ? -Math.pow(-x5, exponent) : Math.pow(x5, exponent);
    };
  }
  function transformSqrt(x5) {
    return x5 < 0 ? -Math.sqrt(-x5) : Math.sqrt(x5);
  }
  function transformSquare(x5) {
    return x5 < 0 ? -x5 * x5 : x5 * x5;
  }
  function powish(transform4) {
    var scale7 = transform4(identity3, identity3), exponent = 1;
    function rescale() {
      return exponent === 1 ? transform4(identity3, identity3) : exponent === 0.5 ? transform4(transformSqrt, transformSquare) : transform4(transformPow(exponent), transformPow(1 / exponent));
    }
    scale7.exponent = function(_) {
      return arguments.length ? (exponent = +_, rescale()) : exponent;
    };
    return linearish(scale7);
  }
  function pow3() {
    var scale7 = powish(transformer());
    scale7.copy = function() {
      return copy(scale7, pow3()).exponent(scale7.exponent());
    };
    initRange.apply(scale7, arguments);
    return scale7;
  }
  function sqrt2() {
    return pow3.apply(null, arguments).exponent(0.5);
  }

  // node_modules/d3-scale/src/quantile.js
  function quantile2() {
    var domain4 = [], range7 = [], thresholds = [], unknown;
    function rescale() {
      var i2 = 0, n2 = Math.max(1, range7.length);
      thresholds = new Array(n2 - 1);
      while (++i2 < n2) thresholds[i2 - 1] = quantileSorted(domain4, i2 / n2);
      return scale7;
    }
    function scale7(x5) {
      return x5 == null || isNaN(x5 = +x5) ? unknown : range7[bisect_default2(thresholds, x5)];
    }
    scale7.invertExtent = function(y5) {
      var i2 = range7.indexOf(y5);
      return i2 < 0 ? [NaN, NaN] : [
        i2 > 0 ? thresholds[i2 - 1] : domain4[0],
        i2 < thresholds.length ? thresholds[i2] : domain4[domain4.length - 1]
      ];
    };
    scale7.domain = function(_) {
      if (!arguments.length) return domain4.slice();
      domain4 = [];
      for (let d2 of _) if (d2 != null && !isNaN(d2 = +d2)) domain4.push(d2);
      domain4.sort(ascending2);
      return rescale();
    };
    scale7.range = function(_) {
      return arguments.length ? (range7 = Array.from(_), rescale()) : range7.slice();
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    scale7.quantiles = function() {
      return thresholds.slice();
    };
    scale7.copy = function() {
      return quantile2().domain(domain4).range(range7).unknown(unknown);
    };
    return initRange.apply(scale7, arguments);
  }

  // node_modules/d3-scale/src/quantize.js
  function quantize() {
    var x06 = 0, x12 = 1, n2 = 1, domain4 = [0.5], range7 = [0, 1], unknown;
    function scale7(x5) {
      return x5 != null && x5 <= x5 ? range7[bisect_default2(domain4, x5, 0, n2)] : unknown;
    }
    function rescale() {
      var i2 = -1;
      domain4 = new Array(n2);
      while (++i2 < n2) domain4[i2] = ((i2 + 1) * x12 - (i2 - n2) * x06) / (n2 + 1);
      return scale7;
    }
    scale7.domain = function(_) {
      return arguments.length ? ([x06, x12] = _, x06 = +x06, x12 = +x12, rescale()) : [x06, x12];
    };
    scale7.range = function(_) {
      return arguments.length ? (n2 = (range7 = Array.from(_)).length - 1, rescale()) : range7.slice();
    };
    scale7.invertExtent = function(y5) {
      var i2 = range7.indexOf(y5);
      return i2 < 0 ? [NaN, NaN] : i2 < 1 ? [x06, domain4[0]] : i2 >= n2 ? [domain4[n2 - 1], x12] : [domain4[i2 - 1], domain4[i2]];
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : scale7;
    };
    scale7.thresholds = function() {
      return domain4.slice();
    };
    scale7.copy = function() {
      return quantize().domain([x06, x12]).range(range7).unknown(unknown);
    };
    return initRange.apply(linearish(scale7), arguments);
  }

  // node_modules/d3-scale/src/threshold.js
  function threshold() {
    var domain4 = [0.5], range7 = [0, 1], unknown, n2 = 1;
    function scale7(x5) {
      return x5 != null && x5 <= x5 ? range7[bisect_default2(domain4, x5, 0, n2)] : unknown;
    }
    scale7.domain = function(_) {
      return arguments.length ? (domain4 = Array.from(_), n2 = Math.min(domain4.length, range7.length - 1), scale7) : domain4.slice();
    };
    scale7.range = function(_) {
      return arguments.length ? (range7 = Array.from(_), n2 = Math.min(domain4.length, range7.length - 1), scale7) : range7.slice();
    };
    scale7.invertExtent = function(y5) {
      var i2 = range7.indexOf(y5);
      return [domain4[i2 - 1], domain4[i2]];
    };
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    scale7.copy = function() {
      return threshold().domain(domain4).range(range7).unknown(unknown);
    };
    return initRange.apply(scale7, arguments);
  }

  // node_modules/d3-scale/src/time.js
  function date(t4) {
    return new Date(t4);
  }
  function number3(t4) {
    return t4 instanceof Date ? +t4 : +/* @__PURE__ */ new Date(+t4);
  }
  function calendar(ticks2, tickInterval, year, month, week2, day, hour, minute, second2, format5) {
    var scale7 = continuous(), invert2 = scale7.invert, domain4 = scale7.domain;
    var formatMillisecond = format5(".%L"), formatSecond = format5(":%S"), formatMinute = format5("%I:%M"), formatHour = format5("%I %p"), formatDay = format5("%a %d"), formatWeek = format5("%b %d"), formatMonth = format5("%B"), formatYear3 = format5("%Y");
    function tickFormat3(date2) {
      return (second2(date2) < date2 ? formatMillisecond : minute(date2) < date2 ? formatSecond : hour(date2) < date2 ? formatMinute : day(date2) < date2 ? formatHour : month(date2) < date2 ? week2(date2) < date2 ? formatDay : formatWeek : year(date2) < date2 ? formatMonth : formatYear3)(date2);
    }
    scale7.invert = function(y5) {
      return new Date(invert2(y5));
    };
    scale7.domain = function(_) {
      return arguments.length ? domain4(Array.from(_, number3)) : domain4().map(date);
    };
    scale7.ticks = function(interval3) {
      var d2 = domain4();
      return ticks2(d2[0], d2[d2.length - 1], interval3 == null ? 10 : interval3);
    };
    scale7.tickFormat = function(count2, specifier) {
      return specifier == null ? tickFormat3 : format5(specifier);
    };
    scale7.nice = function(interval3) {
      var d2 = domain4();
      if (!interval3 || typeof interval3.range !== "function") interval3 = tickInterval(d2[0], d2[d2.length - 1], interval3 == null ? 10 : interval3);
      return interval3 ? domain4(nice(d2, interval3)) : scale7;
    };
    scale7.copy = function() {
      return copy(scale7, calendar(ticks2, tickInterval, year, month, week2, day, hour, minute, second2, format5));
    };
    return scale7;
  }
  function time() {
    return initRange.apply(calendar(timeTicks, timeTickInterval, timeYear, timeMonth, timeSunday, timeDay, timeHour, timeMinute, second, timeFormat).domain([new Date(2e3, 0, 1), new Date(2e3, 0, 2)]), arguments);
  }

  // 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-scale/src/sequential.js
  function transformer2() {
    var x06 = 0, x12 = 1, t04, t13, k10, transform4, interpolator = identity3, clamp2 = false, unknown;
    function scale7(x5) {
      return x5 == null || isNaN(x5 = +x5) ? unknown : interpolator(k10 === 0 ? 0.5 : (x5 = (transform4(x5) - t04) * k10, clamp2 ? Math.max(0, Math.min(1, x5)) : x5));
    }
    scale7.domain = function(_) {
      return arguments.length ? ([x06, x12] = _, t04 = transform4(x06 = +x06), t13 = transform4(x12 = +x12), k10 = t04 === t13 ? 0 : 1 / (t13 - t04), scale7) : [x06, x12];
    };
    scale7.clamp = function(_) {
      return arguments.length ? (clamp2 = !!_, scale7) : clamp2;
    };
    scale7.interpolator = function(_) {
      return arguments.length ? (interpolator = _, scale7) : interpolator;
    };
    function range7(interpolate3) {
      return function(_) {
        var r0, r1;
        return arguments.length ? ([r0, r1] = _, interpolator = interpolate3(r0, r1), scale7) : [interpolator(0), interpolator(1)];
      };
    }
    scale7.range = range7(value_default);
    scale7.rangeRound = range7(round_default);
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    return function(t4) {
      transform4 = t4, t04 = t4(x06), t13 = t4(x12), k10 = t04 === t13 ? 0 : 1 / (t13 - t04);
      return scale7;
    };
  }
  function copy2(source4, target2) {
    return target2.domain(source4.domain()).interpolator(source4.interpolator()).clamp(source4.clamp()).unknown(source4.unknown());
  }
  function sequential() {
    var scale7 = linearish(transformer2()(identity3));
    scale7.copy = function() {
      return copy2(scale7, sequential());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function sequentialLog() {
    var scale7 = loggish(transformer2()).domain([1, 10]);
    scale7.copy = function() {
      return copy2(scale7, sequentialLog()).base(scale7.base());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function sequentialSymlog() {
    var scale7 = symlogish(transformer2());
    scale7.copy = function() {
      return copy2(scale7, sequentialSymlog()).constant(scale7.constant());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function sequentialPow() {
    var scale7 = powish(transformer2());
    scale7.copy = function() {
      return copy2(scale7, sequentialPow()).exponent(scale7.exponent());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function sequentialSqrt() {
    return sequentialPow.apply(null, arguments).exponent(0.5);
  }

  // node_modules/d3-scale/src/diverging.js
  function transformer3() {
    var x06 = 0, x12 = 0.5, x22 = 1, s2 = 1, t04, t13, t22, k10, k21, interpolator = identity3, transform4, clamp2 = false, unknown;
    function scale7(x5) {
      return isNaN(x5 = +x5) ? unknown : (x5 = 0.5 + ((x5 = +transform4(x5)) - t13) * (s2 * x5 < s2 * t13 ? k10 : k21), interpolator(clamp2 ? Math.max(0, Math.min(1, x5)) : x5));
    }
    scale7.domain = function(_) {
      return arguments.length ? ([x06, x12, x22] = _, t04 = transform4(x06 = +x06), t13 = transform4(x12 = +x12), t22 = transform4(x22 = +x22), k10 = t04 === t13 ? 0 : 0.5 / (t13 - t04), k21 = t13 === t22 ? 0 : 0.5 / (t22 - t13), s2 = t13 < t04 ? -1 : 1, scale7) : [x06, x12, x22];
    };
    scale7.clamp = function(_) {
      return arguments.length ? (clamp2 = !!_, scale7) : clamp2;
    };
    scale7.interpolator = function(_) {
      return arguments.length ? (interpolator = _, scale7) : interpolator;
    };
    function range7(interpolate3) {
      return function(_) {
        var r0, r1, r2;
        return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate3, [r0, r1, r2]), scale7) : [interpolator(0), interpolator(0.5), interpolator(1)];
      };
    }
    scale7.range = range7(value_default);
    scale7.rangeRound = range7(round_default);
    scale7.unknown = function(_) {
      return arguments.length ? (unknown = _, scale7) : unknown;
    };
    return function(t4) {
      transform4 = t4, t04 = t4(x06), t13 = t4(x12), t22 = t4(x22), k10 = t04 === t13 ? 0 : 0.5 / (t13 - t04), k21 = t13 === t22 ? 0 : 0.5 / (t22 - t13), s2 = t13 < t04 ? -1 : 1;
      return scale7;
    };
  }
  function diverging() {
    var scale7 = linearish(transformer3()(identity3));
    scale7.copy = function() {
      return copy2(scale7, diverging());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function divergingLog() {
    var scale7 = loggish(transformer3()).domain([0.1, 1, 10]);
    scale7.copy = function() {
      return copy2(scale7, divergingLog()).base(scale7.base());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function divergingSymlog() {
    var scale7 = symlogish(transformer3());
    scale7.copy = function() {
      return copy2(scale7, divergingSymlog()).constant(scale7.constant());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function divergingPow() {
    var scale7 = powish(transformer3());
    scale7.copy = function() {
      return copy2(scale7, divergingPow()).exponent(scale7.exponent());
    };
    return initInterpolator.apply(scale7, arguments);
  }
  function divergingSqrt() {
    return divergingPow.apply(null, arguments).exponent(0.5);
  }

  // node_modules/d3-scale-chromatic/src/colors.js
  function colors_default(specifier) {
    var n2 = specifier.length / 6 | 0, colors2 = new Array(n2), i2 = 0;
    while (i2 < n2) colors2[i2] = "#" + specifier.slice(i2 * 6, ++i2 * 6);
    return colors2;
  }

  // node_modules/d3-scale-chromatic/src/categorical/category10.js
  var category10_default = colors_default("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf");

  // node_modules/d3-scale-chromatic/src/categorical/Accent.js
  var Accent_default = colors_default("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666");

  // node_modules/d3-scale-chromatic/src/categorical/Dark2.js
  var Dark2_default = colors_default("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666");

  // node_modules/d3-scale-chromatic/src/categorical/observable10.js
  var observable10_default = colors_default("4269d0efb118ff725c6cc5b03ca951ff8ab7a463f297bbf59c6b4e9498a0");

  // node_modules/d3-scale-chromatic/src/categorical/Paired.js
  var Paired_default = colors_default("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");

  // node_modules/d3-scale-chromatic/src/categorical/Pastel1.js
  var Pastel1_default = colors_default("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2");

  // node_modules/d3-scale-chromatic/src/categorical/Pastel2.js
  var Pastel2_default = colors_default("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc");

  // node_modules/d3-scale-chromatic/src/categorical/Set1.js
  var Set1_default = colors_default("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999");

  // node_modules/d3-scale-chromatic/src/categorical/Set2.js
  var Set2_default = colors_default("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3");

  // node_modules/d3-scale-chromatic/src/categorical/Set3.js
  var Set3_default = colors_default("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f");

  // node_modules/vega-scale/build/vega-scale.module.js
  function bandSpace(count2, paddingInner2, paddingOuter2) {
    const space = count2 - paddingInner2 + paddingOuter2 * 2;
    return count2 ? space > 0 ? space : 1 : 0;
  }
  var Identity = "identity";
  var Linear2 = "linear";
  var Log = "log";
  var Pow = "pow";
  var Sqrt = "sqrt";
  var Symlog = "symlog";
  var Time = "time";
  var UTC = "utc";
  var Sequential = "sequential";
  var Diverging = "diverging";
  var Quantile2 = "quantile";
  var Quantize = "quantize";
  var Threshold = "threshold";
  var Ordinal = "ordinal";
  var Point = "point";
  var Band = "band";
  var BinOrdinal = "bin-ordinal";
  var Continuous = "continuous";
  var Discrete = "discrete";
  var Discretizing = "discretizing";
  var Interpolating = "interpolating";
  var Temporal = "temporal";
  function invertRange(scale7) {
    return function(_) {
      let lo = _[0], hi = _[1], t4;
      if (hi < lo) {
        t4 = lo;
        lo = hi;
        hi = t4;
      }
      return [scale7.invert(lo), scale7.invert(hi)];
    };
  }
  function invertRangeExtent(scale7) {
    return function(_) {
      const range7 = scale7.range();
      let lo = _[0], hi = _[1], min4 = -1, max4, t4, i2, n2;
      if (hi < lo) {
        t4 = lo;
        lo = hi;
        hi = t4;
      }
      for (i2 = 0, n2 = range7.length; i2 < n2; ++i2) {
        if (range7[i2] >= lo && range7[i2] <= hi) {
          if (min4 < 0) min4 = i2;
          max4 = i2;
        }
      }
      if (min4 < 0) return void 0;
      lo = scale7.invertExtent(range7[min4]);
      hi = scale7.invertExtent(range7[max4]);
      return [lo[0] === void 0 ? lo[1] : lo[0], hi[1] === void 0 ? hi[0] : hi[1]];
    };
  }
  function band() {
    const scale7 = ordinal().unknown(void 0), domain4 = scale7.domain, ordinalRange = scale7.range;
    let range$1 = [0, 1], step, bandwidth2, round = false, paddingInner2 = 0, paddingOuter2 = 0, align2 = 0.5;
    delete scale7.unknown;
    function rescale() {
      const n2 = domain4().length, reverse3 = range$1[1] < range$1[0], stop2 = range$1[1 - reverse3], space = bandSpace(n2, paddingInner2, paddingOuter2);
      let start = range$1[reverse3 - 0];
      step = (stop2 - start) / (space || 1);
      if (round) {
        step = Math.floor(step);
      }
      start += (stop2 - start - step * (n2 - paddingInner2)) * align2;
      bandwidth2 = step * (1 - paddingInner2);
      if (round) {
        start = Math.round(start);
        bandwidth2 = Math.round(bandwidth2);
      }
      const values4 = range(n2).map((i2) => start + step * i2);
      return ordinalRange(reverse3 ? values4.reverse() : values4);
    }
    scale7.domain = function(_) {
      if (arguments.length) {
        domain4(_);
        return rescale();
      } else {
        return domain4();
      }
    };
    scale7.range = function(_) {
      if (arguments.length) {
        range$1 = [+_[0], +_[1]];
        return rescale();
      } else {
        return range$1.slice();
      }
    };
    scale7.rangeRound = function(_) {
      range$1 = [+_[0], +_[1]];
      round = true;
      return rescale();
    };
    scale7.bandwidth = function() {
      return bandwidth2;
    };
    scale7.step = function() {
      return step;
    };
    scale7.round = function(_) {
      if (arguments.length) {
        round = !!_;
        return rescale();
      } else {
        return round;
      }
    };
    scale7.padding = function(_) {
      if (arguments.length) {
        paddingOuter2 = Math.max(0, Math.min(1, _));
        paddingInner2 = paddingOuter2;
        return rescale();
      } else {
        return paddingInner2;
      }
    };
    scale7.paddingInner = function(_) {
      if (arguments.length) {
        paddingInner2 = Math.max(0, Math.min(1, _));
        return rescale();
      } else {
        return paddingInner2;
      }
    };
    scale7.paddingOuter = function(_) {
      if (arguments.length) {
        paddingOuter2 = Math.max(0, Math.min(1, _));
        return rescale();
      } else {
        return paddingOuter2;
      }
    };
    scale7.align = function(_) {
      if (arguments.length) {
        align2 = Math.max(0, Math.min(1, _));
        return rescale();
      } else {
        return align2;
      }
    };
    scale7.invertRange = function(_) {
      if (_[0] == null || _[1] == null) return;
      const reverse3 = range$1[1] < range$1[0], values4 = reverse3 ? ordinalRange().reverse() : ordinalRange(), n2 = values4.length - 1;
      let lo = +_[0], hi = +_[1], a4, b3, t4;
      if (lo !== lo || hi !== hi) return;
      if (hi < lo) {
        t4 = lo;
        lo = hi;
        hi = t4;
      }
      if (hi < values4[0] || lo > range$1[1 - reverse3]) return;
      a4 = Math.max(0, bisectRight(values4, lo) - 1);
      b3 = lo === hi ? a4 : bisectRight(values4, hi) - 1;
      if (lo - values4[a4] > bandwidth2 + 1e-10) ++a4;
      if (reverse3) {
        t4 = a4;
        a4 = n2 - b3;
        b3 = n2 - t4;
      }
      return a4 > b3 ? void 0 : domain4().slice(a4, b3 + 1);
    };
    scale7.invert = function(_) {
      const value3 = scale7.invertRange([_, _]);
      return value3 ? value3[0] : value3;
    };
    scale7.copy = function() {
      return band().domain(domain4()).range(range$1).round(round).paddingInner(paddingInner2).paddingOuter(paddingOuter2).align(align2);
    };
    return rescale();
  }
  function pointish(scale7) {
    const copy4 = scale7.copy;
    scale7.padding = scale7.paddingOuter;
    delete scale7.paddingInner;
    scale7.copy = function() {
      return pointish(copy4());
    };
    return scale7;
  }
  function point5() {
    return pointish(band().paddingInner(1));
  }
  var map2 = Array.prototype.map;
  function numbers3(_) {
    return map2.call(_, toNumber);
  }
  var slice2 = Array.prototype.slice;
  function scaleBinOrdinal() {
    let domain4 = [], range7 = [];
    function scale7(x5) {
      return x5 == null || x5 !== x5 ? void 0 : range7[(bisect_default2(domain4, x5) - 1) % range7.length];
    }
    scale7.domain = function(_) {
      if (arguments.length) {
        domain4 = numbers3(_);
        return scale7;
      } else {
        return domain4.slice();
      }
    };
    scale7.range = function(_) {
      if (arguments.length) {
        range7 = slice2.call(_);
        return scale7;
      } else {
        return range7.slice();
      }
    };
    scale7.tickFormat = function(count2, specifier) {
      return tickFormat(domain4[0], peek(domain4), count2 == null ? 10 : count2, specifier);
    };
    scale7.copy = function() {
      return scaleBinOrdinal().domain(scale7.domain()).range(scale7.range());
    };
    return scale7;
  }
  var scales = /* @__PURE__ */ new Map();
  var VEGA_SCALE = Symbol("vega_scale");
  function registerScale(scale7) {
    scale7[VEGA_SCALE] = true;
    return scale7;
  }
  function isRegisteredScale(scale7) {
    return scale7 && scale7[VEGA_SCALE] === true;
  }
  function create(type3, constructor, metadata2) {
    const ctr = function scale7() {
      const s2 = constructor();
      if (!s2.invertRange) {
        s2.invertRange = s2.invert ? invertRange(s2) : s2.invertExtent ? invertRangeExtent(s2) : void 0;
      }
      s2.type = type3;
      return registerScale(s2);
    };
    ctr.metadata = toSet(array(metadata2));
    return ctr;
  }
  function scale(type3, scale7, metadata2) {
    if (arguments.length > 1) {
      scales.set(type3, create(type3, scale7, metadata2));
      return this;
    } else {
      return isValidScaleType(type3) ? scales.get(type3) : void 0;
    }
  }
  scale(Identity, identity4);
  scale(Linear2, linear3, Continuous);
  scale(Log, log3, [Continuous, Log]);
  scale(Pow, pow3, Continuous);
  scale(Sqrt, sqrt2, Continuous);
  scale(Symlog, symlog2, Continuous);
  scale(Time, time, [Continuous, Temporal]);
  scale(UTC, utcTime, [Continuous, Temporal]);
  scale(Sequential, sequential, [Continuous, Interpolating]);
  scale(`${Sequential}-${Linear2}`, sequential, [Continuous, Interpolating]);
  scale(`${Sequential}-${Log}`, sequentialLog, [Continuous, Interpolating, Log]);
  scale(`${Sequential}-${Pow}`, sequentialPow, [Continuous, Interpolating]);
  scale(`${Sequential}-${Sqrt}`, sequentialSqrt, [Continuous, Interpolating]);
  scale(`${Sequential}-${Symlog}`, sequentialSymlog, [Continuous, Interpolating]);
  scale(`${Diverging}-${Linear2}`, diverging, [Continuous, Interpolating]);
  scale(`${Diverging}-${Log}`, divergingLog, [Continuous, Interpolating, Log]);
  scale(`${Diverging}-${Pow}`, divergingPow, [Continuous, Interpolating]);
  scale(`${Diverging}-${Sqrt}`, divergingSqrt, [Continuous, Interpolating]);
  scale(`${Diverging}-${Symlog}`, divergingSymlog, [Continuous, Interpolating]);
  scale(Quantile2, quantile2, [Discretizing, Quantile2]);
  scale(Quantize, quantize, Discretizing);
  scale(Threshold, threshold, Discretizing);
  scale(BinOrdinal, scaleBinOrdinal, [Discrete, Discretizing]);
  scale(Ordinal, ordinal, Discrete);
  scale(Band, band, Discrete);
  scale(Point, point5, Discrete);
  function isValidScaleType(type3) {
    return scales.has(type3);
  }
  function hasType(key2, type3) {
    const s2 = scales.get(key2);
    return s2 && s2.metadata[type3];
  }
  function isContinuous(key2) {
    return hasType(key2, Continuous);
  }
  function isDiscrete(key2) {
    return hasType(key2, Discrete);
  }
  function isDiscretizing(key2) {
    return hasType(key2, Discretizing);
  }
  function isLogarithmic(key2) {
    return hasType(key2, Log);
  }
  function isTemporal(key2) {
    return hasType(key2, Temporal);
  }
  function isInterpolating(key2) {
    return hasType(key2, Interpolating);
  }
  function isQuantile(key2) {
    return hasType(key2, Quantile2);
  }
  var scaleProps = ["clamp", "base", "constant", "exponent"];
  function interpolateRange(interpolator, range7) {
    const start = range7[0], span2 = peek(range7) - start;
    return function(i2) {
      return interpolator(start + i2 * span2);
    };
  }
  function interpolateColors(colors2, type3, gamma2) {
    return piecewise(interpolate(type3 || "rgb", gamma2), colors2);
  }
  function quantizeInterpolator(interpolator, count2) {
    const samples = new Array(count2), n2 = count2 + 1;
    for (let i2 = 0; i2 < count2; ) samples[i2] = interpolator(++i2 / n2);
    return samples;
  }
  function scaleFraction(scale$12, min4, max4) {
    const delta = max4 - min4;
    let i2, t4, s2;
    if (!delta || !Number.isFinite(delta)) {
      return constant(0.5);
    } else {
      i2 = (t4 = scale$12.type).indexOf("-");
      t4 = i2 < 0 ? t4 : t4.slice(i2 + 1);
      s2 = scale(t4)().domain([min4, max4]).range([0, 1]);
      scaleProps.forEach((m4) => scale$12[m4] ? s2[m4](scale$12[m4]()) : 0);
      return s2;
    }
  }
  function interpolate(type3, gamma2) {
    const interp = src_exports[method(type3)];
    return gamma2 != null && interp && interp.gamma ? interp.gamma(gamma2) : interp;
  }
  function method(type3) {
    return "interpolate" + type3.toLowerCase().split("-").map((s2) => s2[0].toUpperCase() + s2.slice(1)).join("");
  }
  var continuous2 = {
    blues: "cfe1f2bed8eca8cee58fc1de74b2d75ba3cf4592c63181bd206fb2125ca40a4a90",
    greens: "d3eecdc0e6baabdda594d3917bc77d60ba6c46ab5e329a512089430e7735036429",
    greys: "e2e2e2d4d4d4c4c4c4b1b1b19d9d9d8888887575756262624d4d4d3535351e1e1e",
    oranges: "fdd8b3fdc998fdb87bfda55efc9244f87f2cf06b18e4580bd14904b93d029f3303",
    purples: "e2e1efd4d4e8c4c5e0b4b3d6a3a0cc928ec3827cb97566ae684ea25c3696501f8c",
    reds: "fdc9b4fcb49afc9e80fc8767fa7051f6573fec3f2fdc2a25c81b1db21218970b13",
    blueGreen: "d5efedc1e8e0a7ddd18bd2be70c6a958ba9144ad77319c5d2089460e7736036429",
    bluePurple: "ccddecbad0e4a8c2dd9ab0d4919cc98d85be8b6db28a55a6873c99822287730f71",
    greenBlue: "d3eecec5e8c3b1e1bb9bd8bb82cec269c2ca51b2cd3c9fc7288abd1675b10b60a1",
    orangeRed: "fddcaffdcf9bfdc18afdad77fb9562f67d53ee6545e24932d32d1ebf130da70403",
    purpleBlue: "dbdaebc8cee4b1c3de97b7d87bacd15b9fc93a90c01e7fb70b70ab056199045281",
    purpleBlueGreen: "dbd8eac8cee4b0c3de93b7d872acd1549fc83892bb1c88a3097f8702736b016353",
    purpleRed: "dcc9e2d3b3d7ce9eccd186c0da6bb2e14da0e23189d91e6fc61159ab07498f023a",
    redPurple: "fccfccfcbec0faa9b8f98faff571a5ec539ddb3695c41b8aa908808d0179700174",
    yellowGreen: "e4f4acd1eca0b9e2949ed68880c97c62bb6e47aa5e3297502083440e723b036034",
    yellowOrangeBrown: "feeaa1fedd84fecc63feb746fca031f68921eb7215db5e0bc54c05ab3d038f3204",
    yellowOrangeRed: "fee087fed16ffebd59fea849fd903efc7335f9522bee3423de1b20ca0b22af0225",
    blueOrange: "134b852f78b35da2cb9dcae1d2e5eff2f0ebfce0bafbbf74e8932fc5690d994a07",
    brownBlueGreen: "704108a0651ac79548e3c78af3e6c6eef1eac9e9e48ed1c74da79e187a72025147",
    purpleGreen: "5b1667834792a67fb6c9aed3e6d6e8eff0efd9efd5aedda971bb75368e490e5e29",
    purpleOrange: "4114696647968f83b7b9b4d6dadbebf3eeeafce0bafbbf74e8932fc5690d994a07",
    redBlue: "8c0d25bf363adf745ef4ae91fbdbc9f2efeed2e5ef9dcae15da2cb2f78b3134b85",
    redGrey: "8c0d25bf363adf745ef4ae91fcdccbfaf4f1e2e2e2c0c0c0969696646464343434",
    yellowGreenBlue: "eff9bddbf1b4bde5b594d5b969c5be45b4c22c9ec02182b82163aa23479c1c3185",
    redYellowBlue: "a50026d4322cf16e43fcac64fedd90faf8c1dcf1ecabd6e875abd04a74b4313695",
    redYellowGreen: "a50026d4322cf16e43fcac63fedd8df9f7aed7ee8ea4d86e64bc6122964f006837",
    pinkYellowGreen: "8e0152c0267edd72adf0b3d6faddedf5f3efe1f2cab6de8780bb474f9125276419",
    spectral: "9e0142d13c4bf0704afcac63fedd8dfbf8b0e0f3a1a9dda269bda94288b55e4fa2",
    viridis: "440154470e61481a6c482575472f7d443a834144873d4e8a39568c35608d31688e2d708e2a788e27818e23888e21918d1f988b1fa08822a8842ab07f35b77943bf7154c56866cc5d7ad1518fd744a5db36bcdf27d2e21be9e51afde725",
    magma: "0000040404130b0924150e3720114b2c11603b0f704a107957157e651a80721f817f24828c29819a2e80a8327db6377ac43c75d1426fde4968e95462f1605df76f5cfa7f5efc8f65fe9f6dfeaf78febf84fece91fddea0fcedaffcfdbf",
    inferno: "0000040403130c0826170c3b240c4f330a5f420a68500d6c5d126e6b176e781c6d86216b932667a12b62ae305cbb3755c73e4cd24644dd513ae65c30ed6925f3771af8850ffb9506fca50afcb519fac62df6d645f2e661f3f484fcffa4",
    plasma: "0d088723069033059742039d5002a25d01a66a00a87801a88405a7900da49c179ea72198b12a90ba3488c33d80cb4779d35171da5a69e16462e76e5bed7953f2834cf68f44fa9a3dfca636fdb32ffec029fcce25f9dc24f5ea27f0f921",
    cividis: "00205100235800265d002961012b65042e670831690d346b11366c16396d1c3c6e213f6e26426e2c456e31476e374a6e3c4d6e42506e47536d4c566d51586e555b6e5a5e6e5e616e62646f66676f6a6a706e6d717270717573727976737c79747f7c75827f758682768985778c8877908b78938e789691789a94789e9778a19b78a59e77a9a177aea575b2a874b6ab73bbaf71c0b26fc5b66dc9b96acebd68d3c065d8c462ddc85fe2cb5ce7cf58ebd355f0d652f3da4ff7de4cfae249fce647",
    rainbow: "6e40aa883eb1a43db3bf3cafd83fa4ee4395fe4b83ff576eff6659ff7847ff8c38f3a130e2b72fcfcc36bee044aff05b8ff4576ff65b52f6673af27828ea8d1ddfa319d0b81cbecb23abd82f96e03d82e14c6edb5a5dd0664dbf6e40aa",
    sinebow: "ff4040fc582af47218e78d0bd5a703bfbf00a7d5038de70b72f41858fc2a40ff402afc5818f4720be78d03d5a700bfbf03a7d50b8de71872f42a58fc4040ff582afc7218f48d0be7a703d5bf00bfd503a7e70b8df41872fc2a58ff4040",
    turbo: "23171b32204a3e2a71453493493eae4b49c54a53d7485ee44569ee4074f53c7ff8378af93295f72e9ff42ba9ef28b3e926bce125c5d925cdcf27d5c629dcbc2de3b232e9a738ee9d3ff39347f68950f9805afc7765fd6e70fe667cfd5e88fc5795fb51a1f84badf545b9f140c5ec3cd0e637dae034e4d931ecd12ef4c92bfac029ffb626ffad24ffa223ff9821ff8d1fff821dff771cfd6c1af76118f05616e84b14df4111d5380fcb2f0dc0260ab61f07ac1805a313029b0f00950c00910b00",
    browns: "eedbbdecca96e9b97ae4a865dc9856d18954c7784cc0673fb85536ad44339f3632",
    tealBlues: "bce4d89dd3d181c3cb65b3c245a2b9368fae347da0306a932c5985",
    teals: "bbdfdfa2d4d58ac9c975bcbb61b0af4da5a43799982b8b8c1e7f7f127273006667",
    warmGreys: "dcd4d0cec5c1c0b8b4b3aaa7a59c9998908c8b827f7e7673726866665c5a59504e",
    goldGreen: "f4d166d5ca60b6c35c98bb597cb25760a6564b9c533f8f4f33834a257740146c36",
    goldOrange: "f4d166f8be5cf8aa4cf5983bf3852aef701be2621fd65322c54923b142239e3a26",
    goldRed: "f4d166f6be59f9aa51fc964ef6834bee734ae56249db5247cf4244c43141b71d3e",
    lightGreyRed: "efe9e6e1dad7d5cbc8c8bdb9bbaea9cd967ddc7b43e15f19df4011dc000b",
    lightGreyTeal: "e4eaead6dcddc8ced2b7c2c7a6b4bc64b0bf22a6c32295c11f85be1876bc",
    lightMulti: "e0f1f2c4e9d0b0de9fd0e181f6e072f6c053f3993ef77440ef4a3c",
    lightOrange: "f2e7daf7d5baf9c499fab184fa9c73f68967ef7860e8645bde515bd43d5b",
    lightTealBlue: "e3e9e0c0dccf9aceca7abfc859afc0389fb9328dad2f7ca0276b95255988",
    darkBlue: "3232322d46681a5c930074af008cbf05a7ce25c0dd38daed50f3faffffff",
    darkGold: "3c3c3c584b37725e348c7631ae8b2bcfa424ecc31ef9de30fff184ffffff",
    darkGreen: "3a3a3a215748006f4d048942489e4276b340a6c63dd2d836ffeb2cffffaa",
    darkMulti: "3737371f5287197d8c29a86995ce3fffe800ffffff",
    darkRed: "3434347036339e3c38cc4037e75d1eec8620eeab29f0ce32ffeb2c"
  };
  var discrete = {
    accent: Accent_default,
    category10: category10_default,
    category20: "1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5",
    category20b: "393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6",
    category20c: "3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9",
    dark2: Dark2_default,
    observable10: observable10_default,
    paired: Paired_default,
    pastel1: Pastel1_default,
    pastel2: Pastel2_default,
    set1: Set1_default,
    set2: Set2_default,
    set3: Set3_default,
    tableau10: "4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac",
    tableau20: "4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5"
  };
  function colors(palette) {
    if (isArray(palette)) return palette;
    const n2 = palette.length / 6 | 0, c4 = new Array(n2);
    for (let i2 = 0; i2 < n2; ) {
      c4[i2] = "#" + palette.slice(i2 * 6, ++i2 * 6);
    }
    return c4;
  }
  function apply(_, f2) {
    for (const k2 in _) scheme(k2, f2(_[k2]));
  }
  var schemes = {};
  apply(discrete, colors);
  apply(continuous2, (_) => interpolateColors(colors(_)));
  function scheme(name4, scheme3) {
    name4 = name4 && name4.toLowerCase();
    if (arguments.length > 1) {
      schemes[name4] = scheme3;
      return this;
    } else {
      return schemes[name4];
    }
  }
  var SymbolLegend = "symbol";
  var DiscreteLegend = "discrete";
  var GradientLegend = "gradient";
  var defaultFormatter = (value3) => isArray(value3) ? value3.map((v3) => String(v3)) : String(value3);
  var ascending3 = (a4, b3) => a4[1] - b3[1];
  var descending2 = (a4, b3) => b3[1] - a4[1];
  function tickCount(scale7, count2, minStep) {
    let step;
    if (isNumber(count2)) {
      if (scale7.bins) {
        count2 = Math.max(count2, scale7.bins.length);
      }
      if (minStep != null) {
        count2 = Math.min(count2, Math.floor(span(scale7.domain()) / minStep || 1) + 1);
      }
    }
    if (isObject(count2)) {
      step = count2.step;
      count2 = count2.interval;
    }
    if (isString(count2)) {
      count2 = scale7.type === Time ? timeInterval2(count2) : scale7.type == UTC ? utcInterval(count2) : error("Only time and utc scales accept interval strings.");
      if (step) count2 = count2.every(step);
    }
    return count2;
  }
  function validTicks(scale7, ticks2, count2) {
    let range7 = scale7.range(), lo = range7[0], hi = peek(range7), cmp = ascending3;
    if (lo > hi) {
      range7 = hi;
      hi = lo;
      lo = range7;
      cmp = descending2;
    }
    lo = Math.floor(lo);
    hi = Math.ceil(hi);
    ticks2 = ticks2.map((v3) => [v3, scale7(v3)]).filter((_) => lo <= _[1] && _[1] <= hi).sort(cmp).map((_) => _[0]);
    if (count2 > 0 && ticks2.length > 1) {
      const endpoints = [ticks2[0], peek(ticks2)];
      while (ticks2.length > count2 && ticks2.length >= 3) {
        ticks2 = ticks2.filter((_, i2) => !(i2 % 2));
      }
      if (ticks2.length < 3) {
        ticks2 = endpoints;
      }
    }
    return ticks2;
  }
  function tickValues(scale7, count2) {
    return scale7.bins ? validTicks(scale7, scale7.bins, count2) : scale7.ticks ? scale7.ticks(count2) : scale7.domain();
  }
  function tickFormat2(locale4, scale7, count2, specifier, formatType, noSkip) {
    const type3 = scale7.type;
    let format5 = defaultFormatter;
    if (type3 === Time || formatType === Time) {
      format5 = locale4.timeFormat(specifier);
    } else if (type3 === UTC || formatType === UTC) {
      format5 = locale4.utcFormat(specifier);
    } else if (isLogarithmic(type3)) {
      const varfmt = locale4.formatFloat(specifier);
      if (noSkip || scale7.bins) {
        format5 = varfmt;
      } else {
        const test2 = tickLog(scale7, count2, false);
        format5 = (_) => test2(_) ? varfmt(_) : "";
      }
    } else if (scale7.tickFormat) {
      const d2 = scale7.domain();
      format5 = locale4.formatSpan(d2[0], d2[d2.length - 1], count2, specifier);
    } else if (specifier) {
      format5 = locale4.format(specifier);
    }
    return format5;
  }
  function tickLog(scale7, count2, values4) {
    const ticks2 = tickValues(scale7, count2), base = scale7.base(), logb = Math.log(base), k2 = Math.max(1, base * count2 / ticks2.length);
    const test2 = (d2) => {
      let i2 = d2 / Math.pow(base, Math.round(Math.log(d2) / logb));
      if (i2 * base < base - 0.5) i2 *= base;
      return i2 <= k2;
    };
    return values4 ? ticks2.filter(test2) : test2;
  }
  var symbols = {
    [Quantile2]: "quantiles",
    [Quantize]: "thresholds",
    [Threshold]: "domain"
  };
  var formats2 = {
    [Quantile2]: "quantiles",
    [Quantize]: "domain"
  };
  function labelValues(scale7, count2) {
    return scale7.bins ? binValues(scale7.bins) : scale7.type === Log ? tickLog(scale7, count2, true) : symbols[scale7.type] ? thresholdValues(scale7[symbols[scale7.type]]()) : tickValues(scale7, count2);
  }
  function thresholdFormat(locale4, scale7, specifier) {
    const _ = scale7[formats2[scale7.type]](), n2 = _.length;
    let d2 = n2 > 1 ? _[1] - _[0] : _[0], i2;
    for (i2 = 1; i2 < n2; ++i2) {
      d2 = Math.min(d2, _[i2] - _[i2 - 1]);
    }
    return locale4.formatSpan(0, d2, 3 * 10, specifier);
  }
  function thresholdValues(thresholds) {
    const values4 = [-Infinity].concat(thresholds);
    values4.max = Infinity;
    return values4;
  }
  function binValues(bins2) {
    const values4 = bins2.slice(0, -1);
    values4.max = peek(bins2);
    return values4;
  }
  var isDiscreteRange = (scale7) => symbols[scale7.type] || scale7.bins;
  function labelFormat(locale4, scale7, count2, type3, specifier, formatType, noSkip) {
    const format5 = formats2[scale7.type] && formatType !== Time && formatType !== UTC ? thresholdFormat(locale4, scale7, specifier) : tickFormat2(locale4, scale7, count2, specifier, formatType, noSkip);
    return type3 === SymbolLegend && isDiscreteRange(scale7) ? formatRange(format5) : type3 === DiscreteLegend ? formatDiscrete(format5) : formatPoint(format5);
  }
  var formatRange = (format5) => (value3, index4, array4) => {
    const limit = get2(array4[index4 + 1], get2(array4.max, Infinity)), lo = formatValue(value3, format5), hi = formatValue(limit, format5);
    return lo && hi ? lo + " \u2013 " + hi : hi ? "< " + hi : "\u2265 " + lo;
  };
  var get2 = (value3, dflt) => value3 != null ? value3 : dflt;
  var formatDiscrete = (format5) => (value3, index4) => index4 ? format5(value3) : null;
  var formatPoint = (format5) => (value3) => format5(value3);
  var formatValue = (value3, format5) => Number.isFinite(value3) ? format5(value3) : null;
  function labelFraction(scale7) {
    const domain4 = scale7.domain(), count2 = domain4.length - 1;
    let lo = +domain4[0], hi = +peek(domain4), span2 = hi - lo;
    if (scale7.type === Threshold) {
      const adjust = count2 ? span2 / count2 : 0.1;
      lo -= adjust;
      hi += adjust;
      span2 = hi - lo;
    }
    return (value3) => (value3 - lo) / span2;
  }
  function format3(locale4, scale7, specifier, formatType) {
    const type3 = formatType || scale7.type;
    if (isString(specifier) && isTemporal(type3)) {
      specifier = specifier.replace(/%a/g, "%A").replace(/%b/g, "%B");
    }
    return !specifier && type3 === Time ? locale4.timeFormat("%A, %d %B %Y, %X") : !specifier && type3 === UTC ? locale4.utcFormat("%A, %d %B %Y, %X UTC") : labelFormat(locale4, scale7, 5, null, specifier, formatType, true);
  }
  function domainCaption(locale4, scale7, opt) {
    opt = opt || {};
    const max4 = Math.max(3, opt.maxlen || 7), fmt = format3(locale4, scale7, opt.format, opt.formatType);
    if (isDiscretizing(scale7.type)) {
      const v3 = labelValues(scale7).slice(1).map(fmt), n2 = v3.length;
      return `${n2} boundar${n2 === 1 ? "y" : "ies"}: ${v3.join(", ")}`;
    } else if (isDiscrete(scale7.type)) {
      const d2 = scale7.domain(), n2 = d2.length, v3 = n2 > max4 ? d2.slice(0, max4 - 2).map(fmt).join(", ") + ", ending with " + d2.slice(-1).map(fmt) : d2.map(fmt).join(", ");
      return `${n2} value${n2 === 1 ? "" : "s"}: ${v3}`;
    } else {
      const d2 = scale7.domain();
      return `values from ${fmt(d2[0])} to ${fmt(peek(d2))}`;
    }
  }

  // node_modules/vega-scenegraph/build/vega-scenegraph.module.js
  var gradient_id = 0;
  function resetSVGGradientId() {
    gradient_id = 0;
  }
  var patternPrefix = "p_";
  function isGradient(value3) {
    return value3 && value3.gradient;
  }
  function gradientRef(g2, defs, base) {
    const type3 = g2.gradient;
    let id2 = g2.id, prefix = type3 === "radial" ? patternPrefix : "";
    if (!id2) {
      id2 = g2.id = "gradient_" + gradient_id++;
      if (type3 === "radial") {
        g2.x1 = get3(g2.x1, 0.5);
        g2.y1 = get3(g2.y1, 0.5);
        g2.r1 = get3(g2.r1, 0);
        g2.x2 = get3(g2.x2, 0.5);
        g2.y2 = get3(g2.y2, 0.5);
        g2.r2 = get3(g2.r2, 0.5);
        prefix = patternPrefix;
      } else {
        g2.x1 = get3(g2.x1, 0);
        g2.y1 = get3(g2.y1, 0);
        g2.x2 = get3(g2.x2, 1);
        g2.y2 = get3(g2.y2, 0);
      }
    }
    defs[id2] = g2;
    return "url(" + (base || "") + "#" + prefix + id2 + ")";
  }
  function get3(val, def2) {
    return val != null ? val : def2;
  }
  function Gradient(p02, p1) {
    var stops = [], gradient4;
    return gradient4 = {
      gradient: "linear",
      x1: p02 ? p02[0] : 0,
      y1: p02 ? p02[1] : 0,
      x2: p1 ? p1[0] : 1,
      y2: p1 ? p1[1] : 0,
      stops,
      stop: function(offset4, color5) {
        stops.push({
          offset: offset4,
          color: color5
        });
        return gradient4;
      }
    };
  }
  var lookup = {
    "basis": {
      curve: basis_default
    },
    "basis-closed": {
      curve: basisClosed_default
    },
    "basis-open": {
      curve: basisOpen_default
    },
    "bundle": {
      curve: bundle_default,
      tension: "beta",
      value: 0.85
    },
    "cardinal": {
      curve: cardinal_default,
      tension: "tension",
      value: 0
    },
    "cardinal-open": {
      curve: cardinalOpen_default,
      tension: "tension",
      value: 0
    },
    "cardinal-closed": {
      curve: cardinalClosed_default,
      tension: "tension",
      value: 0
    },
    "catmull-rom": {
      curve: catmullRom_default,
      tension: "alpha",
      value: 0.5
    },
    "catmull-rom-closed": {
      curve: catmullRomClosed_default,
      tension: "alpha",
      value: 0.5
    },
    "catmull-rom-open": {
      curve: catmullRomOpen_default,
      tension: "alpha",
      value: 0.5
    },
    "linear": {
      curve: linear_default
    },
    "linear-closed": {
      curve: linearClosed_default
    },
    "monotone": {
      horizontal: monotoneY,
      vertical: monotoneX
    },
    "natural": {
      curve: natural_default
    },
    "step": {
      curve: step_default
    },
    "step-after": {
      curve: stepAfter
    },
    "step-before": {
      curve: stepBefore
    }
  };
  function curves(type3, orientation, tension) {
    var entry2 = has(lookup, type3) && lookup[type3], curve2 = null;
    if (entry2) {
      curve2 = entry2.curve || entry2[orientation || "vertical"];
      if (entry2.tension && tension != null) {
        curve2 = curve2[entry2.tension](tension);
      }
    }
    return curve2;
  }
  var paramCounts = {
    m: 2,
    l: 2,
    h: 1,
    v: 1,
    z: 0,
    c: 6,
    s: 4,
    q: 4,
    t: 2,
    a: 7
  };
  var commandPattern = /[mlhvzcsqta]([^mlhvzcsqta]+|$)/gi;
  var numberPattern = /^[+-]?(([0-9]*\.[0-9]+)|([0-9]+\.)|([0-9]+))([eE][+-]?[0-9]+)?/;
  var spacePattern = /^((\s+,?\s*)|(,\s*))/;
  var flagPattern = /^[01]/;
  function parse4(path3) {
    const commands = [];
    const matches = path3.match(commandPattern) || [];
    matches.forEach((str) => {
      let cmd = str[0];
      const type3 = cmd.toLowerCase();
      const paramCount = paramCounts[type3];
      const params2 = parseParams(type3, paramCount, str.slice(1).trim());
      const count2 = params2.length;
      if (count2 < paramCount || count2 && count2 % paramCount !== 0) {
        throw Error("Invalid SVG path, incorrect parameter count");
      }
      commands.push([cmd, ...params2.slice(0, paramCount)]);
      if (count2 === paramCount) {
        return;
      }
      if (type3 === "m") {
        cmd = cmd === "M" ? "L" : "l";
      }
      for (let i2 = paramCount; i2 < count2; i2 += paramCount) {
        commands.push([cmd, ...params2.slice(i2, i2 + paramCount)]);
      }
    });
    return commands;
  }
  function parseParams(type3, paramCount, segment) {
    const params2 = [];
    for (let index4 = 0; paramCount && index4 < segment.length; ) {
      for (let i2 = 0; i2 < paramCount; ++i2) {
        const pattern = type3 === "a" && (i2 === 3 || i2 === 4) ? flagPattern : numberPattern;
        const match3 = segment.slice(index4).match(pattern);
        if (match3 === null) {
          throw Error("Invalid SVG path, incorrect parameter type");
        }
        index4 += match3[0].length;
        params2.push(+match3[0]);
        const ws = segment.slice(index4).match(spacePattern);
        if (ws !== null) {
          index4 += ws[0].length;
        }
      }
    }
    return params2;
  }
  var DegToRad = Math.PI / 180;
  var Epsilon = 1e-14;
  var HalfPi = Math.PI / 2;
  var Tau = Math.PI * 2;
  var HalfSqrt3 = Math.sqrt(3) / 2;
  var segmentCache = {};
  var bezierCache = {};
  var join = [].join;
  function segments(x5, y5, rx, ry, large, sweep, rotateX, ox, oy) {
    const key2 = join.call(arguments);
    if (segmentCache[key2]) {
      return segmentCache[key2];
    }
    const th = rotateX * DegToRad;
    const sin_th = Math.sin(th);
    const cos_th = Math.cos(th);
    rx = Math.abs(rx);
    ry = Math.abs(ry);
    const px2 = cos_th * (ox - x5) * 0.5 + sin_th * (oy - y5) * 0.5;
    const py2 = cos_th * (oy - y5) * 0.5 - sin_th * (ox - x5) * 0.5;
    let pl = px2 * px2 / (rx * rx) + py2 * py2 / (ry * ry);
    if (pl > 1) {
      pl = Math.sqrt(pl);
      rx *= pl;
      ry *= pl;
    }
    const a00 = cos_th / rx;
    const a01 = sin_th / rx;
    const a10 = -sin_th / ry;
    const a11 = cos_th / ry;
    const x06 = a00 * ox + a01 * oy;
    const y06 = a10 * ox + a11 * oy;
    const x12 = a00 * x5 + a01 * y5;
    const y12 = a10 * x5 + a11 * y5;
    const d2 = (x12 - x06) * (x12 - x06) + (y12 - y06) * (y12 - y06);
    let sfactor_sq = 1 / d2 - 0.25;
    if (sfactor_sq < 0) sfactor_sq = 0;
    let sfactor = Math.sqrt(sfactor_sq);
    if (sweep == large) sfactor = -sfactor;
    const xc = 0.5 * (x06 + x12) - sfactor * (y12 - y06);
    const yc = 0.5 * (y06 + y12) + sfactor * (x12 - x06);
    const th0 = Math.atan2(y06 - yc, x06 - xc);
    const th1 = Math.atan2(y12 - yc, x12 - xc);
    let th_arc = th1 - th0;
    if (th_arc < 0 && sweep === 1) {
      th_arc += Tau;
    } else if (th_arc > 0 && sweep === 0) {
      th_arc -= Tau;
    }
    const segs = Math.ceil(Math.abs(th_arc / (HalfPi + 1e-3)));
    const result = [];
    for (let i2 = 0; i2 < segs; ++i2) {
      const th2 = th0 + i2 * th_arc / segs;
      const th3 = th0 + (i2 + 1) * th_arc / segs;
      result[i2] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th];
    }
    return segmentCache[key2] = result;
  }
  function bezier(params2) {
    const key2 = join.call(params2);
    if (bezierCache[key2]) {
      return bezierCache[key2];
    }
    var cx = params2[0], cy = params2[1], th0 = params2[2], th1 = params2[3], rx = params2[4], ry = params2[5], sin_th = params2[6], cos_th = params2[7];
    const a00 = cos_th * rx;
    const a01 = -sin_th * ry;
    const a10 = sin_th * rx;
    const a11 = cos_th * ry;
    const cos_th0 = Math.cos(th0);
    const sin_th0 = Math.sin(th0);
    const cos_th1 = Math.cos(th1);
    const sin_th1 = Math.sin(th1);
    const th_half = 0.5 * (th1 - th0);
    const sin_th_h2 = Math.sin(th_half * 0.5);
    const t4 = 8 / 3 * sin_th_h2 * sin_th_h2 / Math.sin(th_half);
    const x12 = cx + cos_th0 - t4 * sin_th0;
    const y12 = cy + sin_th0 + t4 * cos_th0;
    const x32 = cx + cos_th1;
    const y32 = cy + sin_th1;
    const x22 = x32 + t4 * sin_th1;
    const y22 = y32 - t4 * cos_th1;
    return bezierCache[key2] = [a00 * x12 + a01 * y12, a10 * x12 + a11 * y12, a00 * x22 + a01 * y22, a10 * x22 + a11 * y22, a00 * x32 + a01 * y32, a10 * x32 + a11 * y32];
  }
  var temp = ["l", 0, 0, 0, 0, 0, 0, 0];
  function scale$1(current2, sX, sY) {
    const c4 = temp[0] = current2[0];
    if (c4 === "a" || c4 === "A") {
      temp[1] = sX * current2[1];
      temp[2] = sY * current2[2];
      temp[3] = current2[3];
      temp[4] = current2[4];
      temp[5] = current2[5];
      temp[6] = sX * current2[6];
      temp[7] = sY * current2[7];
    } else if (c4 === "h" || c4 === "H") {
      temp[1] = sX * current2[1];
    } else if (c4 === "v" || c4 === "V") {
      temp[1] = sY * current2[1];
    } else {
      for (var i2 = 1, n2 = current2.length; i2 < n2; ++i2) {
        temp[i2] = (i2 % 2 == 1 ? sX : sY) * current2[i2];
      }
    }
    return temp;
  }
  function pathRender(context3, path3, l2, t4, sX, sY) {
    var current2, previous = null, x5 = 0, y5 = 0, controlX = 0, controlY = 0, tempX, tempY, tempControlX, tempControlY, anchorX = 0, anchorY = 0;
    if (l2 == null) l2 = 0;
    if (t4 == null) t4 = 0;
    if (sX == null) sX = 1;
    if (sY == null) sY = sX;
    if (context3.beginPath) context3.beginPath();
    for (var i2 = 0, len = path3.length; i2 < len; ++i2) {
      current2 = path3[i2];
      if (sX !== 1 || sY !== 1) {
        current2 = scale$1(current2, sX, sY);
      }
      switch (current2[0]) {
        // first letter
        case "l":
          x5 += current2[1];
          y5 += current2[2];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "L":
          x5 = current2[1];
          y5 = current2[2];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "h":
          x5 += current2[1];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "H":
          x5 = current2[1];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "v":
          y5 += current2[1];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "V":
          y5 = current2[1];
          context3.lineTo(x5 + l2, y5 + t4);
          break;
        case "m":
          x5 += current2[1];
          y5 += current2[2];
          anchorX = x5;
          anchorY = y5;
          context3.moveTo(x5 + l2, y5 + t4);
          break;
        case "M":
          x5 = current2[1];
          y5 = current2[2];
          anchorX = x5;
          anchorY = y5;
          context3.moveTo(x5 + l2, y5 + t4);
          break;
        case "c":
          tempX = x5 + current2[5];
          tempY = y5 + current2[6];
          controlX = x5 + current2[3];
          controlY = y5 + current2[4];
          context3.bezierCurveTo(
            x5 + current2[1] + l2,
            // x1
            y5 + current2[2] + t4,
            // y1
            controlX + l2,
            // x2
            controlY + t4,
            // y2
            tempX + l2,
            tempY + t4
          );
          x5 = tempX;
          y5 = tempY;
          break;
        case "C":
          x5 = current2[5];
          y5 = current2[6];
          controlX = current2[3];
          controlY = current2[4];
          context3.bezierCurveTo(current2[1] + l2, current2[2] + t4, controlX + l2, controlY + t4, x5 + l2, y5 + t4);
          break;
        case "s":
          tempX = x5 + current2[3];
          tempY = y5 + current2[4];
          controlX = 2 * x5 - controlX;
          controlY = 2 * y5 - controlY;
          context3.bezierCurveTo(controlX + l2, controlY + t4, x5 + current2[1] + l2, y5 + current2[2] + t4, tempX + l2, tempY + t4);
          controlX = x5 + current2[1];
          controlY = y5 + current2[2];
          x5 = tempX;
          y5 = tempY;
          break;
        case "S":
          tempX = current2[3];
          tempY = current2[4];
          controlX = 2 * x5 - controlX;
          controlY = 2 * y5 - controlY;
          context3.bezierCurveTo(controlX + l2, controlY + t4, current2[1] + l2, current2[2] + t4, tempX + l2, tempY + t4);
          x5 = tempX;
          y5 = tempY;
          controlX = current2[1];
          controlY = current2[2];
          break;
        case "q":
          tempX = x5 + current2[3];
          tempY = y5 + current2[4];
          controlX = x5 + current2[1];
          controlY = y5 + current2[2];
          context3.quadraticCurveTo(controlX + l2, controlY + t4, tempX + l2, tempY + t4);
          x5 = tempX;
          y5 = tempY;
          break;
        case "Q":
          tempX = current2[3];
          tempY = current2[4];
          context3.quadraticCurveTo(current2[1] + l2, current2[2] + t4, tempX + l2, tempY + t4);
          x5 = tempX;
          y5 = tempY;
          controlX = current2[1];
          controlY = current2[2];
          break;
        case "t":
          tempX = x5 + current2[1];
          tempY = y5 + current2[2];
          if (previous[0].match(/[QqTt]/) === null) {
            controlX = x5;
            controlY = y5;
          } else if (previous[0] === "t") {
            controlX = 2 * x5 - tempControlX;
            controlY = 2 * y5 - tempControlY;
          } else if (previous[0] === "q") {
            controlX = 2 * x5 - controlX;
            controlY = 2 * y5 - controlY;
          }
          tempControlX = controlX;
          tempControlY = controlY;
          context3.quadraticCurveTo(controlX + l2, controlY + t4, tempX + l2, tempY + t4);
          x5 = tempX;
          y5 = tempY;
          controlX = x5 + current2[1];
          controlY = y5 + current2[2];
          break;
        case "T":
          tempX = current2[1];
          tempY = current2[2];
          controlX = 2 * x5 - controlX;
          controlY = 2 * y5 - controlY;
          context3.quadraticCurveTo(controlX + l2, controlY + t4, tempX + l2, tempY + t4);
          x5 = tempX;
          y5 = tempY;
          break;
        case "a":
          drawArc(context3, x5 + l2, y5 + t4, [current2[1], current2[2], current2[3], current2[4], current2[5], current2[6] + x5 + l2, current2[7] + y5 + t4]);
          x5 += current2[6];
          y5 += current2[7];
          break;
        case "A":
          drawArc(context3, x5 + l2, y5 + t4, [current2[1], current2[2], current2[3], current2[4], current2[5], current2[6] + l2, current2[7] + t4]);
          x5 = current2[6];
          y5 = current2[7];
          break;
        case "z":
        case "Z":
          x5 = anchorX;
          y5 = anchorY;
          context3.closePath();
          break;
      }
      previous = current2;
    }
  }
  function drawArc(context3, x5, y5, coords) {
    const seg = segments(
      coords[5],
      // end x
      coords[6],
      // end y
      coords[0],
      // radius x
      coords[1],
      // radius y
      coords[3],
      // large flag
      coords[4],
      // sweep flag
      coords[2],
      // rotation
      x5,
      y5
    );
    for (let i2 = 0; i2 < seg.length; ++i2) {
      const bez = bezier(seg[i2]);
      context3.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]);
    }
  }
  var Tan30 = 0.5773502691896257;
  var builtins = {
    "circle": {
      draw: function(context3, size) {
        const r2 = Math.sqrt(size) / 2;
        context3.moveTo(r2, 0);
        context3.arc(0, 0, r2, 0, Tau);
      }
    },
    "cross": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, s2 = r2 / 2.5;
        context3.moveTo(-r2, -s2);
        context3.lineTo(-r2, s2);
        context3.lineTo(-s2, s2);
        context3.lineTo(-s2, r2);
        context3.lineTo(s2, r2);
        context3.lineTo(s2, s2);
        context3.lineTo(r2, s2);
        context3.lineTo(r2, -s2);
        context3.lineTo(s2, -s2);
        context3.lineTo(s2, -r2);
        context3.lineTo(-s2, -r2);
        context3.lineTo(-s2, -s2);
        context3.closePath();
      }
    },
    "diamond": {
      draw: function(context3, size) {
        const r2 = Math.sqrt(size) / 2;
        context3.moveTo(-r2, 0);
        context3.lineTo(0, -r2);
        context3.lineTo(r2, 0);
        context3.lineTo(0, r2);
        context3.closePath();
      }
    },
    "square": {
      draw: function(context3, size) {
        var w3 = Math.sqrt(size), x5 = -w3 / 2;
        context3.rect(x5, x5, w3, w3);
      }
    },
    "arrow": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, s2 = r2 / 7, t4 = r2 / 2.5, v3 = r2 / 8;
        context3.moveTo(-s2, r2);
        context3.lineTo(s2, r2);
        context3.lineTo(s2, -v3);
        context3.lineTo(t4, -v3);
        context3.lineTo(0, -r2);
        context3.lineTo(-t4, -v3);
        context3.lineTo(-s2, -v3);
        context3.closePath();
      }
    },
    "wedge": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2, o2 = h3 - r2 * Tan30, b3 = r2 / 4;
        context3.moveTo(0, -h3 - o2);
        context3.lineTo(-b3, h3 - o2);
        context3.lineTo(b3, h3 - o2);
        context3.closePath();
      }
    },
    "triangle": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2, o2 = h3 - r2 * Tan30;
        context3.moveTo(0, -h3 - o2);
        context3.lineTo(-r2, h3 - o2);
        context3.lineTo(r2, h3 - o2);
        context3.closePath();
      }
    },
    "triangle-up": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2;
        context3.moveTo(0, -h3);
        context3.lineTo(-r2, h3);
        context3.lineTo(r2, h3);
        context3.closePath();
      }
    },
    "triangle-down": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2;
        context3.moveTo(0, h3);
        context3.lineTo(-r2, -h3);
        context3.lineTo(r2, -h3);
        context3.closePath();
      }
    },
    "triangle-right": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2;
        context3.moveTo(h3, 0);
        context3.lineTo(-h3, -r2);
        context3.lineTo(-h3, r2);
        context3.closePath();
      }
    },
    "triangle-left": {
      draw: function(context3, size) {
        var r2 = Math.sqrt(size) / 2, h3 = HalfSqrt3 * r2;
        context3.moveTo(-h3, 0);
        context3.lineTo(h3, -r2);
        context3.lineTo(h3, r2);
        context3.closePath();
      }
    },
    "stroke": {
      draw: function(context3, size) {
        const r2 = Math.sqrt(size) / 2;
        context3.moveTo(-r2, 0);
        context3.lineTo(r2, 0);
      }
    }
  };
  function symbols2(_) {
    return has(builtins, _) ? builtins[_] : customSymbol(_);
  }
  var custom8 = {};
  function customSymbol(path3) {
    if (!has(custom8, path3)) {
      const parsed = parse4(path3);
      custom8[path3] = {
        draw: function(context3, size) {
          pathRender(context3, parsed, 0, 0, Math.sqrt(size) / 2);
        }
      };
    }
    return custom8[path3];
  }
  var C2 = 0.448084975506;
  function rectangleX(d2) {
    return d2.x;
  }
  function rectangleY(d2) {
    return d2.y;
  }
  function rectangleWidth(d2) {
    return d2.width;
  }
  function rectangleHeight(d2) {
    return d2.height;
  }
  function number4(_) {
    return typeof _ === "function" ? _ : () => +_;
  }
  function clamp(value3, min4, max4) {
    return Math.max(min4, Math.min(value3, max4));
  }
  function vg_rect() {
    var x5 = rectangleX, y5 = rectangleY, width2 = rectangleWidth, height2 = rectangleHeight, crTL = number4(0), crTR = crTL, crBL = crTL, crBR = crTL, context3 = null;
    function rectangle2(_, x06, y06) {
      var buffer, x12 = x06 != null ? x06 : +x5.call(this, _), y12 = y06 != null ? y06 : +y5.call(this, _), w3 = +width2.call(this, _), h3 = +height2.call(this, _), s2 = Math.min(w3, h3) / 2, tl2 = clamp(+crTL.call(this, _), 0, s2), tr2 = clamp(+crTR.call(this, _), 0, s2), bl2 = clamp(+crBL.call(this, _), 0, s2), br2 = clamp(+crBR.call(this, _), 0, s2);
      if (!context3) context3 = buffer = path();
      if (tl2 <= 0 && tr2 <= 0 && bl2 <= 0 && br2 <= 0) {
        context3.rect(x12, y12, w3, h3);
      } else {
        var x22 = x12 + w3, y22 = y12 + h3;
        context3.moveTo(x12 + tl2, y12);
        context3.lineTo(x22 - tr2, y12);
        context3.bezierCurveTo(x22 - C2 * tr2, y12, x22, y12 + C2 * tr2, x22, y12 + tr2);
        context3.lineTo(x22, y22 - br2);
        context3.bezierCurveTo(x22, y22 - C2 * br2, x22 - C2 * br2, y22, x22 - br2, y22);
        context3.lineTo(x12 + bl2, y22);
        context3.bezierCurveTo(x12 + C2 * bl2, y22, x12, y22 - C2 * bl2, x12, y22 - bl2);
        context3.lineTo(x12, y12 + tl2);
        context3.bezierCurveTo(x12, y12 + C2 * tl2, x12 + C2 * tl2, y12, x12 + tl2, y12);
        context3.closePath();
      }
      if (buffer) {
        context3 = null;
        return buffer + "" || null;
      }
    }
    rectangle2.x = function(_) {
      if (arguments.length) {
        x5 = number4(_);
        return rectangle2;
      } else {
        return x5;
      }
    };
    rectangle2.y = function(_) {
      if (arguments.length) {
        y5 = number4(_);
        return rectangle2;
      } else {
        return y5;
      }
    };
    rectangle2.width = function(_) {
      if (arguments.length) {
        width2 = number4(_);
        return rectangle2;
      } else {
        return width2;
      }
    };
    rectangle2.height = function(_) {
      if (arguments.length) {
        height2 = number4(_);
        return rectangle2;
      } else {
        return height2;
      }
    };
    rectangle2.cornerRadius = function(tl2, tr2, br2, bl2) {
      if (arguments.length) {
        crTL = number4(tl2);
        crTR = tr2 != null ? number4(tr2) : crTL;
        crBR = br2 != null ? number4(br2) : crTL;
        crBL = bl2 != null ? number4(bl2) : crTR;
        return rectangle2;
      } else {
        return crTL;
      }
    };
    rectangle2.context = function(_) {
      if (arguments.length) {
        context3 = _ == null ? null : _;
        return rectangle2;
      } else {
        return context3;
      }
    };
    return rectangle2;
  }
  function vg_trail() {
    var x5, y5, size, defined2, context3 = null, ready, x12, y12, r1;
    function point9(x22, y22, w22) {
      const r2 = w22 / 2;
      if (ready) {
        var ux = y12 - y22, uy = x22 - x12;
        if (ux || uy) {
          var ud = Math.hypot(ux, uy), rx = (ux /= ud) * r1, ry = (uy /= ud) * r1, t4 = Math.atan2(uy, ux);
          context3.moveTo(x12 - rx, y12 - ry);
          context3.lineTo(x22 - ux * r2, y22 - uy * r2);
          context3.arc(x22, y22, r2, t4 - Math.PI, t4);
          context3.lineTo(x12 + rx, y12 + ry);
          context3.arc(x12, y12, r1, t4, t4 + Math.PI);
        } else {
          context3.arc(x22, y22, r2, 0, Tau);
        }
        context3.closePath();
      } else {
        ready = 1;
      }
      x12 = x22;
      y12 = y22;
      r1 = r2;
    }
    function trail3(data3) {
      var i2, n2 = data3.length, d2, defined0 = false, buffer;
      if (context3 == null) context3 = buffer = path();
      for (i2 = 0; i2 <= n2; ++i2) {
        if (!(i2 < n2 && defined2(d2 = data3[i2], i2, data3)) === defined0) {
          if (defined0 = !defined0) ready = 0;
        }
        if (defined0) point9(+x5(d2, i2, data3), +y5(d2, i2, data3), +size(d2, i2, data3));
      }
      if (buffer) {
        context3 = null;
        return buffer + "" || null;
      }
    }
    trail3.x = function(_) {
      if (arguments.length) {
        x5 = _;
        return trail3;
      } else {
        return x5;
      }
    };
    trail3.y = function(_) {
      if (arguments.length) {
        y5 = _;
        return trail3;
      } else {
        return y5;
      }
    };
    trail3.size = function(_) {
      if (arguments.length) {
        size = _;
        return trail3;
      } else {
        return size;
      }
    };
    trail3.defined = function(_) {
      if (arguments.length) {
        defined2 = _;
        return trail3;
      } else {
        return defined2;
      }
    };
    trail3.context = function(_) {
      if (arguments.length) {
        if (_ == null) {
          context3 = null;
        } else {
          context3 = _;
        }
        return trail3;
      } else {
        return context3;
      }
    };
    return trail3;
  }
  function value$1(a4, b3) {
    return a4 != null ? a4 : b3;
  }
  var x2 = (item) => item.x || 0;
  var y2 = (item) => item.y || 0;
  var w = (item) => item.width || 0;
  var h = (item) => item.height || 0;
  var xw = (item) => (item.x || 0) + (item.width || 0);
  var yh = (item) => (item.y || 0) + (item.height || 0);
  var sa = (item) => item.startAngle || 0;
  var ea = (item) => item.endAngle || 0;
  var pa = (item) => item.padAngle || 0;
  var ir = (item) => item.innerRadius || 0;
  var or = (item) => item.outerRadius || 0;
  var cr = (item) => item.cornerRadius || 0;
  var tl = (item) => value$1(item.cornerRadiusTopLeft, item.cornerRadius) || 0;
  var tr = (item) => value$1(item.cornerRadiusTopRight, item.cornerRadius) || 0;
  var br = (item) => value$1(item.cornerRadiusBottomRight, item.cornerRadius) || 0;
  var bl = (item) => value$1(item.cornerRadiusBottomLeft, item.cornerRadius) || 0;
  var sz = (item) => value$1(item.size, 64);
  var ts = (item) => item.size || 1;
  var def = (item) => !(item.defined === false);
  var type = (item) => symbols2(item.shape || "circle");
  var arcShape = arc_default().startAngle(sa).endAngle(ea).padAngle(pa).innerRadius(ir).outerRadius(or).cornerRadius(cr);
  var areavShape = area_default().x(x2).y1(y2).y0(yh).defined(def);
  var areahShape = area_default().y(y2).x1(x2).x0(xw).defined(def);
  var lineShape = line_default().x(x2).y(y2).defined(def);
  var rectShape = vg_rect().x(x2).y(y2).width(w).height(h).cornerRadius(tl, tr, br, bl);
  var symbolShape = Symbol2().type(type).size(sz);
  var trailShape = vg_trail().x(x2).y(y2).defined(def).size(ts);
  function hasCornerRadius(item) {
    return item.cornerRadius || item.cornerRadiusTopLeft || item.cornerRadiusTopRight || item.cornerRadiusBottomRight || item.cornerRadiusBottomLeft;
  }
  function arc$1(context3, item) {
    return arcShape.context(context3)(item);
  }
  function area$1(context3, items) {
    const item = items[0], interp = item.interpolate || "linear";
    return (item.orient === "horizontal" ? areahShape : areavShape).curve(curves(interp, item.orient, item.tension)).context(context3)(items);
  }
  function line$1(context3, items) {
    const item = items[0], interp = item.interpolate || "linear";
    return lineShape.curve(curves(interp, item.orient, item.tension)).context(context3)(items);
  }
  function rectangle(context3, item, x5, y5) {
    return rectShape.context(context3)(item, x5, y5);
  }
  function shape$1(context3, item) {
    return (item.mark.shape || item.shape).context(context3)(item);
  }
  function symbol$1(context3, item) {
    return symbolShape.context(context3)(item);
  }
  function trail$1(context3, items) {
    return trailShape.context(context3)(items);
  }
  var clip_id = 1;
  function resetSVGClipId() {
    clip_id = 1;
  }
  function clip$1(renderer, item, size) {
    var clip3 = item.clip, defs = renderer._defs, id2 = item.clip_id || (item.clip_id = "clip" + clip_id++), c4 = defs.clipping[id2] || (defs.clipping[id2] = {
      id: id2
    });
    if (isFunction(clip3)) {
      c4.path = clip3(null);
    } else if (hasCornerRadius(size)) {
      c4.path = rectangle(null, size, 0, 0);
    } else {
      c4.width = size.width || 0;
      c4.height = size.height || 0;
    }
    return "url(#" + id2 + ")";
  }
  function Bounds(b3) {
    this.clear();
    if (b3) this.union(b3);
  }
  Bounds.prototype = {
    clone() {
      return new Bounds(this);
    },
    clear() {
      this.x1 = +Number.MAX_VALUE;
      this.y1 = +Number.MAX_VALUE;
      this.x2 = -Number.MAX_VALUE;
      this.y2 = -Number.MAX_VALUE;
      return this;
    },
    empty() {
      return this.x1 === +Number.MAX_VALUE && this.y1 === +Number.MAX_VALUE && this.x2 === -Number.MAX_VALUE && this.y2 === -Number.MAX_VALUE;
    },
    equals(b3) {
      return this.x1 === b3.x1 && this.y1 === b3.y1 && this.x2 === b3.x2 && this.y2 === b3.y2;
    },
    set(x12, y12, x22, y22) {
      if (x22 < x12) {
        this.x2 = x12;
        this.x1 = x22;
      } else {
        this.x1 = x12;
        this.x2 = x22;
      }
      if (y22 < y12) {
        this.y2 = y12;
        this.y1 = y22;
      } else {
        this.y1 = y12;
        this.y2 = y22;
      }
      return this;
    },
    add(x5, y5) {
      if (x5 < this.x1) this.x1 = x5;
      if (y5 < this.y1) this.y1 = y5;
      if (x5 > this.x2) this.x2 = x5;
      if (y5 > this.y2) this.y2 = y5;
      return this;
    },
    expand(d2) {
      this.x1 -= d2;
      this.y1 -= d2;
      this.x2 += d2;
      this.y2 += d2;
      return this;
    },
    round() {
      this.x1 = Math.floor(this.x1);
      this.y1 = Math.floor(this.y1);
      this.x2 = Math.ceil(this.x2);
      this.y2 = Math.ceil(this.y2);
      return this;
    },
    scale(s2) {
      this.x1 *= s2;
      this.y1 *= s2;
      this.x2 *= s2;
      this.y2 *= s2;
      return this;
    },
    translate(dx, dy) {
      this.x1 += dx;
      this.x2 += dx;
      this.y1 += dy;
      this.y2 += dy;
      return this;
    },
    rotate(angle2, x5, y5) {
      const p2 = this.rotatedPoints(angle2, x5, y5);
      return this.clear().add(p2[0], p2[1]).add(p2[2], p2[3]).add(p2[4], p2[5]).add(p2[6], p2[7]);
    },
    rotatedPoints(angle2, x5, y5) {
      var {
        x1: x12,
        y1: y12,
        x2: x22,
        y2: y22
      } = this, cos4 = Math.cos(angle2), sin4 = Math.sin(angle2), cx = x5 - x5 * cos4 + y5 * sin4, cy = y5 - x5 * sin4 - y5 * cos4;
      return [cos4 * x12 - sin4 * y12 + cx, sin4 * x12 + cos4 * y12 + cy, cos4 * x12 - sin4 * y22 + cx, sin4 * x12 + cos4 * y22 + cy, cos4 * x22 - sin4 * y12 + cx, sin4 * x22 + cos4 * y12 + cy, cos4 * x22 - sin4 * y22 + cx, sin4 * x22 + cos4 * y22 + cy];
    },
    union(b3) {
      if (b3.x1 < this.x1) this.x1 = b3.x1;
      if (b3.y1 < this.y1) this.y1 = b3.y1;
      if (b3.x2 > this.x2) this.x2 = b3.x2;
      if (b3.y2 > this.y2) this.y2 = b3.y2;
      return this;
    },
    intersect(b3) {
      if (b3.x1 > this.x1) this.x1 = b3.x1;
      if (b3.y1 > this.y1) this.y1 = b3.y1;
      if (b3.x2 < this.x2) this.x2 = b3.x2;
      if (b3.y2 < this.y2) this.y2 = b3.y2;
      return this;
    },
    encloses(b3) {
      return b3 && this.x1 <= b3.x1 && this.x2 >= b3.x2 && this.y1 <= b3.y1 && this.y2 >= b3.y2;
    },
    alignsWith(b3) {
      return b3 && (this.x1 == b3.x1 || this.x2 == b3.x2 || this.y1 == b3.y1 || this.y2 == b3.y2);
    },
    intersects(b3) {
      return b3 && !(this.x2 < b3.x1 || this.x1 > b3.x2 || this.y2 < b3.y1 || this.y1 > b3.y2);
    },
    contains(x5, y5) {
      return !(x5 < this.x1 || x5 > this.x2 || y5 < this.y1 || y5 > this.y2);
    },
    width() {
      return this.x2 - this.x1;
    },
    height() {
      return this.y2 - this.y1;
    }
  };
  function Item(mark) {
    this.mark = mark;
    this.bounds = this.bounds || new Bounds();
  }
  function GroupItem(mark) {
    Item.call(this, mark);
    this.items = this.items || [];
  }
  inherits(GroupItem, Item);
  var ResourceLoader = class {
    constructor(customLoader) {
      this._pending = 0;
      this._loader = customLoader || loader();
    }
    pending() {
      return this._pending;
    }
    sanitizeURL(uri) {
      const loader2 = this;
      increment(loader2);
      return loader2._loader.sanitize(uri, {
        context: "href"
      }).then((opt) => {
        decrement(loader2);
        return opt;
      }).catch(() => {
        decrement(loader2);
        return null;
      });
    }
    loadImage(uri) {
      const loader2 = this, Image2 = domImage();
      increment(loader2);
      return loader2._loader.sanitize(uri, {
        context: "image"
      }).then((opt) => {
        const url = opt.href;
        if (!url || !Image2) throw {
          url
        };
        const img = new Image2();
        const cors = has(opt, "crossOrigin") ? opt.crossOrigin : "anonymous";
        if (cors != null) img.crossOrigin = cors;
        img.onload = () => decrement(loader2);
        img.onerror = () => decrement(loader2);
        img.src = url;
        return img;
      }).catch((e4) => {
        decrement(loader2);
        return {
          complete: false,
          width: 0,
          height: 0,
          src: e4 && e4.url || ""
        };
      });
    }
    ready() {
      const loader2 = this;
      return new Promise((accept) => {
        function poll(value3) {
          if (!loader2.pending()) accept(value3);
          else setTimeout(() => {
            poll(true);
          }, 10);
        }
        poll(false);
      });
    }
  };
  function increment(loader2) {
    loader2._pending += 1;
  }
  function decrement(loader2) {
    loader2._pending -= 1;
  }
  function boundStroke(bounds2, item, miter) {
    if (item.stroke && item.opacity !== 0 && item.strokeOpacity !== 0) {
      const sw = item.strokeWidth != null ? +item.strokeWidth : 1;
      bounds2.expand(sw + (miter ? miterAdjustment(item, sw) : 0));
    }
    return bounds2;
  }
  function miterAdjustment(item, strokeWidth) {
    return item.strokeJoin && item.strokeJoin !== "miter" ? 0 : strokeWidth;
  }
  var circleThreshold = Tau - 1e-8;
  var bounds;
  var lx;
  var ly;
  var rot;
  var ma;
  var mb;
  var mc;
  var md;
  var add3 = (x5, y5) => bounds.add(x5, y5);
  var addL = (x5, y5) => add3(lx = x5, ly = y5);
  var addX = (x5) => add3(x5, bounds.y1);
  var addY = (y5) => add3(bounds.x1, y5);
  var px = (x5, y5) => ma * x5 + mc * y5;
  var py = (x5, y5) => mb * x5 + md * y5;
  var addp = (x5, y5) => add3(px(x5, y5), py(x5, y5));
  var addpL = (x5, y5) => addL(px(x5, y5), py(x5, y5));
  function boundContext(_, deg) {
    bounds = _;
    if (deg) {
      rot = deg * DegToRad;
      ma = md = Math.cos(rot);
      mb = Math.sin(rot);
      mc = -mb;
    } else {
      ma = md = 1;
      rot = mb = mc = 0;
    }
    return context$1;
  }
  var context$1 = {
    beginPath() {
    },
    closePath() {
    },
    moveTo: addpL,
    lineTo: addpL,
    rect(x5, y5, w3, h3) {
      if (rot) {
        addp(x5 + w3, y5);
        addp(x5 + w3, y5 + h3);
        addp(x5, y5 + h3);
        addpL(x5, y5);
      } else {
        add3(x5 + w3, y5 + h3);
        addL(x5, y5);
      }
    },
    quadraticCurveTo(x12, y12, x22, y22) {
      const px1 = px(x12, y12), py1 = py(x12, y12), px2 = px(x22, y22), py2 = py(x22, y22);
      quadExtrema(lx, px1, px2, addX);
      quadExtrema(ly, py1, py2, addY);
      addL(px2, py2);
    },
    bezierCurveTo(x12, y12, x22, y22, x32, y32) {
      const px1 = px(x12, y12), py1 = py(x12, y12), px2 = px(x22, y22), py2 = py(x22, y22), px3 = px(x32, y32), py3 = py(x32, y32);
      cubicExtrema(lx, px1, px2, px3, addX);
      cubicExtrema(ly, py1, py2, py3, addY);
      addL(px3, py3);
    },
    arc(cx, cy, r2, sa2, ea3, ccw) {
      sa2 += rot;
      ea3 += rot;
      lx = r2 * Math.cos(ea3) + cx;
      ly = r2 * Math.sin(ea3) + cy;
      if (Math.abs(ea3 - sa2) > circleThreshold) {
        add3(cx - r2, cy - r2);
        add3(cx + r2, cy + r2);
      } else {
        const update3 = (a4) => add3(r2 * Math.cos(a4) + cx, r2 * Math.sin(a4) + cy);
        let s2, i2;
        update3(sa2);
        update3(ea3);
        if (ea3 !== sa2) {
          sa2 = sa2 % Tau;
          if (sa2 < 0) sa2 += Tau;
          ea3 = ea3 % Tau;
          if (ea3 < 0) ea3 += Tau;
          if (ea3 < sa2) {
            ccw = !ccw;
            s2 = sa2;
            sa2 = ea3;
            ea3 = s2;
          }
          if (ccw) {
            ea3 -= Tau;
            s2 = sa2 - sa2 % HalfPi;
            for (i2 = 0; i2 < 4 && s2 > ea3; ++i2, s2 -= HalfPi) update3(s2);
          } else {
            s2 = sa2 - sa2 % HalfPi + HalfPi;
            for (i2 = 0; i2 < 4 && s2 < ea3; ++i2, s2 = s2 + HalfPi) update3(s2);
          }
        }
      }
    }
  };
  function quadExtrema(x06, x12, x22, cb) {
    const t4 = (x06 - x12) / (x06 + x22 - 2 * x12);
    if (0 < t4 && t4 < 1) cb(x06 + (x12 - x06) * t4);
  }
  function cubicExtrema(x06, x12, x22, x32, cb) {
    const a4 = x32 - x06 + 3 * x12 - 3 * x22, b3 = x06 + x22 - 2 * x12, c4 = x06 - x12;
    let t04 = 0, t13 = 0, r2;
    if (Math.abs(a4) > Epsilon) {
      r2 = b3 * b3 + c4 * a4;
      if (r2 >= 0) {
        r2 = Math.sqrt(r2);
        t04 = (-b3 + r2) / a4;
        t13 = (-b3 - r2) / a4;
      }
    } else {
      t04 = 0.5 * c4 / b3;
    }
    if (0 < t04 && t04 < 1) cb(cubic(t04, x06, x12, x22, x32));
    if (0 < t13 && t13 < 1) cb(cubic(t13, x06, x12, x22, x32));
  }
  function cubic(t4, x06, x12, x22, x32) {
    const s2 = 1 - t4, s22 = s2 * s2, t22 = t4 * t4;
    return s22 * s2 * x06 + 3 * s22 * t4 * x12 + 3 * s2 * t22 * x22 + t22 * t4 * x32;
  }
  var context = (context = domCanvas(1, 1)) ? context.getContext("2d") : null;
  var b = new Bounds();
  function intersectPath(draw3) {
    return function(item, brush) {
      if (!context) return true;
      draw3(context, item);
      b.clear().union(item.bounds).intersect(brush).round();
      const {
        x1: x12,
        y1: y12,
        x2: x22,
        y2: y22
      } = b;
      for (let y5 = y12; y5 <= y22; ++y5) {
        for (let x5 = x12; x5 <= x22; ++x5) {
          if (context.isPointInPath(x5, y5)) {
            return true;
          }
        }
      }
      return false;
    };
  }
  function intersectPoint(item, box) {
    return box.contains(item.x || 0, item.y || 0);
  }
  function intersectRect(item, box) {
    const x5 = item.x || 0, y5 = item.y || 0, w3 = item.width || 0, h3 = item.height || 0;
    return box.intersects(b.set(x5, y5, x5 + w3, y5 + h3));
  }
  function intersectRule(item, box) {
    const x5 = item.x || 0, y5 = item.y || 0, x22 = item.x2 != null ? item.x2 : x5, y22 = item.y2 != null ? item.y2 : y5;
    return intersectBoxLine(box, x5, y5, x22, y22);
  }
  function intersectBoxLine(box, x5, y5, u5, v3) {
    const {
      x1: x12,
      y1: y12,
      x2: x22,
      y2: y22
    } = box, dx = u5 - x5, dy = v3 - y5;
    let t04 = 0, t13 = 1, p2, q2, r2, e4;
    for (e4 = 0; e4 < 4; ++e4) {
      if (e4 === 0) {
        p2 = -dx;
        q2 = -(x12 - x5);
      }
      if (e4 === 1) {
        p2 = dx;
        q2 = x22 - x5;
      }
      if (e4 === 2) {
        p2 = -dy;
        q2 = -(y12 - y5);
      }
      if (e4 === 3) {
        p2 = dy;
        q2 = y22 - y5;
      }
      if (Math.abs(p2) < 1e-10 && q2 < 0) return false;
      r2 = q2 / p2;
      if (p2 < 0) {
        if (r2 > t13) return false;
        else if (r2 > t04) t04 = r2;
      } else if (p2 > 0) {
        if (r2 < t04) return false;
        else if (r2 < t13) t13 = r2;
      }
    }
    return true;
  }
  function blend(context3, item) {
    context3.globalCompositeOperation = item.blend || "source-over";
  }
  function value(value3, dflt) {
    return value3 == null ? dflt : value3;
  }
  function addStops(gradient4, stops) {
    const n2 = stops.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      gradient4.addColorStop(stops[i2].offset, stops[i2].color);
    }
    return gradient4;
  }
  function gradient(context3, spec, bounds2) {
    const w3 = bounds2.width(), h3 = bounds2.height();
    let gradient4;
    if (spec.gradient === "radial") {
      gradient4 = context3.createRadialGradient(bounds2.x1 + value(spec.x1, 0.5) * w3, bounds2.y1 + value(spec.y1, 0.5) * h3, Math.max(w3, h3) * value(spec.r1, 0), bounds2.x1 + value(spec.x2, 0.5) * w3, bounds2.y1 + value(spec.y2, 0.5) * h3, Math.max(w3, h3) * value(spec.r2, 0.5));
    } else {
      const x12 = value(spec.x1, 0), y12 = value(spec.y1, 0), x22 = value(spec.x2, 1), y22 = value(spec.y2, 0);
      if (x12 === x22 || y12 === y22 || w3 === h3) {
        gradient4 = context3.createLinearGradient(bounds2.x1 + x12 * w3, bounds2.y1 + y12 * h3, bounds2.x1 + x22 * w3, bounds2.y1 + y22 * h3);
      } else {
        const image3 = domCanvas(Math.ceil(w3), Math.ceil(h3)), ictx = image3.getContext("2d");
        ictx.scale(w3, h3);
        ictx.fillStyle = addStops(ictx.createLinearGradient(x12, y12, x22, y22), spec.stops);
        ictx.fillRect(0, 0, w3, h3);
        return context3.createPattern(image3, "no-repeat");
      }
    }
    return addStops(gradient4, spec.stops);
  }
  function color2(context3, item, value3) {
    return isGradient(value3) ? gradient(context3, value3, item.bounds) : value3;
  }
  function fill(context3, item, opacity2) {
    opacity2 *= item.fillOpacity == null ? 1 : item.fillOpacity;
    if (opacity2 > 0) {
      context3.globalAlpha = opacity2;
      context3.fillStyle = color2(context3, item, item.fill);
      return true;
    } else {
      return false;
    }
  }
  var Empty2 = [];
  function stroke(context3, item, opacity2) {
    var lw = (lw = item.strokeWidth) != null ? lw : 1;
    if (lw <= 0) return false;
    opacity2 *= item.strokeOpacity == null ? 1 : item.strokeOpacity;
    if (opacity2 > 0) {
      context3.globalAlpha = opacity2;
      context3.strokeStyle = color2(context3, item, item.stroke);
      context3.lineWidth = lw;
      context3.lineCap = item.strokeCap || "butt";
      context3.lineJoin = item.strokeJoin || "miter";
      context3.miterLimit = item.strokeMiterLimit || 10;
      if (context3.setLineDash) {
        context3.setLineDash(item.strokeDash || Empty2);
        context3.lineDashOffset = item.strokeDashOffset || 0;
      }
      return true;
    } else {
      return false;
    }
  }
  function compare2(a4, b3) {
    return a4.zindex - b3.zindex || a4.index - b3.index;
  }
  function zorder(scene) {
    if (!scene.zdirty) return scene.zitems;
    var items = scene.items, output3 = [], item, i2, n2;
    for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
      item = items[i2];
      item.index = i2;
      if (item.zindex) output3.push(item);
    }
    scene.zdirty = false;
    return scene.zitems = output3.sort(compare2);
  }
  function visit(scene, visitor) {
    var items = scene.items, i2, n2;
    if (!items || !items.length) return;
    const zitems = zorder(scene);
    if (zitems && zitems.length) {
      for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
        if (!items[i2].zindex) visitor(items[i2]);
      }
      items = zitems;
    }
    for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
      visitor(items[i2]);
    }
  }
  function pickVisit(scene, visitor) {
    var items = scene.items, hit2, i2;
    if (!items || !items.length) return null;
    const zitems = zorder(scene);
    if (zitems && zitems.length) items = zitems;
    for (i2 = items.length; --i2 >= 0; ) {
      if (hit2 = visitor(items[i2])) return hit2;
    }
    if (items === zitems) {
      for (items = scene.items, i2 = items.length; --i2 >= 0; ) {
        if (!items[i2].zindex) {
          if (hit2 = visitor(items[i2])) return hit2;
        }
      }
    }
    return null;
  }
  function drawAll(path3) {
    return function(context3, scene, bounds2) {
      visit(scene, (item) => {
        if (!bounds2 || bounds2.intersects(item.bounds)) {
          drawPath(path3, context3, item, item);
        }
      });
    };
  }
  function drawOne(path3) {
    return function(context3, scene, bounds2) {
      if (scene.items.length && (!bounds2 || bounds2.intersects(scene.bounds))) {
        drawPath(path3, context3, scene.items[0], scene.items);
      }
    };
  }
  function drawPath(path3, context3, item, items) {
    var opacity2 = item.opacity == null ? 1 : item.opacity;
    if (opacity2 === 0) return;
    if (path3(context3, items)) return;
    blend(context3, item);
    if (item.fill && fill(context3, item, opacity2)) {
      context3.fill();
    }
    if (item.stroke && stroke(context3, item, opacity2)) {
      context3.stroke();
    }
  }
  function pick$1(test2) {
    test2 = test2 || truthy;
    return function(context3, scene, x5, y5, gx, gy) {
      x5 *= context3.pixelRatio;
      y5 *= context3.pixelRatio;
      return pickVisit(scene, (item) => {
        const b3 = item.bounds;
        if (b3 && !b3.contains(gx, gy) || !b3) return;
        if (test2(context3, item, x5, y5, gx, gy)) return item;
      });
    };
  }
  function hitPath(path3, filled) {
    return function(context3, o2, x5, y5) {
      var item = Array.isArray(o2) ? o2[0] : o2, fill2 = filled == null ? item.fill : filled, stroke2 = item.stroke && context3.isPointInStroke, lw, lc;
      if (stroke2) {
        lw = item.strokeWidth;
        lc = item.strokeCap;
        context3.lineWidth = lw != null ? lw : 1;
        context3.lineCap = lc != null ? lc : "butt";
      }
      return path3(context3, o2) ? false : fill2 && context3.isPointInPath(x5, y5) || stroke2 && context3.isPointInStroke(x5, y5);
    };
  }
  function pickPath(path3) {
    return pick$1(hitPath(path3));
  }
  function translate(x5, y5) {
    return "translate(" + x5 + "," + y5 + ")";
  }
  function rotate(a4) {
    return "rotate(" + a4 + ")";
  }
  function scale2(scaleX, scaleY2) {
    return "scale(" + scaleX + "," + scaleY2 + ")";
  }
  function translateItem(item) {
    return translate(item.x || 0, item.y || 0);
  }
  function rotateItem(item) {
    return translate(item.x || 0, item.y || 0) + (item.angle ? " " + rotate(item.angle) : "");
  }
  function transformItem(item) {
    return translate(item.x || 0, item.y || 0) + (item.angle ? " " + rotate(item.angle) : "") + (item.scaleX || item.scaleY ? " " + scale2(item.scaleX || 1, item.scaleY || 1) : "");
  }
  function markItemPath(type3, shape2, isect) {
    function attr2(emit2, item) {
      emit2("transform", rotateItem(item));
      emit2("d", shape2(null, item));
    }
    function bound2(bounds2, item) {
      shape2(boundContext(bounds2, item.angle), item);
      return boundStroke(bounds2, item).translate(item.x || 0, item.y || 0);
    }
    function draw3(context3, item) {
      var x5 = item.x || 0, y5 = item.y || 0, a4 = item.angle || 0;
      context3.translate(x5, y5);
      if (a4) context3.rotate(a4 *= DegToRad);
      context3.beginPath();
      shape2(context3, item);
      if (a4) context3.rotate(-a4);
      context3.translate(-x5, -y5);
    }
    return {
      type: type3,
      tag: "path",
      nested: false,
      attr: attr2,
      bound: bound2,
      draw: drawAll(draw3),
      pick: pickPath(draw3),
      isect: isect || intersectPath(draw3)
    };
  }
  var arc = markItemPath("arc", arc$1);
  function pickArea(a4, p2) {
    var v3 = a4[0].orient === "horizontal" ? p2[1] : p2[0], z = a4[0].orient === "horizontal" ? "y" : "x", i2 = a4.length, min4 = Infinity, hit2, d2;
    while (--i2 >= 0) {
      if (a4[i2].defined === false) continue;
      d2 = Math.abs(a4[i2][z] - v3);
      if (d2 < min4) {
        min4 = d2;
        hit2 = a4[i2];
      }
    }
    return hit2;
  }
  function pickLine(a4, p2) {
    var t4 = Math.pow(a4[0].strokeWidth || 1, 2), i2 = a4.length, dx, dy, dd;
    while (--i2 >= 0) {
      if (a4[i2].defined === false) continue;
      dx = a4[i2].x - p2[0];
      dy = a4[i2].y - p2[1];
      dd = dx * dx + dy * dy;
      if (dd < t4) return a4[i2];
    }
    return null;
  }
  function pickTrail(a4, p2) {
    var i2 = a4.length, dx, dy, dd;
    while (--i2 >= 0) {
      if (a4[i2].defined === false) continue;
      dx = a4[i2].x - p2[0];
      dy = a4[i2].y - p2[1];
      dd = dx * dx + dy * dy;
      dx = a4[i2].size || 1;
      if (dd < dx * dx) return a4[i2];
    }
    return null;
  }
  function markMultiItemPath(type3, shape2, tip) {
    function attr2(emit2, item) {
      var items = item.mark.items;
      if (items.length) emit2("d", shape2(null, items));
    }
    function bound2(bounds2, mark) {
      var items = mark.items;
      if (items.length === 0) {
        return bounds2;
      } else {
        shape2(boundContext(bounds2), items);
        return boundStroke(bounds2, items[0]);
      }
    }
    function draw3(context3, items) {
      context3.beginPath();
      shape2(context3, items);
    }
    const hit2 = hitPath(draw3);
    function pick3(context3, scene, x5, y5, gx, gy) {
      var items = scene.items, b3 = scene.bounds;
      if (!items || !items.length || b3 && !b3.contains(gx, gy)) {
        return null;
      }
      x5 *= context3.pixelRatio;
      y5 *= context3.pixelRatio;
      return hit2(context3, items, x5, y5) ? items[0] : null;
    }
    return {
      type: type3,
      tag: "path",
      nested: true,
      attr: attr2,
      bound: bound2,
      draw: drawOne(draw3),
      pick: pick3,
      isect: intersectPoint,
      tip
    };
  }
  var area = markMultiItemPath("area", area$1, pickArea);
  function clip(context3, scene) {
    var clip3 = scene.clip;
    context3.save();
    if (isFunction(clip3)) {
      context3.beginPath();
      clip3(context3);
      context3.clip();
    } else {
      clipGroup(context3, scene.group);
    }
  }
  function clipGroup(context3, group2) {
    context3.beginPath();
    hasCornerRadius(group2) ? rectangle(context3, group2, 0, 0) : context3.rect(0, 0, group2.width || 0, group2.height || 0);
    context3.clip();
  }
  function offset$1(item) {
    const sw = value(item.strokeWidth, 1);
    return item.strokeOffset != null ? item.strokeOffset : item.stroke && sw > 0.5 && sw < 1.5 ? 0.5 - Math.abs(sw - 1) : 0;
  }
  function attr$5(emit2, item) {
    emit2("transform", translateItem(item));
  }
  function emitRectangle(emit2, item) {
    const off = offset$1(item);
    emit2("d", rectangle(null, item, off, off));
  }
  function background(emit2, item) {
    emit2("class", "background");
    emit2("aria-hidden", true);
    emitRectangle(emit2, item);
  }
  function foreground(emit2, item) {
    emit2("class", "foreground");
    emit2("aria-hidden", true);
    if (item.strokeForeground) {
      emitRectangle(emit2, item);
    } else {
      emit2("d", "");
    }
  }
  function content(emit2, item, renderer) {
    const url = item.clip ? clip$1(renderer, item, item) : null;
    emit2("clip-path", url);
  }
  function bound$5(bounds2, group2) {
    if (!group2.clip && group2.items) {
      const items = group2.items, m4 = items.length;
      for (let j2 = 0; j2 < m4; ++j2) {
        bounds2.union(items[j2].bounds);
      }
    }
    if ((group2.clip || group2.width || group2.height) && !group2.noBound) {
      bounds2.add(0, 0).add(group2.width || 0, group2.height || 0);
    }
    boundStroke(bounds2, group2);
    return bounds2.translate(group2.x || 0, group2.y || 0);
  }
  function rectanglePath(context3, group2, x5, y5) {
    const off = offset$1(group2);
    context3.beginPath();
    rectangle(context3, group2, (x5 || 0) + off, (y5 || 0) + off);
  }
  var hitBackground = hitPath(rectanglePath);
  var hitForeground = hitPath(rectanglePath, false);
  var hitCorner = hitPath(rectanglePath, true);
  function draw$4(context3, scene, bounds2, markTypes) {
    visit(scene, (group2) => {
      const gx = group2.x || 0, gy = group2.y || 0, fore = group2.strokeForeground, opacity2 = group2.opacity == null ? 1 : group2.opacity;
      if ((group2.stroke || group2.fill) && opacity2) {
        rectanglePath(context3, group2, gx, gy);
        blend(context3, group2);
        if (group2.fill && fill(context3, group2, opacity2)) {
          context3.fill();
        }
        if (group2.stroke && !fore && stroke(context3, group2, opacity2)) {
          context3.stroke();
        }
      }
      context3.save();
      context3.translate(gx, gy);
      if (group2.clip) clipGroup(context3, group2);
      if (bounds2) bounds2.translate(-gx, -gy);
      visit(group2, (item) => {
        if (item.marktype === "group" || markTypes == null || markTypes.includes(item.marktype)) {
          this.draw(context3, item, bounds2, markTypes);
        }
      });
      if (bounds2) bounds2.translate(gx, gy);
      context3.restore();
      if (fore && group2.stroke && opacity2) {
        rectanglePath(context3, group2, gx, gy);
        blend(context3, group2);
        if (stroke(context3, group2, opacity2)) {
          context3.stroke();
        }
      }
    });
  }
  function pick(context3, scene, x5, y5, gx, gy) {
    if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) {
      return null;
    }
    const cx = x5 * context3.pixelRatio, cy = y5 * context3.pixelRatio;
    return pickVisit(scene, (group2) => {
      let hit2, dx, dy;
      const b3 = group2.bounds;
      if (b3 && !b3.contains(gx, gy)) return;
      dx = group2.x || 0;
      dy = group2.y || 0;
      const dw = dx + (group2.width || 0), dh = dy + (group2.height || 0), c4 = group2.clip;
      if (c4 && (gx < dx || gx > dw || gy < dy || gy > dh)) return;
      context3.save();
      context3.translate(dx, dy);
      dx = gx - dx;
      dy = gy - dy;
      if (c4 && hasCornerRadius(group2) && !hitCorner(context3, group2, cx, cy)) {
        context3.restore();
        return null;
      }
      const fore = group2.strokeForeground, ix = scene.interactive !== false;
      if (ix && fore && group2.stroke && hitForeground(context3, group2, cx, cy)) {
        context3.restore();
        return group2;
      }
      hit2 = pickVisit(group2, (mark) => pickMark(mark, dx, dy) ? this.pick(mark, x5, y5, dx, dy) : null);
      if (!hit2 && ix && (group2.fill || !fore && group2.stroke) && hitBackground(context3, group2, cx, cy)) {
        hit2 = group2;
      }
      context3.restore();
      return hit2 || null;
    });
  }
  function pickMark(mark, x5, y5) {
    return (mark.interactive !== false || mark.marktype === "group") && mark.bounds && mark.bounds.contains(x5, y5);
  }
  var group = {
    type: "group",
    tag: "g",
    nested: false,
    attr: attr$5,
    bound: bound$5,
    draw: draw$4,
    pick,
    isect: intersectRect,
    content,
    background,
    foreground
  };
  var metadata = {
    "xmlns": "http://www.w3.org/2000/svg",
    "xmlns:xlink": "http://www.w3.org/1999/xlink",
    "version": "1.1"
  };
  function getImage(item, renderer) {
    var image3 = item.image;
    if (!image3 || item.url && item.url !== image3.url) {
      image3 = {
        complete: false,
        width: 0,
        height: 0
      };
      renderer.loadImage(item.url).then((image4) => {
        item.image = image4;
        item.image.url = item.url;
      });
    }
    return image3;
  }
  function imageWidth(item, image3) {
    return item.width != null ? item.width : !image3 || !image3.width ? 0 : item.aspect !== false && item.height ? item.height * image3.width / image3.height : image3.width;
  }
  function imageHeight(item, image3) {
    return item.height != null ? item.height : !image3 || !image3.height ? 0 : item.aspect !== false && item.width ? item.width * image3.height / image3.width : image3.height;
  }
  function imageXOffset(align2, w3) {
    return align2 === "center" ? w3 / 2 : align2 === "right" ? w3 : 0;
  }
  function imageYOffset(baseline3, h3) {
    return baseline3 === "middle" ? h3 / 2 : baseline3 === "bottom" ? h3 : 0;
  }
  function attr$4(emit2, item, renderer) {
    const img = getImage(item, renderer), w3 = imageWidth(item, img), h3 = imageHeight(item, img), x5 = (item.x || 0) - imageXOffset(item.align, w3), y5 = (item.y || 0) - imageYOffset(item.baseline, h3), i2 = !img.src && img.toDataURL ? img.toDataURL() : img.src || "";
    emit2("href", i2, metadata["xmlns:xlink"], "xlink:href");
    emit2("transform", translate(x5, y5));
    emit2("width", w3);
    emit2("height", h3);
    emit2("preserveAspectRatio", item.aspect === false ? "none" : "xMidYMid");
  }
  function bound$4(bounds2, item) {
    const img = item.image, w3 = imageWidth(item, img), h3 = imageHeight(item, img), x5 = (item.x || 0) - imageXOffset(item.align, w3), y5 = (item.y || 0) - imageYOffset(item.baseline, h3);
    return bounds2.set(x5, y5, x5 + w3, y5 + h3);
  }
  function draw$3(context3, scene, bounds2) {
    visit(scene, (item) => {
      if (bounds2 && !bounds2.intersects(item.bounds)) return;
      const img = getImage(item, this);
      let w3 = imageWidth(item, img);
      let h3 = imageHeight(item, img);
      if (w3 === 0 || h3 === 0) return;
      let x5 = (item.x || 0) - imageXOffset(item.align, w3), y5 = (item.y || 0) - imageYOffset(item.baseline, h3), opacity2, ar0, ar1, t4;
      if (item.aspect !== false) {
        ar0 = img.width / img.height;
        ar1 = item.width / item.height;
        if (ar0 === ar0 && ar1 === ar1 && ar0 !== ar1) {
          if (ar1 < ar0) {
            t4 = w3 / ar0;
            y5 += (h3 - t4) / 2;
            h3 = t4;
          } else {
            t4 = h3 * ar0;
            x5 += (w3 - t4) / 2;
            w3 = t4;
          }
        }
      }
      if (img.complete || img.toDataURL) {
        blend(context3, item);
        context3.globalAlpha = (opacity2 = item.opacity) != null ? opacity2 : 1;
        context3.imageSmoothingEnabled = item.smooth !== false;
        context3.drawImage(img, x5, y5, w3, h3);
      }
    });
  }
  var image = {
    type: "image",
    tag: "image",
    nested: false,
    attr: attr$4,
    bound: bound$4,
    draw: draw$3,
    pick: pick$1(),
    isect: truthy,
    // bounds check is sufficient
    get: getImage,
    xOffset: imageXOffset,
    yOffset: imageYOffset
  };
  var line = markMultiItemPath("line", line$1, pickLine);
  function attr$3(emit2, item) {
    var sx = item.scaleX || 1, sy = item.scaleY || 1;
    if (sx !== 1 || sy !== 1) {
      emit2("vector-effect", "non-scaling-stroke");
    }
    emit2("transform", transformItem(item));
    emit2("d", item.path);
  }
  function path$1(context3, item) {
    var path3 = item.path;
    if (path3 == null) return true;
    var x5 = item.x || 0, y5 = item.y || 0, sx = item.scaleX || 1, sy = item.scaleY || 1, a4 = (item.angle || 0) * DegToRad, cache3 = item.pathCache;
    if (!cache3 || cache3.path !== path3) {
      (item.pathCache = cache3 = parse4(path3)).path = path3;
    }
    if (a4 && context3.rotate && context3.translate) {
      context3.translate(x5, y5);
      context3.rotate(a4);
      pathRender(context3, cache3, 0, 0, sx, sy);
      context3.rotate(-a4);
      context3.translate(-x5, -y5);
    } else {
      pathRender(context3, cache3, x5, y5, sx, sy);
    }
  }
  function bound$3(bounds2, item) {
    return path$1(boundContext(bounds2, item.angle), item) ? bounds2.set(0, 0, 0, 0) : boundStroke(bounds2, item, true);
  }
  var path$2 = {
    type: "path",
    tag: "path",
    nested: false,
    attr: attr$3,
    bound: bound$3,
    draw: drawAll(path$1),
    pick: pickPath(path$1),
    isect: intersectPath(path$1)
  };
  function attr$2(emit2, item) {
    emit2("d", rectangle(null, item));
  }
  function bound$2(bounds2, item) {
    var x5, y5;
    return boundStroke(bounds2.set(x5 = item.x || 0, y5 = item.y || 0, x5 + item.width || 0, y5 + item.height || 0), item);
  }
  function draw$2(context3, item) {
    context3.beginPath();
    rectangle(context3, item);
  }
  var rect = {
    type: "rect",
    tag: "path",
    nested: false,
    attr: attr$2,
    bound: bound$2,
    draw: drawAll(draw$2),
    pick: pickPath(draw$2),
    isect: intersectRect
  };
  function attr$1(emit2, item) {
    emit2("transform", translateItem(item));
    emit2("x2", item.x2 != null ? item.x2 - (item.x || 0) : 0);
    emit2("y2", item.y2 != null ? item.y2 - (item.y || 0) : 0);
  }
  function bound$1(bounds2, item) {
    var x12, y12;
    return boundStroke(bounds2.set(x12 = item.x || 0, y12 = item.y || 0, item.x2 != null ? item.x2 : x12, item.y2 != null ? item.y2 : y12), item);
  }
  function path2(context3, item, opacity2) {
    var x12, y12, x22, y22;
    if (item.stroke && stroke(context3, item, opacity2)) {
      x12 = item.x || 0;
      y12 = item.y || 0;
      x22 = item.x2 != null ? item.x2 : x12;
      y22 = item.y2 != null ? item.y2 : y12;
      context3.beginPath();
      context3.moveTo(x12, y12);
      context3.lineTo(x22, y22);
      return true;
    }
    return false;
  }
  function draw$1(context3, scene, bounds2) {
    visit(scene, (item) => {
      if (bounds2 && !bounds2.intersects(item.bounds)) return;
      var opacity2 = item.opacity == null ? 1 : item.opacity;
      if (opacity2 && path2(context3, item, opacity2)) {
        blend(context3, item);
        context3.stroke();
      }
    });
  }
  function hit$1(context3, item, x5, y5) {
    if (!context3.isPointInStroke) return false;
    return path2(context3, item, 1) && context3.isPointInStroke(x5, y5);
  }
  var rule = {
    type: "rule",
    tag: "line",
    nested: false,
    attr: attr$1,
    bound: bound$1,
    draw: draw$1,
    pick: pick$1(hit$1),
    isect: intersectRule
  };
  var shape = markItemPath("shape", shape$1);
  var symbol = markItemPath("symbol", symbol$1, intersectPoint);
  var widthCache = lruCache();
  var textMetrics = {
    height: fontSize,
    measureWidth,
    estimateWidth,
    width: estimateWidth,
    canvas: useCanvas
  };
  useCanvas(true);
  function useCanvas(use) {
    textMetrics.width = use && context ? measureWidth : estimateWidth;
  }
  function estimateWidth(item, text4) {
    return _estimateWidth(textValue(item, text4), fontSize(item));
  }
  function _estimateWidth(text4, currentFontHeight) {
    return ~~(0.8 * text4.length * currentFontHeight);
  }
  function measureWidth(item, text4) {
    return fontSize(item) <= 0 || !(text4 = textValue(item, text4)) ? 0 : _measureWidth(text4, font(item));
  }
  function _measureWidth(text4, currentFont) {
    const key2 = `(${currentFont}) ${text4}`;
    let width2 = widthCache.get(key2);
    if (width2 === void 0) {
      context.font = currentFont;
      width2 = context.measureText(text4).width;
      widthCache.set(key2, width2);
    }
    return width2;
  }
  function fontSize(item) {
    return item.fontSize != null ? +item.fontSize || 0 : 11;
  }
  function lineHeight(item) {
    return item.lineHeight != null ? item.lineHeight : fontSize(item) + 2;
  }
  function lineArray(_) {
    return isArray(_) ? _.length > 1 ? _ : _[0] : _;
  }
  function textLines(item) {
    return lineArray(item.lineBreak && item.text && !isArray(item.text) ? item.text.split(item.lineBreak) : item.text);
  }
  function multiLineOffset(item) {
    const tl2 = textLines(item);
    return (isArray(tl2) ? tl2.length - 1 : 0) * lineHeight(item);
  }
  function textValue(item, line4) {
    const text4 = line4 == null ? "" : (line4 + "").trim();
    return item.limit > 0 && text4.length ? truncate2(item, text4) : text4;
  }
  function widthGetter(item) {
    if (textMetrics.width === measureWidth) {
      const currentFont = font(item);
      return (text4) => _measureWidth(text4, currentFont);
    } else if (textMetrics.width === estimateWidth) {
      const currentFontHeight = fontSize(item);
      return (text4) => _estimateWidth(text4, currentFontHeight);
    } else {
      return (text4) => textMetrics.width(item, text4);
    }
  }
  function truncate2(item, text4) {
    var limit = +item.limit, width2 = widthGetter(item);
    if (width2(text4) < limit) return text4;
    var ellipsis = item.ellipsis || "\u2026", rtl = item.dir === "rtl", lo = 0, hi = text4.length, mid;
    limit -= width2(ellipsis);
    if (rtl) {
      while (lo < hi) {
        mid = lo + hi >>> 1;
        if (width2(text4.slice(mid)) > limit) lo = mid + 1;
        else hi = mid;
      }
      return ellipsis + text4.slice(lo);
    } else {
      while (lo < hi) {
        mid = 1 + (lo + hi >>> 1);
        if (width2(text4.slice(0, mid)) < limit) lo = mid;
        else hi = mid - 1;
      }
      return text4.slice(0, lo) + ellipsis;
    }
  }
  function fontFamily(item, quote) {
    var font3 = item.font;
    return (quote && font3 ? String(font3).replace(/"/g, "'") : font3) || "sans-serif";
  }
  function font(item, quote) {
    return (item.fontStyle ? item.fontStyle + " " : "") + (item.fontVariant ? item.fontVariant + " " : "") + (item.fontWeight ? item.fontWeight + " " : "") + fontSize(item) + "px " + fontFamily(item, quote);
  }
  function offset2(item) {
    var baseline3 = item.baseline, h3 = fontSize(item);
    return Math.round(baseline3 === "top" ? 0.79 * h3 : baseline3 === "middle" ? 0.3 * h3 : baseline3 === "bottom" ? -0.21 * h3 : baseline3 === "line-top" ? 0.29 * h3 + 0.5 * lineHeight(item) : baseline3 === "line-bottom" ? 0.29 * h3 - 0.5 * lineHeight(item) : 0);
  }
  var textAlign = {
    "left": "start",
    "center": "middle",
    "right": "end"
  };
  var tempBounds = new Bounds();
  function anchorPoint(item) {
    var x5 = item.x || 0, y5 = item.y || 0, r2 = item.radius || 0, t4;
    if (r2) {
      t4 = (item.theta || 0) - HalfPi;
      x5 += r2 * Math.cos(t4);
      y5 += r2 * Math.sin(t4);
    }
    tempBounds.x1 = x5;
    tempBounds.y1 = y5;
    return tempBounds;
  }
  function attr(emit2, item) {
    var dx = item.dx || 0, dy = (item.dy || 0) + offset2(item), p2 = anchorPoint(item), x5 = p2.x1, y5 = p2.y1, a4 = item.angle || 0, t4;
    emit2("text-anchor", textAlign[item.align] || "start");
    if (a4) {
      t4 = translate(x5, y5) + " " + rotate(a4);
      if (dx || dy) t4 += " " + translate(dx, dy);
    } else {
      t4 = translate(x5 + dx, y5 + dy);
    }
    emit2("transform", t4);
  }
  function bound(bounds2, item, mode) {
    var h3 = textMetrics.height(item), a4 = item.align, p2 = anchorPoint(item), x5 = p2.x1, y5 = p2.y1, dx = item.dx || 0, dy = (item.dy || 0) + offset2(item) - Math.round(0.8 * h3), tl2 = textLines(item), w3;
    if (isArray(tl2)) {
      h3 += lineHeight(item) * (tl2.length - 1);
      w3 = tl2.reduce((w4, t4) => Math.max(w4, textMetrics.width(item, t4)), 0);
    } else {
      w3 = textMetrics.width(item, tl2);
    }
    if (a4 === "center") {
      dx -= w3 / 2;
    } else if (a4 === "right") {
      dx -= w3;
    } else ;
    bounds2.set(dx += x5, dy += y5, dx + w3, dy + h3);
    if (item.angle && !mode) {
      bounds2.rotate(item.angle * DegToRad, x5, y5);
    } else if (mode === 2) {
      return bounds2.rotatedPoints(item.angle * DegToRad, x5, y5);
    }
    return bounds2;
  }
  function draw(context3, scene, bounds2) {
    visit(scene, (item) => {
      var opacity2 = item.opacity == null ? 1 : item.opacity, p2, x5, y5, i2, lh, tl2, str;
      if (bounds2 && !bounds2.intersects(item.bounds) || // bounds check
      opacity2 === 0 || item.fontSize <= 0 || item.text == null || item.text.length === 0) return;
      context3.font = font(item);
      context3.textAlign = item.align || "left";
      p2 = anchorPoint(item);
      x5 = p2.x1, y5 = p2.y1;
      if (item.angle) {
        context3.save();
        context3.translate(x5, y5);
        context3.rotate(item.angle * DegToRad);
        x5 = y5 = 0;
      }
      x5 += item.dx || 0;
      y5 += (item.dy || 0) + offset2(item);
      tl2 = textLines(item);
      blend(context3, item);
      if (isArray(tl2)) {
        lh = lineHeight(item);
        for (i2 = 0; i2 < tl2.length; ++i2) {
          str = textValue(item, tl2[i2]);
          if (item.fill && fill(context3, item, opacity2)) {
            context3.fillText(str, x5, y5);
          }
          if (item.stroke && stroke(context3, item, opacity2)) {
            context3.strokeText(str, x5, y5);
          }
          y5 += lh;
        }
      } else {
        str = textValue(item, tl2);
        if (item.fill && fill(context3, item, opacity2)) {
          context3.fillText(str, x5, y5);
        }
        if (item.stroke && stroke(context3, item, opacity2)) {
          context3.strokeText(str, x5, y5);
        }
      }
      if (item.angle) context3.restore();
    });
  }
  function hit(context3, item, x5, y5, gx, gy) {
    if (item.fontSize <= 0) return false;
    if (!item.angle) return true;
    var p2 = anchorPoint(item), ax = p2.x1, ay = p2.y1, b3 = bound(tempBounds, item, 1), a4 = -item.angle * DegToRad, cos4 = Math.cos(a4), sin4 = Math.sin(a4), px2 = cos4 * gx - sin4 * gy + (ax - cos4 * ax + sin4 * ay), py2 = sin4 * gx + cos4 * gy + (ay - sin4 * ax - cos4 * ay);
    return b3.contains(px2, py2);
  }
  function intersectText(item, box) {
    const p2 = bound(tempBounds, item, 2);
    return intersectBoxLine(box, p2[0], p2[1], p2[2], p2[3]) || intersectBoxLine(box, p2[0], p2[1], p2[4], p2[5]) || intersectBoxLine(box, p2[4], p2[5], p2[6], p2[7]) || intersectBoxLine(box, p2[2], p2[3], p2[6], p2[7]);
  }
  var text = {
    type: "text",
    tag: "text",
    nested: false,
    attr,
    bound,
    draw,
    pick: pick$1(hit),
    isect: intersectText
  };
  var trail = markMultiItemPath("trail", trail$1, pickTrail);
  var Marks = {
    arc,
    area,
    group,
    image,
    line,
    path: path$2,
    rect,
    rule,
    shape,
    symbol,
    text,
    trail
  };
  function boundItem(item, func, opt) {
    var type3 = Marks[item.mark.marktype], bound2 = func || type3.bound;
    if (type3.nested) item = item.mark;
    return bound2(item.bounds || (item.bounds = new Bounds()), item, opt);
  }
  var DUMMY = {
    mark: null
  };
  function boundMark(mark, bounds2, opt) {
    var type3 = Marks[mark.marktype], bound2 = type3.bound, items = mark.items, hasItems = items && items.length, i2, n2, item, b3;
    if (type3.nested) {
      if (hasItems) {
        item = items[0];
      } else {
        DUMMY.mark = mark;
        item = DUMMY;
      }
      b3 = boundItem(item, bound2, opt);
      bounds2 = bounds2 && bounds2.union(b3) || b3;
      return bounds2;
    }
    bounds2 = bounds2 || mark.bounds && mark.bounds.clear() || new Bounds();
    if (hasItems) {
      for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
        bounds2.union(boundItem(items[i2], bound2, opt));
      }
    }
    return mark.bounds = bounds2;
  }
  var keys = [
    "marktype",
    "name",
    "role",
    "interactive",
    "clip",
    "items",
    "zindex",
    "x",
    "y",
    "width",
    "height",
    "align",
    "baseline",
    // layout
    "fill",
    "fillOpacity",
    "opacity",
    "blend",
    // fill
    "stroke",
    "strokeOpacity",
    "strokeWidth",
    "strokeCap",
    // stroke
    "strokeDash",
    "strokeDashOffset",
    // stroke dash
    "strokeForeground",
    "strokeOffset",
    // group
    "startAngle",
    "endAngle",
    "innerRadius",
    "outerRadius",
    // arc
    "cornerRadius",
    "padAngle",
    // arc, rect
    "cornerRadiusTopLeft",
    "cornerRadiusTopRight",
    // rect, group
    "cornerRadiusBottomLeft",
    "cornerRadiusBottomRight",
    "interpolate",
    "tension",
    "orient",
    "defined",
    // area, line
    "url",
    "aspect",
    "smooth",
    // image
    "path",
    "scaleX",
    "scaleY",
    // path
    "x2",
    "y2",
    // rule
    "size",
    "shape",
    // symbol
    "text",
    "angle",
    "theta",
    "radius",
    "dir",
    "dx",
    "dy",
    // text
    "ellipsis",
    "limit",
    "lineBreak",
    "lineHeight",
    "font",
    "fontSize",
    "fontWeight",
    "fontStyle",
    "fontVariant",
    // font
    "description",
    "aria",
    "ariaRole",
    "ariaRoleDescription"
    // aria
  ];
  function sceneToJSON(scene, indent) {
    return JSON.stringify(scene, keys, indent);
  }
  function sceneFromJSON(json2) {
    const scene = typeof json2 === "string" ? JSON.parse(json2) : json2;
    return initialize(scene);
  }
  function initialize(scene) {
    var type3 = scene.marktype, items = scene.items, parent, i2, n2;
    if (items) {
      for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
        parent = type3 ? "mark" : "group";
        items[i2][parent] = scene;
        if (items[i2].zindex) items[i2][parent].zdirty = true;
        if ("group" === (type3 || parent)) initialize(items[i2]);
      }
    }
    if (type3) boundMark(scene);
    return scene;
  }
  var Scenegraph = class {
    constructor(scene) {
      if (arguments.length) {
        this.root = sceneFromJSON(scene);
      } else {
        this.root = createMark({
          marktype: "group",
          name: "root",
          role: "frame"
        });
        this.root.items = [new GroupItem(this.root)];
      }
    }
    toJSON(indent) {
      return sceneToJSON(this.root, indent || 0);
    }
    mark(markdef, group2, index4) {
      group2 = group2 || this.root.items[0];
      const mark = createMark(markdef, group2);
      group2.items[index4] = mark;
      if (mark.zindex) mark.group.zdirty = true;
      return mark;
    }
  };
  function createMark(def2, group2) {
    const mark = {
      bounds: new Bounds(),
      clip: !!def2.clip,
      group: group2,
      interactive: def2.interactive === false ? false : true,
      items: [],
      marktype: def2.marktype,
      name: def2.name || void 0,
      role: def2.role || void 0,
      zindex: def2.zindex || 0
    };
    if (def2.aria != null) {
      mark.aria = def2.aria;
    }
    if (def2.description) {
      mark.description = def2.description;
    }
    return mark;
  }
  function domCreate(doc, tag, ns) {
    if (!doc && typeof document !== "undefined" && document.createElement) {
      doc = document;
    }
    return doc ? ns ? doc.createElementNS(ns, tag) : doc.createElement(tag) : null;
  }
  function domFind(el, tag) {
    tag = tag.toLowerCase();
    var nodes = el.childNodes, i2 = 0, n2 = nodes.length;
    for (; i2 < n2; ++i2) if (nodes[i2].tagName.toLowerCase() === tag) {
      return nodes[i2];
    }
  }
  function domChild(el, index4, tag, ns) {
    var a4 = el.childNodes[index4], b3;
    if (!a4 || a4.tagName.toLowerCase() !== tag.toLowerCase()) {
      b3 = a4 || null;
      a4 = domCreate(el.ownerDocument, tag, ns);
      el.insertBefore(a4, b3);
    }
    return a4;
  }
  function domClear(el, index4) {
    var nodes = el.childNodes, curr = nodes.length;
    while (curr > index4) el.removeChild(nodes[--curr]);
    return el;
  }
  function cssClass(mark) {
    return "mark-" + mark.marktype + (mark.role ? " role-" + mark.role : "") + (mark.name ? " " + mark.name : "");
  }
  function point6(event2, el) {
    const rect3 = el.getBoundingClientRect();
    return [event2.clientX - rect3.left - (el.clientLeft || 0), event2.clientY - rect3.top - (el.clientTop || 0)];
  }
  function resolveItem(item, event2, el, origin) {
    var mark = item && item.mark, mdef, p2;
    if (mark && (mdef = Marks[mark.marktype]).tip) {
      p2 = point6(event2, el);
      p2[0] -= origin[0];
      p2[1] -= origin[1];
      while (item = item.mark.group) {
        p2[0] -= item.x || 0;
        p2[1] -= item.y || 0;
      }
      item = mdef.tip(mark.items, p2);
    }
    return item;
  }
  var Handler = class {
    /**
     * Create a new Handler instance.
     * @param {object} [customLoader] - Optional loader instance for
     *   href URL sanitization. If not specified, a standard loader
     *   instance will be generated.
     * @param {function} [customTooltip] - Optional tooltip handler
     *   function for custom tooltip display.
     * @constructor
     */
    constructor(customLoader, customTooltip) {
      this._active = null;
      this._handlers = {};
      this._loader = customLoader || loader();
      this._tooltip = customTooltip || defaultTooltip;
    }
    /**
     * Initialize a new Handler instance.
     * @param {DOMElement} el - The containing DOM element for the display.
     * @param {Array<number>} origin - The origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {object} [obj] - Optional context object that should serve as
     *   the "this" context for event callbacks.
     * @return {Handler} - This handler instance.
     */
    initialize(el, origin, obj) {
      this._el = el;
      this._obj = obj || null;
      return this.origin(origin);
    }
    /**
     * Returns the parent container element for a visualization.
     * @return {DOMElement} - The containing DOM element.
     */
    element() {
      return this._el;
    }
    /**
     * Returns the scene element (e.g., canvas or SVG) of the visualization
     * Subclasses must override if the first child is not the scene element.
     * @return {DOMElement} - The scene (e.g., canvas or SVG) element.
     */
    canvas() {
      return this._el && this._el.firstChild;
    }
    /**
     * Get / set the origin coordinates of the visualization.
     */
    origin(origin) {
      if (arguments.length) {
        this._origin = origin || [0, 0];
        return this;
      } else {
        return this._origin.slice();
      }
    }
    /**
     * Get / set the scenegraph root.
     */
    scene(scene) {
      if (!arguments.length) return this._scene;
      this._scene = scene;
      return this;
    }
    /**
     * Add an event handler. Subclasses should override this method.
     */
    on() {
    }
    /**
     * Remove an event handler. Subclasses should override this method.
     */
    off() {
    }
    /**
     * Utility method for finding the array index of an event handler.
     * @param {Array} h - An array of registered event handlers.
     * @param {string} type - The event type.
     * @param {function} handler - The event handler instance to find.
     * @return {number} - The handler's array index or -1 if not registered.
     */
    _handlerIndex(h3, type3, handler) {
      for (let i2 = h3 ? h3.length : 0; --i2 >= 0; ) {
        if (h3[i2].type === type3 && (!handler || h3[i2].handler === handler)) {
          return i2;
        }
      }
      return -1;
    }
    /**
     * Returns an array with registered event handlers.
     * @param {string} [type] - The event type to query. Any annotations
     *   are ignored; for example, for the argument "click.foo", ".foo" will
     *   be ignored and the method returns all "click" handlers. If type is
     *   null or unspecified, this method returns handlers for all types.
     * @return {Array} - A new array containing all registered event handlers.
     */
    handlers(type3) {
      const h3 = this._handlers, a4 = [];
      if (type3) {
        a4.push(...h3[this.eventName(type3)]);
      } else {
        for (const k2 in h3) {
          a4.push(...h3[k2]);
        }
      }
      return a4;
    }
    /**
     * Parses an event name string to return the specific event type.
     * For example, given "click.foo" returns "click"
     * @param {string} name - The input event type string.
     * @return {string} - A string with the event type only.
     */
    eventName(name4) {
      const i2 = name4.indexOf(".");
      return i2 < 0 ? name4 : name4.slice(0, i2);
    }
    /**
     * Handle hyperlink navigation in response to an item.href value.
     * @param {Event} event - The event triggering hyperlink navigation.
     * @param {Item} item - The scenegraph item.
     * @param {string} href - The URL to navigate to.
     */
    handleHref(event2, item, href2) {
      this._loader.sanitize(href2, {
        context: "href"
      }).then((opt) => {
        const e4 = new MouseEvent(event2.type, event2), a4 = domCreate(null, "a");
        for (const name4 in opt) a4.setAttribute(name4, opt[name4]);
        a4.dispatchEvent(e4);
      }).catch(() => {
      });
    }
    /**
     * Handle tooltip display in response to an item.tooltip value.
     * @param {Event} event - The event triggering tooltip display.
     * @param {Item} item - The scenegraph item.
     * @param {boolean} show - A boolean flag indicating whether
     *   to show or hide a tooltip for the given item.
     */
    handleTooltip(event2, item, show) {
      if (item && item.tooltip != null) {
        item = resolveItem(item, event2, this.canvas(), this._origin);
        const value3 = show && item && item.tooltip || null;
        this._tooltip.call(this._obj, this, event2, item, value3);
      }
    }
    /**
     * Returns the size of a scenegraph item and its position relative
     * to the viewport.
     * @param {Item} item - The scenegraph item.
     * @return {object} - A bounding box object (compatible with the
     *   DOMRect type) consisting of x, y, width, heigh, top, left,
     *   right, and bottom properties.
     */
    getItemBoundingClientRect(item) {
      const el = this.canvas();
      if (!el) return;
      const rect3 = el.getBoundingClientRect(), origin = this._origin, bounds2 = item.bounds, width2 = bounds2.width(), height2 = bounds2.height();
      let x5 = bounds2.x1 + origin[0] + rect3.left, y5 = bounds2.y1 + origin[1] + rect3.top;
      while (item.mark && (item = item.mark.group)) {
        x5 += item.x || 0;
        y5 += item.y || 0;
      }
      return {
        x: x5,
        y: y5,
        width: width2,
        height: height2,
        left: x5,
        top: y5,
        right: x5 + width2,
        bottom: y5 + height2
      };
    }
  };
  function defaultTooltip(handler, event2, item, value3) {
    handler.element().setAttribute("title", value3 || "");
  }
  var Renderer = class {
    /**
     * Create a new Renderer instance.
     * @param {object} [loader] - Optional loader instance for
     *   image and href URL sanitization. If not specified, a
     *   standard loader instance will be generated.
     * @constructor
     */
    constructor(loader2) {
      this._el = null;
      this._bgcolor = null;
      this._loader = new ResourceLoader(loader2);
    }
    /**
     * Initialize a new Renderer instance.
     * @param {DOMElement} el - The containing DOM element for the display.
     * @param {number} width - The coordinate width of the display, in pixels.
     * @param {number} height - The coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {Renderer} - This renderer instance.
     */
    initialize(el, width2, height2, origin, scaleFactor) {
      this._el = el;
      return this.resize(width2, height2, origin, scaleFactor);
    }
    /**
     * Returns the parent container element for a visualization.
     * @return {DOMElement} - The containing DOM element.
     */
    element() {
      return this._el;
    }
    /**
     * Returns the scene element (e.g., canvas or SVG) of the visualization
     * Subclasses must override if the first child is not the scene element.
     * @return {DOMElement} - The scene (e.g., canvas or SVG) element.
     */
    canvas() {
      return this._el && this._el.firstChild;
    }
    /**
     * Get / set the background color.
     */
    background(bgcolor) {
      if (arguments.length === 0) return this._bgcolor;
      this._bgcolor = bgcolor;
      return this;
    }
    /**
     * Resize the display.
     * @param {number} width - The new coordinate width of the display, in pixels.
     * @param {number} height - The new coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The new origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {Renderer} - This renderer instance;
     */
    resize(width2, height2, origin, scaleFactor) {
      this._width = width2;
      this._height = height2;
      this._origin = origin || [0, 0];
      this._scale = scaleFactor || 1;
      return this;
    }
    /**
     * Report a dirty item whose bounds should be redrawn.
     * This base class method does nothing. Subclasses that perform
     * incremental should implement this method.
     * @param {Item} item - The dirty item whose bounds should be redrawn.
     */
    dirty() {
    }
    /**
     * Render an input scenegraph, potentially with a set of dirty items.
     * This method will perform an immediate rendering with available resources.
     * The renderer may also need to perform image loading to perform a complete
     * render. This process can lead to asynchronous re-rendering of the scene
     * after this method returns. To receive notification when rendering is
     * complete, use the renderAsync method instead.
     * @param {object} scene - The root mark of a scenegraph to render.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     * @return {Renderer} - This renderer instance.
     */
    render(scene, markTypes) {
      const r2 = this;
      r2._call = function() {
        r2._render(scene, markTypes);
      };
      r2._call();
      r2._call = null;
      return r2;
    }
    /**
     * Internal rendering method. Renderer subclasses should override this
     * method to actually perform rendering.
     * @param {object} scene - The root mark of a scenegraph to render.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     */
    _render() {
    }
    /**
     * Asynchronous rendering method. Similar to render, but returns a Promise
     * that resolves when all rendering is completed. Sometimes a renderer must
     * perform image loading to get a complete rendering. The returned
     * Promise will not resolve until this process completes.
     * @param {object} scene - The root mark of a scenegraph to render.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     * @return {Promise} - A Promise that resolves when rendering is complete.
     */
    renderAsync(scene, markTypes) {
      const r2 = this.render(scene, markTypes);
      return this._ready ? this._ready.then(() => r2) : Promise.resolve(r2);
    }
    /**
     * Internal method for asynchronous resource loading.
     * Proxies method calls to the ImageLoader, and tracks loading
     * progress to invoke a re-render once complete.
     * @param {string} method - The method name to invoke on the ImageLoader.
     * @param {string} uri - The URI for the requested resource.
     * @return {Promise} - A Promise that resolves to the requested resource.
     */
    _load(method2, uri) {
      var r2 = this, p2 = r2._loader[method2](uri);
      if (!r2._ready) {
        const call = r2._call;
        r2._ready = r2._loader.ready().then((redraw) => {
          if (redraw) call();
          r2._ready = null;
        });
      }
      return p2;
    }
    /**
     * Sanitize a URL to include as a hyperlink in the rendered scene.
     * This method proxies a call to ImageLoader.sanitizeURL, but also tracks
     * image loading progress and invokes a re-render once complete.
     * @param {string} uri - The URI string to sanitize.
     * @return {Promise} - A Promise that resolves to the sanitized URL.
     */
    sanitizeURL(uri) {
      return this._load("sanitizeURL", uri);
    }
    /**
     * Requests an image to include in the rendered scene.
     * This method proxies a call to ImageLoader.loadImage, but also tracks
     * image loading progress and invokes a re-render once complete.
     * @param {string} uri - The URI string of the image.
     * @return {Promise} - A Promise that resolves to the loaded Image.
     */
    loadImage(uri) {
      return this._load("loadImage", uri);
    }
  };
  var KeyDownEvent = "keydown";
  var KeyPressEvent = "keypress";
  var KeyUpEvent = "keyup";
  var DragEnterEvent = "dragenter";
  var DragLeaveEvent = "dragleave";
  var DragOverEvent = "dragover";
  var PointerDownEvent = "pointerdown";
  var PointerUpEvent = "pointerup";
  var PointerMoveEvent = "pointermove";
  var PointerOutEvent = "pointerout";
  var PointerOverEvent = "pointerover";
  var MouseDownEvent = "mousedown";
  var MouseUpEvent = "mouseup";
  var MouseMoveEvent = "mousemove";
  var MouseOutEvent = "mouseout";
  var MouseOverEvent = "mouseover";
  var ClickEvent = "click";
  var DoubleClickEvent = "dblclick";
  var WheelEvent = "wheel";
  var MouseWheelEvent = "mousewheel";
  var TouchStartEvent = "touchstart";
  var TouchMoveEvent = "touchmove";
  var TouchEndEvent = "touchend";
  var Events = [KeyDownEvent, KeyPressEvent, KeyUpEvent, DragEnterEvent, DragLeaveEvent, DragOverEvent, PointerDownEvent, PointerUpEvent, PointerMoveEvent, PointerOutEvent, PointerOverEvent, MouseDownEvent, MouseUpEvent, MouseMoveEvent, MouseOutEvent, MouseOverEvent, ClickEvent, DoubleClickEvent, WheelEvent, MouseWheelEvent, TouchStartEvent, TouchMoveEvent, TouchEndEvent];
  var TooltipShowEvent = PointerMoveEvent;
  var TooltipHideEvent = MouseOutEvent;
  var HrefEvent = ClickEvent;
  var CanvasHandler = class extends Handler {
    constructor(loader2, tooltip2) {
      super(loader2, tooltip2);
      this._down = null;
      this._touch = null;
      this._first = true;
      this._events = {};
      this.events = Events;
      this.pointermove = move([PointerMoveEvent, MouseMoveEvent], [PointerOverEvent, MouseOverEvent], [PointerOutEvent, MouseOutEvent]);
      this.dragover = move([DragOverEvent], [DragEnterEvent], [DragLeaveEvent]), this.pointerout = inactive([PointerOutEvent, MouseOutEvent]);
      this.dragleave = inactive([DragLeaveEvent]);
    }
    initialize(el, origin, obj) {
      this._canvas = el && domFind(el, "canvas");
      [ClickEvent, MouseDownEvent, PointerDownEvent, PointerMoveEvent, PointerOutEvent, DragLeaveEvent].forEach((type3) => eventListenerCheck(this, type3));
      return super.initialize(el, origin, obj);
    }
    // return the backing canvas instance
    canvas() {
      return this._canvas;
    }
    // retrieve the current canvas context
    context() {
      return this._canvas.getContext("2d");
    }
    // to keep old versions of firefox happy
    DOMMouseScroll(evt) {
      this.fire(MouseWheelEvent, evt);
    }
    pointerdown(evt) {
      this._down = this._active;
      this.fire(PointerDownEvent, evt);
    }
    mousedown(evt) {
      this._down = this._active;
      this.fire(MouseDownEvent, evt);
    }
    click(evt) {
      if (this._down === this._active) {
        this.fire(ClickEvent, evt);
        this._down = null;
      }
    }
    touchstart(evt) {
      this._touch = this.pickEvent(evt.changedTouches[0]);
      if (this._first) {
        this._active = this._touch;
        this._first = false;
      }
      this.fire(TouchStartEvent, evt, true);
    }
    touchmove(evt) {
      this.fire(TouchMoveEvent, evt, true);
    }
    touchend(evt) {
      this.fire(TouchEndEvent, evt, true);
      this._touch = null;
    }
    // fire an event
    fire(type3, evt, touch2) {
      const a4 = touch2 ? this._touch : this._active, h3 = this._handlers[type3];
      evt.vegaType = type3;
      if (type3 === HrefEvent && a4 && a4.href) {
        this.handleHref(evt, a4, a4.href);
      } else if (type3 === TooltipShowEvent || type3 === TooltipHideEvent) {
        this.handleTooltip(evt, a4, type3 !== TooltipHideEvent);
      }
      if (h3) {
        for (let i2 = 0, len = h3.length; i2 < len; ++i2) {
          h3[i2].handler.call(this._obj, evt, a4);
        }
      }
    }
    // add an event handler
    on(type3, handler) {
      const name4 = this.eventName(type3), h3 = this._handlers, i2 = this._handlerIndex(h3[name4], type3, handler);
      if (i2 < 0) {
        eventListenerCheck(this, type3);
        (h3[name4] || (h3[name4] = [])).push({
          type: type3,
          handler
        });
      }
      return this;
    }
    // remove an event handler
    off(type3, handler) {
      const name4 = this.eventName(type3), h3 = this._handlers[name4], i2 = this._handlerIndex(h3, type3, handler);
      if (i2 >= 0) {
        h3.splice(i2, 1);
      }
      return this;
    }
    pickEvent(evt) {
      const p2 = point6(evt, this._canvas), o2 = this._origin;
      return this.pick(this._scene, p2[0], p2[1], p2[0] - o2[0], p2[1] - o2[1]);
    }
    // find the scenegraph item at the current pointer position
    // x, y -- the absolute x, y pointer coordinates on the canvas element
    // gx, gy -- the relative coordinates within the current group
    pick(scene, x5, y5, gx, gy) {
      const g2 = this.context(), mark = Marks[scene.marktype];
      return mark.pick.call(this, g2, scene, x5, y5, gx, gy);
    }
  };
  var eventBundle = (type3) => type3 === TouchStartEvent || type3 === TouchMoveEvent || type3 === TouchEndEvent ? [TouchStartEvent, TouchMoveEvent, TouchEndEvent] : [type3];
  function eventListenerCheck(handler, type3) {
    eventBundle(type3).forEach((_) => addEventListener(handler, _));
  }
  function addEventListener(handler, type3) {
    const canvas = handler.canvas();
    if (canvas && !handler._events[type3]) {
      handler._events[type3] = 1;
      canvas.addEventListener(type3, handler[type3] ? (evt) => handler[type3](evt) : (evt) => handler.fire(type3, evt));
    }
  }
  function fireAll(handler, types4, event2) {
    types4.forEach((type3) => handler.fire(type3, event2));
  }
  function move(moveEvents, overEvents, outEvents) {
    return function(evt) {
      const a4 = this._active, p2 = this.pickEvent(evt);
      if (p2 === a4) {
        fireAll(this, moveEvents, evt);
      } else {
        if (!a4 || !a4.exit) {
          fireAll(this, outEvents, evt);
        }
        this._active = p2;
        fireAll(this, overEvents, evt);
        fireAll(this, moveEvents, evt);
      }
    };
  }
  function inactive(types4) {
    return function(evt) {
      fireAll(this, types4, evt);
      this._active = null;
    };
  }
  function devicePixelRatio() {
    return typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
  }
  function resize(canvas, width2, height2, origin, scaleFactor, opt) {
    const inDOM = typeof HTMLElement !== "undefined" && canvas instanceof HTMLElement && canvas.parentNode != null, context3 = canvas.getContext("2d"), ratio = inDOM ? devicePixelRatio() : scaleFactor;
    canvas.width = width2 * ratio;
    canvas.height = height2 * ratio;
    for (const key2 in opt) {
      context3[key2] = opt[key2];
    }
    if (inDOM && ratio !== 1) {
      canvas.style.width = width2 + "px";
      canvas.style.height = height2 + "px";
    }
    context3.pixelRatio = ratio;
    context3.setTransform(ratio, 0, 0, ratio, ratio * origin[0], ratio * origin[1]);
    return canvas;
  }
  var CanvasRenderer = class extends Renderer {
    constructor(loader2) {
      super(loader2);
      this._options = {};
      this._redraw = false;
      this._dirty = new Bounds();
      this._tempb = new Bounds();
    }
    initialize(el, width2, height2, origin, scaleFactor, options) {
      this._options = options || {};
      this._canvas = this._options.externalContext ? null : domCanvas(1, 1, this._options.type);
      if (el && this._canvas) {
        domClear(el, 0).appendChild(this._canvas);
        this._canvas.setAttribute("class", "marks");
      }
      return super.initialize(el, width2, height2, origin, scaleFactor);
    }
    resize(width2, height2, origin, scaleFactor) {
      super.resize(width2, height2, origin, scaleFactor);
      if (this._canvas) {
        resize(this._canvas, this._width, this._height, this._origin, this._scale, this._options.context);
      } else {
        const ctx = this._options.externalContext;
        if (!ctx) error("CanvasRenderer is missing a valid canvas or context");
        ctx.scale(this._scale, this._scale);
        ctx.translate(this._origin[0], this._origin[1]);
      }
      this._redraw = true;
      return this;
    }
    canvas() {
      return this._canvas;
    }
    context() {
      return this._options.externalContext || (this._canvas ? this._canvas.getContext("2d") : null);
    }
    dirty(item) {
      const b3 = this._tempb.clear().union(item.bounds);
      let g2 = item.mark.group;
      while (g2) {
        b3.translate(g2.x || 0, g2.y || 0);
        g2 = g2.mark.group;
      }
      this._dirty.union(b3);
    }
    _render(scene, markTypes) {
      const g2 = this.context(), o2 = this._origin, w3 = this._width, h3 = this._height, db = this._dirty, vb = viewBounds(o2, w3, h3);
      g2.save();
      const b3 = this._redraw || db.empty() ? (this._redraw = false, vb.expand(1)) : clipToBounds(g2, vb.intersect(db), o2);
      this.clear(-o2[0], -o2[1], w3, h3);
      this.draw(g2, scene, b3, markTypes);
      g2.restore();
      db.clear();
      return this;
    }
    draw(ctx, scene, bounds2, markTypes) {
      if (scene.marktype !== "group" && markTypes != null && !markTypes.includes(scene.marktype)) {
        return;
      }
      const mark = Marks[scene.marktype];
      if (scene.clip) clip(ctx, scene);
      mark.draw.call(this, ctx, scene, bounds2, markTypes);
      if (scene.clip) ctx.restore();
    }
    clear(x5, y5, w3, h3) {
      const opt = this._options, g2 = this.context();
      if (opt.type !== "pdf" && !opt.externalContext) {
        g2.clearRect(x5, y5, w3, h3);
      }
      if (this._bgcolor != null) {
        g2.fillStyle = this._bgcolor;
        g2.fillRect(x5, y5, w3, h3);
      }
    }
  };
  var viewBounds = (origin, width2, height2) => new Bounds().set(0, 0, width2, height2).translate(-origin[0], -origin[1]);
  function clipToBounds(g2, b3, origin) {
    b3.expand(1).round();
    if (g2.pixelRatio % 1) {
      b3.scale(g2.pixelRatio).round().scale(1 / g2.pixelRatio);
    }
    b3.translate(-(origin[0] % 1), -(origin[1] % 1));
    g2.beginPath();
    g2.rect(b3.x1, b3.y1, b3.width(), b3.height());
    g2.clip();
    return b3;
  }
  var SVGHandler = class extends Handler {
    constructor(loader2, tooltip2) {
      super(loader2, tooltip2);
      const h3 = this;
      h3._hrefHandler = listener(h3, (evt, item) => {
        if (item && item.href) h3.handleHref(evt, item, item.href);
      });
      h3._tooltipHandler = listener(h3, (evt, item) => {
        h3.handleTooltip(evt, item, evt.type !== TooltipHideEvent);
      });
    }
    initialize(el, origin, obj) {
      let svg = this._svg;
      if (svg) {
        svg.removeEventListener(HrefEvent, this._hrefHandler);
        svg.removeEventListener(TooltipShowEvent, this._tooltipHandler);
        svg.removeEventListener(TooltipHideEvent, this._tooltipHandler);
      }
      this._svg = svg = el && domFind(el, "svg");
      if (svg) {
        svg.addEventListener(HrefEvent, this._hrefHandler);
        svg.addEventListener(TooltipShowEvent, this._tooltipHandler);
        svg.addEventListener(TooltipHideEvent, this._tooltipHandler);
      }
      return super.initialize(el, origin, obj);
    }
    canvas() {
      return this._svg;
    }
    // add an event handler
    on(type3, handler) {
      const name4 = this.eventName(type3), h3 = this._handlers, i2 = this._handlerIndex(h3[name4], type3, handler);
      if (i2 < 0) {
        const x5 = {
          type: type3,
          handler,
          listener: listener(this, handler)
        };
        (h3[name4] || (h3[name4] = [])).push(x5);
        if (this._svg) {
          this._svg.addEventListener(name4, x5.listener);
        }
      }
      return this;
    }
    // remove an event handler
    off(type3, handler) {
      const name4 = this.eventName(type3), h3 = this._handlers[name4], i2 = this._handlerIndex(h3, type3, handler);
      if (i2 >= 0) {
        if (this._svg) {
          this._svg.removeEventListener(name4, h3[i2].listener);
        }
        h3.splice(i2, 1);
      }
      return this;
    }
  };
  var listener = (context3, handler) => (evt) => {
    let item = evt.target.__data__;
    item = Array.isArray(item) ? item[0] : item;
    evt.vegaType = evt.type;
    handler.call(context3._obj, evt, item);
  };
  var ARIA_HIDDEN = "aria-hidden";
  var ARIA_LABEL = "aria-label";
  var ARIA_ROLE = "role";
  var ARIA_ROLEDESCRIPTION = "aria-roledescription";
  var GRAPHICS_OBJECT = "graphics-object";
  var GRAPHICS_SYMBOL = "graphics-symbol";
  var bundle = (role, roledesc, label) => ({
    [ARIA_ROLE]: role,
    [ARIA_ROLEDESCRIPTION]: roledesc,
    [ARIA_LABEL]: label || void 0
  });
  var AriaIgnore = toSet(["axis-domain", "axis-grid", "axis-label", "axis-tick", "axis-title", "legend-band", "legend-entry", "legend-gradient", "legend-label", "legend-title", "legend-symbol", "title"]);
  var AriaGuides = {
    "axis": {
      desc: "axis",
      caption: axisCaption
    },
    "legend": {
      desc: "legend",
      caption: legendCaption
    },
    "title-text": {
      desc: "title",
      caption: (item) => `Title text '${titleCaption(item)}'`
    },
    "title-subtitle": {
      desc: "subtitle",
      caption: (item) => `Subtitle text '${titleCaption(item)}'`
    }
  };
  var AriaEncode = {
    ariaRole: ARIA_ROLE,
    ariaRoleDescription: ARIA_ROLEDESCRIPTION,
    description: ARIA_LABEL
  };
  function ariaItemAttributes(emit2, item) {
    const hide = item.aria === false;
    emit2(ARIA_HIDDEN, hide || void 0);
    if (hide || item.description == null) {
      for (const prop in AriaEncode) {
        emit2(AriaEncode[prop], void 0);
      }
    } else {
      const type3 = item.mark.marktype;
      emit2(ARIA_LABEL, item.description);
      emit2(ARIA_ROLE, item.ariaRole || (type3 === "group" ? GRAPHICS_OBJECT : GRAPHICS_SYMBOL));
      emit2(ARIA_ROLEDESCRIPTION, item.ariaRoleDescription || `${type3} mark`);
    }
  }
  function ariaMarkAttributes(mark) {
    return mark.aria === false ? {
      [ARIA_HIDDEN]: true
    } : AriaIgnore[mark.role] ? null : AriaGuides[mark.role] ? ariaGuide(mark, AriaGuides[mark.role]) : ariaMark(mark);
  }
  function ariaMark(mark) {
    const type3 = mark.marktype;
    const recurse2 = type3 === "group" || type3 === "text" || mark.items.some((_) => _.description != null && _.aria !== false);
    return bundle(recurse2 ? GRAPHICS_OBJECT : GRAPHICS_SYMBOL, `${type3} mark container`, mark.description);
  }
  function ariaGuide(mark, opt) {
    try {
      const item = mark.items[0], caption = opt.caption || (() => "");
      return bundle(opt.role || GRAPHICS_SYMBOL, opt.desc, item.description || caption(item));
    } catch (err) {
      return null;
    }
  }
  function titleCaption(item) {
    return array(item.text).join(" ");
  }
  function axisCaption(item) {
    const datum2 = item.datum, orient2 = item.orient, title2 = datum2.title ? extractTitle(item) : null, ctx = item.context, scale7 = ctx.scales[datum2.scale].value, locale4 = ctx.dataflow.locale(), type3 = scale7.type, xy = orient2 === "left" || orient2 === "right" ? "Y" : "X";
    return `${xy}-axis` + (title2 ? ` titled '${title2}'` : "") + ` for a ${isDiscrete(type3) ? "discrete" : type3} scale with ${domainCaption(locale4, scale7, item)}`;
  }
  function legendCaption(item) {
    const datum2 = item.datum, title2 = datum2.title ? extractTitle(item) : null, type3 = `${datum2.type || ""} legend`.trim(), scales2 = datum2.scales, props = Object.keys(scales2), ctx = item.context, scale7 = ctx.scales[scales2[props[0]]].value, locale4 = ctx.dataflow.locale();
    return capitalize(type3) + (title2 ? ` titled '${title2}'` : "") + ` for ${channelCaption(props)} with ${domainCaption(locale4, scale7, item)}`;
  }
  function extractTitle(item) {
    try {
      return array(peek(item.items).items[0].text).join(" ");
    } catch (err) {
      return null;
    }
  }
  function channelCaption(props) {
    props = props.map((p2) => p2 + (p2 === "fill" || p2 === "stroke" ? " color" : ""));
    return props.length < 2 ? props[0] : props.slice(0, -1).join(", ") + " and " + peek(props);
  }
  function capitalize(s2) {
    return s2.length ? s2[0].toUpperCase() + s2.slice(1) : s2;
  }
  var innerText = (val) => (val + "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  var attrText = (val) => innerText(val).replace(/"/g, "&quot;").replace(/\t/g, "&#x9;").replace(/\n/g, "&#xA;").replace(/\r/g, "&#xD;");
  function markup() {
    let buf = "", outer = "", inner = "";
    const stack2 = [], clear2 = () => outer = inner = "", push = (tag) => {
      if (outer) {
        buf += `${outer}>${inner}`;
        clear2();
      }
      stack2.push(tag);
    }, attr2 = (name4, value3) => {
      if (value3 != null) outer += ` ${name4}="${attrText(value3)}"`;
      return m4;
    }, m4 = {
      open(tag) {
        push(tag);
        outer = "<" + tag;
        for (var _len = arguments.length, attrs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          attrs[_key - 1] = arguments[_key];
        }
        for (const set7 of attrs) {
          for (const key2 in set7) attr2(key2, set7[key2]);
        }
        return m4;
      },
      close() {
        const tag = stack2.pop();
        if (outer) {
          buf += outer + (inner ? `>${inner}</${tag}>` : "/>");
        } else {
          buf += `</${tag}>`;
        }
        clear2();
        return m4;
      },
      attr: attr2,
      text: (t4) => (inner += innerText(t4), m4),
      toString: () => buf
    };
    return m4;
  }
  var serializeXML = (node) => _serialize(markup(), node) + "";
  function _serialize(m4, node) {
    m4.open(node.tagName);
    if (node.hasAttributes()) {
      const attrs = node.attributes, n2 = attrs.length;
      for (let i2 = 0; i2 < n2; ++i2) {
        m4.attr(attrs[i2].name, attrs[i2].value);
      }
    }
    if (node.hasChildNodes()) {
      const children4 = node.childNodes;
      for (const child of children4) {
        child.nodeType === 3 ? m4.text(child.nodeValue) : _serialize(m4, child);
      }
    }
    return m4.close();
  }
  var stylesAttr = {
    fill: "fill",
    fillOpacity: "fill-opacity",
    stroke: "stroke",
    strokeOpacity: "stroke-opacity",
    strokeWidth: "stroke-width",
    strokeCap: "stroke-linecap",
    strokeJoin: "stroke-linejoin",
    strokeDash: "stroke-dasharray",
    strokeDashOffset: "stroke-dashoffset",
    strokeMiterLimit: "stroke-miterlimit",
    opacity: "opacity"
  };
  var stylesCss = {
    blend: "mix-blend-mode"
  };
  var rootAttributes = {
    "fill": "none",
    "stroke-miterlimit": 10
  };
  var RootIndex = 0;
  var xmlns = "http://www.w3.org/2000/xmlns/";
  var svgns = metadata.xmlns;
  var SVGRenderer = class extends Renderer {
    constructor(loader2) {
      super(loader2);
      this._dirtyID = 0;
      this._dirty = [];
      this._svg = null;
      this._root = null;
      this._defs = null;
    }
    /**
     * Initialize a new SVGRenderer instance.
     * @param {DOMElement} el - The containing DOM element for the display.
     * @param {number} width - The coordinate width of the display, in pixels.
     * @param {number} height - The coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {SVGRenderer} - This renderer instance.
     */
    initialize(el, width2, height2, origin, scaleFactor) {
      this._defs = {};
      this._clearDefs();
      if (el) {
        this._svg = domChild(el, 0, "svg", svgns);
        this._svg.setAttributeNS(xmlns, "xmlns", svgns);
        this._svg.setAttributeNS(xmlns, "xmlns:xlink", metadata["xmlns:xlink"]);
        this._svg.setAttribute("version", metadata["version"]);
        this._svg.setAttribute("class", "marks");
        domClear(el, 1);
        this._root = domChild(this._svg, RootIndex, "g", svgns);
        setAttributes(this._root, rootAttributes);
        domClear(this._svg, RootIndex + 1);
      }
      this.background(this._bgcolor);
      return super.initialize(el, width2, height2, origin, scaleFactor);
    }
    /**
     * Get / set the background color.
     */
    background(bgcolor) {
      if (arguments.length && this._svg) {
        this._svg.style.setProperty("background-color", bgcolor);
      }
      return super.background(...arguments);
    }
    /**
     * Resize the display.
     * @param {number} width - The new coordinate width of the display, in pixels.
     * @param {number} height - The new coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The new origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {SVGRenderer} - This renderer instance;
     */
    resize(width2, height2, origin, scaleFactor) {
      super.resize(width2, height2, origin, scaleFactor);
      if (this._svg) {
        setAttributes(this._svg, {
          width: this._width * this._scale,
          height: this._height * this._scale,
          viewBox: `0 0 ${this._width} ${this._height}`
        });
        this._root.setAttribute("transform", `translate(${this._origin})`);
      }
      this._dirty = [];
      return this;
    }
    /**
     * Returns the SVG element of the visualization.
     * @return {DOMElement} - The SVG element.
     */
    canvas() {
      return this._svg;
    }
    /**
     * Returns an SVG text string for the rendered content,
     * or null if this renderer is currently headless.
     */
    svg() {
      const svg = this._svg, bg = this._bgcolor;
      if (!svg) return null;
      let node;
      if (bg) {
        svg.removeAttribute("style");
        node = domChild(svg, RootIndex, "rect", svgns);
        setAttributes(node, {
          width: this._width,
          height: this._height,
          fill: bg
        });
      }
      const text4 = serializeXML(svg);
      if (bg) {
        svg.removeChild(node);
        this._svg.style.setProperty("background-color", bg);
      }
      return text4;
    }
    /**
     * Internal rendering method.
     * @param {object} scene - The root mark of a scenegraph to render.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     */
    _render(scene, markTypes) {
      if (this._dirtyCheck()) {
        if (this._dirtyAll) this._clearDefs();
        this.mark(this._root, scene, void 0, markTypes);
        domClear(this._root, 1);
      }
      this.defs();
      this._dirty = [];
      ++this._dirtyID;
      return this;
    }
    // -- Manage rendering of items marked as dirty --
    /**
     * Flag a mark item as dirty.
     * @param {Item} item - The mark item.
     */
    dirty(item) {
      if (item.dirty !== this._dirtyID) {
        item.dirty = this._dirtyID;
        this._dirty.push(item);
      }
    }
    /**
     * Check if a mark item is considered dirty.
     * @param {Item} item - The mark item.
     */
    isDirty(item) {
      return this._dirtyAll || !item._svg || !item._svg.ownerSVGElement || item.dirty === this._dirtyID;
    }
    /**
     * Internal method to check dirty status and, if possible,
     * make targetted updates without a full rendering pass.
     */
    _dirtyCheck() {
      this._dirtyAll = true;
      const items = this._dirty;
      if (!items.length || !this._dirtyID) return true;
      const id2 = ++this._dirtyID;
      let item, mark, type3, mdef, i2, n2, o2;
      for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
        item = items[i2];
        mark = item.mark;
        if (mark.marktype !== type3) {
          type3 = mark.marktype;
          mdef = Marks[type3];
        }
        if (mark.zdirty && mark.dirty !== id2) {
          this._dirtyAll = false;
          dirtyParents(item, id2);
          mark.items.forEach((i3) => {
            i3.dirty = id2;
          });
        }
        if (mark.zdirty) continue;
        if (item.exit) {
          if (mdef.nested && mark.items.length) {
            o2 = mark.items[0];
            if (o2._svg) this._update(mdef, o2._svg, o2);
          } else if (item._svg) {
            o2 = item._svg.parentNode;
            if (o2) o2.removeChild(item._svg);
          }
          item._svg = null;
          continue;
        }
        item = mdef.nested ? mark.items[0] : item;
        if (item._update === id2) continue;
        if (!item._svg || !item._svg.ownerSVGElement) {
          this._dirtyAll = false;
          dirtyParents(item, id2);
        } else {
          this._update(mdef, item._svg, item);
        }
        item._update = id2;
      }
      return !this._dirtyAll;
    }
    // -- Construct & maintain scenegraph to SVG mapping ---
    /**
     * Render a set of mark items.
     * @param {SVGElement} el - The parent element in the SVG tree.
     * @param {object} scene - The mark parent to render.
     * @param {SVGElement} prev - The previous sibling in the SVG tree.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     */
    mark(el, scene, prev, markTypes) {
      if (!this.isDirty(scene)) {
        return scene._svg;
      }
      const svg = this._svg, markType2 = scene.marktype, mdef = Marks[markType2], events3 = scene.interactive === false ? "none" : null, isGroup = mdef.tag === "g";
      const parent = bind(scene, el, prev, "g", svg);
      if (markType2 !== "group" && markTypes != null && !markTypes.includes(markType2)) {
        domClear(parent, 0);
        return scene._svg;
      }
      parent.setAttribute("class", cssClass(scene));
      const aria2 = ariaMarkAttributes(scene);
      for (const key2 in aria2) setAttribute(parent, key2, aria2[key2]);
      if (!isGroup) {
        setAttribute(parent, "pointer-events", events3);
      }
      setAttribute(parent, "clip-path", scene.clip ? clip$1(this, scene, scene.group) : null);
      let sibling = null, i2 = 0;
      const process2 = (item) => {
        const dirty = this.isDirty(item), node = bind(item, parent, sibling, mdef.tag, svg);
        if (dirty) {
          this._update(mdef, node, item);
          if (isGroup) recurse(this, node, item, markTypes);
        }
        sibling = node;
        ++i2;
      };
      if (mdef.nested) {
        if (scene.items.length) process2(scene.items[0]);
      } else {
        visit(scene, process2);
      }
      domClear(parent, i2);
      return parent;
    }
    /**
     * Update the attributes of an SVG element for a mark item.
     * @param {object} mdef - The mark definition object
     * @param {SVGElement} el - The SVG element.
     * @param {Item} item - The mark item.
     */
    _update(mdef, el, item) {
      element = el;
      values = el.__values__;
      ariaItemAttributes(emit, item);
      mdef.attr(emit, item, this);
      const extra = mark_extras[mdef.type];
      if (extra) extra.call(this, mdef, el, item);
      if (element) this.style(element, item);
    }
    /**
     * Update the presentation attributes of an SVG element for a mark item.
     * @param {SVGElement} el - The SVG element.
     * @param {Item} item - The mark item.
     */
    style(el, item) {
      if (item == null) return;
      for (const prop in stylesAttr) {
        let value3 = prop === "font" ? fontFamily(item) : item[prop];
        if (value3 === values[prop]) continue;
        const name4 = stylesAttr[prop];
        if (value3 == null) {
          el.removeAttribute(name4);
        } else {
          if (isGradient(value3)) {
            value3 = gradientRef(value3, this._defs.gradient, href());
          }
          el.setAttribute(name4, value3 + "");
        }
        values[prop] = value3;
      }
      for (const prop in stylesCss) {
        setStyle(el, stylesCss[prop], item[prop]);
      }
    }
    /**
     * Render SVG defs, as needed.
     * Must be called *after* marks have been processed to ensure the
     * collected state is current and accurate.
     */
    defs() {
      const svg = this._svg, defs = this._defs;
      let el = defs.el, index4 = 0;
      for (const id2 in defs.gradient) {
        if (!el) defs.el = el = domChild(svg, RootIndex + 1, "defs", svgns);
        index4 = updateGradient(el, defs.gradient[id2], index4);
      }
      for (const id2 in defs.clipping) {
        if (!el) defs.el = el = domChild(svg, RootIndex + 1, "defs", svgns);
        index4 = updateClipping(el, defs.clipping[id2], index4);
      }
      if (el) {
        index4 === 0 ? (svg.removeChild(el), defs.el = null) : domClear(el, index4);
      }
    }
    /**
     * Clear defs caches.
     */
    _clearDefs() {
      const def2 = this._defs;
      def2.gradient = {};
      def2.clipping = {};
    }
  };
  function dirtyParents(item, id2) {
    for (; item && item.dirty !== id2; item = item.mark.group) {
      item.dirty = id2;
      if (item.mark && item.mark.dirty !== id2) {
        item.mark.dirty = id2;
      } else return;
    }
  }
  function updateGradient(el, grad, index4) {
    let i2, n2, stop2;
    if (grad.gradient === "radial") {
      let pt = domChild(el, index4++, "pattern", svgns);
      setAttributes(pt, {
        id: patternPrefix + grad.id,
        viewBox: "0,0,1,1",
        width: "100%",
        height: "100%",
        preserveAspectRatio: "xMidYMid slice"
      });
      pt = domChild(pt, 0, "rect", svgns);
      setAttributes(pt, {
        width: 1,
        height: 1,
        fill: `url(${href()}#${grad.id})`
      });
      el = domChild(el, index4++, "radialGradient", svgns);
      setAttributes(el, {
        id: grad.id,
        fx: grad.x1,
        fy: grad.y1,
        fr: grad.r1,
        cx: grad.x2,
        cy: grad.y2,
        r: grad.r2
      });
    } else {
      el = domChild(el, index4++, "linearGradient", svgns);
      setAttributes(el, {
        id: grad.id,
        x1: grad.x1,
        x2: grad.x2,
        y1: grad.y1,
        y2: grad.y2
      });
    }
    for (i2 = 0, n2 = grad.stops.length; i2 < n2; ++i2) {
      stop2 = domChild(el, i2, "stop", svgns);
      stop2.setAttribute("offset", grad.stops[i2].offset);
      stop2.setAttribute("stop-color", grad.stops[i2].color);
    }
    domClear(el, i2);
    return index4;
  }
  function updateClipping(el, clip3, index4) {
    let mask;
    el = domChild(el, index4, "clipPath", svgns);
    el.setAttribute("id", clip3.id);
    if (clip3.path) {
      mask = domChild(el, 0, "path", svgns);
      mask.setAttribute("d", clip3.path);
    } else {
      mask = domChild(el, 0, "rect", svgns);
      setAttributes(mask, {
        x: 0,
        y: 0,
        width: clip3.width,
        height: clip3.height
      });
    }
    domClear(el, 1);
    return index4 + 1;
  }
  function recurse(renderer, el, group2, markTypes) {
    el = el.lastChild.previousSibling;
    let prev, idx = 0;
    visit(group2, (item) => {
      prev = renderer.mark(el, item, prev, markTypes);
      ++idx;
    });
    domClear(el, 1 + idx);
  }
  function bind(item, el, sibling, tag, svg) {
    let node = item._svg, doc;
    if (!node) {
      doc = el.ownerDocument;
      node = domCreate(doc, tag, svgns);
      item._svg = node;
      if (item.mark) {
        node.__data__ = item;
        node.__values__ = {
          fill: "default"
        };
        if (tag === "g") {
          const bg = domCreate(doc, "path", svgns);
          node.appendChild(bg);
          bg.__data__ = item;
          const cg = domCreate(doc, "g", svgns);
          node.appendChild(cg);
          cg.__data__ = item;
          const fg = domCreate(doc, "path", svgns);
          node.appendChild(fg);
          fg.__data__ = item;
          fg.__values__ = {
            fill: "default"
          };
        }
      }
    }
    if (node.ownerSVGElement !== svg || siblingCheck(node, sibling)) {
      el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild);
    }
    return node;
  }
  function siblingCheck(node, sibling) {
    return node.parentNode && node.parentNode.childNodes.length > 1 && node.previousSibling != sibling;
  }
  var element = null;
  var values = null;
  var mark_extras = {
    group(mdef, el, item) {
      const fg = element = el.childNodes[2];
      values = fg.__values__;
      mdef.foreground(emit, item, this);
      values = el.__values__;
      element = el.childNodes[1];
      mdef.content(emit, item, this);
      const bg = element = el.childNodes[0];
      mdef.background(emit, item, this);
      const value3 = item.mark.interactive === false ? "none" : null;
      if (value3 !== values.events) {
        setAttribute(fg, "pointer-events", value3);
        setAttribute(bg, "pointer-events", value3);
        values.events = value3;
      }
      if (item.strokeForeground && item.stroke) {
        const fill2 = item.fill;
        setAttribute(fg, "display", null);
        this.style(bg, item);
        setAttribute(bg, "stroke", null);
        if (fill2) item.fill = null;
        values = fg.__values__;
        this.style(fg, item);
        if (fill2) item.fill = fill2;
        element = null;
      } else {
        setAttribute(fg, "display", "none");
      }
    },
    image(mdef, el, item) {
      if (item.smooth === false) {
        setStyle(el, "image-rendering", "optimizeSpeed");
        setStyle(el, "image-rendering", "pixelated");
      } else {
        setStyle(el, "image-rendering", null);
      }
    },
    text(mdef, el, item) {
      const tl2 = textLines(item);
      let key2, value3, doc, lh;
      if (isArray(tl2)) {
        value3 = tl2.map((_) => textValue(item, _));
        key2 = value3.join("\n");
        if (key2 !== values.text) {
          domClear(el, 0);
          doc = el.ownerDocument;
          lh = lineHeight(item);
          value3.forEach((t4, i2) => {
            const ts2 = domCreate(doc, "tspan", svgns);
            ts2.__data__ = item;
            ts2.textContent = t4;
            if (i2) {
              ts2.setAttribute("x", 0);
              ts2.setAttribute("dy", lh);
            }
            el.appendChild(ts2);
          });
          values.text = key2;
        }
      } else {
        value3 = textValue(item, tl2);
        if (value3 !== values.text) {
          el.textContent = value3;
          values.text = value3;
        }
      }
      setAttribute(el, "font-family", fontFamily(item));
      setAttribute(el, "font-size", fontSize(item) + "px");
      setAttribute(el, "font-style", item.fontStyle);
      setAttribute(el, "font-variant", item.fontVariant);
      setAttribute(el, "font-weight", item.fontWeight);
    }
  };
  function emit(name4, value3, ns) {
    if (value3 === values[name4]) return;
    if (ns) {
      setAttributeNS(element, name4, value3, ns);
    } else {
      setAttribute(element, name4, value3);
    }
    values[name4] = value3;
  }
  function setStyle(el, name4, value3) {
    if (value3 !== values[name4]) {
      if (value3 == null) {
        el.style.removeProperty(name4);
      } else {
        el.style.setProperty(name4, value3 + "");
      }
      values[name4] = value3;
    }
  }
  function setAttributes(el, attrs) {
    for (const key2 in attrs) {
      setAttribute(el, key2, attrs[key2]);
    }
  }
  function setAttribute(el, name4, value3) {
    if (value3 != null) {
      el.setAttribute(name4, value3);
    } else {
      el.removeAttribute(name4);
    }
  }
  function setAttributeNS(el, name4, value3, ns) {
    if (value3 != null) {
      el.setAttributeNS(ns, name4, value3);
    } else {
      el.removeAttributeNS(ns, name4);
    }
  }
  function href() {
    let loc;
    return typeof window === "undefined" ? "" : (loc = window.location).hash ? loc.href.slice(0, -loc.hash.length) : loc.href;
  }
  var SVGStringRenderer = class extends Renderer {
    constructor(loader2) {
      super(loader2);
      this._text = null;
      this._defs = {
        gradient: {},
        clipping: {}
      };
    }
    /**
     * Returns the rendered SVG text string,
     * or null if rendering has not yet occurred.
     */
    svg() {
      return this._text;
    }
    /**
     * Internal rendering method.
     * @param {object} scene - The root mark of a scenegraph to render.
     */
    _render(scene) {
      const m4 = markup();
      m4.open("svg", extend({}, metadata, {
        class: "marks",
        width: this._width * this._scale,
        height: this._height * this._scale,
        viewBox: `0 0 ${this._width} ${this._height}`
      }));
      const bg = this._bgcolor;
      if (bg && bg !== "transparent" && bg !== "none") {
        m4.open("rect", {
          width: this._width,
          height: this._height,
          fill: bg
        }).close();
      }
      m4.open("g", rootAttributes, {
        transform: "translate(" + this._origin + ")"
      });
      this.mark(m4, scene);
      m4.close();
      this.defs(m4);
      this._text = m4.close() + "";
      return this;
    }
    /**
     * Render a set of mark items.
     * @param {object} m - The markup context.
     * @param {object} scene - The mark parent to render.
     */
    mark(m4, scene) {
      const mdef = Marks[scene.marktype], tag = mdef.tag, attrList = [ariaItemAttributes, mdef.attr];
      m4.open("g", {
        "class": cssClass(scene),
        "clip-path": scene.clip ? clip$1(this, scene, scene.group) : null
      }, ariaMarkAttributes(scene), {
        "pointer-events": tag !== "g" && scene.interactive === false ? "none" : null
      });
      const process2 = (item) => {
        const href2 = this.href(item);
        if (href2) m4.open("a", href2);
        m4.open(tag, this.attr(scene, item, attrList, tag !== "g" ? tag : null));
        if (tag === "text") {
          const tl2 = textLines(item);
          if (isArray(tl2)) {
            const attrs = {
              x: 0,
              dy: lineHeight(item)
            };
            for (let i2 = 0; i2 < tl2.length; ++i2) {
              m4.open("tspan", i2 ? attrs : null).text(textValue(item, tl2[i2])).close();
            }
          } else {
            m4.text(textValue(item, tl2));
          }
        } else if (tag === "g") {
          const fore = item.strokeForeground, fill2 = item.fill, stroke2 = item.stroke;
          if (fore && stroke2) {
            item.stroke = null;
          }
          m4.open("path", this.attr(scene, item, mdef.background, "bgrect")).close();
          m4.open("g", this.attr(scene, item, mdef.content));
          visit(item, (scene2) => this.mark(m4, scene2));
          m4.close();
          if (fore && stroke2) {
            if (fill2) item.fill = null;
            item.stroke = stroke2;
            m4.open("path", this.attr(scene, item, mdef.foreground, "bgrect")).close();
            if (fill2) item.fill = fill2;
          } else {
            m4.open("path", this.attr(scene, item, mdef.foreground, "bgfore")).close();
          }
        }
        m4.close();
        if (href2) m4.close();
      };
      if (mdef.nested) {
        if (scene.items && scene.items.length) process2(scene.items[0]);
      } else {
        visit(scene, process2);
      }
      return m4.close();
    }
    /**
     * Get href attributes for a hyperlinked mark item.
     * @param {Item} item - The mark item.
     */
    href(item) {
      const href2 = item.href;
      let attr2;
      if (href2) {
        if (attr2 = this._hrefs && this._hrefs[href2]) {
          return attr2;
        } else {
          this.sanitizeURL(href2).then((attr3) => {
            attr3["xlink:href"] = attr3.href;
            attr3.href = null;
            (this._hrefs || (this._hrefs = {}))[href2] = attr3;
          });
        }
      }
      return null;
    }
    /**
     * Get an object of SVG attributes for a mark item.
     * @param {object} scene - The mark parent.
     * @param {Item} item - The mark item.
     * @param {array|function} attrs - One or more attribute emitters.
     * @param {string} tag - The tag being rendered.
     */
    attr(scene, item, attrs, tag) {
      const object2 = {}, emit2 = (name4, value3, ns, prefixed) => {
        object2[prefixed || name4] = value3;
      };
      if (Array.isArray(attrs)) {
        attrs.forEach((fn) => fn(emit2, item, this));
      } else {
        attrs(emit2, item, this);
      }
      if (tag) {
        style(object2, item, scene, tag, this._defs);
      }
      return object2;
    }
    /**
     * Render SVG defs, as needed.
     * Must be called *after* marks have been processed to ensure the
     * collected state is current and accurate.
     * @param {object} m - The markup context.
     */
    defs(m4) {
      const gradient4 = this._defs.gradient, clipping = this._defs.clipping, count2 = Object.keys(gradient4).length + Object.keys(clipping).length;
      if (count2 === 0) return;
      m4.open("defs");
      for (const id2 in gradient4) {
        const def2 = gradient4[id2], stops = def2.stops;
        if (def2.gradient === "radial") {
          m4.open("pattern", {
            id: patternPrefix + id2,
            viewBox: "0,0,1,1",
            width: "100%",
            height: "100%",
            preserveAspectRatio: "xMidYMid slice"
          });
          m4.open("rect", {
            width: "1",
            height: "1",
            fill: "url(#" + id2 + ")"
          }).close();
          m4.close();
          m4.open("radialGradient", {
            id: id2,
            fx: def2.x1,
            fy: def2.y1,
            fr: def2.r1,
            cx: def2.x2,
            cy: def2.y2,
            r: def2.r2
          });
        } else {
          m4.open("linearGradient", {
            id: id2,
            x1: def2.x1,
            x2: def2.x2,
            y1: def2.y1,
            y2: def2.y2
          });
        }
        for (let i2 = 0; i2 < stops.length; ++i2) {
          m4.open("stop", {
            offset: stops[i2].offset,
            "stop-color": stops[i2].color
          }).close();
        }
        m4.close();
      }
      for (const id2 in clipping) {
        const def2 = clipping[id2];
        m4.open("clipPath", {
          id: id2
        });
        if (def2.path) {
          m4.open("path", {
            d: def2.path
          }).close();
        } else {
          m4.open("rect", {
            x: 0,
            y: 0,
            width: def2.width,
            height: def2.height
          }).close();
        }
        m4.close();
      }
      m4.close();
    }
  };
  function style(s2, item, scene, tag, defs) {
    let styleList;
    if (item == null) return s2;
    if (tag === "bgrect" && scene.interactive === false) {
      s2["pointer-events"] = "none";
    }
    if (tag === "bgfore") {
      if (scene.interactive === false) {
        s2["pointer-events"] = "none";
      }
      s2.display = "none";
      if (item.fill !== null) return s2;
    }
    if (tag === "image" && item.smooth === false) {
      styleList = ["image-rendering: optimizeSpeed;", "image-rendering: pixelated;"];
    }
    if (tag === "text") {
      s2["font-family"] = fontFamily(item);
      s2["font-size"] = fontSize(item) + "px";
      s2["font-style"] = item.fontStyle;
      s2["font-variant"] = item.fontVariant;
      s2["font-weight"] = item.fontWeight;
    }
    for (const prop in stylesAttr) {
      let value3 = item[prop];
      const name4 = stylesAttr[prop];
      if (value3 === "transparent" && (name4 === "fill" || name4 === "stroke")) ;
      else if (value3 != null) {
        if (isGradient(value3)) {
          value3 = gradientRef(value3, defs.gradient, "");
        }
        s2[name4] = value3;
      }
    }
    for (const prop in stylesCss) {
      const value3 = item[prop];
      if (value3 != null) {
        styleList = styleList || [];
        styleList.push(`${stylesCss[prop]}: ${value3};`);
      }
    }
    if (styleList) {
      s2.style = styleList.join(" ");
    }
    return s2;
  }
  var OPTS = {
    svgMarkTypes: ["text"],
    svgOnTop: true,
    debug: false
  };
  function setHybridRendererOptions(options) {
    OPTS["svgMarkTypes"] = options.svgMarkTypes ?? ["text"];
    OPTS["svgOnTop"] = options.svgOnTop ?? true;
    OPTS["debug"] = options.debug ?? false;
  }
  var HybridRenderer = class extends Renderer {
    constructor(loader2) {
      super(loader2);
      this._svgRenderer = new SVGRenderer(loader2);
      this._canvasRenderer = new CanvasRenderer(loader2);
    }
    /**
     * Initialize a new HybridRenderer instance.
     * @param {DOMElement} el - The containing DOM element for the display.
     * @param {number} width - The coordinate width of the display, in pixels.
     * @param {number} height - The coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {HybridRenderer} - This renderer instance.
     */
    initialize(el, width2, height2, origin, scaleFactor) {
      this._root_el = domChild(el, 0, "div");
      const bottomEl = domChild(this._root_el, 0, "div");
      const topEl = domChild(this._root_el, 1, "div");
      this._root_el.style.position = "relative";
      if (!OPTS.debug) {
        bottomEl.style.height = "100%";
        topEl.style.position = "absolute";
        topEl.style.top = "0";
        topEl.style.left = "0";
        topEl.style.height = "100%";
        topEl.style.width = "100%";
      }
      this._svgEl = OPTS.svgOnTop ? topEl : bottomEl;
      this._canvasEl = OPTS.svgOnTop ? bottomEl : topEl;
      this._svgEl.style.pointerEvents = "none";
      this._canvasRenderer.initialize(this._canvasEl, width2, height2, origin, scaleFactor);
      this._svgRenderer.initialize(this._svgEl, width2, height2, origin, scaleFactor);
      return super.initialize(el, width2, height2, origin, scaleFactor);
    }
    /**
     * Flag a mark item as dirty.
     * @param {Item} item - The mark item.
     */
    dirty(item) {
      if (OPTS.svgMarkTypes.includes(item.mark.marktype)) {
        this._svgRenderer.dirty(item);
      } else {
        this._canvasRenderer.dirty(item);
      }
      return this;
    }
    /**
     * Internal rendering method.
     * @param {object} scene - The root mark of a scenegraph to render.
     * @param {Array} markTypes - Array of the mark types to render.
     *                            If undefined, render all mark types
     */
    _render(scene, markTypes) {
      const allMarkTypes = markTypes ?? ["arc", "area", "image", "line", "path", "rect", "rule", "shape", "symbol", "text", "trail"];
      const canvasMarkTypes = allMarkTypes.filter((m4) => !OPTS.svgMarkTypes.includes(m4));
      this._svgRenderer.render(scene, OPTS.svgMarkTypes);
      this._canvasRenderer.render(scene, canvasMarkTypes);
    }
    /**
     * Resize the display.
     * @param {number} width - The new coordinate width of the display, in pixels.
     * @param {number} height - The new coordinate height of the display, in pixels.
     * @param {Array<number>} origin - The new origin of the display, in pixels.
     *   The coordinate system will be translated to this point.
     * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply
     *   the width and height to determine the final pixel size.
     * @return {SVGRenderer} - This renderer instance;
     */
    resize(width2, height2, origin, scaleFactor) {
      super.resize(width2, height2, origin, scaleFactor);
      this._svgRenderer.resize(width2, height2, origin, scaleFactor);
      this._canvasRenderer.resize(width2, height2, origin, scaleFactor);
      return this;
    }
    background(bgcolor) {
      if (OPTS.svgOnTop) {
        this._canvasRenderer.background(bgcolor);
      } else {
        this._svgRenderer.background(bgcolor);
      }
      return this;
    }
  };
  var HybridHandler = class extends CanvasHandler {
    constructor(loader2, tooltip2) {
      super(loader2, tooltip2);
    }
    initialize(el, origin, obj) {
      const canvas = domChild(domChild(el, 0, "div"), OPTS.svgOnTop ? 0 : 1, "div");
      return super.initialize(canvas, origin, obj);
    }
  };
  var Canvas = "canvas";
  var Hybrid = "hybrid";
  var PNG = "png";
  var SVG = "svg";
  var None2 = "none";
  var RenderType = {
    Canvas,
    PNG,
    SVG,
    Hybrid,
    None: None2
  };
  var modules = {};
  modules[Canvas] = modules[PNG] = {
    renderer: CanvasRenderer,
    headless: CanvasRenderer,
    handler: CanvasHandler
  };
  modules[SVG] = {
    renderer: SVGRenderer,
    headless: SVGStringRenderer,
    handler: SVGHandler
  };
  modules[Hybrid] = {
    renderer: HybridRenderer,
    headless: HybridRenderer,
    handler: HybridHandler
  };
  modules[None2] = {};
  function renderModule(name4, _) {
    name4 = String(name4 || "").toLowerCase();
    if (arguments.length > 1) {
      modules[name4] = _;
      return this;
    } else {
      return modules[name4];
    }
  }
  function intersect2(scene, bounds2, filter3) {
    const hits = [], box = new Bounds().union(bounds2), type3 = scene.marktype;
    return type3 ? intersectMark(scene, box, filter3, hits) : type3 === "group" ? intersectGroup(scene, box, filter3, hits) : error("Intersect scene must be mark node or group item.");
  }
  function intersectMark(mark, box, filter3, hits) {
    if (visitMark(mark, box, filter3)) {
      const items = mark.items, type3 = mark.marktype, n2 = items.length;
      let i2 = 0;
      if (type3 === "group") {
        for (; i2 < n2; ++i2) {
          intersectGroup(items[i2], box, filter3, hits);
        }
      } else {
        for (const test2 = Marks[type3].isect; i2 < n2; ++i2) {
          const item = items[i2];
          if (intersectItem(item, box, test2)) hits.push(item);
        }
      }
    }
    return hits;
  }
  function visitMark(mark, box, filter3) {
    return mark.bounds && box.intersects(mark.bounds) && (mark.marktype === "group" || mark.interactive !== false && (!filter3 || filter3(mark)));
  }
  function intersectGroup(group2, box, filter3, hits) {
    if (filter3 && filter3(group2.mark) && intersectItem(group2, box, Marks.group.isect)) {
      hits.push(group2);
    }
    const marks = group2.items, n2 = marks && marks.length;
    if (n2) {
      const x5 = group2.x || 0, y5 = group2.y || 0;
      box.translate(-x5, -y5);
      for (let i2 = 0; i2 < n2; ++i2) {
        intersectMark(marks[i2], box, filter3, hits);
      }
      box.translate(x5, y5);
    }
    return hits;
  }
  function intersectItem(item, box, test2) {
    const bounds2 = item.bounds;
    return box.encloses(bounds2) || box.intersects(bounds2) && test2(item, box);
  }
  var clipBounds = new Bounds();
  function boundClip(mark) {
    const clip3 = mark.clip;
    if (isFunction(clip3)) {
      clip3(boundContext(clipBounds.clear()));
    } else if (clip3) {
      clipBounds.set(0, 0, mark.group.width, mark.group.height);
    } else return;
    mark.bounds.intersect(clipBounds);
  }
  var TOLERANCE = 1e-9;
  function sceneEqual(a4, b3, key2) {
    return a4 === b3 ? true : key2 === "path" ? pathEqual(a4, b3) : a4 instanceof Date && b3 instanceof Date ? +a4 === +b3 : isNumber(a4) && isNumber(b3) ? Math.abs(a4 - b3) <= TOLERANCE : !a4 || !b3 || !isObject(a4) && !isObject(b3) ? a4 == b3 : objectEqual(a4, b3);
  }
  function pathEqual(a4, b3) {
    return sceneEqual(parse4(a4), parse4(b3));
  }
  function objectEqual(a4, b3) {
    var ka = Object.keys(a4), kb = Object.keys(b3), key2, i2;
    if (ka.length !== kb.length) return false;
    ka.sort();
    kb.sort();
    for (i2 = ka.length - 1; i2 >= 0; i2--) {
      if (ka[i2] != kb[i2]) return false;
    }
    for (i2 = ka.length - 1; i2 >= 0; i2--) {
      key2 = ka[i2];
      if (!sceneEqual(a4[key2], b3[key2], key2)) return false;
    }
    return typeof a4 === typeof b3;
  }
  function resetSVGDefIds() {
    resetSVGClipId();
    resetSVGGradientId();
  }

  // node_modules/vega-view-transforms/build/vega-view-transforms.module.js
  var Top = "top";
  var Left = "left";
  var Right = "right";
  var Bottom = "bottom";
  var TopLeft = "top-left";
  var TopRight = "top-right";
  var BottomLeft = "bottom-left";
  var BottomRight = "bottom-right";
  var Start = "start";
  var Middle = "middle";
  var End = "end";
  var X = "x";
  var Y = "y";
  var Group = "group";
  var AxisRole = "axis";
  var TitleRole = "title";
  var FrameRole = "frame";
  var ScopeRole = "scope";
  var LegendRole = "legend";
  var RowHeader = "row-header";
  var RowFooter = "row-footer";
  var RowTitle = "row-title";
  var ColHeader = "column-header";
  var ColFooter = "column-footer";
  var ColTitle = "column-title";
  var Padding = "padding";
  var Symbols = "symbol";
  var Fit = "fit";
  var FitX = "fit-x";
  var FitY = "fit-y";
  var Pad = "pad";
  var None3 = "none";
  var All = "all";
  var Each = "each";
  var Flush = "flush";
  var Column = "column";
  var Row = "row";
  function Bound(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Bound, Transform, {
    transform(_, pulse2) {
      const view = pulse2.dataflow, mark = _.mark, type3 = mark.marktype, entry2 = Marks[type3], bound2 = entry2.bound;
      let markBounds = mark.bounds, rebound;
      if (entry2.nested) {
        if (mark.items.length) view.dirty(mark.items[0]);
        markBounds = boundItem2(mark, bound2);
        mark.items.forEach((item) => {
          item.bounds.clear().union(markBounds);
        });
      } else if (type3 === Group || _.modified()) {
        pulse2.visit(pulse2.MOD, (item) => view.dirty(item));
        markBounds.clear();
        mark.items.forEach((item) => markBounds.union(boundItem2(item, bound2)));
        switch (mark.role) {
          case AxisRole:
          case LegendRole:
          case TitleRole:
            pulse2.reflow();
        }
      } else {
        rebound = pulse2.changed(pulse2.REM);
        pulse2.visit(pulse2.ADD, (item) => {
          markBounds.union(boundItem2(item, bound2));
        });
        pulse2.visit(pulse2.MOD, (item) => {
          rebound = rebound || markBounds.alignsWith(item.bounds);
          view.dirty(item);
          markBounds.union(boundItem2(item, bound2));
        });
        if (rebound) {
          markBounds.clear();
          mark.items.forEach((item) => markBounds.union(item.bounds));
        }
      }
      boundClip(mark);
      return pulse2.modifies("bounds");
    }
  });
  function boundItem2(item, bound2, opt) {
    return bound2(item.bounds.clear(), item, opt);
  }
  var COUNTER_NAME = ":vega_identifier:";
  function Identifier(params2) {
    Transform.call(this, 0, params2);
  }
  Identifier.Definition = {
    "type": "Identifier",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "as",
      "type": "string",
      "required": true
    }]
  };
  inherits(Identifier, Transform, {
    transform(_, pulse2) {
      const counter = getCounter(pulse2.dataflow), as = _.as;
      let id2 = counter.value;
      pulse2.visit(pulse2.ADD, (t4) => t4[as] = t4[as] || ++id2);
      counter.set(this.value = id2);
      return pulse2;
    }
  });
  function getCounter(view) {
    return view._signals[COUNTER_NAME] || (view._signals[COUNTER_NAME] = view.add(0));
  }
  function Mark(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Mark, Transform, {
    transform(_, pulse2) {
      let mark = this.value;
      if (!mark) {
        mark = pulse2.dataflow.scenegraph().mark(_.markdef, lookup$1(_), _.index);
        mark.group.context = _.context;
        if (!_.context.group) _.context.group = mark.group;
        mark.source = this.source;
        mark.clip = _.clip;
        mark.interactive = _.interactive;
        this.value = mark;
      }
      const Init = mark.marktype === Group ? GroupItem : Item;
      pulse2.visit(pulse2.ADD, (item) => Init.call(item, mark));
      if (_.modified("clip") || _.modified("interactive")) {
        mark.clip = _.clip;
        mark.interactive = !!_.interactive;
        mark.zdirty = true;
        pulse2.reflow();
      }
      mark.items = pulse2.source;
      return pulse2;
    }
  });
  function lookup$1(_) {
    const g2 = _.groups, p2 = _.parent;
    return g2 && g2.size === 1 ? g2.get(Object.keys(g2.object)[0]) : g2 && p2 ? g2.lookup(p2) : null;
  }
  function Overlap(params2) {
    Transform.call(this, null, params2);
  }
  var methods = {
    parity: (items) => items.filter((item, i2) => i2 % 2 ? item.opacity = 0 : 1),
    greedy: (items, sep) => {
      let a4;
      return items.filter((b3, i2) => !i2 || !intersect3(a4.bounds, b3.bounds, sep) ? (a4 = b3, 1) : b3.opacity = 0);
    }
  };
  var intersect3 = (a4, b3, sep) => sep > Math.max(b3.x1 - a4.x2, a4.x1 - b3.x2, b3.y1 - a4.y2, a4.y1 - b3.y2);
  var hasOverlap = (items, pad4) => {
    for (var i2 = 1, n2 = items.length, a4 = items[0].bounds, b3; i2 < n2; a4 = b3, ++i2) {
      if (intersect3(a4, b3 = items[i2].bounds, pad4)) return true;
    }
  };
  var hasBounds = (item) => {
    const b3 = item.bounds;
    return b3.width() > 1 && b3.height() > 1;
  };
  var boundTest = (scale7, orient2, tolerance) => {
    var range7 = scale7.range(), b3 = new Bounds();
    if (orient2 === Top || orient2 === Bottom) {
      b3.set(range7[0], -Infinity, range7[1], Infinity);
    } else {
      b3.set(-Infinity, range7[0], Infinity, range7[1]);
    }
    b3.expand(tolerance || 1);
    return (item) => b3.encloses(item.bounds);
  };
  var reset = (source4) => {
    source4.forEach((item) => item.opacity = 1);
    return source4;
  };
  var reflow = (pulse2, _) => pulse2.reflow(_.modified()).modifies("opacity");
  inherits(Overlap, Transform, {
    transform(_, pulse2) {
      const reduce2 = methods[_.method] || methods.parity, sep = _.separation || 0;
      let source4 = pulse2.materialize(pulse2.SOURCE).source, items, test2;
      if (!source4 || !source4.length) return;
      if (!_.method) {
        if (_.modified("method")) {
          reset(source4);
          pulse2 = reflow(pulse2, _);
        }
        return pulse2;
      }
      source4 = source4.filter(hasBounds);
      if (!source4.length) return;
      if (_.sort) {
        source4 = source4.slice().sort(_.sort);
      }
      items = reset(source4);
      pulse2 = reflow(pulse2, _);
      if (items.length >= 3 && hasOverlap(items, sep)) {
        do {
          items = reduce2(items, sep);
        } while (items.length >= 3 && hasOverlap(items, sep));
        if (items.length < 3 && !peek(source4).opacity) {
          if (items.length > 1) peek(items).opacity = 0;
          peek(source4).opacity = 1;
        }
      }
      if (_.boundScale && _.boundTolerance >= 0) {
        test2 = boundTest(_.boundScale, _.boundOrient, +_.boundTolerance);
        source4.forEach((item) => {
          if (!test2(item)) item.opacity = 0;
        });
      }
      const bounds2 = items[0].mark.bounds.clear();
      source4.forEach((item) => {
        if (item.opacity) bounds2.union(item.bounds);
      });
      return pulse2;
    }
  });
  function Render(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Render, Transform, {
    transform(_, pulse2) {
      const view = pulse2.dataflow;
      pulse2.visit(pulse2.ALL, (item) => view.dirty(item));
      if (pulse2.fields && pulse2.fields["zindex"]) {
        const item = pulse2.source && pulse2.source[0];
        if (item) item.mark.zdirty = true;
      }
    }
  });
  var tempBounds2 = new Bounds();
  function set3(item, property2, value3) {
    return item[property2] === value3 ? 0 : (item[property2] = value3, 1);
  }
  function isYAxis(mark) {
    var orient2 = mark.items[0].orient;
    return orient2 === Left || orient2 === Right;
  }
  function axisIndices(datum2) {
    let index4 = +datum2.grid;
    return [
      datum2.ticks ? index4++ : -1,
      // ticks index
      datum2.labels ? index4++ : -1,
      // labels index
      index4 + +datum2.domain
      // title index
    ];
  }
  function axisLayout(view, axis, width2, height2) {
    var item = axis.items[0], datum2 = item.datum, delta = item.translate != null ? item.translate : 0.5, orient2 = item.orient, indices = axisIndices(datum2), range7 = item.range, offset4 = item.offset, position2 = item.position, minExtent = item.minExtent, maxExtent = item.maxExtent, title2 = datum2.title && item.items[indices[2]].items[0], titlePadding = item.titlePadding, bounds2 = item.bounds, dl = title2 && multiLineOffset(title2), x5 = 0, y5 = 0, i2, s2;
    tempBounds2.clear().union(bounds2);
    bounds2.clear();
    if ((i2 = indices[0]) > -1) bounds2.union(item.items[i2].bounds);
    if ((i2 = indices[1]) > -1) bounds2.union(item.items[i2].bounds);
    switch (orient2) {
      case Top:
        x5 = position2 || 0;
        y5 = -offset4;
        s2 = Math.max(minExtent, Math.min(maxExtent, -bounds2.y1));
        bounds2.add(0, -s2).add(range7, 0);
        if (title2) axisTitleLayout(view, title2, s2, titlePadding, dl, 0, -1, bounds2);
        break;
      case Left:
        x5 = -offset4;
        y5 = position2 || 0;
        s2 = Math.max(minExtent, Math.min(maxExtent, -bounds2.x1));
        bounds2.add(-s2, 0).add(0, range7);
        if (title2) axisTitleLayout(view, title2, s2, titlePadding, dl, 1, -1, bounds2);
        break;
      case Right:
        x5 = width2 + offset4;
        y5 = position2 || 0;
        s2 = Math.max(minExtent, Math.min(maxExtent, bounds2.x2));
        bounds2.add(0, 0).add(s2, range7);
        if (title2) axisTitleLayout(view, title2, s2, titlePadding, dl, 1, 1, bounds2);
        break;
      case Bottom:
        x5 = position2 || 0;
        y5 = height2 + offset4;
        s2 = Math.max(minExtent, Math.min(maxExtent, bounds2.y2));
        bounds2.add(0, 0).add(range7, s2);
        if (title2) axisTitleLayout(view, title2, s2, titlePadding, 0, 0, 1, bounds2);
        break;
      default:
        x5 = item.x;
        y5 = item.y;
    }
    boundStroke(bounds2.translate(x5, y5), item);
    if (set3(item, "x", x5 + delta) | set3(item, "y", y5 + delta)) {
      item.bounds = tempBounds2;
      view.dirty(item);
      item.bounds = bounds2;
      view.dirty(item);
    }
    return item.mark.bounds.clear().union(bounds2);
  }
  function axisTitleLayout(view, title2, offset4, pad4, dl, isYAxis2, sign3, bounds2) {
    const b3 = title2.bounds;
    if (title2.auto) {
      const v3 = sign3 * (offset4 + dl + pad4);
      let dx = 0, dy = 0;
      view.dirty(title2);
      isYAxis2 ? dx = (title2.x || 0) - (title2.x = v3) : dy = (title2.y || 0) - (title2.y = v3);
      title2.mark.bounds.clear().union(b3.translate(-dx, -dy));
      view.dirty(title2);
    }
    bounds2.union(b3);
  }
  var min3 = (a4, b3) => Math.floor(Math.min(a4, b3));
  var max3 = (a4, b3) => Math.ceil(Math.max(a4, b3));
  function gridLayoutGroups(group2) {
    var groups = group2.items, n2 = groups.length, i2 = 0, mark, items;
    const views = {
      marks: [],
      rowheaders: [],
      rowfooters: [],
      colheaders: [],
      colfooters: [],
      rowtitle: null,
      coltitle: null
    };
    for (; i2 < n2; ++i2) {
      mark = groups[i2];
      items = mark.items;
      if (mark.marktype === Group) {
        switch (mark.role) {
          case AxisRole:
          case LegendRole:
          case TitleRole:
            break;
          case RowHeader:
            views.rowheaders.push(...items);
            break;
          case RowFooter:
            views.rowfooters.push(...items);
            break;
          case ColHeader:
            views.colheaders.push(...items);
            break;
          case ColFooter:
            views.colfooters.push(...items);
            break;
          case RowTitle:
            views.rowtitle = items[0];
            break;
          case ColTitle:
            views.coltitle = items[0];
            break;
          default:
            views.marks.push(...items);
        }
      }
    }
    return views;
  }
  function bboxFlush(item) {
    return new Bounds().set(0, 0, item.width || 0, item.height || 0);
  }
  function bboxFull(item) {
    const b3 = item.bounds.clone();
    return b3.empty() ? b3.set(0, 0, 0, 0) : b3.translate(-(item.x || 0), -(item.y || 0));
  }
  function get4(opt, key2, d2) {
    const v3 = isObject(opt) ? opt[key2] : opt;
    return v3 != null ? v3 : d2 !== void 0 ? d2 : 0;
  }
  function offsetValue(v3) {
    return v3 < 0 ? Math.ceil(-v3) : 0;
  }
  function gridLayout(view, groups, opt) {
    var dirty = !opt.nodirty, bbox = opt.bounds === Flush ? bboxFlush : bboxFull, bounds2 = tempBounds2.set(0, 0, 0, 0), alignCol = get4(opt.align, Column), alignRow = get4(opt.align, Row), padCol = get4(opt.padding, Column), padRow = get4(opt.padding, Row), ncols = opt.columns || groups.length, nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols), n2 = groups.length, xOffset = Array(n2), xExtent = Array(ncols), xMax = 0, yOffset = Array(n2), yExtent = Array(nrows), yMax = 0, dx = Array(n2), dy = Array(n2), boxes = Array(n2), m4, i2, c4, r2, b3, g2, px2, py2, x5, y5, offset4;
    for (i2 = 0; i2 < ncols; ++i2) xExtent[i2] = 0;
    for (i2 = 0; i2 < nrows; ++i2) yExtent[i2] = 0;
    for (i2 = 0; i2 < n2; ++i2) {
      g2 = groups[i2];
      b3 = boxes[i2] = bbox(g2);
      g2.x = g2.x || 0;
      dx[i2] = 0;
      g2.y = g2.y || 0;
      dy[i2] = 0;
      c4 = i2 % ncols;
      r2 = ~~(i2 / ncols);
      xMax = Math.max(xMax, px2 = Math.ceil(b3.x2));
      yMax = Math.max(yMax, py2 = Math.ceil(b3.y2));
      xExtent[c4] = Math.max(xExtent[c4], px2);
      yExtent[r2] = Math.max(yExtent[r2], py2);
      xOffset[i2] = padCol + offsetValue(b3.x1);
      yOffset[i2] = padRow + offsetValue(b3.y1);
      if (dirty) view.dirty(groups[i2]);
    }
    for (i2 = 0; i2 < n2; ++i2) {
      if (i2 % ncols === 0) xOffset[i2] = 0;
      if (i2 < ncols) yOffset[i2] = 0;
    }
    if (alignCol === Each) {
      for (c4 = 1; c4 < ncols; ++c4) {
        for (offset4 = 0, i2 = c4; i2 < n2; i2 += ncols) {
          if (offset4 < xOffset[i2]) offset4 = xOffset[i2];
        }
        for (i2 = c4; i2 < n2; i2 += ncols) {
          xOffset[i2] = offset4 + xExtent[c4 - 1];
        }
      }
    } else if (alignCol === All) {
      for (offset4 = 0, i2 = 0; i2 < n2; ++i2) {
        if (i2 % ncols && offset4 < xOffset[i2]) offset4 = xOffset[i2];
      }
      for (i2 = 0; i2 < n2; ++i2) {
        if (i2 % ncols) xOffset[i2] = offset4 + xMax;
      }
    } else {
      for (alignCol = false, c4 = 1; c4 < ncols; ++c4) {
        for (i2 = c4; i2 < n2; i2 += ncols) {
          xOffset[i2] += xExtent[c4 - 1];
        }
      }
    }
    if (alignRow === Each) {
      for (r2 = 1; r2 < nrows; ++r2) {
        for (offset4 = 0, i2 = r2 * ncols, m4 = i2 + ncols; i2 < m4; ++i2) {
          if (offset4 < yOffset[i2]) offset4 = yOffset[i2];
        }
        for (i2 = r2 * ncols; i2 < m4; ++i2) {
          yOffset[i2] = offset4 + yExtent[r2 - 1];
        }
      }
    } else if (alignRow === All) {
      for (offset4 = 0, i2 = ncols; i2 < n2; ++i2) {
        if (offset4 < yOffset[i2]) offset4 = yOffset[i2];
      }
      for (i2 = ncols; i2 < n2; ++i2) {
        yOffset[i2] = offset4 + yMax;
      }
    } else {
      for (alignRow = false, r2 = 1; r2 < nrows; ++r2) {
        for (i2 = r2 * ncols, m4 = i2 + ncols; i2 < m4; ++i2) {
          yOffset[i2] += yExtent[r2 - 1];
        }
      }
    }
    for (x5 = 0, i2 = 0; i2 < n2; ++i2) {
      x5 = xOffset[i2] + (i2 % ncols ? x5 : 0);
      dx[i2] += x5 - groups[i2].x;
    }
    for (c4 = 0; c4 < ncols; ++c4) {
      for (y5 = 0, i2 = c4; i2 < n2; i2 += ncols) {
        y5 += yOffset[i2];
        dy[i2] += y5 - groups[i2].y;
      }
    }
    if (alignCol && get4(opt.center, Column) && nrows > 1) {
      for (i2 = 0; i2 < n2; ++i2) {
        b3 = alignCol === All ? xMax : xExtent[i2 % ncols];
        x5 = b3 - boxes[i2].x2 - groups[i2].x - dx[i2];
        if (x5 > 0) dx[i2] += x5 / 2;
      }
    }
    if (alignRow && get4(opt.center, Row) && ncols !== 1) {
      for (i2 = 0; i2 < n2; ++i2) {
        b3 = alignRow === All ? yMax : yExtent[~~(i2 / ncols)];
        y5 = b3 - boxes[i2].y2 - groups[i2].y - dy[i2];
        if (y5 > 0) dy[i2] += y5 / 2;
      }
    }
    for (i2 = 0; i2 < n2; ++i2) {
      bounds2.union(boxes[i2].translate(dx[i2], dy[i2]));
    }
    x5 = get4(opt.anchor, X);
    y5 = get4(opt.anchor, Y);
    switch (get4(opt.anchor, Column)) {
      case End:
        x5 -= bounds2.width();
        break;
      case Middle:
        x5 -= bounds2.width() / 2;
    }
    switch (get4(opt.anchor, Row)) {
      case End:
        y5 -= bounds2.height();
        break;
      case Middle:
        y5 -= bounds2.height() / 2;
    }
    x5 = Math.round(x5);
    y5 = Math.round(y5);
    bounds2.clear();
    for (i2 = 0; i2 < n2; ++i2) {
      groups[i2].mark.bounds.clear();
    }
    for (i2 = 0; i2 < n2; ++i2) {
      g2 = groups[i2];
      g2.x += dx[i2] += x5;
      g2.y += dy[i2] += y5;
      bounds2.union(g2.mark.bounds.union(g2.bounds.translate(dx[i2], dy[i2])));
      if (dirty) view.dirty(g2);
    }
    return bounds2;
  }
  function trellisLayout(view, group2, opt) {
    var views = gridLayoutGroups(group2), groups = views.marks, bbox = opt.bounds === Flush ? boundFlush : boundFull, off = opt.offset, ncols = opt.columns || groups.length, nrows = ncols <= 0 ? 1 : Math.ceil(groups.length / ncols), cells = nrows * ncols, x5, y5, x22, y22, anchor, band2, offset4;
    const bounds2 = gridLayout(view, groups, opt);
    if (bounds2.empty()) bounds2.set(0, 0, 0, 0);
    if (views.rowheaders) {
      band2 = get4(opt.headerBand, Row, null);
      x5 = layoutHeaders(view, views.rowheaders, groups, ncols, nrows, -get4(off, "rowHeader"), min3, 0, bbox, "x1", 0, ncols, 1, band2);
    }
    if (views.colheaders) {
      band2 = get4(opt.headerBand, Column, null);
      y5 = layoutHeaders(view, views.colheaders, groups, ncols, ncols, -get4(off, "columnHeader"), min3, 1, bbox, "y1", 0, 1, ncols, band2);
    }
    if (views.rowfooters) {
      band2 = get4(opt.footerBand, Row, null);
      x22 = layoutHeaders(view, views.rowfooters, groups, ncols, nrows, get4(off, "rowFooter"), max3, 0, bbox, "x2", ncols - 1, ncols, 1, band2);
    }
    if (views.colfooters) {
      band2 = get4(opt.footerBand, Column, null);
      y22 = layoutHeaders(view, views.colfooters, groups, ncols, ncols, get4(off, "columnFooter"), max3, 1, bbox, "y2", cells - ncols, 1, ncols, band2);
    }
    if (views.rowtitle) {
      anchor = get4(opt.titleAnchor, Row);
      offset4 = get4(off, "rowTitle");
      offset4 = anchor === End ? x22 + offset4 : x5 - offset4;
      band2 = get4(opt.titleBand, Row, 0.5);
      layoutTitle(view, views.rowtitle, offset4, 0, bounds2, band2);
    }
    if (views.coltitle) {
      anchor = get4(opt.titleAnchor, Column);
      offset4 = get4(off, "columnTitle");
      offset4 = anchor === End ? y22 + offset4 : y5 - offset4;
      band2 = get4(opt.titleBand, Column, 0.5);
      layoutTitle(view, views.coltitle, offset4, 1, bounds2, band2);
    }
  }
  function boundFlush(item, field3) {
    return field3 === "x1" ? item.x || 0 : field3 === "y1" ? item.y || 0 : field3 === "x2" ? (item.x || 0) + (item.width || 0) : field3 === "y2" ? (item.y || 0) + (item.height || 0) : void 0;
  }
  function boundFull(item, field3) {
    return item.bounds[field3];
  }
  function layoutHeaders(view, headers, groups, ncols, limit, offset4, agg, isX2, bound2, bf, start, stride, back, band2) {
    var n2 = groups.length, init2 = 0, edge = 0, i2, j2, k2, m4, b3, h3, g2, x5, y5;
    if (!n2) return init2;
    for (i2 = start; i2 < n2; i2 += stride) {
      if (groups[i2]) init2 = agg(init2, bound2(groups[i2], bf));
    }
    if (!headers.length) return init2;
    if (headers.length > limit) {
      view.warn("Grid headers exceed limit: " + limit);
      headers = headers.slice(0, limit);
    }
    init2 += offset4;
    for (j2 = 0, m4 = headers.length; j2 < m4; ++j2) {
      view.dirty(headers[j2]);
      headers[j2].mark.bounds.clear();
    }
    for (i2 = start, j2 = 0, m4 = headers.length; j2 < m4; ++j2, i2 += stride) {
      h3 = headers[j2];
      b3 = h3.mark.bounds;
      for (k2 = i2; k2 >= 0 && (g2 = groups[k2]) == null; k2 -= back) ;
      if (isX2) {
        x5 = band2 == null ? g2.x : Math.round(g2.bounds.x1 + band2 * g2.bounds.width());
        y5 = init2;
      } else {
        x5 = init2;
        y5 = band2 == null ? g2.y : Math.round(g2.bounds.y1 + band2 * g2.bounds.height());
      }
      b3.union(h3.bounds.translate(x5 - (h3.x || 0), y5 - (h3.y || 0)));
      h3.x = x5;
      h3.y = y5;
      view.dirty(h3);
      edge = agg(edge, b3[bf]);
    }
    return edge;
  }
  function layoutTitle(view, g2, offset4, isX2, bounds2, band2) {
    if (!g2) return;
    view.dirty(g2);
    var x5 = offset4, y5 = offset4;
    isX2 ? x5 = Math.round(bounds2.x1 + band2 * bounds2.width()) : y5 = Math.round(bounds2.y1 + band2 * bounds2.height());
    g2.bounds.translate(x5 - (g2.x || 0), y5 - (g2.y || 0));
    g2.mark.bounds.clear().union(g2.bounds);
    g2.x = x5;
    g2.y = y5;
    view.dirty(g2);
  }
  function lookup2(config, orient2) {
    const opt = config[orient2] || {};
    return (key2, d2) => opt[key2] != null ? opt[key2] : config[key2] != null ? config[key2] : d2;
  }
  function offsets(legends, value3) {
    let max4 = -Infinity;
    legends.forEach((item) => {
      if (item.offset != null) max4 = Math.max(max4, item.offset);
    });
    return max4 > -Infinity ? max4 : value3;
  }
  function legendParams(g2, orient2, config, xb, yb, w3, h3) {
    const _ = lookup2(config, orient2), offset4 = offsets(g2, _("offset", 0)), anchor = _("anchor", Start), mult2 = anchor === End ? 1 : anchor === Middle ? 0.5 : 0;
    const p2 = {
      align: Each,
      bounds: _("bounds", Flush),
      columns: _("direction") === "vertical" ? 1 : g2.length,
      padding: _("margin", 8),
      center: _("center"),
      nodirty: true
    };
    switch (orient2) {
      case Left:
        p2.anchor = {
          x: Math.floor(xb.x1) - offset4,
          column: End,
          y: mult2 * (h3 || xb.height() + 2 * xb.y1),
          row: anchor
        };
        break;
      case Right:
        p2.anchor = {
          x: Math.ceil(xb.x2) + offset4,
          y: mult2 * (h3 || xb.height() + 2 * xb.y1),
          row: anchor
        };
        break;
      case Top:
        p2.anchor = {
          y: Math.floor(yb.y1) - offset4,
          row: End,
          x: mult2 * (w3 || yb.width() + 2 * yb.x1),
          column: anchor
        };
        break;
      case Bottom:
        p2.anchor = {
          y: Math.ceil(yb.y2) + offset4,
          x: mult2 * (w3 || yb.width() + 2 * yb.x1),
          column: anchor
        };
        break;
      case TopLeft:
        p2.anchor = {
          x: offset4,
          y: offset4
        };
        break;
      case TopRight:
        p2.anchor = {
          x: w3 - offset4,
          y: offset4,
          column: End
        };
        break;
      case BottomLeft:
        p2.anchor = {
          x: offset4,
          y: h3 - offset4,
          row: End
        };
        break;
      case BottomRight:
        p2.anchor = {
          x: w3 - offset4,
          y: h3 - offset4,
          column: End,
          row: End
        };
        break;
    }
    return p2;
  }
  function legendLayout(view, legend) {
    var item = legend.items[0], datum2 = item.datum, orient2 = item.orient, bounds2 = item.bounds, x5 = item.x, y5 = item.y, w3, h3;
    item._bounds ? item._bounds.clear().union(bounds2) : item._bounds = bounds2.clone();
    bounds2.clear();
    legendGroupLayout(view, item, item.items[0].items[0]);
    bounds2 = legendBounds(item, bounds2);
    w3 = 2 * item.padding;
    h3 = 2 * item.padding;
    if (!bounds2.empty()) {
      w3 = Math.ceil(bounds2.width() + w3);
      h3 = Math.ceil(bounds2.height() + h3);
    }
    if (datum2.type === Symbols) {
      legendEntryLayout(item.items[0].items[0].items[0].items);
    }
    if (orient2 !== None3) {
      item.x = x5 = 0;
      item.y = y5 = 0;
    }
    item.width = w3;
    item.height = h3;
    boundStroke(bounds2.set(x5, y5, x5 + w3, y5 + h3), item);
    item.mark.bounds.clear().union(bounds2);
    return item;
  }
  function legendBounds(item, b3) {
    item.items.forEach((_) => b3.union(_.bounds));
    b3.x1 = item.padding;
    b3.y1 = item.padding;
    return b3;
  }
  function legendGroupLayout(view, item, entry2) {
    var pad4 = item.padding, ex = pad4 - entry2.x, ey = pad4 - entry2.y;
    if (!item.datum.title) {
      if (ex || ey) translate2(view, entry2, ex, ey);
    } else {
      var title2 = item.items[1].items[0], anchor = title2.anchor, tpad = item.titlePadding || 0, tx = pad4 - title2.x, ty = pad4 - title2.y;
      switch (title2.orient) {
        case Left:
          ex += Math.ceil(title2.bounds.width()) + tpad;
          break;
        case Right:
        case Bottom:
          break;
        default:
          ey += title2.bounds.height() + tpad;
      }
      if (ex || ey) translate2(view, entry2, ex, ey);
      switch (title2.orient) {
        case Left:
          ty += legendTitleOffset(item, entry2, title2, anchor, 1, 1);
          break;
        case Right:
          tx += legendTitleOffset(item, entry2, title2, End, 0, 0) + tpad;
          ty += legendTitleOffset(item, entry2, title2, anchor, 1, 1);
          break;
        case Bottom:
          tx += legendTitleOffset(item, entry2, title2, anchor, 0, 0);
          ty += legendTitleOffset(item, entry2, title2, End, -1, 0, 1) + tpad;
          break;
        default:
          tx += legendTitleOffset(item, entry2, title2, anchor, 0, 0);
      }
      if (tx || ty) translate2(view, title2, tx, ty);
      if ((tx = Math.round(title2.bounds.x1 - pad4)) < 0) {
        translate2(view, entry2, -tx, 0);
        translate2(view, title2, -tx, 0);
      }
    }
  }
  function legendTitleOffset(item, entry2, title2, anchor, y5, lr, noBar) {
    const grad = item.datum.type !== "symbol", vgrad = title2.datum.vgrad, e4 = grad && (lr || !vgrad) && !noBar ? entry2.items[0] : entry2, s2 = e4.bounds[y5 ? "y2" : "x2"] - item.padding, u5 = vgrad && lr ? s2 : 0, v3 = vgrad && lr ? 0 : s2, o2 = y5 <= 0 ? 0 : multiLineOffset(title2);
    return Math.round(anchor === Start ? u5 : anchor === End ? v3 - o2 : 0.5 * (s2 - o2));
  }
  function translate2(view, item, dx, dy) {
    item.x += dx;
    item.y += dy;
    item.bounds.translate(dx, dy);
    item.mark.bounds.translate(dx, dy);
    view.dirty(item);
  }
  function legendEntryLayout(entries3) {
    const widths = entries3.reduce((w3, g2) => {
      w3[g2.column] = Math.max(g2.bounds.x2 - g2.x, w3[g2.column] || 0);
      return w3;
    }, {});
    entries3.forEach((g2) => {
      g2.width = widths[g2.column];
      g2.height = g2.bounds.y2 - g2.y;
    });
  }
  function titleLayout(view, mark, width2, height2, viewBounds2) {
    var group2 = mark.items[0], frame2 = group2.frame, orient2 = group2.orient, anchor = group2.anchor, offset4 = group2.offset, padding3 = group2.padding, title2 = group2.items[0].items[0], subtitle = group2.items[1] && group2.items[1].items[0], end = orient2 === Left || orient2 === Right ? height2 : width2, start = 0, x5 = 0, y5 = 0, sx = 0, sy = 0, pos;
    if (frame2 !== Group) {
      orient2 === Left ? (start = viewBounds2.y2, end = viewBounds2.y1) : orient2 === Right ? (start = viewBounds2.y1, end = viewBounds2.y2) : (start = viewBounds2.x1, end = viewBounds2.x2);
    } else if (orient2 === Left) {
      start = height2, end = 0;
    }
    pos = anchor === Start ? start : anchor === End ? end : (start + end) / 2;
    if (subtitle && subtitle.text) {
      switch (orient2) {
        case Top:
        case Bottom:
          sy = title2.bounds.height() + padding3;
          break;
        case Left:
          sx = title2.bounds.width() + padding3;
          break;
        case Right:
          sx = -title2.bounds.width() - padding3;
          break;
      }
      tempBounds2.clear().union(subtitle.bounds);
      tempBounds2.translate(sx - (subtitle.x || 0), sy - (subtitle.y || 0));
      if (set3(subtitle, "x", sx) | set3(subtitle, "y", sy)) {
        view.dirty(subtitle);
        subtitle.bounds.clear().union(tempBounds2);
        subtitle.mark.bounds.clear().union(tempBounds2);
        view.dirty(subtitle);
      }
      tempBounds2.clear().union(subtitle.bounds);
    } else {
      tempBounds2.clear();
    }
    tempBounds2.union(title2.bounds);
    switch (orient2) {
      case Top:
        x5 = pos;
        y5 = viewBounds2.y1 - tempBounds2.height() - offset4;
        break;
      case Left:
        x5 = viewBounds2.x1 - tempBounds2.width() - offset4;
        y5 = pos;
        break;
      case Right:
        x5 = viewBounds2.x2 + tempBounds2.width() + offset4;
        y5 = pos;
        break;
      case Bottom:
        x5 = pos;
        y5 = viewBounds2.y2 + offset4;
        break;
      default:
        x5 = group2.x;
        y5 = group2.y;
    }
    if (set3(group2, "x", x5) | set3(group2, "y", y5)) {
      tempBounds2.translate(x5, y5);
      view.dirty(group2);
      group2.bounds.clear().union(tempBounds2);
      mark.bounds.clear().union(tempBounds2);
      view.dirty(group2);
    }
    return group2.bounds;
  }
  function ViewLayout(params2) {
    Transform.call(this, null, params2);
  }
  inherits(ViewLayout, Transform, {
    transform(_, pulse2) {
      const view = pulse2.dataflow;
      _.mark.items.forEach((group2) => {
        if (_.layout) trellisLayout(view, group2, _.layout);
        layoutGroup(view, group2, _);
      });
      return shouldReflow(_.mark.group) ? pulse2.reflow() : pulse2;
    }
  });
  function shouldReflow(group2) {
    return group2 && group2.mark.role !== "legend-entry";
  }
  function layoutGroup(view, group2, _) {
    var items = group2.items, width2 = Math.max(0, group2.width || 0), height2 = Math.max(0, group2.height || 0), viewBounds2 = new Bounds().set(0, 0, width2, height2), xBounds = viewBounds2.clone(), yBounds = viewBounds2.clone(), legends = [], title2, mark, orient2, b3, i2, n2;
    for (i2 = 0, n2 = items.length; i2 < n2; ++i2) {
      mark = items[i2];
      switch (mark.role) {
        case AxisRole:
          b3 = isYAxis(mark) ? xBounds : yBounds;
          b3.union(axisLayout(view, mark, width2, height2));
          break;
        case TitleRole:
          title2 = mark;
          break;
        case LegendRole:
          legends.push(legendLayout(view, mark));
          break;
        case FrameRole:
        case ScopeRole:
        case RowHeader:
        case RowFooter:
        case RowTitle:
        case ColHeader:
        case ColFooter:
        case ColTitle:
          xBounds.union(mark.bounds);
          yBounds.union(mark.bounds);
          break;
        default:
          viewBounds2.union(mark.bounds);
      }
    }
    if (legends.length) {
      const l2 = {};
      legends.forEach((item) => {
        orient2 = item.orient || Right;
        if (orient2 !== None3) (l2[orient2] || (l2[orient2] = [])).push(item);
      });
      for (const orient3 in l2) {
        const g2 = l2[orient3];
        gridLayout(view, g2, legendParams(g2, orient3, _.legends, xBounds, yBounds, width2, height2));
      }
      legends.forEach((item) => {
        const b4 = item.bounds;
        if (!b4.equals(item._bounds)) {
          item.bounds = item._bounds;
          view.dirty(item);
          item.bounds = b4;
          view.dirty(item);
        }
        if (_.autosize && (_.autosize.type === Fit || _.autosize.type === FitX || _.autosize.type === FitY)) {
          switch (item.orient) {
            case Left:
            case Right:
              viewBounds2.add(b4.x1, 0).add(b4.x2, 0);
              break;
            case Top:
            case Bottom:
              viewBounds2.add(0, b4.y1).add(0, b4.y2);
          }
        } else {
          viewBounds2.union(b4);
        }
      });
    }
    viewBounds2.union(xBounds).union(yBounds);
    if (title2) {
      viewBounds2.union(titleLayout(view, title2, width2, height2, viewBounds2));
    }
    if (group2.clip) {
      viewBounds2.set(0, 0, group2.width || 0, group2.height || 0);
    }
    viewSizeLayout(view, group2, viewBounds2, _);
  }
  function viewSizeLayout(view, group2, viewBounds2, _) {
    const auto = _.autosize || {}, type3 = auto.type;
    if (view._autosize < 1 || !type3) return;
    let viewWidth2 = view._width, viewHeight2 = view._height, width2 = Math.max(0, group2.width || 0), left = Math.max(0, Math.ceil(-viewBounds2.x1)), height2 = Math.max(0, group2.height || 0), top = Math.max(0, Math.ceil(-viewBounds2.y1));
    const right = Math.max(0, Math.ceil(viewBounds2.x2 - width2)), bottom = Math.max(0, Math.ceil(viewBounds2.y2 - height2));
    if (auto.contains === Padding) {
      const padding3 = view.padding();
      viewWidth2 -= padding3.left + padding3.right;
      viewHeight2 -= padding3.top + padding3.bottom;
    }
    if (type3 === None3) {
      left = 0;
      top = 0;
      width2 = viewWidth2;
      height2 = viewHeight2;
    } else if (type3 === Fit) {
      width2 = Math.max(0, viewWidth2 - left - right);
      height2 = Math.max(0, viewHeight2 - top - bottom);
    } else if (type3 === FitX) {
      width2 = Math.max(0, viewWidth2 - left - right);
      viewHeight2 = height2 + top + bottom;
    } else if (type3 === FitY) {
      viewWidth2 = width2 + left + right;
      height2 = Math.max(0, viewHeight2 - top - bottom);
    } else if (type3 === Pad) {
      viewWidth2 = width2 + left + right;
      viewHeight2 = height2 + top + bottom;
    }
    view._resizeView(viewWidth2, viewHeight2, width2, height2, [left, top], auto.resize);
  }

  // node_modules/vega-encode/build/vega-encode.module.js
  var vega_encode_module_exports = {};
  __export(vega_encode_module_exports, {
    axisticks: () => AxisTicks,
    datajoin: () => DataJoin,
    encode: () => Encode,
    legendentries: () => LegendEntries,
    linkpath: () => LinkPath,
    pie: () => Pie,
    scale: () => Scale,
    sortitems: () => SortItems,
    stack: () => Stack
  });
  function AxisTicks(params2) {
    Transform.call(this, null, params2);
  }
  inherits(AxisTicks, Transform, {
    transform(_, pulse2) {
      if (this.value && !_.modified()) {
        return pulse2.StopPropagation;
      }
      var locale4 = pulse2.dataflow.locale(), out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), ticks2 = this.value, scale7 = _.scale, tally = _.count == null ? _.values ? _.values.length : 10 : _.count, count2 = tickCount(scale7, tally, _.minstep), format5 = _.format || tickFormat2(locale4, scale7, count2, _.formatSpecifier, _.formatType, !!_.values), values4 = _.values ? validTicks(scale7, _.values, count2) : tickValues(scale7, count2);
      if (ticks2) out.rem = ticks2;
      ticks2 = values4.map((value3, i2) => ingest$1({
        index: i2 / (values4.length - 1 || 1),
        value: value3,
        label: format5(value3)
      }));
      if (_.extra && ticks2.length) {
        ticks2.push(ingest$1({
          index: -1,
          extra: {
            value: ticks2[0].value
          },
          label: ""
        }));
      }
      out.source = ticks2;
      out.add = ticks2;
      this.value = ticks2;
      return out;
    }
  });
  function DataJoin(params2) {
    Transform.call(this, null, params2);
  }
  function defaultItemCreate() {
    return ingest$1({});
  }
  function newMap(key2) {
    const map4 = fastmap().test((t4) => t4.exit);
    map4.lookup = (t4) => map4.get(key2(t4));
    return map4;
  }
  inherits(DataJoin, Transform, {
    transform(_, pulse2) {
      var df = pulse2.dataflow, out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), item = _.item || defaultItemCreate, key2 = _.key || tupleid, map4 = this.value;
      if (isArray(out.encode)) {
        out.encode = null;
      }
      if (map4 && (_.modified("key") || pulse2.modified(key2))) {
        error("DataJoin does not support modified key function or fields.");
      }
      if (!map4) {
        pulse2 = pulse2.addAll();
        this.value = map4 = newMap(key2);
      }
      pulse2.visit(pulse2.ADD, (t4) => {
        const k2 = key2(t4);
        let x5 = map4.get(k2);
        if (x5) {
          if (x5.exit) {
            map4.empty--;
            out.add.push(x5);
          } else {
            out.mod.push(x5);
          }
        } else {
          x5 = item(t4);
          map4.set(k2, x5);
          out.add.push(x5);
        }
        x5.datum = t4;
        x5.exit = false;
      });
      pulse2.visit(pulse2.MOD, (t4) => {
        const k2 = key2(t4), x5 = map4.get(k2);
        if (x5) {
          x5.datum = t4;
          out.mod.push(x5);
        }
      });
      pulse2.visit(pulse2.REM, (t4) => {
        const k2 = key2(t4), x5 = map4.get(k2);
        if (t4 === x5.datum && !x5.exit) {
          out.rem.push(x5);
          x5.exit = true;
          ++map4.empty;
        }
      });
      if (pulse2.changed(pulse2.ADD_MOD)) out.modifies("datum");
      if (pulse2.clean() || _.clean && map4.empty > df.cleanThreshold) {
        df.runAfter(map4.clean);
      }
      return out;
    }
  });
  function Encode(params2) {
    Transform.call(this, null, params2);
  }
  inherits(Encode, Transform, {
    transform(_, pulse2) {
      var out = pulse2.fork(pulse2.ADD_REM), fmod = _.mod || false, encoders = _.encoders, encode2 = pulse2.encode;
      if (isArray(encode2)) {
        if (out.changed() || encode2.every((e4) => encoders[e4])) {
          encode2 = encode2[0];
          out.encode = null;
        } else {
          return pulse2.StopPropagation;
        }
      }
      var reenter = encode2 === "enter", update3 = encoders.update || falsy, enter = encoders.enter || falsy, exit = encoders.exit || falsy, set7 = (encode2 && !reenter ? encoders[encode2] : update3) || falsy;
      if (pulse2.changed(pulse2.ADD)) {
        pulse2.visit(pulse2.ADD, (t4) => {
          enter(t4, _);
          update3(t4, _);
        });
        out.modifies(enter.output);
        out.modifies(update3.output);
        if (set7 !== falsy && set7 !== update3) {
          pulse2.visit(pulse2.ADD, (t4) => {
            set7(t4, _);
          });
          out.modifies(set7.output);
        }
      }
      if (pulse2.changed(pulse2.REM) && exit !== falsy) {
        pulse2.visit(pulse2.REM, (t4) => {
          exit(t4, _);
        });
        out.modifies(exit.output);
      }
      if (reenter || set7 !== falsy) {
        const flag2 = pulse2.MOD | (_.modified() ? pulse2.REFLOW : 0);
        if (reenter) {
          pulse2.visit(flag2, (t4) => {
            const mod = enter(t4, _) || fmod;
            if (set7(t4, _) || mod) out.mod.push(t4);
          });
          if (out.mod.length) out.modifies(enter.output);
        } else {
          pulse2.visit(flag2, (t4) => {
            if (set7(t4, _) || fmod) out.mod.push(t4);
          });
        }
        if (out.mod.length) out.modifies(set7.output);
      }
      return out.changed() ? out : pulse2.StopPropagation;
    }
  });
  function LegendEntries(params2) {
    Transform.call(this, [], params2);
  }
  inherits(LegendEntries, Transform, {
    transform(_, pulse2) {
      if (this.value != null && !_.modified()) {
        return pulse2.StopPropagation;
      }
      var locale4 = pulse2.dataflow.locale(), out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), items = this.value, type3 = _.type || SymbolLegend, scale7 = _.scale, limit = +_.limit, count2 = tickCount(scale7, _.count == null ? 5 : _.count, _.minstep), lskip = !!_.values || type3 === SymbolLegend, format5 = _.format || labelFormat(locale4, scale7, count2, type3, _.formatSpecifier, _.formatType, lskip), values4 = _.values || labelValues(scale7, count2), domain4, fraction, size, offset4, ellipsis;
      if (items) out.rem = items;
      if (type3 === SymbolLegend) {
        if (limit && values4.length > limit) {
          pulse2.dataflow.warn("Symbol legend count exceeds limit, filtering items.");
          items = values4.slice(0, limit - 1);
          ellipsis = true;
        } else {
          items = values4;
        }
        if (isFunction(size = _.size)) {
          if (!_.values && scale7(items[0]) === 0) {
            items = items.slice(1);
          }
          offset4 = items.reduce((max4, value3) => Math.max(max4, size(value3, _)), 0);
        } else {
          size = constant(offset4 = size || 8);
        }
        items = items.map((value3, index4) => ingest$1({
          index: index4,
          label: format5(value3, index4, items),
          value: value3,
          offset: offset4,
          size: size(value3, _)
        }));
        if (ellipsis) {
          ellipsis = values4[items.length];
          items.push(ingest$1({
            index: items.length,
            label: `\u2026${values4.length - items.length} entries`,
            value: ellipsis,
            offset: offset4,
            size: size(ellipsis, _)
          }));
        }
      } else if (type3 === GradientLegend) {
        domain4 = scale7.domain(), fraction = scaleFraction(scale7, domain4[0], peek(domain4));
        if (values4.length < 3 && !_.values && domain4[0] !== peek(domain4)) {
          values4 = [domain4[0], peek(domain4)];
        }
        items = values4.map((value3, index4) => ingest$1({
          index: index4,
          label: format5(value3, index4, values4),
          value: value3,
          perc: fraction(value3)
        }));
      } else {
        size = values4.length - 1;
        fraction = labelFraction(scale7);
        items = values4.map((value3, index4) => ingest$1({
          index: index4,
          label: format5(value3, index4, values4),
          value: value3,
          perc: index4 ? fraction(value3) : 0,
          perc2: index4 === size ? 1 : fraction(values4[index4 + 1])
        }));
      }
      out.source = items;
      out.add = items;
      this.value = items;
      return out;
    }
  });
  var sourceX = (t4) => t4.source.x;
  var sourceY = (t4) => t4.source.y;
  var targetX = (t4) => t4.target.x;
  var targetY = (t4) => t4.target.y;
  function LinkPath(params2) {
    Transform.call(this, {}, params2);
  }
  LinkPath.Definition = {
    "type": "LinkPath",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "sourceX",
      "type": "field",
      "default": "source.x"
    }, {
      "name": "sourceY",
      "type": "field",
      "default": "source.y"
    }, {
      "name": "targetX",
      "type": "field",
      "default": "target.x"
    }, {
      "name": "targetY",
      "type": "field",
      "default": "target.y"
    }, {
      "name": "orient",
      "type": "enum",
      "default": "vertical",
      "values": ["horizontal", "vertical", "radial"]
    }, {
      "name": "shape",
      "type": "enum",
      "default": "line",
      "values": ["line", "arc", "curve", "diagonal", "orthogonal"]
    }, {
      "name": "require",
      "type": "signal"
    }, {
      "name": "as",
      "type": "string",
      "default": "path"
    }]
  };
  inherits(LinkPath, Transform, {
    transform(_, pulse2) {
      var sx = _.sourceX || sourceX, sy = _.sourceY || sourceY, tx = _.targetX || targetX, ty = _.targetY || targetY, as = _.as || "path", orient2 = _.orient || "vertical", shape2 = _.shape || "line", path3 = Paths.get(shape2 + "-" + orient2) || Paths.get(shape2);
      if (!path3) {
        error("LinkPath unsupported type: " + _.shape + (_.orient ? "-" + _.orient : ""));
      }
      pulse2.visit(pulse2.SOURCE, (t4) => {
        t4[as] = path3(sx(t4), sy(t4), tx(t4), ty(t4));
      });
      return pulse2.reflow(_.modified()).modifies(as);
    }
  });
  var line2 = (sx, sy, tx, ty) => "M" + sx + "," + sy + "L" + tx + "," + ty;
  var lineR = (sa2, sr, ta, tr2) => line2(sr * Math.cos(sa2), sr * Math.sin(sa2), tr2 * Math.cos(ta), tr2 * Math.sin(ta));
  var arc2 = (sx, sy, tx, ty) => {
    var dx = tx - sx, dy = ty - sy, rr = Math.hypot(dx, dy) / 2, ra = 180 * Math.atan2(dy, dx) / Math.PI;
    return "M" + sx + "," + sy + "A" + rr + "," + rr + " " + ra + " 0 1 " + tx + "," + ty;
  };
  var arcR = (sa2, sr, ta, tr2) => arc2(sr * Math.cos(sa2), sr * Math.sin(sa2), tr2 * Math.cos(ta), tr2 * Math.sin(ta));
  var curve = (sx, sy, tx, ty) => {
    const dx = tx - sx, dy = ty - sy, ix = 0.2 * (dx + dy), iy = 0.2 * (dy - dx);
    return "M" + sx + "," + sy + "C" + (sx + ix) + "," + (sy + iy) + " " + (tx + iy) + "," + (ty - ix) + " " + tx + "," + ty;
  };
  var curveR = (sa2, sr, ta, tr2) => curve(sr * Math.cos(sa2), sr * Math.sin(sa2), tr2 * Math.cos(ta), tr2 * Math.sin(ta));
  var orthoX = (sx, sy, tx, ty) => "M" + sx + "," + sy + "V" + ty + "H" + tx;
  var orthoY = (sx, sy, tx, ty) => "M" + sx + "," + sy + "H" + tx + "V" + ty;
  var orthoR = (sa2, sr, ta, tr2) => {
    const sc = Math.cos(sa2), ss = Math.sin(sa2), tc = Math.cos(ta), ts2 = Math.sin(ta), sf = Math.abs(ta - sa2) > Math.PI ? ta <= sa2 : ta > sa2;
    return "M" + sr * sc + "," + sr * ss + "A" + sr + "," + sr + " 0 0," + (sf ? 1 : 0) + " " + sr * tc + "," + sr * ts2 + "L" + tr2 * tc + "," + tr2 * ts2;
  };
  var diagonalX = (sx, sy, tx, ty) => {
    const m4 = (sx + tx) / 2;
    return "M" + sx + "," + sy + "C" + m4 + "," + sy + " " + m4 + "," + ty + " " + tx + "," + ty;
  };
  var diagonalY = (sx, sy, tx, ty) => {
    const m4 = (sy + ty) / 2;
    return "M" + sx + "," + sy + "C" + sx + "," + m4 + " " + tx + "," + m4 + " " + tx + "," + ty;
  };
  var diagonalR = (sa2, sr, ta, tr2) => {
    const sc = Math.cos(sa2), ss = Math.sin(sa2), tc = Math.cos(ta), ts2 = Math.sin(ta), mr = (sr + tr2) / 2;
    return "M" + sr * sc + "," + sr * ss + "C" + mr * sc + "," + mr * ss + " " + mr * tc + "," + mr * ts2 + " " + tr2 * tc + "," + tr2 * ts2;
  };
  var Paths = fastmap({
    "line": line2,
    "line-radial": lineR,
    "arc": arc2,
    "arc-radial": arcR,
    "curve": curve,
    "curve-radial": curveR,
    "orthogonal-horizontal": orthoX,
    "orthogonal-vertical": orthoY,
    "orthogonal-radial": orthoR,
    "diagonal-horizontal": diagonalX,
    "diagonal-vertical": diagonalY,
    "diagonal-radial": diagonalR
  });
  function Pie(params2) {
    Transform.call(this, null, params2);
  }
  Pie.Definition = {
    "type": "Pie",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "startAngle",
      "type": "number",
      "default": 0
    }, {
      "name": "endAngle",
      "type": "number",
      "default": 6.283185307179586
    }, {
      "name": "sort",
      "type": "boolean",
      "default": false
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["startAngle", "endAngle"]
    }]
  };
  inherits(Pie, Transform, {
    transform(_, pulse2) {
      var as = _.as || ["startAngle", "endAngle"], startAngle = as[0], endAngle = as[1], field3 = _.field || one, start = _.startAngle || 0, stop2 = _.endAngle != null ? _.endAngle : 2 * Math.PI, data3 = pulse2.source, values4 = data3.map(field3), n2 = values4.length, a4 = start, k2 = (stop2 - start) / sum(values4), index4 = range(n2), i2, t4, v3;
      if (_.sort) {
        index4.sort((a5, b3) => values4[a5] - values4[b3]);
      }
      for (i2 = 0; i2 < n2; ++i2) {
        v3 = values4[index4[i2]];
        t4 = data3[index4[i2]];
        t4[startAngle] = a4;
        t4[endAngle] = a4 += v3 * k2;
      }
      this.value = values4;
      return pulse2.reflow(_.modified()).modifies(as);
    }
  });
  var DEFAULT_COUNT = 5;
  function includeZero(scale7) {
    const type3 = scale7.type;
    return !scale7.bins && (type3 === Linear2 || type3 === Pow || type3 === Sqrt);
  }
  function includePad(type3) {
    return isContinuous(type3) && type3 !== Sequential;
  }
  var SKIP2 = toSet(["set", "modified", "clear", "type", "scheme", "schemeExtent", "schemeCount", "domain", "domainMin", "domainMid", "domainMax", "domainRaw", "domainImplicit", "nice", "zero", "bins", "range", "rangeStep", "round", "reverse", "interpolate", "interpolateGamma"]);
  function Scale(params2) {
    Transform.call(this, null, params2);
    this.modified(true);
  }
  inherits(Scale, Transform, {
    transform(_, pulse2) {
      var df = pulse2.dataflow, scale$12 = this.value, key2 = scaleKey(_);
      if (!scale$12 || key2 !== scale$12.type) {
        this.value = scale$12 = scale(key2)();
      }
      for (key2 in _) if (!SKIP2[key2]) {
        if (key2 === "padding" && includePad(scale$12.type)) continue;
        isFunction(scale$12[key2]) ? scale$12[key2](_[key2]) : df.warn("Unsupported scale property: " + key2);
      }
      configureRange(scale$12, _, configureBins(scale$12, _, configureDomain(scale$12, _, df)));
      return pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
    }
  });
  function scaleKey(_) {
    var t4 = _.type, d2 = "", n2;
    if (t4 === Sequential) return Sequential + "-" + Linear2;
    if (isContinuousColor(_)) {
      n2 = _.rawDomain ? _.rawDomain.length : _.domain ? _.domain.length + +(_.domainMid != null) : 0;
      d2 = n2 === 2 ? Sequential + "-" : n2 === 3 ? Diverging + "-" : "";
    }
    return (d2 + t4 || Linear2).toLowerCase();
  }
  function isContinuousColor(_) {
    const t4 = _.type;
    return isContinuous(t4) && t4 !== Time && t4 !== UTC && (_.scheme || _.range && _.range.length && _.range.every(isString));
  }
  function configureDomain(scale7, _, df) {
    const raw = rawDomain(scale7, _.domainRaw, df);
    if (raw > -1) return raw;
    var domain4 = _.domain, type3 = scale7.type, zero6 = _.zero || _.zero === void 0 && includeZero(scale7), n2, mid;
    if (!domain4) return 0;
    if (zero6 || _.domainMin != null || _.domainMax != null || _.domainMid != null) {
      n2 = (domain4 = domain4.slice()).length - 1 || 1;
      if (zero6) {
        if (domain4[0] > 0) domain4[0] = 0;
        if (domain4[n2] < 0) domain4[n2] = 0;
      }
      if (_.domainMin != null) domain4[0] = _.domainMin;
      if (_.domainMax != null) domain4[n2] = _.domainMax;
      if (_.domainMid != null) {
        mid = _.domainMid;
        const i2 = mid > domain4[n2] ? n2 + 1 : mid < domain4[0] ? 0 : n2;
        if (i2 !== n2) df.warn("Scale domainMid exceeds domain min or max.", mid);
        domain4.splice(i2, 0, mid);
      }
    }
    if (includePad(type3) && _.padding && domain4[0] !== peek(domain4)) {
      domain4 = padDomain(type3, domain4, _.range, _.padding, _.exponent, _.constant);
    }
    scale7.domain(domainCheck(type3, domain4, df));
    if (type3 === Ordinal) {
      scale7.unknown(_.domainImplicit ? implicit : void 0);
    }
    if (_.nice && scale7.nice) {
      scale7.nice(_.nice !== true && tickCount(scale7, _.nice) || null);
    }
    return domain4.length;
  }
  function rawDomain(scale7, raw, df) {
    if (raw) {
      scale7.domain(domainCheck(scale7.type, raw, df));
      return raw.length;
    } else {
      return -1;
    }
  }
  function padDomain(type3, domain4, range7, pad4, exponent, constant3) {
    var span2 = Math.abs(peek(range7) - range7[0]), frac = span2 / (span2 - 2 * pad4), d2 = type3 === Log ? zoomLog(domain4, null, frac) : type3 === Sqrt ? zoomPow(domain4, null, frac, 0.5) : type3 === Pow ? zoomPow(domain4, null, frac, exponent || 1) : type3 === Symlog ? zoomSymlog(domain4, null, frac, constant3 || 1) : zoomLinear(domain4, null, frac);
    domain4 = domain4.slice();
    domain4[0] = d2[0];
    domain4[domain4.length - 1] = d2[1];
    return domain4;
  }
  function domainCheck(type3, domain4, df) {
    if (isLogarithmic(type3)) {
      var s2 = Math.abs(domain4.reduce((s3, v3) => s3 + (v3 < 0 ? -1 : v3 > 0 ? 1 : 0), 0));
      if (s2 !== domain4.length) {
        df.warn("Log scale domain includes zero: " + $(domain4));
      }
    }
    return domain4;
  }
  function configureBins(scale7, _, count2) {
    let bins2 = _.bins;
    if (bins2 && !isArray(bins2)) {
      const domain4 = scale7.domain(), lo = domain4[0], hi = peek(domain4), step = bins2.step;
      let start = bins2.start == null ? lo : bins2.start, stop2 = bins2.stop == null ? hi : bins2.stop;
      if (!step) error("Scale bins parameter missing step property.");
      if (start < lo) start = step * Math.ceil(lo / step);
      if (stop2 > hi) stop2 = step * Math.floor(hi / step);
      bins2 = range(start, stop2 + step / 2, step);
    }
    if (bins2) {
      scale7.bins = bins2;
    } else if (scale7.bins) {
      delete scale7.bins;
    }
    if (scale7.type === BinOrdinal) {
      if (!bins2) {
        scale7.bins = scale7.domain();
      } else if (!_.domain && !_.domainRaw) {
        scale7.domain(bins2);
        count2 = bins2.length;
      }
    }
    return count2;
  }
  function configureRange(scale7, _, count2) {
    var type3 = scale7.type, round = _.round || false, range7 = _.range;
    if (_.rangeStep != null) {
      range7 = configureRangeStep(type3, _, count2);
    } else if (_.scheme) {
      range7 = configureScheme(type3, _, count2);
      if (isFunction(range7)) {
        if (scale7.interpolator) {
          return scale7.interpolator(range7);
        } else {
          error(`Scale type ${type3} does not support interpolating color schemes.`);
        }
      }
    }
    if (range7 && isInterpolating(type3)) {
      return scale7.interpolator(interpolateColors(flip(range7, _.reverse), _.interpolate, _.interpolateGamma));
    }
    if (range7 && _.interpolate && scale7.interpolate) {
      scale7.interpolate(interpolate(_.interpolate, _.interpolateGamma));
    } else if (isFunction(scale7.round)) {
      scale7.round(round);
    } else if (isFunction(scale7.rangeRound)) {
      scale7.interpolate(round ? round_default : value_default);
    }
    if (range7) scale7.range(flip(range7, _.reverse));
  }
  function configureRangeStep(type3, _, count2) {
    if (type3 !== Band && type3 !== Point) {
      error("Only band and point scales support rangeStep.");
    }
    var outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0, inner = type3 === Point ? 1 : (_.paddingInner != null ? _.paddingInner : _.padding) || 0;
    return [0, _.rangeStep * bandSpace(count2, inner, outer)];
  }
  function configureScheme(type3, _, count2) {
    var extent2 = _.schemeExtent, name4, scheme$1;
    if (isArray(_.scheme)) {
      scheme$1 = interpolateColors(_.scheme, _.interpolate, _.interpolateGamma);
    } else {
      name4 = _.scheme.toLowerCase();
      scheme$1 = scheme(name4);
      if (!scheme$1) error(`Unrecognized scheme name: ${_.scheme}`);
    }
    count2 = type3 === Threshold ? count2 + 1 : type3 === BinOrdinal ? count2 - 1 : type3 === Quantile2 || type3 === Quantize ? +_.schemeCount || DEFAULT_COUNT : count2;
    return isInterpolating(type3) ? adjustScheme(scheme$1, extent2, _.reverse) : isFunction(scheme$1) ? quantizeInterpolator(adjustScheme(scheme$1, extent2), count2) : type3 === Ordinal ? scheme$1 : scheme$1.slice(0, count2);
  }
  function adjustScheme(scheme3, extent2, reverse3) {
    return isFunction(scheme3) && (extent2 || reverse3) ? interpolateRange(scheme3, flip(extent2 || [0, 1], reverse3)) : scheme3;
  }
  function flip(array4, reverse3) {
    return reverse3 ? array4.slice().reverse() : array4;
  }
  function SortItems(params2) {
    Transform.call(this, null, params2);
  }
  inherits(SortItems, Transform, {
    transform(_, pulse2) {
      const mod = _.modified("sort") || pulse2.changed(pulse2.ADD) || pulse2.modified(_.sort.fields) || pulse2.modified("datum");
      if (mod) pulse2.source.sort(stableCompare(_.sort));
      this.modified(mod);
      return pulse2;
    }
  });
  var Zero = "zero";
  var Center = "center";
  var Normalize = "normalize";
  var DefOutput = ["y0", "y1"];
  function Stack(params2) {
    Transform.call(this, null, params2);
  }
  Stack.Definition = {
    "type": "Stack",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "sort",
      "type": "compare"
    }, {
      "name": "offset",
      "type": "enum",
      "default": Zero,
      "values": [Zero, Center, Normalize]
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": DefOutput
    }]
  };
  inherits(Stack, Transform, {
    transform(_, pulse2) {
      var as = _.as || DefOutput, y06 = as[0], y12 = as[1], sort3 = stableCompare(_.sort), field3 = _.field || one, stack2 = _.offset === Center ? stackCenter : _.offset === Normalize ? stackNormalize : stackZero, groups, i2, n2, max4;
      groups = partition2(pulse2.source, _.groupby, sort3, field3);
      for (i2 = 0, n2 = groups.length, max4 = groups.max; i2 < n2; ++i2) {
        stack2(groups[i2], max4, field3, y06, y12);
      }
      return pulse2.reflow(_.modified()).modifies(as);
    }
  });
  function stackCenter(group2, max4, field3, y06, y12) {
    var last = (max4 - group2.sum) / 2, m4 = group2.length, j2 = 0, t4;
    for (; j2 < m4; ++j2) {
      t4 = group2[j2];
      t4[y06] = last;
      t4[y12] = last += Math.abs(field3(t4));
    }
  }
  function stackNormalize(group2, max4, field3, y06, y12) {
    var scale7 = 1 / group2.sum, last = 0, m4 = group2.length, j2 = 0, v3 = 0, t4;
    for (; j2 < m4; ++j2) {
      t4 = group2[j2];
      t4[y06] = last;
      t4[y12] = last = scale7 * (v3 += Math.abs(field3(t4)));
    }
  }
  function stackZero(group2, max4, field3, y06, y12) {
    var lastPos = 0, lastNeg = 0, m4 = group2.length, j2 = 0, v3, t4;
    for (; j2 < m4; ++j2) {
      t4 = group2[j2];
      v3 = +field3(t4);
      if (v3 < 0) {
        t4[y06] = lastNeg;
        t4[y12] = lastNeg += v3;
      } else {
        t4[y06] = lastPos;
        t4[y12] = lastPos += v3;
      }
    }
  }
  function partition2(data3, groupby, sort3, field3) {
    var groups = [], get6 = (f2) => f2(t4), map4, i2, n2, m4, t4, k2, g2, s2, max4;
    if (groupby == null) {
      groups.push(data3.slice());
    } else {
      for (map4 = {}, i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
        t4 = data3[i2];
        k2 = groupby.map(get6);
        g2 = map4[k2];
        if (!g2) {
          map4[k2] = g2 = [];
          groups.push(g2);
        }
        g2.push(t4);
      }
    }
    for (k2 = 0, max4 = 0, m4 = groups.length; k2 < m4; ++k2) {
      g2 = groups[k2];
      for (i2 = 0, s2 = 0, n2 = g2.length; i2 < n2; ++i2) {
        s2 += Math.abs(field3(g2[i2]));
      }
      g2.sum = s2;
      if (s2 > max4) max4 = s2;
      if (sort3) g2.sort(sort3);
    }
    groups.max = max4;
    return groups;
  }

  // node_modules/vega-geo/build/vega-geo.module.js
  var vega_geo_module_exports = {};
  __export(vega_geo_module_exports, {
    contour: () => Contour,
    geojson: () => GeoJSON,
    geopath: () => GeoPath,
    geopoint: () => GeoPoint,
    geoshape: () => GeoShape,
    graticule: () => Graticule,
    heatmap: () => Heatmap,
    isocontour: () => Isocontour,
    kde2d: () => KDE2D,
    projection: () => Projection
  });

  // node_modules/d3-geo/src/math.js
  var epsilon4 = 1e-6;
  var epsilon23 = 1e-12;
  var pi3 = Math.PI;
  var halfPi2 = pi3 / 2;
  var quarterPi = pi3 / 4;
  var tau3 = pi3 * 2;
  var degrees3 = 180 / pi3;
  var radians2 = pi3 / 180;
  var abs2 = Math.abs;
  var atan = Math.atan;
  var atan22 = Math.atan2;
  var cos2 = Math.cos;
  var ceil = Math.ceil;
  var exp3 = Math.exp;
  var hypot = Math.hypot;
  var log4 = Math.log;
  var pow4 = Math.pow;
  var sin2 = Math.sin;
  var sign2 = Math.sign || function(x5) {
    return x5 > 0 ? 1 : x5 < 0 ? -1 : 0;
  };
  var sqrt3 = Math.sqrt;
  var tan = Math.tan;
  function acos2(x5) {
    return x5 > 1 ? 0 : x5 < -1 ? pi3 : Math.acos(x5);
  }
  function asin2(x5) {
    return x5 > 1 ? halfPi2 : x5 < -1 ? -halfPi2 : Math.asin(x5);
  }

  // node_modules/d3-geo/src/noop.js
  function noop2() {
  }

  // node_modules/d3-geo/src/stream.js
  function streamGeometry(geometry, stream2) {
    if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {
      streamGeometryType[geometry.type](geometry, stream2);
    }
  }
  var streamObjectType = {
    Feature: function(object2, stream2) {
      streamGeometry(object2.geometry, stream2);
    },
    FeatureCollection: function(object2, stream2) {
      var features = object2.features, i2 = -1, n2 = features.length;
      while (++i2 < n2) streamGeometry(features[i2].geometry, stream2);
    }
  };
  var streamGeometryType = {
    Sphere: function(object2, stream2) {
      stream2.sphere();
    },
    Point: function(object2, stream2) {
      object2 = object2.coordinates;
      stream2.point(object2[0], object2[1], object2[2]);
    },
    MultiPoint: function(object2, stream2) {
      var coordinates = object2.coordinates, i2 = -1, n2 = coordinates.length;
      while (++i2 < n2) object2 = coordinates[i2], stream2.point(object2[0], object2[1], object2[2]);
    },
    LineString: function(object2, stream2) {
      streamLine(object2.coordinates, stream2, 0);
    },
    MultiLineString: function(object2, stream2) {
      var coordinates = object2.coordinates, i2 = -1, n2 = coordinates.length;
      while (++i2 < n2) streamLine(coordinates[i2], stream2, 0);
    },
    Polygon: function(object2, stream2) {
      streamPolygon(object2.coordinates, stream2);
    },
    MultiPolygon: function(object2, stream2) {
      var coordinates = object2.coordinates, i2 = -1, n2 = coordinates.length;
      while (++i2 < n2) streamPolygon(coordinates[i2], stream2);
    },
    GeometryCollection: function(object2, stream2) {
      var geometries = object2.geometries, i2 = -1, n2 = geometries.length;
      while (++i2 < n2) streamGeometry(geometries[i2], stream2);
    }
  };
  function streamLine(coordinates, stream2, closed) {
    var i2 = -1, n2 = coordinates.length - closed, coordinate;
    stream2.lineStart();
    while (++i2 < n2) coordinate = coordinates[i2], stream2.point(coordinate[0], coordinate[1], coordinate[2]);
    stream2.lineEnd();
  }
  function streamPolygon(coordinates, stream2) {
    var i2 = -1, n2 = coordinates.length;
    stream2.polygonStart();
    while (++i2 < n2) streamLine(coordinates[i2], stream2, 1);
    stream2.polygonEnd();
  }
  function stream_default(object2, stream2) {
    if (object2 && streamObjectType.hasOwnProperty(object2.type)) {
      streamObjectType[object2.type](object2, stream2);
    } else {
      streamGeometry(object2, stream2);
    }
  }

  // node_modules/d3-geo/src/area.js
  var areaRingSum = new Adder();
  var areaSum = new Adder();
  var lambda00;
  var phi00;
  var lambda0;
  var cosPhi0;
  var sinPhi0;
  var areaStream = {
    point: noop2,
    lineStart: noop2,
    lineEnd: noop2,
    polygonStart: function() {
      areaRingSum = new Adder();
      areaStream.lineStart = areaRingStart;
      areaStream.lineEnd = areaRingEnd;
    },
    polygonEnd: function() {
      var areaRing = +areaRingSum;
      areaSum.add(areaRing < 0 ? tau3 + areaRing : areaRing);
      this.lineStart = this.lineEnd = this.point = noop2;
    },
    sphere: function() {
      areaSum.add(tau3);
    }
  };
  function areaRingStart() {
    areaStream.point = areaPointFirst;
  }
  function areaRingEnd() {
    areaPoint(lambda00, phi00);
  }
  function areaPointFirst(lambda, phi2) {
    areaStream.point = areaPoint;
    lambda00 = lambda, phi00 = phi2;
    lambda *= radians2, phi2 *= radians2;
    lambda0 = lambda, cosPhi0 = cos2(phi2 = phi2 / 2 + quarterPi), sinPhi0 = sin2(phi2);
  }
  function areaPoint(lambda, phi2) {
    lambda *= radians2, phi2 *= radians2;
    phi2 = phi2 / 2 + quarterPi;
    var dLambda = lambda - lambda0, sdLambda = dLambda >= 0 ? 1 : -1, adLambda = sdLambda * dLambda, cosPhi = cos2(phi2), sinPhi = sin2(phi2), k2 = sinPhi0 * sinPhi, u5 = cosPhi0 * cosPhi + k2 * cos2(adLambda), v3 = k2 * sdLambda * sin2(adLambda);
    areaRingSum.add(atan22(v3, u5));
    lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;
  }
  function area_default2(object2) {
    areaSum = new Adder();
    stream_default(object2, areaStream);
    return areaSum * 2;
  }

  // node_modules/d3-geo/src/cartesian.js
  function spherical(cartesian2) {
    return [atan22(cartesian2[1], cartesian2[0]), asin2(cartesian2[2])];
  }
  function cartesian(spherical2) {
    var lambda = spherical2[0], phi2 = spherical2[1], cosPhi = cos2(phi2);
    return [cosPhi * cos2(lambda), cosPhi * sin2(lambda), sin2(phi2)];
  }
  function cartesianDot(a4, b3) {
    return a4[0] * b3[0] + a4[1] * b3[1] + a4[2] * b3[2];
  }
  function cartesianCross(a4, b3) {
    return [a4[1] * b3[2] - a4[2] * b3[1], a4[2] * b3[0] - a4[0] * b3[2], a4[0] * b3[1] - a4[1] * b3[0]];
  }
  function cartesianAddInPlace(a4, b3) {
    a4[0] += b3[0], a4[1] += b3[1], a4[2] += b3[2];
  }
  function cartesianScale(vector, k2) {
    return [vector[0] * k2, vector[1] * k2, vector[2] * k2];
  }
  function cartesianNormalizeInPlace(d2) {
    var l2 = sqrt3(d2[0] * d2[0] + d2[1] * d2[1] + d2[2] * d2[2]);
    d2[0] /= l2, d2[1] /= l2, d2[2] /= l2;
  }

  // node_modules/d3-geo/src/bounds.js
  var lambda02;
  var phi0;
  var lambda1;
  var phi1;
  var lambda2;
  var lambda002;
  var phi002;
  var p0;
  var deltaSum;
  var ranges;
  var range2;
  var boundsStream = {
    point: boundsPoint,
    lineStart: boundsLineStart,
    lineEnd: boundsLineEnd,
    polygonStart: function() {
      boundsStream.point = boundsRingPoint;
      boundsStream.lineStart = boundsRingStart;
      boundsStream.lineEnd = boundsRingEnd;
      deltaSum = new Adder();
      areaStream.polygonStart();
    },
    polygonEnd: function() {
      areaStream.polygonEnd();
      boundsStream.point = boundsPoint;
      boundsStream.lineStart = boundsLineStart;
      boundsStream.lineEnd = boundsLineEnd;
      if (areaRingSum < 0) lambda02 = -(lambda1 = 180), phi0 = -(phi1 = 90);
      else if (deltaSum > epsilon4) phi1 = 90;
      else if (deltaSum < -epsilon4) phi0 = -90;
      range2[0] = lambda02, range2[1] = lambda1;
    },
    sphere: function() {
      lambda02 = -(lambda1 = 180), phi0 = -(phi1 = 90);
    }
  };
  function boundsPoint(lambda, phi2) {
    ranges.push(range2 = [lambda02 = lambda, lambda1 = lambda]);
    if (phi2 < phi0) phi0 = phi2;
    if (phi2 > phi1) phi1 = phi2;
  }
  function linePoint(lambda, phi2) {
    var p2 = cartesian([lambda * radians2, phi2 * radians2]);
    if (p0) {
      var normal = cartesianCross(p0, p2), equatorial = [normal[1], -normal[0], 0], inflection = cartesianCross(equatorial, normal);
      cartesianNormalizeInPlace(inflection);
      inflection = spherical(inflection);
      var delta = lambda - lambda2, sign3 = delta > 0 ? 1 : -1, lambdai = inflection[0] * degrees3 * sign3, phii, antimeridian = abs2(delta) > 180;
      if (antimeridian ^ (sign3 * lambda2 < lambdai && lambdai < sign3 * lambda)) {
        phii = inflection[1] * degrees3;
        if (phii > phi1) phi1 = phii;
      } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign3 * lambda2 < lambdai && lambdai < sign3 * lambda)) {
        phii = -inflection[1] * degrees3;
        if (phii < phi0) phi0 = phii;
      } else {
        if (phi2 < phi0) phi0 = phi2;
        if (phi2 > phi1) phi1 = phi2;
      }
      if (antimeridian) {
        if (lambda < lambda2) {
          if (angle(lambda02, lambda) > angle(lambda02, lambda1)) lambda1 = lambda;
        } else {
          if (angle(lambda, lambda1) > angle(lambda02, lambda1)) lambda02 = lambda;
        }
      } else {
        if (lambda1 >= lambda02) {
          if (lambda < lambda02) lambda02 = lambda;
          if (lambda > lambda1) lambda1 = lambda;
        } else {
          if (lambda > lambda2) {
            if (angle(lambda02, lambda) > angle(lambda02, lambda1)) lambda1 = lambda;
          } else {
            if (angle(lambda, lambda1) > angle(lambda02, lambda1)) lambda02 = lambda;
          }
        }
      }
    } else {
      ranges.push(range2 = [lambda02 = lambda, lambda1 = lambda]);
    }
    if (phi2 < phi0) phi0 = phi2;
    if (phi2 > phi1) phi1 = phi2;
    p0 = p2, lambda2 = lambda;
  }
  function boundsLineStart() {
    boundsStream.point = linePoint;
  }
  function boundsLineEnd() {
    range2[0] = lambda02, range2[1] = lambda1;
    boundsStream.point = boundsPoint;
    p0 = null;
  }
  function boundsRingPoint(lambda, phi2) {
    if (p0) {
      var delta = lambda - lambda2;
      deltaSum.add(abs2(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
    } else {
      lambda002 = lambda, phi002 = phi2;
    }
    areaStream.point(lambda, phi2);
    linePoint(lambda, phi2);
  }
  function boundsRingStart() {
    areaStream.lineStart();
  }
  function boundsRingEnd() {
    boundsRingPoint(lambda002, phi002);
    areaStream.lineEnd();
    if (abs2(deltaSum) > epsilon4) lambda02 = -(lambda1 = 180);
    range2[0] = lambda02, range2[1] = lambda1;
    p0 = null;
  }
  function angle(lambda03, lambda12) {
    return (lambda12 -= lambda03) < 0 ? lambda12 + 360 : lambda12;
  }
  function rangeCompare(a4, b3) {
    return a4[0] - b3[0];
  }
  function rangeContains(range7, x5) {
    return range7[0] <= range7[1] ? range7[0] <= x5 && x5 <= range7[1] : x5 < range7[0] || range7[1] < x5;
  }
  function bounds_default(feature2) {
    var i2, n2, a4, b3, merged, deltaMax, delta;
    phi1 = lambda1 = -(lambda02 = phi0 = Infinity);
    ranges = [];
    stream_default(feature2, boundsStream);
    if (n2 = ranges.length) {
      ranges.sort(rangeCompare);
      for (i2 = 1, a4 = ranges[0], merged = [a4]; i2 < n2; ++i2) {
        b3 = ranges[i2];
        if (rangeContains(a4, b3[0]) || rangeContains(a4, b3[1])) {
          if (angle(a4[0], b3[1]) > angle(a4[0], a4[1])) a4[1] = b3[1];
          if (angle(b3[0], a4[1]) > angle(a4[0], a4[1])) a4[0] = b3[0];
        } else {
          merged.push(a4 = b3);
        }
      }
      for (deltaMax = -Infinity, n2 = merged.length - 1, i2 = 0, a4 = merged[n2]; i2 <= n2; a4 = b3, ++i2) {
        b3 = merged[i2];
        if ((delta = angle(a4[1], b3[0])) > deltaMax) deltaMax = delta, lambda02 = b3[0], lambda1 = a4[1];
      }
    }
    ranges = range2 = null;
    return lambda02 === Infinity || phi0 === Infinity ? [[NaN, NaN], [NaN, NaN]] : [[lambda02, phi0], [lambda1, phi1]];
  }

  // node_modules/d3-geo/src/centroid.js
  var W0;
  var W1;
  var X0;
  var Y0;
  var Z0;
  var X1;
  var Y1;
  var Z1;
  var X2;
  var Y2;
  var Z2;
  var lambda003;
  var phi003;
  var x0;
  var y0;
  var z0;
  var centroidStream = {
    sphere: noop2,
    point: centroidPoint,
    lineStart: centroidLineStart,
    lineEnd: centroidLineEnd,
    polygonStart: function() {
      centroidStream.lineStart = centroidRingStart;
      centroidStream.lineEnd = centroidRingEnd;
    },
    polygonEnd: function() {
      centroidStream.lineStart = centroidLineStart;
      centroidStream.lineEnd = centroidLineEnd;
    }
  };
  function centroidPoint(lambda, phi2) {
    lambda *= radians2, phi2 *= radians2;
    var cosPhi = cos2(phi2);
    centroidPointCartesian(cosPhi * cos2(lambda), cosPhi * sin2(lambda), sin2(phi2));
  }
  function centroidPointCartesian(x5, y5, z) {
    ++W0;
    X0 += (x5 - X0) / W0;
    Y0 += (y5 - Y0) / W0;
    Z0 += (z - Z0) / W0;
  }
  function centroidLineStart() {
    centroidStream.point = centroidLinePointFirst;
  }
  function centroidLinePointFirst(lambda, phi2) {
    lambda *= radians2, phi2 *= radians2;
    var cosPhi = cos2(phi2);
    x0 = cosPhi * cos2(lambda);
    y0 = cosPhi * sin2(lambda);
    z0 = sin2(phi2);
    centroidStream.point = centroidLinePoint;
    centroidPointCartesian(x0, y0, z0);
  }
  function centroidLinePoint(lambda, phi2) {
    lambda *= radians2, phi2 *= radians2;
    var cosPhi = cos2(phi2), x5 = cosPhi * cos2(lambda), y5 = cosPhi * sin2(lambda), z = sin2(phi2), w3 = atan22(sqrt3((w3 = y0 * z - z0 * y5) * w3 + (w3 = z0 * x5 - x0 * z) * w3 + (w3 = x0 * y5 - y0 * x5) * w3), x0 * x5 + y0 * y5 + z0 * z);
    W1 += w3;
    X1 += w3 * (x0 + (x0 = x5));
    Y1 += w3 * (y0 + (y0 = y5));
    Z1 += w3 * (z0 + (z0 = z));
    centroidPointCartesian(x0, y0, z0);
  }
  function centroidLineEnd() {
    centroidStream.point = centroidPoint;
  }
  function centroidRingStart() {
    centroidStream.point = centroidRingPointFirst;
  }
  function centroidRingEnd() {
    centroidRingPoint(lambda003, phi003);
    centroidStream.point = centroidPoint;
  }
  function centroidRingPointFirst(lambda, phi2) {
    lambda003 = lambda, phi003 = phi2;
    lambda *= radians2, phi2 *= radians2;
    centroidStream.point = centroidRingPoint;
    var cosPhi = cos2(phi2);
    x0 = cosPhi * cos2(lambda);
    y0 = cosPhi * sin2(lambda);
    z0 = sin2(phi2);
    centroidPointCartesian(x0, y0, z0);
  }
  function centroidRingPoint(lambda, phi2) {
    lambda *= radians2, phi2 *= radians2;
    var cosPhi = cos2(phi2), x5 = cosPhi * cos2(lambda), y5 = cosPhi * sin2(lambda), z = sin2(phi2), cx = y0 * z - z0 * y5, cy = z0 * x5 - x0 * z, cz = x0 * y5 - y0 * x5, m4 = hypot(cx, cy, cz), w3 = asin2(m4), v3 = m4 && -w3 / m4;
    X2.add(v3 * cx);
    Y2.add(v3 * cy);
    Z2.add(v3 * cz);
    W1 += w3;
    X1 += w3 * (x0 + (x0 = x5));
    Y1 += w3 * (y0 + (y0 = y5));
    Z1 += w3 * (z0 + (z0 = z));
    centroidPointCartesian(x0, y0, z0);
  }
  function centroid_default(object2) {
    W0 = W1 = X0 = Y0 = Z0 = X1 = Y1 = Z1 = 0;
    X2 = new Adder();
    Y2 = new Adder();
    Z2 = new Adder();
    stream_default(object2, centroidStream);
    var x5 = +X2, y5 = +Y2, z = +Z2, m4 = hypot(x5, y5, z);
    if (m4 < epsilon23) {
      x5 = X1, y5 = Y1, z = Z1;
      if (W1 < epsilon4) x5 = X0, y5 = Y0, z = Z0;
      m4 = hypot(x5, y5, z);
      if (m4 < epsilon23) return [NaN, NaN];
    }
    return [atan22(y5, x5) * degrees3, asin2(z / m4) * degrees3];
  }

  // node_modules/d3-geo/src/compose.js
  function compose_default(a4, b3) {
    function compose(x5, y5) {
      return x5 = a4(x5, y5), b3(x5[0], x5[1]);
    }
    if (a4.invert && b3.invert) compose.invert = function(x5, y5) {
      return x5 = b3.invert(x5, y5), x5 && a4.invert(x5[0], x5[1]);
    };
    return compose;
  }

  // node_modules/d3-geo/src/rotation.js
  function rotationIdentity(lambda, phi2) {
    if (abs2(lambda) > pi3) lambda -= Math.round(lambda / tau3) * tau3;
    return [lambda, phi2];
  }
  rotationIdentity.invert = rotationIdentity;
  function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
    return (deltaLambda %= tau3) ? deltaPhi || deltaGamma ? compose_default(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma)) : rotationLambda(deltaLambda) : deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma) : rotationIdentity;
  }
  function forwardRotationLambda(deltaLambda) {
    return function(lambda, phi2) {
      lambda += deltaLambda;
      if (abs2(lambda) > pi3) lambda -= Math.round(lambda / tau3) * tau3;
      return [lambda, phi2];
    };
  }
  function rotationLambda(deltaLambda) {
    var rotation = forwardRotationLambda(deltaLambda);
    rotation.invert = forwardRotationLambda(-deltaLambda);
    return rotation;
  }
  function rotationPhiGamma(deltaPhi, deltaGamma) {
    var cosDeltaPhi = cos2(deltaPhi), sinDeltaPhi = sin2(deltaPhi), cosDeltaGamma = cos2(deltaGamma), sinDeltaGamma = sin2(deltaGamma);
    function rotation(lambda, phi2) {
      var cosPhi = cos2(phi2), x5 = cos2(lambda) * cosPhi, y5 = sin2(lambda) * cosPhi, z = sin2(phi2), k2 = z * cosDeltaPhi + x5 * sinDeltaPhi;
      return [
        atan22(y5 * cosDeltaGamma - k2 * sinDeltaGamma, x5 * cosDeltaPhi - z * sinDeltaPhi),
        asin2(k2 * cosDeltaGamma + y5 * sinDeltaGamma)
      ];
    }
    rotation.invert = function(lambda, phi2) {
      var cosPhi = cos2(phi2), x5 = cos2(lambda) * cosPhi, y5 = sin2(lambda) * cosPhi, z = sin2(phi2), k2 = z * cosDeltaGamma - y5 * sinDeltaGamma;
      return [
        atan22(y5 * cosDeltaGamma + z * sinDeltaGamma, x5 * cosDeltaPhi + k2 * sinDeltaPhi),
        asin2(k2 * cosDeltaPhi - x5 * sinDeltaPhi)
      ];
    };
    return rotation;
  }
  function rotation_default(rotate2) {
    rotate2 = rotateRadians(rotate2[0] * radians2, rotate2[1] * radians2, rotate2.length > 2 ? rotate2[2] * radians2 : 0);
    function forward(coordinates) {
      coordinates = rotate2(coordinates[0] * radians2, coordinates[1] * radians2);
      return coordinates[0] *= degrees3, coordinates[1] *= degrees3, coordinates;
    }
    forward.invert = function(coordinates) {
      coordinates = rotate2.invert(coordinates[0] * radians2, coordinates[1] * radians2);
      return coordinates[0] *= degrees3, coordinates[1] *= degrees3, coordinates;
    };
    return forward;
  }

  // node_modules/d3-geo/src/circle.js
  function circleStream(stream2, radius2, delta, direction, t04, t13) {
    if (!delta) return;
    var cosRadius = cos2(radius2), sinRadius = sin2(radius2), step = direction * delta;
    if (t04 == null) {
      t04 = radius2 + direction * tau3;
      t13 = radius2 - step / 2;
    } else {
      t04 = circleRadius(cosRadius, t04);
      t13 = circleRadius(cosRadius, t13);
      if (direction > 0 ? t04 < t13 : t04 > t13) t04 += direction * tau3;
    }
    for (var point9, t4 = t04; direction > 0 ? t4 > t13 : t4 < t13; t4 -= step) {
      point9 = spherical([cosRadius, -sinRadius * cos2(t4), -sinRadius * sin2(t4)]);
      stream2.point(point9[0], point9[1]);
    }
  }
  function circleRadius(cosRadius, point9) {
    point9 = cartesian(point9), point9[0] -= cosRadius;
    cartesianNormalizeInPlace(point9);
    var radius2 = acos2(-point9[1]);
    return ((-point9[2] < 0 ? -radius2 : radius2) + tau3 - epsilon4) % tau3;
  }

  // node_modules/d3-geo/src/clip/buffer.js
  function buffer_default() {
    var lines = [], line4;
    return {
      point: function(x5, y5, m4) {
        line4.push([x5, y5, m4]);
      },
      lineStart: function() {
        lines.push(line4 = []);
      },
      lineEnd: noop2,
      rejoin: function() {
        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
      },
      result: function() {
        var result = lines;
        lines = [];
        line4 = null;
        return result;
      }
    };
  }

  // node_modules/d3-geo/src/pointEqual.js
  function pointEqual_default(a4, b3) {
    return abs2(a4[0] - b3[0]) < epsilon4 && abs2(a4[1] - b3[1]) < epsilon4;
  }

  // node_modules/d3-geo/src/clip/rejoin.js
  function Intersection(point9, points2, other, entry2) {
    this.x = point9;
    this.z = points2;
    this.o = other;
    this.e = entry2;
    this.v = false;
    this.n = this.p = null;
  }
  function rejoin_default(segments2, compareIntersection2, startInside, interpolate3, stream2) {
    var subject = [], clip3 = [], i2, n2;
    segments2.forEach(function(segment) {
      if ((n3 = segment.length - 1) <= 0) return;
      var n3, p02 = segment[0], p1 = segment[n3], x5;
      if (pointEqual_default(p02, p1)) {
        if (!p02[2] && !p1[2]) {
          stream2.lineStart();
          for (i2 = 0; i2 < n3; ++i2) stream2.point((p02 = segment[i2])[0], p02[1]);
          stream2.lineEnd();
          return;
        }
        p1[0] += 2 * epsilon4;
      }
      subject.push(x5 = new Intersection(p02, segment, null, true));
      clip3.push(x5.o = new Intersection(p02, null, x5, false));
      subject.push(x5 = new Intersection(p1, segment, null, false));
      clip3.push(x5.o = new Intersection(p1, null, x5, true));
    });
    if (!subject.length) return;
    clip3.sort(compareIntersection2);
    link(subject);
    link(clip3);
    for (i2 = 0, n2 = clip3.length; i2 < n2; ++i2) {
      clip3[i2].e = startInside = !startInside;
    }
    var start = subject[0], points2, point9;
    while (1) {
      var current2 = start, isSubject = true;
      while (current2.v) if ((current2 = current2.n) === start) return;
      points2 = current2.z;
      stream2.lineStart();
      do {
        current2.v = current2.o.v = true;
        if (current2.e) {
          if (isSubject) {
            for (i2 = 0, n2 = points2.length; i2 < n2; ++i2) stream2.point((point9 = points2[i2])[0], point9[1]);
          } else {
            interpolate3(current2.x, current2.n.x, 1, stream2);
          }
          current2 = current2.n;
        } else {
          if (isSubject) {
            points2 = current2.p.z;
            for (i2 = points2.length - 1; i2 >= 0; --i2) stream2.point((point9 = points2[i2])[0], point9[1]);
          } else {
            interpolate3(current2.x, current2.p.x, -1, stream2);
          }
          current2 = current2.p;
        }
        current2 = current2.o;
        points2 = current2.z;
        isSubject = !isSubject;
      } while (!current2.v);
      stream2.lineEnd();
    }
  }
  function link(array4) {
    if (!(n2 = array4.length)) return;
    var n2, i2 = 0, a4 = array4[0], b3;
    while (++i2 < n2) {
      a4.n = b3 = array4[i2];
      b3.p = a4;
      a4 = b3;
    }
    a4.n = b3 = array4[0];
    b3.p = a4;
  }

  // node_modules/d3-geo/src/polygonContains.js
  function longitude(point9) {
    return abs2(point9[0]) <= pi3 ? point9[0] : sign2(point9[0]) * ((abs2(point9[0]) + pi3) % tau3 - pi3);
  }
  function polygonContains_default(polygon, point9) {
    var lambda = longitude(point9), phi2 = point9[1], sinPhi = sin2(phi2), normal = [sin2(lambda), -cos2(lambda), 0], angle2 = 0, winding = 0;
    var sum3 = new Adder();
    if (sinPhi === 1) phi2 = halfPi2 + epsilon4;
    else if (sinPhi === -1) phi2 = -halfPi2 - epsilon4;
    for (var i2 = 0, n2 = polygon.length; i2 < n2; ++i2) {
      if (!(m4 = (ring = polygon[i2]).length)) continue;
      var ring, m4, point0 = ring[m4 - 1], lambda03 = longitude(point0), phi02 = point0[1] / 2 + quarterPi, sinPhi02 = sin2(phi02), cosPhi02 = cos2(phi02);
      for (var j2 = 0; j2 < m4; ++j2, lambda03 = lambda12, sinPhi02 = sinPhi1, cosPhi02 = cosPhi1, point0 = point1) {
        var point1 = ring[j2], lambda12 = longitude(point1), phi12 = point1[1] / 2 + quarterPi, sinPhi1 = sin2(phi12), cosPhi1 = cos2(phi12), delta = lambda12 - lambda03, sign3 = delta >= 0 ? 1 : -1, absDelta = sign3 * delta, antimeridian = absDelta > pi3, k2 = sinPhi02 * sinPhi1;
        sum3.add(atan22(k2 * sign3 * sin2(absDelta), cosPhi02 * cosPhi1 + k2 * cos2(absDelta)));
        angle2 += antimeridian ? delta + sign3 * tau3 : delta;
        if (antimeridian ^ lambda03 >= lambda ^ lambda12 >= lambda) {
          var arc4 = cartesianCross(cartesian(point0), cartesian(point1));
          cartesianNormalizeInPlace(arc4);
          var intersection2 = cartesianCross(normal, arc4);
          cartesianNormalizeInPlace(intersection2);
          var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin2(intersection2[2]);
          if (phi2 > phiArc || phi2 === phiArc && (arc4[0] || arc4[1])) {
            winding += antimeridian ^ delta >= 0 ? 1 : -1;
          }
        }
      }
    }
    return (angle2 < -epsilon4 || angle2 < epsilon4 && sum3 < -epsilon23) ^ winding & 1;
  }

  // node_modules/d3-geo/src/clip/index.js
  function clip_default(pointVisible, clipLine, interpolate3, start) {
    return function(sink) {
      var line4 = clipLine(sink), ringBuffer = buffer_default(), ringSink = clipLine(ringBuffer), polygonStarted = false, polygon, segments2, ring;
      var clip3 = {
        point: point9,
        lineStart,
        lineEnd,
        polygonStart: function() {
          clip3.point = pointRing;
          clip3.lineStart = ringStart;
          clip3.lineEnd = ringEnd;
          segments2 = [];
          polygon = [];
        },
        polygonEnd: function() {
          clip3.point = point9;
          clip3.lineStart = lineStart;
          clip3.lineEnd = lineEnd;
          segments2 = merge2(segments2);
          var startInside = polygonContains_default(polygon, start);
          if (segments2.length) {
            if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
            rejoin_default(segments2, compareIntersection, startInside, interpolate3, sink);
          } else if (startInside) {
            if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
            sink.lineStart();
            interpolate3(null, null, 1, sink);
            sink.lineEnd();
          }
          if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
          segments2 = polygon = null;
        },
        sphere: function() {
          sink.polygonStart();
          sink.lineStart();
          interpolate3(null, null, 1, sink);
          sink.lineEnd();
          sink.polygonEnd();
        }
      };
      function point9(lambda, phi2) {
        if (pointVisible(lambda, phi2)) sink.point(lambda, phi2);
      }
      function pointLine(lambda, phi2) {
        line4.point(lambda, phi2);
      }
      function lineStart() {
        clip3.point = pointLine;
        line4.lineStart();
      }
      function lineEnd() {
        clip3.point = point9;
        line4.lineEnd();
      }
      function pointRing(lambda, phi2) {
        ring.push([lambda, phi2]);
        ringSink.point(lambda, phi2);
      }
      function ringStart() {
        ringSink.lineStart();
        ring = [];
      }
      function ringEnd() {
        pointRing(ring[0][0], ring[0][1]);
        ringSink.lineEnd();
        var clean = ringSink.clean(), ringSegments = ringBuffer.result(), i2, n2 = ringSegments.length, m4, segment, point10;
        ring.pop();
        polygon.push(ring);
        ring = null;
        if (!n2) return;
        if (clean & 1) {
          segment = ringSegments[0];
          if ((m4 = segment.length - 1) > 0) {
            if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
            sink.lineStart();
            for (i2 = 0; i2 < m4; ++i2) sink.point((point10 = segment[i2])[0], point10[1]);
            sink.lineEnd();
          }
          return;
        }
        if (n2 > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
        segments2.push(ringSegments.filter(validSegment));
      }
      return clip3;
    };
  }
  function validSegment(segment) {
    return segment.length > 1;
  }
  function compareIntersection(a4, b3) {
    return ((a4 = a4.x)[0] < 0 ? a4[1] - halfPi2 - epsilon4 : halfPi2 - a4[1]) - ((b3 = b3.x)[0] < 0 ? b3[1] - halfPi2 - epsilon4 : halfPi2 - b3[1]);
  }

  // node_modules/d3-geo/src/clip/antimeridian.js
  var antimeridian_default = clip_default(
    function() {
      return true;
    },
    clipAntimeridianLine,
    clipAntimeridianInterpolate,
    [-pi3, -halfPi2]
  );
  function clipAntimeridianLine(stream2) {
    var lambda03 = NaN, phi02 = NaN, sign0 = NaN, clean;
    return {
      lineStart: function() {
        stream2.lineStart();
        clean = 1;
      },
      point: function(lambda12, phi12) {
        var sign1 = lambda12 > 0 ? pi3 : -pi3, delta = abs2(lambda12 - lambda03);
        if (abs2(delta - pi3) < epsilon4) {
          stream2.point(lambda03, phi02 = (phi02 + phi12) / 2 > 0 ? halfPi2 : -halfPi2);
          stream2.point(sign0, phi02);
          stream2.lineEnd();
          stream2.lineStart();
          stream2.point(sign1, phi02);
          stream2.point(lambda12, phi02);
          clean = 0;
        } else if (sign0 !== sign1 && delta >= pi3) {
          if (abs2(lambda03 - sign0) < epsilon4) lambda03 -= sign0 * epsilon4;
          if (abs2(lambda12 - sign1) < epsilon4) lambda12 -= sign1 * epsilon4;
          phi02 = clipAntimeridianIntersect(lambda03, phi02, lambda12, phi12);
          stream2.point(sign0, phi02);
          stream2.lineEnd();
          stream2.lineStart();
          stream2.point(sign1, phi02);
          clean = 0;
        }
        stream2.point(lambda03 = lambda12, phi02 = phi12);
        sign0 = sign1;
      },
      lineEnd: function() {
        stream2.lineEnd();
        lambda03 = phi02 = NaN;
      },
      clean: function() {
        return 2 - clean;
      }
    };
  }
  function clipAntimeridianIntersect(lambda03, phi02, lambda12, phi12) {
    var cosPhi02, cosPhi1, sinLambda0Lambda1 = sin2(lambda03 - lambda12);
    return abs2(sinLambda0Lambda1) > epsilon4 ? atan((sin2(phi02) * (cosPhi1 = cos2(phi12)) * sin2(lambda12) - sin2(phi12) * (cosPhi02 = cos2(phi02)) * sin2(lambda03)) / (cosPhi02 * cosPhi1 * sinLambda0Lambda1)) : (phi02 + phi12) / 2;
  }
  function clipAntimeridianInterpolate(from, to, direction, stream2) {
    var phi2;
    if (from == null) {
      phi2 = direction * halfPi2;
      stream2.point(-pi3, phi2);
      stream2.point(0, phi2);
      stream2.point(pi3, phi2);
      stream2.point(pi3, 0);
      stream2.point(pi3, -phi2);
      stream2.point(0, -phi2);
      stream2.point(-pi3, -phi2);
      stream2.point(-pi3, 0);
      stream2.point(-pi3, phi2);
    } else if (abs2(from[0] - to[0]) > epsilon4) {
      var lambda = from[0] < to[0] ? pi3 : -pi3;
      phi2 = direction * lambda / 2;
      stream2.point(-lambda, phi2);
      stream2.point(0, phi2);
      stream2.point(lambda, phi2);
    } else {
      stream2.point(to[0], to[1]);
    }
  }

  // node_modules/d3-geo/src/clip/circle.js
  function circle_default2(radius2) {
    var cr2 = cos2(radius2), delta = 2 * radians2, smallRadius = cr2 > 0, notHemisphere = abs2(cr2) > epsilon4;
    function interpolate3(from, to, direction, stream2) {
      circleStream(stream2, radius2, delta, direction, from, to);
    }
    function visible(lambda, phi2) {
      return cos2(lambda) * cos2(phi2) > cr2;
    }
    function clipLine(stream2) {
      var point0, c0, v0, v00, clean;
      return {
        lineStart: function() {
          v00 = v0 = false;
          clean = 1;
        },
        point: function(lambda, phi2) {
          var point1 = [lambda, phi2], point22, v3 = visible(lambda, phi2), c4 = smallRadius ? v3 ? 0 : code(lambda, phi2) : v3 ? code(lambda + (lambda < 0 ? pi3 : -pi3), phi2) : 0;
          if (!point0 && (v00 = v0 = v3)) stream2.lineStart();
          if (v3 !== v0) {
            point22 = intersect5(point0, point1);
            if (!point22 || pointEqual_default(point0, point22) || pointEqual_default(point1, point22))
              point1[2] = 1;
          }
          if (v3 !== v0) {
            clean = 0;
            if (v3) {
              stream2.lineStart();
              point22 = intersect5(point1, point0);
              stream2.point(point22[0], point22[1]);
            } else {
              point22 = intersect5(point0, point1);
              stream2.point(point22[0], point22[1], 2);
              stream2.lineEnd();
            }
            point0 = point22;
          } else if (notHemisphere && point0 && smallRadius ^ v3) {
            var t4;
            if (!(c4 & c0) && (t4 = intersect5(point1, point0, true))) {
              clean = 0;
              if (smallRadius) {
                stream2.lineStart();
                stream2.point(t4[0][0], t4[0][1]);
                stream2.point(t4[1][0], t4[1][1]);
                stream2.lineEnd();
              } else {
                stream2.point(t4[1][0], t4[1][1]);
                stream2.lineEnd();
                stream2.lineStart();
                stream2.point(t4[0][0], t4[0][1], 3);
              }
            }
          }
          if (v3 && (!point0 || !pointEqual_default(point0, point1))) {
            stream2.point(point1[0], point1[1]);
          }
          point0 = point1, v0 = v3, c0 = c4;
        },
        lineEnd: function() {
          if (v0) stream2.lineEnd();
          point0 = null;
        },
        // Rejoin first and last segments if there were intersections and the first
        // and last points were visible.
        clean: function() {
          return clean | (v00 && v0) << 1;
        }
      };
    }
    function intersect5(a4, b3, two) {
      var pa2 = cartesian(a4), pb = cartesian(b3);
      var n1 = [1, 0, 0], n2 = cartesianCross(pa2, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
      if (!determinant) return !two && a4;
      var c1 = cr2 * n2n2 / determinant, c22 = -cr2 * n1n2 / determinant, n1xn2 = cartesianCross(n1, n2), A5 = cartesianScale(n1, c1), B3 = cartesianScale(n2, c22);
      cartesianAddInPlace(A5, B3);
      var u5 = n1xn2, w3 = cartesianDot(A5, u5), uu = cartesianDot(u5, u5), t22 = w3 * w3 - uu * (cartesianDot(A5, A5) - 1);
      if (t22 < 0) return;
      var t4 = sqrt3(t22), q2 = cartesianScale(u5, (-w3 - t4) / uu);
      cartesianAddInPlace(q2, A5);
      q2 = spherical(q2);
      if (!two) return q2;
      var lambda03 = a4[0], lambda12 = b3[0], phi02 = a4[1], phi12 = b3[1], z;
      if (lambda12 < lambda03) z = lambda03, lambda03 = lambda12, lambda12 = z;
      var delta2 = lambda12 - lambda03, polar = abs2(delta2 - pi3) < epsilon4, meridian = polar || delta2 < epsilon4;
      if (!polar && phi12 < phi02) z = phi02, phi02 = phi12, phi12 = z;
      if (meridian ? polar ? phi02 + phi12 > 0 ^ q2[1] < (abs2(q2[0] - lambda03) < epsilon4 ? phi02 : phi12) : phi02 <= q2[1] && q2[1] <= phi12 : delta2 > pi3 ^ (lambda03 <= q2[0] && q2[0] <= lambda12)) {
        var q1 = cartesianScale(u5, (-w3 + t4) / uu);
        cartesianAddInPlace(q1, A5);
        return [q2, spherical(q1)];
      }
    }
    function code(lambda, phi2) {
      var r2 = smallRadius ? radius2 : pi3 - radius2, code2 = 0;
      if (lambda < -r2) code2 |= 1;
      else if (lambda > r2) code2 |= 2;
      if (phi2 < -r2) code2 |= 4;
      else if (phi2 > r2) code2 |= 8;
      return code2;
    }
    return clip_default(visible, clipLine, interpolate3, smallRadius ? [0, -radius2] : [-pi3, radius2 - pi3]);
  }

  // node_modules/d3-geo/src/clip/line.js
  function line_default2(a4, b3, x06, y06, x12, y12) {
    var ax = a4[0], ay = a4[1], bx = b3[0], by = b3[1], t04 = 0, t13 = 1, dx = bx - ax, dy = by - ay, r2;
    r2 = x06 - ax;
    if (!dx && r2 > 0) return;
    r2 /= dx;
    if (dx < 0) {
      if (r2 < t04) return;
      if (r2 < t13) t13 = r2;
    } else if (dx > 0) {
      if (r2 > t13) return;
      if (r2 > t04) t04 = r2;
    }
    r2 = x12 - ax;
    if (!dx && r2 < 0) return;
    r2 /= dx;
    if (dx < 0) {
      if (r2 > t13) return;
      if (r2 > t04) t04 = r2;
    } else if (dx > 0) {
      if (r2 < t04) return;
      if (r2 < t13) t13 = r2;
    }
    r2 = y06 - ay;
    if (!dy && r2 > 0) return;
    r2 /= dy;
    if (dy < 0) {
      if (r2 < t04) return;
      if (r2 < t13) t13 = r2;
    } else if (dy > 0) {
      if (r2 > t13) return;
      if (r2 > t04) t04 = r2;
    }
    r2 = y12 - ay;
    if (!dy && r2 < 0) return;
    r2 /= dy;
    if (dy < 0) {
      if (r2 > t13) return;
      if (r2 > t04) t04 = r2;
    } else if (dy > 0) {
      if (r2 < t04) return;
      if (r2 < t13) t13 = r2;
    }
    if (t04 > 0) a4[0] = ax + t04 * dx, a4[1] = ay + t04 * dy;
    if (t13 < 1) b3[0] = ax + t13 * dx, b3[1] = ay + t13 * dy;
    return true;
  }

  // node_modules/d3-geo/src/clip/rectangle.js
  var clipMax = 1e9;
  var clipMin = -clipMax;
  function clipRectangle(x06, y06, x12, y12) {
    function visible(x5, y5) {
      return x06 <= x5 && x5 <= x12 && y06 <= y5 && y5 <= y12;
    }
    function interpolate3(from, to, direction, stream2) {
      var a4 = 0, a1 = 0;
      if (from == null || (a4 = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoint(from, to) < 0 ^ direction > 0) {
        do
          stream2.point(a4 === 0 || a4 === 3 ? x06 : x12, a4 > 1 ? y12 : y06);
        while ((a4 = (a4 + direction + 4) % 4) !== a1);
      } else {
        stream2.point(to[0], to[1]);
      }
    }
    function corner(p2, direction) {
      return abs2(p2[0] - x06) < epsilon4 ? direction > 0 ? 0 : 3 : abs2(p2[0] - x12) < epsilon4 ? direction > 0 ? 2 : 1 : abs2(p2[1] - y06) < epsilon4 ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
    }
    function compareIntersection2(a4, b3) {
      return comparePoint(a4.x, b3.x);
    }
    function comparePoint(a4, b3) {
      var ca3 = corner(a4, 1), cb = corner(b3, 1);
      return ca3 !== cb ? ca3 - cb : ca3 === 0 ? b3[1] - a4[1] : ca3 === 1 ? a4[0] - b3[0] : ca3 === 2 ? a4[1] - b3[1] : b3[0] - a4[0];
    }
    return function(stream2) {
      var activeStream = stream2, bufferStream = buffer_default(), segments2, polygon, ring, x__, y__, v__, x_, y_, v_, first, clean;
      var clipStream = {
        point: point9,
        lineStart,
        lineEnd,
        polygonStart,
        polygonEnd
      };
      function point9(x5, y5) {
        if (visible(x5, y5)) activeStream.point(x5, y5);
      }
      function polygonInside() {
        var winding = 0;
        for (var i2 = 0, n2 = polygon.length; i2 < n2; ++i2) {
          for (var ring2 = polygon[i2], j2 = 1, m4 = ring2.length, point10 = ring2[0], a0, a1, b0 = point10[0], b1 = point10[1]; j2 < m4; ++j2) {
            a0 = b0, a1 = b1, point10 = ring2[j2], b0 = point10[0], b1 = point10[1];
            if (a1 <= y12) {
              if (b1 > y12 && (b0 - a0) * (y12 - a1) > (b1 - a1) * (x06 - a0)) ++winding;
            } else {
              if (b1 <= y12 && (b0 - a0) * (y12 - a1) < (b1 - a1) * (x06 - a0)) --winding;
            }
          }
        }
        return winding;
      }
      function polygonStart() {
        activeStream = bufferStream, segments2 = [], polygon = [], clean = true;
      }
      function polygonEnd() {
        var startInside = polygonInside(), cleanInside = clean && startInside, visible2 = (segments2 = merge2(segments2)).length;
        if (cleanInside || visible2) {
          stream2.polygonStart();
          if (cleanInside) {
            stream2.lineStart();
            interpolate3(null, null, 1, stream2);
            stream2.lineEnd();
          }
          if (visible2) {
            rejoin_default(segments2, compareIntersection2, startInside, interpolate3, stream2);
          }
          stream2.polygonEnd();
        }
        activeStream = stream2, segments2 = polygon = ring = null;
      }
      function lineStart() {
        clipStream.point = linePoint2;
        if (polygon) polygon.push(ring = []);
        first = true;
        v_ = false;
        x_ = y_ = NaN;
      }
      function lineEnd() {
        if (segments2) {
          linePoint2(x__, y__);
          if (v__ && v_) bufferStream.rejoin();
          segments2.push(bufferStream.result());
        }
        clipStream.point = point9;
        if (v_) activeStream.lineEnd();
      }
      function linePoint2(x5, y5) {
        var v3 = visible(x5, y5);
        if (polygon) ring.push([x5, y5]);
        if (first) {
          x__ = x5, y__ = y5, v__ = v3;
          first = false;
          if (v3) {
            activeStream.lineStart();
            activeStream.point(x5, y5);
          }
        } else {
          if (v3 && v_) activeStream.point(x5, y5);
          else {
            var a4 = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))], b3 = [x5 = Math.max(clipMin, Math.min(clipMax, x5)), y5 = Math.max(clipMin, Math.min(clipMax, y5))];
            if (line_default2(a4, b3, x06, y06, x12, y12)) {
              if (!v_) {
                activeStream.lineStart();
                activeStream.point(a4[0], a4[1]);
              }
              activeStream.point(b3[0], b3[1]);
              if (!v3) activeStream.lineEnd();
              clean = false;
            } else if (v3) {
              activeStream.lineStart();
              activeStream.point(x5, y5);
              clean = false;
            }
          }
        }
        x_ = x5, y_ = y5, v_ = v3;
      }
      return clipStream;
    };
  }

  // node_modules/d3-geo/src/graticule.js
  function graticuleX(y06, y12, dy) {
    var y5 = range(y06, y12 - epsilon4, dy).concat(y12);
    return function(x5) {
      return y5.map(function(y6) {
        return [x5, y6];
      });
    };
  }
  function graticuleY(x06, x12, dx) {
    var x5 = range(x06, x12 - epsilon4, dx).concat(x12);
    return function(y5) {
      return x5.map(function(x6) {
        return [x6, y5];
      });
    };
  }
  function graticule() {
    var x12, x06, X13, X03, y12, y06, Y13, Y03, dx = 10, dy = dx, DX = 90, DY = 360, x5, y5, X4, Y4, precision = 2.5;
    function graticule2() {
      return { type: "MultiLineString", coordinates: lines() };
    }
    function lines() {
      return range(ceil(X03 / DX) * DX, X13, DX).map(X4).concat(range(ceil(Y03 / DY) * DY, Y13, DY).map(Y4)).concat(range(ceil(x06 / dx) * dx, x12, dx).filter(function(x6) {
        return abs2(x6 % DX) > epsilon4;
      }).map(x5)).concat(range(ceil(y06 / dy) * dy, y12, dy).filter(function(y6) {
        return abs2(y6 % DY) > epsilon4;
      }).map(y5));
    }
    graticule2.lines = function() {
      return lines().map(function(coordinates) {
        return { type: "LineString", coordinates };
      });
    };
    graticule2.outline = function() {
      return {
        type: "Polygon",
        coordinates: [
          X4(X03).concat(
            Y4(Y13).slice(1),
            X4(X13).reverse().slice(1),
            Y4(Y03).reverse().slice(1)
          )
        ]
      };
    };
    graticule2.extent = function(_) {
      if (!arguments.length) return graticule2.extentMinor();
      return graticule2.extentMajor(_).extentMinor(_);
    };
    graticule2.extentMajor = function(_) {
      if (!arguments.length) return [[X03, Y03], [X13, Y13]];
      X03 = +_[0][0], X13 = +_[1][0];
      Y03 = +_[0][1], Y13 = +_[1][1];
      if (X03 > X13) _ = X03, X03 = X13, X13 = _;
      if (Y03 > Y13) _ = Y03, Y03 = Y13, Y13 = _;
      return graticule2.precision(precision);
    };
    graticule2.extentMinor = function(_) {
      if (!arguments.length) return [[x06, y06], [x12, y12]];
      x06 = +_[0][0], x12 = +_[1][0];
      y06 = +_[0][1], y12 = +_[1][1];
      if (x06 > x12) _ = x06, x06 = x12, x12 = _;
      if (y06 > y12) _ = y06, y06 = y12, y12 = _;
      return graticule2.precision(precision);
    };
    graticule2.step = function(_) {
      if (!arguments.length) return graticule2.stepMinor();
      return graticule2.stepMajor(_).stepMinor(_);
    };
    graticule2.stepMajor = function(_) {
      if (!arguments.length) return [DX, DY];
      DX = +_[0], DY = +_[1];
      return graticule2;
    };
    graticule2.stepMinor = function(_) {
      if (!arguments.length) return [dx, dy];
      dx = +_[0], dy = +_[1];
      return graticule2;
    };
    graticule2.precision = function(_) {
      if (!arguments.length) return precision;
      precision = +_;
      x5 = graticuleX(y06, y12, 90);
      y5 = graticuleY(x06, x12, precision);
      X4 = graticuleX(Y03, Y13, 90);
      Y4 = graticuleY(X03, X13, precision);
      return graticule2;
    };
    return graticule2.extentMajor([[-180, -90 + epsilon4], [180, 90 - epsilon4]]).extentMinor([[-180, -80 - epsilon4], [180, 80 + epsilon4]]);
  }

  // node_modules/d3-geo/src/identity.js
  var identity_default3 = (x5) => x5;

  // node_modules/d3-geo/src/path/area.js
  var areaSum2 = new Adder();
  var areaRingSum2 = new Adder();
  var x00;
  var y00;
  var x02;
  var y02;
  var areaStream2 = {
    point: noop2,
    lineStart: noop2,
    lineEnd: noop2,
    polygonStart: function() {
      areaStream2.lineStart = areaRingStart2;
      areaStream2.lineEnd = areaRingEnd2;
    },
    polygonEnd: function() {
      areaStream2.lineStart = areaStream2.lineEnd = areaStream2.point = noop2;
      areaSum2.add(abs2(areaRingSum2));
      areaRingSum2 = new Adder();
    },
    result: function() {
      var area4 = areaSum2 / 2;
      areaSum2 = new Adder();
      return area4;
    }
  };
  function areaRingStart2() {
    areaStream2.point = areaPointFirst2;
  }
  function areaPointFirst2(x5, y5) {
    areaStream2.point = areaPoint2;
    x00 = x02 = x5, y00 = y02 = y5;
  }
  function areaPoint2(x5, y5) {
    areaRingSum2.add(y02 * x5 - x02 * y5);
    x02 = x5, y02 = y5;
  }
  function areaRingEnd2() {
    areaPoint2(x00, y00);
  }
  var area_default3 = areaStream2;

  // node_modules/d3-geo/src/path/bounds.js
  var x03 = Infinity;
  var y03 = x03;
  var x1 = -x03;
  var y1 = x1;
  var boundsStream2 = {
    point: boundsPoint2,
    lineStart: noop2,
    lineEnd: noop2,
    polygonStart: noop2,
    polygonEnd: noop2,
    result: function() {
      var bounds2 = [[x03, y03], [x1, y1]];
      x1 = y1 = -(y03 = x03 = Infinity);
      return bounds2;
    }
  };
  function boundsPoint2(x5, y5) {
    if (x5 < x03) x03 = x5;
    if (x5 > x1) x1 = x5;
    if (y5 < y03) y03 = y5;
    if (y5 > y1) y1 = y5;
  }
  var bounds_default2 = boundsStream2;

  // node_modules/d3-geo/src/path/centroid.js
  var X02 = 0;
  var Y02 = 0;
  var Z02 = 0;
  var X12 = 0;
  var Y12 = 0;
  var Z12 = 0;
  var X22 = 0;
  var Y22 = 0;
  var Z22 = 0;
  var x002;
  var y002;
  var x04;
  var y04;
  var centroidStream2 = {
    point: centroidPoint2,
    lineStart: centroidLineStart2,
    lineEnd: centroidLineEnd2,
    polygonStart: function() {
      centroidStream2.lineStart = centroidRingStart2;
      centroidStream2.lineEnd = centroidRingEnd2;
    },
    polygonEnd: function() {
      centroidStream2.point = centroidPoint2;
      centroidStream2.lineStart = centroidLineStart2;
      centroidStream2.lineEnd = centroidLineEnd2;
    },
    result: function() {
      var centroid = Z22 ? [X22 / Z22, Y22 / Z22] : Z12 ? [X12 / Z12, Y12 / Z12] : Z02 ? [X02 / Z02, Y02 / Z02] : [NaN, NaN];
      X02 = Y02 = Z02 = X12 = Y12 = Z12 = X22 = Y22 = Z22 = 0;
      return centroid;
    }
  };
  function centroidPoint2(x5, y5) {
    X02 += x5;
    Y02 += y5;
    ++Z02;
  }
  function centroidLineStart2() {
    centroidStream2.point = centroidPointFirstLine;
  }
  function centroidPointFirstLine(x5, y5) {
    centroidStream2.point = centroidPointLine;
    centroidPoint2(x04 = x5, y04 = y5);
  }
  function centroidPointLine(x5, y5) {
    var dx = x5 - x04, dy = y5 - y04, z = sqrt3(dx * dx + dy * dy);
    X12 += z * (x04 + x5) / 2;
    Y12 += z * (y04 + y5) / 2;
    Z12 += z;
    centroidPoint2(x04 = x5, y04 = y5);
  }
  function centroidLineEnd2() {
    centroidStream2.point = centroidPoint2;
  }
  function centroidRingStart2() {
    centroidStream2.point = centroidPointFirstRing;
  }
  function centroidRingEnd2() {
    centroidPointRing(x002, y002);
  }
  function centroidPointFirstRing(x5, y5) {
    centroidStream2.point = centroidPointRing;
    centroidPoint2(x002 = x04 = x5, y002 = y04 = y5);
  }
  function centroidPointRing(x5, y5) {
    var dx = x5 - x04, dy = y5 - y04, z = sqrt3(dx * dx + dy * dy);
    X12 += z * (x04 + x5) / 2;
    Y12 += z * (y04 + y5) / 2;
    Z12 += z;
    z = y04 * x5 - x04 * y5;
    X22 += z * (x04 + x5);
    Y22 += z * (y04 + y5);
    Z22 += z * 3;
    centroidPoint2(x04 = x5, y04 = y5);
  }
  var centroid_default2 = centroidStream2;

  // node_modules/d3-geo/src/path/context.js
  function PathContext(context3) {
    this._context = context3;
  }
  PathContext.prototype = {
    _radius: 4.5,
    pointRadius: function(_) {
      return this._radius = _, this;
    },
    polygonStart: function() {
      this._line = 0;
    },
    polygonEnd: function() {
      this._line = NaN;
    },
    lineStart: function() {
      this._point = 0;
    },
    lineEnd: function() {
      if (this._line === 0) this._context.closePath();
      this._point = NaN;
    },
    point: function(x5, y5) {
      switch (this._point) {
        case 0: {
          this._context.moveTo(x5, y5);
          this._point = 1;
          break;
        }
        case 1: {
          this._context.lineTo(x5, y5);
          break;
        }
        default: {
          this._context.moveTo(x5 + this._radius, y5);
          this._context.arc(x5, y5, this._radius, 0, tau3);
          break;
        }
      }
    },
    result: noop2
  };

  // node_modules/d3-geo/src/path/measure.js
  var lengthSum = new Adder();
  var lengthRing;
  var x003;
  var y003;
  var x05;
  var y05;
  var lengthStream = {
    point: noop2,
    lineStart: function() {
      lengthStream.point = lengthPointFirst;
    },
    lineEnd: function() {
      if (lengthRing) lengthPoint(x003, y003);
      lengthStream.point = noop2;
    },
    polygonStart: function() {
      lengthRing = true;
    },
    polygonEnd: function() {
      lengthRing = null;
    },
    result: function() {
      var length3 = +lengthSum;
      lengthSum = new Adder();
      return length3;
    }
  };
  function lengthPointFirst(x5, y5) {
    lengthStream.point = lengthPoint;
    x003 = x05 = x5, y003 = y05 = y5;
  }
  function lengthPoint(x5, y5) {
    x05 -= x5, y05 -= y5;
    lengthSum.add(sqrt3(x05 * x05 + y05 * y05));
    x05 = x5, y05 = y5;
  }
  var measure_default = lengthStream;

  // node_modules/d3-geo/src/path/string.js
  var cacheDigits;
  var cacheAppend;
  var cacheRadius;
  var cacheCircle;
  var PathString = class {
    constructor(digits) {
      this._append = digits == null ? append2 : appendRound2(digits);
      this._radius = 4.5;
      this._ = "";
    }
    pointRadius(_) {
      this._radius = +_;
      return this;
    }
    polygonStart() {
      this._line = 0;
    }
    polygonEnd() {
      this._line = NaN;
    }
    lineStart() {
      this._point = 0;
    }
    lineEnd() {
      if (this._line === 0) this._ += "Z";
      this._point = NaN;
    }
    point(x5, y5) {
      switch (this._point) {
        case 0: {
          this._append`M${x5},${y5}`;
          this._point = 1;
          break;
        }
        case 1: {
          this._append`L${x5},${y5}`;
          break;
        }
        default: {
          this._append`M${x5},${y5}`;
          if (this._radius !== cacheRadius || this._append !== cacheAppend) {
            const r2 = this._radius;
            const s2 = this._;
            this._ = "";
            this._append`m0,${r2}a${r2},${r2} 0 1,1 0,${-2 * r2}a${r2},${r2} 0 1,1 0,${2 * r2}z`;
            cacheRadius = r2;
            cacheAppend = this._append;
            cacheCircle = this._;
            this._ = s2;
          }
          this._ += cacheCircle;
          break;
        }
      }
    }
    result() {
      const result = this._;
      this._ = "";
      return result.length ? result : null;
    }
  };
  function append2(strings) {
    let i2 = 1;
    this._ += strings[0];
    for (const j2 = strings.length; i2 < j2; ++i2) {
      this._ += arguments[i2] + strings[i2];
    }
  }
  function appendRound2(digits) {
    const d2 = Math.floor(digits);
    if (!(d2 >= 0)) throw new RangeError(`invalid digits: ${digits}`);
    if (d2 > 15) return append2;
    if (d2 !== cacheDigits) {
      const k2 = 10 ** d2;
      cacheDigits = d2;
      cacheAppend = function append3(strings) {
        let i2 = 1;
        this._ += strings[0];
        for (const j2 = strings.length; i2 < j2; ++i2) {
          this._ += Math.round(arguments[i2] * k2) / k2 + strings[i2];
        }
      };
    }
    return cacheAppend;
  }

  // node_modules/d3-geo/src/path/index.js
  function path_default(projection3, context3) {
    let digits = 3, pointRadius = 4.5, projectionStream, contextStream;
    function path3(object2) {
      if (object2) {
        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
        stream_default(object2, projectionStream(contextStream));
      }
      return contextStream.result();
    }
    path3.area = function(object2) {
      stream_default(object2, projectionStream(area_default3));
      return area_default3.result();
    };
    path3.measure = function(object2) {
      stream_default(object2, projectionStream(measure_default));
      return measure_default.result();
    };
    path3.bounds = function(object2) {
      stream_default(object2, projectionStream(bounds_default2));
      return bounds_default2.result();
    };
    path3.centroid = function(object2) {
      stream_default(object2, projectionStream(centroid_default2));
      return centroid_default2.result();
    };
    path3.projection = function(_) {
      if (!arguments.length) return projection3;
      projectionStream = _ == null ? (projection3 = null, identity_default3) : (projection3 = _).stream;
      return path3;
    };
    path3.context = function(_) {
      if (!arguments.length) return context3;
      contextStream = _ == null ? (context3 = null, new PathString(digits)) : new PathContext(context3 = _);
      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
      return path3;
    };
    path3.pointRadius = function(_) {
      if (!arguments.length) return pointRadius;
      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
      return path3;
    };
    path3.digits = function(_) {
      if (!arguments.length) return digits;
      if (_ == null) digits = null;
      else {
        const d2 = Math.floor(_);
        if (!(d2 >= 0)) throw new RangeError(`invalid digits: ${_}`);
        digits = d2;
      }
      if (context3 === null) contextStream = new PathString(digits);
      return path3;
    };
    return path3.projection(projection3).digits(digits).context(context3);
  }

  // node_modules/d3-geo/src/transform.js
  function transformer4(methods2) {
    return function(stream2) {
      var s2 = new TransformStream2();
      for (var key2 in methods2) s2[key2] = methods2[key2];
      s2.stream = stream2;
      return s2;
    };
  }
  function TransformStream2() {
  }
  TransformStream2.prototype = {
    constructor: TransformStream2,
    point: function(x5, y5) {
      this.stream.point(x5, y5);
    },
    sphere: function() {
      this.stream.sphere();
    },
    lineStart: function() {
      this.stream.lineStart();
    },
    lineEnd: function() {
      this.stream.lineEnd();
    },
    polygonStart: function() {
      this.stream.polygonStart();
    },
    polygonEnd: function() {
      this.stream.polygonEnd();
    }
  };

  // node_modules/d3-geo/src/projection/fit.js
  function fit(projection3, fitBounds, object2) {
    var clip3 = projection3.clipExtent && projection3.clipExtent();
    projection3.scale(150).translate([0, 0]);
    if (clip3 != null) projection3.clipExtent(null);
    stream_default(object2, projection3.stream(bounds_default2));
    fitBounds(bounds_default2.result());
    if (clip3 != null) projection3.clipExtent(clip3);
    return projection3;
  }
  function fitExtent(projection3, extent2, object2) {
    return fit(projection3, function(b3) {
      var w3 = extent2[1][0] - extent2[0][0], h3 = extent2[1][1] - extent2[0][1], k2 = Math.min(w3 / (b3[1][0] - b3[0][0]), h3 / (b3[1][1] - b3[0][1])), x5 = +extent2[0][0] + (w3 - k2 * (b3[1][0] + b3[0][0])) / 2, y5 = +extent2[0][1] + (h3 - k2 * (b3[1][1] + b3[0][1])) / 2;
      projection3.scale(150 * k2).translate([x5, y5]);
    }, object2);
  }
  function fitSize(projection3, size, object2) {
    return fitExtent(projection3, [[0, 0], size], object2);
  }
  function fitWidth(projection3, width2, object2) {
    return fit(projection3, function(b3) {
      var w3 = +width2, k2 = w3 / (b3[1][0] - b3[0][0]), x5 = (w3 - k2 * (b3[1][0] + b3[0][0])) / 2, y5 = -k2 * b3[0][1];
      projection3.scale(150 * k2).translate([x5, y5]);
    }, object2);
  }
  function fitHeight(projection3, height2, object2) {
    return fit(projection3, function(b3) {
      var h3 = +height2, k2 = h3 / (b3[1][1] - b3[0][1]), x5 = -k2 * b3[0][0], y5 = (h3 - k2 * (b3[1][1] + b3[0][1])) / 2;
      projection3.scale(150 * k2).translate([x5, y5]);
    }, object2);
  }

  // node_modules/d3-geo/src/projection/resample.js
  var maxDepth = 16;
  var cosMinDistance = cos2(30 * radians2);
  function resample_default(project3, delta2) {
    return +delta2 ? resample(project3, delta2) : resampleNone(project3);
  }
  function resampleNone(project3) {
    return transformer4({
      point: function(x5, y5) {
        x5 = project3(x5, y5);
        this.stream.point(x5[0], x5[1]);
      }
    });
  }
  function resample(project3, delta2) {
    function resampleLineTo(x06, y06, lambda03, a0, b0, c0, x12, y12, lambda12, a1, b1, c1, depth, stream2) {
      var dx = x12 - x06, dy = y12 - y06, d2 = dx * dx + dy * dy;
      if (d2 > 4 * delta2 && depth--) {
        var a4 = a0 + a1, b3 = b0 + b1, c4 = c0 + c1, m4 = sqrt3(a4 * a4 + b3 * b3 + c4 * c4), phi2 = asin2(c4 /= m4), lambda22 = abs2(abs2(c4) - 1) < epsilon4 || abs2(lambda03 - lambda12) < epsilon4 ? (lambda03 + lambda12) / 2 : atan22(b3, a4), p2 = project3(lambda22, phi2), x22 = p2[0], y22 = p2[1], dx2 = x22 - x06, dy2 = y22 - y06, dz = dy * dx2 - dx * dy2;
        if (dz * dz / d2 > delta2 || abs2((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
          resampleLineTo(x06, y06, lambda03, a0, b0, c0, x22, y22, lambda22, a4 /= m4, b3 /= m4, c4, depth, stream2);
          stream2.point(x22, y22);
          resampleLineTo(x22, y22, lambda22, a4, b3, c4, x12, y12, lambda12, a1, b1, c1, depth, stream2);
        }
      }
    }
    return function(stream2) {
      var lambda004, x004, y004, a00, b00, c00, lambda03, x06, y06, a0, b0, c0;
      var resampleStream = {
        point: point9,
        lineStart,
        lineEnd,
        polygonStart: function() {
          stream2.polygonStart();
          resampleStream.lineStart = ringStart;
        },
        polygonEnd: function() {
          stream2.polygonEnd();
          resampleStream.lineStart = lineStart;
        }
      };
      function point9(x5, y5) {
        x5 = project3(x5, y5);
        stream2.point(x5[0], x5[1]);
      }
      function lineStart() {
        x06 = NaN;
        resampleStream.point = linePoint2;
        stream2.lineStart();
      }
      function linePoint2(lambda, phi2) {
        var c4 = cartesian([lambda, phi2]), p2 = project3(lambda, phi2);
        resampleLineTo(x06, y06, lambda03, a0, b0, c0, x06 = p2[0], y06 = p2[1], lambda03 = lambda, a0 = c4[0], b0 = c4[1], c0 = c4[2], maxDepth, stream2);
        stream2.point(x06, y06);
      }
      function lineEnd() {
        resampleStream.point = point9;
        stream2.lineEnd();
      }
      function ringStart() {
        lineStart();
        resampleStream.point = ringPoint;
        resampleStream.lineEnd = ringEnd;
      }
      function ringPoint(lambda, phi2) {
        linePoint2(lambda004 = lambda, phi2), x004 = x06, y004 = y06, a00 = a0, b00 = b0, c00 = c0;
        resampleStream.point = linePoint2;
      }
      function ringEnd() {
        resampleLineTo(x06, y06, lambda03, a0, b0, c0, x004, y004, lambda004, a00, b00, c00, maxDepth, stream2);
        resampleStream.lineEnd = lineEnd;
        lineEnd();
      }
      return resampleStream;
    };
  }

  // node_modules/d3-geo/src/projection/index.js
  var transformRadians = transformer4({
    point: function(x5, y5) {
      this.stream.point(x5 * radians2, y5 * radians2);
    }
  });
  function transformRotate(rotate2) {
    return transformer4({
      point: function(x5, y5) {
        var r2 = rotate2(x5, y5);
        return this.stream.point(r2[0], r2[1]);
      }
    });
  }
  function scaleTranslate(k2, dx, dy, sx, sy) {
    function transform4(x5, y5) {
      x5 *= sx;
      y5 *= sy;
      return [dx + k2 * x5, dy - k2 * y5];
    }
    transform4.invert = function(x5, y5) {
      return [(x5 - dx) / k2 * sx, (dy - y5) / k2 * sy];
    };
    return transform4;
  }
  function scaleTranslateRotate(k2, dx, dy, sx, sy, alpha) {
    if (!alpha) return scaleTranslate(k2, dx, dy, sx, sy);
    var cosAlpha = cos2(alpha), sinAlpha = sin2(alpha), a4 = cosAlpha * k2, b3 = sinAlpha * k2, ai = cosAlpha / k2, bi = sinAlpha / k2, ci = (sinAlpha * dy - cosAlpha * dx) / k2, fi = (sinAlpha * dx + cosAlpha * dy) / k2;
    function transform4(x5, y5) {
      x5 *= sx;
      y5 *= sy;
      return [a4 * x5 - b3 * y5 + dx, dy - b3 * x5 - a4 * y5];
    }
    transform4.invert = function(x5, y5) {
      return [sx * (ai * x5 - bi * y5 + ci), sy * (fi - bi * x5 - ai * y5)];
    };
    return transform4;
  }
  function projection(project3) {
    return projectionMutator(function() {
      return project3;
    })();
  }
  function projectionMutator(projectAt) {
    var project3, k2 = 150, x5 = 480, y5 = 250, lambda = 0, phi2 = 0, deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate2, alpha = 0, sx = 1, sy = 1, theta = null, preclip = antimeridian_default, x06 = null, y06, x12, y12, postclip = identity_default3, delta2 = 0.5, projectResample, projectTransform, projectRotateTransform, cache3, cacheStream;
    function projection3(point9) {
      return projectRotateTransform(point9[0] * radians2, point9[1] * radians2);
    }
    function invert2(point9) {
      point9 = projectRotateTransform.invert(point9[0], point9[1]);
      return point9 && [point9[0] * degrees3, point9[1] * degrees3];
    }
    projection3.stream = function(stream2) {
      return cache3 && cacheStream === stream2 ? cache3 : cache3 = transformRadians(transformRotate(rotate2)(preclip(projectResample(postclip(cacheStream = stream2)))));
    };
    projection3.preclip = function(_) {
      return arguments.length ? (preclip = _, theta = void 0, reset3()) : preclip;
    };
    projection3.postclip = function(_) {
      return arguments.length ? (postclip = _, x06 = y06 = x12 = y12 = null, reset3()) : postclip;
    };
    projection3.clipAngle = function(_) {
      return arguments.length ? (preclip = +_ ? circle_default2(theta = _ * radians2) : (theta = null, antimeridian_default), reset3()) : theta * degrees3;
    };
    projection3.clipExtent = function(_) {
      return arguments.length ? (postclip = _ == null ? (x06 = y06 = x12 = y12 = null, identity_default3) : clipRectangle(x06 = +_[0][0], y06 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reset3()) : x06 == null ? null : [[x06, y06], [x12, y12]];
    };
    projection3.scale = function(_) {
      return arguments.length ? (k2 = +_, recenter()) : k2;
    };
    projection3.translate = function(_) {
      return arguments.length ? (x5 = +_[0], y5 = +_[1], recenter()) : [x5, y5];
    };
    projection3.center = function(_) {
      return arguments.length ? (lambda = _[0] % 360 * radians2, phi2 = _[1] % 360 * radians2, recenter()) : [lambda * degrees3, phi2 * degrees3];
    };
    projection3.rotate = function(_) {
      return arguments.length ? (deltaLambda = _[0] % 360 * radians2, deltaPhi = _[1] % 360 * radians2, deltaGamma = _.length > 2 ? _[2] % 360 * radians2 : 0, recenter()) : [deltaLambda * degrees3, deltaPhi * degrees3, deltaGamma * degrees3];
    };
    projection3.angle = function(_) {
      return arguments.length ? (alpha = _ % 360 * radians2, recenter()) : alpha * degrees3;
    };
    projection3.reflectX = function(_) {
      return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;
    };
    projection3.reflectY = function(_) {
      return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;
    };
    projection3.precision = function(_) {
      return arguments.length ? (projectResample = resample_default(projectTransform, delta2 = _ * _), reset3()) : sqrt3(delta2);
    };
    projection3.fitExtent = function(extent2, object2) {
      return fitExtent(projection3, extent2, object2);
    };
    projection3.fitSize = function(size, object2) {
      return fitSize(projection3, size, object2);
    };
    projection3.fitWidth = function(width2, object2) {
      return fitWidth(projection3, width2, object2);
    };
    projection3.fitHeight = function(height2, object2) {
      return fitHeight(projection3, height2, object2);
    };
    function recenter() {
      var center = scaleTranslateRotate(k2, 0, 0, sx, sy, alpha).apply(null, project3(lambda, phi2)), transform4 = scaleTranslateRotate(k2, x5 - center[0], y5 - center[1], sx, sy, alpha);
      rotate2 = rotateRadians(deltaLambda, deltaPhi, deltaGamma);
      projectTransform = compose_default(project3, transform4);
      projectRotateTransform = compose_default(rotate2, projectTransform);
      projectResample = resample_default(projectTransform, delta2);
      return reset3();
    }
    function reset3() {
      cache3 = cacheStream = null;
      return projection3;
    }
    return function() {
      project3 = projectAt.apply(this, arguments);
      projection3.invert = project3.invert && invert2;
      return recenter();
    };
  }

  // node_modules/d3-geo/src/projection/conic.js
  function conicProjection(projectAt) {
    var phi02 = 0, phi12 = pi3 / 3, m4 = projectionMutator(projectAt), p2 = m4(phi02, phi12);
    p2.parallels = function(_) {
      return arguments.length ? m4(phi02 = _[0] * radians2, phi12 = _[1] * radians2) : [phi02 * degrees3, phi12 * degrees3];
    };
    return p2;
  }

  // node_modules/d3-geo/src/projection/cylindricalEqualArea.js
  function cylindricalEqualAreaRaw(phi02) {
    var cosPhi02 = cos2(phi02);
    function forward(lambda, phi2) {
      return [lambda * cosPhi02, sin2(phi2) / cosPhi02];
    }
    forward.invert = function(x5, y5) {
      return [x5 / cosPhi02, asin2(y5 * cosPhi02)];
    };
    return forward;
  }

  // node_modules/d3-geo/src/projection/conicEqualArea.js
  function conicEqualAreaRaw(y06, y12) {
    var sy0 = sin2(y06), n2 = (sy0 + sin2(y12)) / 2;
    if (abs2(n2) < epsilon4) return cylindricalEqualAreaRaw(y06);
    var c4 = 1 + sy0 * (2 * n2 - sy0), r0 = sqrt3(c4) / n2;
    function project3(x5, y5) {
      var r2 = sqrt3(c4 - 2 * n2 * sin2(y5)) / n2;
      return [r2 * sin2(x5 *= n2), r0 - r2 * cos2(x5)];
    }
    project3.invert = function(x5, y5) {
      var r0y = r0 - y5, l2 = atan22(x5, abs2(r0y)) * sign2(r0y);
      if (r0y * n2 < 0)
        l2 -= pi3 * sign2(x5) * sign2(r0y);
      return [l2 / n2, asin2((c4 - (x5 * x5 + r0y * r0y) * n2 * n2) / (2 * n2))];
    };
    return project3;
  }
  function conicEqualArea_default() {
    return conicProjection(conicEqualAreaRaw).scale(155.424).center([0, 33.6442]);
  }

  // node_modules/d3-geo/src/projection/albers.js
  function albers_default() {
    return conicEqualArea_default().parallels([29.5, 45.5]).scale(1070).translate([480, 250]).rotate([96, 0]).center([-0.6, 38.7]);
  }

  // node_modules/d3-geo/src/projection/albersUsa.js
  function multiplex(streams) {
    var n2 = streams.length;
    return {
      point: function(x5, y5) {
        var i2 = -1;
        while (++i2 < n2) streams[i2].point(x5, y5);
      },
      sphere: function() {
        var i2 = -1;
        while (++i2 < n2) streams[i2].sphere();
      },
      lineStart: function() {
        var i2 = -1;
        while (++i2 < n2) streams[i2].lineStart();
      },
      lineEnd: function() {
        var i2 = -1;
        while (++i2 < n2) streams[i2].lineEnd();
      },
      polygonStart: function() {
        var i2 = -1;
        while (++i2 < n2) streams[i2].polygonStart();
      },
      polygonEnd: function() {
        var i2 = -1;
        while (++i2 < n2) streams[i2].polygonEnd();
      }
    };
  }
  function albersUsa_default() {
    var cache3, cacheStream, lower48 = albers_default(), lower48Point, alaska = conicEqualArea_default().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, hawaii = conicEqualArea_default().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, point9, pointStream = { point: function(x5, y5) {
      point9 = [x5, y5];
    } };
    function albersUsa(coordinates) {
      var x5 = coordinates[0], y5 = coordinates[1];
      return point9 = null, (lower48Point.point(x5, y5), point9) || (alaskaPoint.point(x5, y5), point9) || (hawaiiPoint.point(x5, y5), point9);
    }
    albersUsa.invert = function(coordinates) {
      var k2 = lower48.scale(), t4 = lower48.translate(), x5 = (coordinates[0] - t4[0]) / k2, y5 = (coordinates[1] - t4[1]) / k2;
      return (y5 >= 0.12 && y5 < 0.234 && x5 >= -0.425 && x5 < -0.214 ? alaska : y5 >= 0.166 && y5 < 0.234 && x5 >= -0.214 && x5 < -0.115 ? hawaii : lower48).invert(coordinates);
    };
    albersUsa.stream = function(stream2) {
      return cache3 && cacheStream === stream2 ? cache3 : cache3 = multiplex([lower48.stream(cacheStream = stream2), alaska.stream(stream2), hawaii.stream(stream2)]);
    };
    albersUsa.precision = function(_) {
      if (!arguments.length) return lower48.precision();
      lower48.precision(_), alaska.precision(_), hawaii.precision(_);
      return reset3();
    };
    albersUsa.scale = function(_) {
      if (!arguments.length) return lower48.scale();
      lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
      return albersUsa.translate(lower48.translate());
    };
    albersUsa.translate = function(_) {
      if (!arguments.length) return lower48.translate();
      var k2 = lower48.scale(), x5 = +_[0], y5 = +_[1];
      lower48Point = lower48.translate(_).clipExtent([[x5 - 0.455 * k2, y5 - 0.238 * k2], [x5 + 0.455 * k2, y5 + 0.238 * k2]]).stream(pointStream);
      alaskaPoint = alaska.translate([x5 - 0.307 * k2, y5 + 0.201 * k2]).clipExtent([[x5 - 0.425 * k2 + epsilon4, y5 + 0.12 * k2 + epsilon4], [x5 - 0.214 * k2 - epsilon4, y5 + 0.234 * k2 - epsilon4]]).stream(pointStream);
      hawaiiPoint = hawaii.translate([x5 - 0.205 * k2, y5 + 0.212 * k2]).clipExtent([[x5 - 0.214 * k2 + epsilon4, y5 + 0.166 * k2 + epsilon4], [x5 - 0.115 * k2 - epsilon4, y5 + 0.234 * k2 - epsilon4]]).stream(pointStream);
      return reset3();
    };
    albersUsa.fitExtent = function(extent2, object2) {
      return fitExtent(albersUsa, extent2, object2);
    };
    albersUsa.fitSize = function(size, object2) {
      return fitSize(albersUsa, size, object2);
    };
    albersUsa.fitWidth = function(width2, object2) {
      return fitWidth(albersUsa, width2, object2);
    };
    albersUsa.fitHeight = function(height2, object2) {
      return fitHeight(albersUsa, height2, object2);
    };
    function reset3() {
      cache3 = cacheStream = null;
      return albersUsa;
    }
    return albersUsa.scale(1070);
  }

  // node_modules/d3-geo/src/projection/azimuthal.js
  function azimuthalRaw(scale7) {
    return function(x5, y5) {
      var cx = cos2(x5), cy = cos2(y5), k2 = scale7(cx * cy);
      if (k2 === Infinity) return [2, 0];
      return [
        k2 * cy * sin2(x5),
        k2 * sin2(y5)
      ];
    };
  }
  function azimuthalInvert(angle2) {
    return function(x5, y5) {
      var z = sqrt3(x5 * x5 + y5 * y5), c4 = angle2(z), sc = sin2(c4), cc2 = cos2(c4);
      return [
        atan22(x5 * sc, z * cc2),
        asin2(z && y5 * sc / z)
      ];
    };
  }

  // node_modules/d3-geo/src/projection/azimuthalEqualArea.js
  var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
    return sqrt3(2 / (1 + cxcy));
  });
  azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
    return 2 * asin2(z / 2);
  });
  function azimuthalEqualArea_default() {
    return projection(azimuthalEqualAreaRaw).scale(124.75).clipAngle(180 - 1e-3);
  }

  // node_modules/d3-geo/src/projection/azimuthalEquidistant.js
  var azimuthalEquidistantRaw = azimuthalRaw(function(c4) {
    return (c4 = acos2(c4)) && c4 / sin2(c4);
  });
  azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
    return z;
  });
  function azimuthalEquidistant_default() {
    return projection(azimuthalEquidistantRaw).scale(79.4188).clipAngle(180 - 1e-3);
  }

  // node_modules/d3-geo/src/projection/mercator.js
  function mercatorRaw(lambda, phi2) {
    return [lambda, log4(tan((halfPi2 + phi2) / 2))];
  }
  mercatorRaw.invert = function(x5, y5) {
    return [x5, 2 * atan(exp3(y5)) - halfPi2];
  };
  function mercator_default() {
    return mercatorProjection(mercatorRaw).scale(961 / tau3);
  }
  function mercatorProjection(project3) {
    var m4 = projection(project3), center = m4.center, scale7 = m4.scale, translate4 = m4.translate, clipExtent = m4.clipExtent, x06 = null, y06, x12, y12;
    m4.scale = function(_) {
      return arguments.length ? (scale7(_), reclip()) : scale7();
    };
    m4.translate = function(_) {
      return arguments.length ? (translate4(_), reclip()) : translate4();
    };
    m4.center = function(_) {
      return arguments.length ? (center(_), reclip()) : center();
    };
    m4.clipExtent = function(_) {
      return arguments.length ? (_ == null ? x06 = y06 = x12 = y12 = null : (x06 = +_[0][0], y06 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reclip()) : x06 == null ? null : [[x06, y06], [x12, y12]];
    };
    function reclip() {
      var k2 = pi3 * scale7(), t4 = m4(rotation_default(m4.rotate()).invert([0, 0]));
      return clipExtent(x06 == null ? [[t4[0] - k2, t4[1] - k2], [t4[0] + k2, t4[1] + k2]] : project3 === mercatorRaw ? [[Math.max(t4[0] - k2, x06), y06], [Math.min(t4[0] + k2, x12), y12]] : [[x06, Math.max(t4[1] - k2, y06)], [x12, Math.min(t4[1] + k2, y12)]]);
    }
    return reclip();
  }

  // node_modules/d3-geo/src/projection/conicConformal.js
  function tany(y5) {
    return tan((halfPi2 + y5) / 2);
  }
  function conicConformalRaw(y06, y12) {
    var cy0 = cos2(y06), n2 = y06 === y12 ? sin2(y06) : log4(cy0 / cos2(y12)) / log4(tany(y12) / tany(y06)), f2 = cy0 * pow4(tany(y06), n2) / n2;
    if (!n2) return mercatorRaw;
    function project3(x5, y5) {
      if (f2 > 0) {
        if (y5 < -halfPi2 + epsilon4) y5 = -halfPi2 + epsilon4;
      } else {
        if (y5 > halfPi2 - epsilon4) y5 = halfPi2 - epsilon4;
      }
      var r2 = f2 / pow4(tany(y5), n2);
      return [r2 * sin2(n2 * x5), f2 - r2 * cos2(n2 * x5)];
    }
    project3.invert = function(x5, y5) {
      var fy = f2 - y5, r2 = sign2(n2) * sqrt3(x5 * x5 + fy * fy), l2 = atan22(x5, abs2(fy)) * sign2(fy);
      if (fy * n2 < 0)
        l2 -= pi3 * sign2(x5) * sign2(fy);
      return [l2 / n2, 2 * atan(pow4(f2 / r2, 1 / n2)) - halfPi2];
    };
    return project3;
  }
  function conicConformal_default() {
    return conicProjection(conicConformalRaw).scale(109.5).parallels([30, 30]);
  }

  // node_modules/d3-geo/src/projection/equirectangular.js
  function equirectangularRaw(lambda, phi2) {
    return [lambda, phi2];
  }
  equirectangularRaw.invert = equirectangularRaw;
  function equirectangular_default() {
    return projection(equirectangularRaw).scale(152.63);
  }

  // node_modules/d3-geo/src/projection/conicEquidistant.js
  function conicEquidistantRaw(y06, y12) {
    var cy0 = cos2(y06), n2 = y06 === y12 ? sin2(y06) : (cy0 - cos2(y12)) / (y12 - y06), g2 = cy0 / n2 + y06;
    if (abs2(n2) < epsilon4) return equirectangularRaw;
    function project3(x5, y5) {
      var gy = g2 - y5, nx = n2 * x5;
      return [gy * sin2(nx), g2 - gy * cos2(nx)];
    }
    project3.invert = function(x5, y5) {
      var gy = g2 - y5, l2 = atan22(x5, abs2(gy)) * sign2(gy);
      if (gy * n2 < 0)
        l2 -= pi3 * sign2(x5) * sign2(gy);
      return [l2 / n2, g2 - sign2(n2) * sqrt3(x5 * x5 + gy * gy)];
    };
    return project3;
  }
  function conicEquidistant_default() {
    return conicProjection(conicEquidistantRaw).scale(131.154).center([0, 13.9389]);
  }

  // node_modules/d3-geo/src/projection/equalEarth.js
  var A1 = 1.340264;
  var A2 = -0.081106;
  var A3 = 893e-6;
  var A4 = 3796e-6;
  var M = sqrt3(3) / 2;
  var iterations = 12;
  function equalEarthRaw(lambda, phi2) {
    var l2 = asin2(M * sin2(phi2)), l22 = l2 * l2, l6 = l22 * l22 * l22;
    return [
      lambda * cos2(l2) / (M * (A1 + 3 * A2 * l22 + l6 * (7 * A3 + 9 * A4 * l22))),
      l2 * (A1 + A2 * l22 + l6 * (A3 + A4 * l22))
    ];
  }
  equalEarthRaw.invert = function(x5, y5) {
    var l2 = y5, l22 = l2 * l2, l6 = l22 * l22 * l22;
    for (var i2 = 0, delta, fy, fpy; i2 < iterations; ++i2) {
      fy = l2 * (A1 + A2 * l22 + l6 * (A3 + A4 * l22)) - y5;
      fpy = A1 + 3 * A2 * l22 + l6 * (7 * A3 + 9 * A4 * l22);
      l2 -= delta = fy / fpy, l22 = l2 * l2, l6 = l22 * l22 * l22;
      if (abs2(delta) < epsilon23) break;
    }
    return [
      M * x5 * (A1 + 3 * A2 * l22 + l6 * (7 * A3 + 9 * A4 * l22)) / cos2(l2),
      asin2(sin2(l2) / M)
    ];
  };
  function equalEarth_default() {
    return projection(equalEarthRaw).scale(177.158);
  }

  // node_modules/d3-geo/src/projection/gnomonic.js
  function gnomonicRaw(x5, y5) {
    var cy = cos2(y5), k2 = cos2(x5) * cy;
    return [cy * sin2(x5) / k2, sin2(y5) / k2];
  }
  gnomonicRaw.invert = azimuthalInvert(atan);
  function gnomonic_default() {
    return projection(gnomonicRaw).scale(144.049).clipAngle(60);
  }

  // node_modules/d3-geo/src/projection/identity.js
  function identity_default4() {
    var k2 = 1, tx = 0, ty = 0, sx = 1, sy = 1, alpha = 0, ca3, sa2, x06 = null, y06, x12, y12, kx = 1, ky = 1, transform4 = transformer4({
      point: function(x5, y5) {
        var p2 = projection3([x5, y5]);
        this.stream.point(p2[0], p2[1]);
      }
    }), postclip = identity_default3, cache3, cacheStream;
    function reset3() {
      kx = k2 * sx;
      ky = k2 * sy;
      cache3 = cacheStream = null;
      return projection3;
    }
    function projection3(p2) {
      var x5 = p2[0] * kx, y5 = p2[1] * ky;
      if (alpha) {
        var t4 = y5 * ca3 - x5 * sa2;
        x5 = x5 * ca3 + y5 * sa2;
        y5 = t4;
      }
      return [x5 + tx, y5 + ty];
    }
    projection3.invert = function(p2) {
      var x5 = p2[0] - tx, y5 = p2[1] - ty;
      if (alpha) {
        var t4 = y5 * ca3 + x5 * sa2;
        x5 = x5 * ca3 - y5 * sa2;
        y5 = t4;
      }
      return [x5 / kx, y5 / ky];
    };
    projection3.stream = function(stream2) {
      return cache3 && cacheStream === stream2 ? cache3 : cache3 = transform4(postclip(cacheStream = stream2));
    };
    projection3.postclip = function(_) {
      return arguments.length ? (postclip = _, x06 = y06 = x12 = y12 = null, reset3()) : postclip;
    };
    projection3.clipExtent = function(_) {
      return arguments.length ? (postclip = _ == null ? (x06 = y06 = x12 = y12 = null, identity_default3) : clipRectangle(x06 = +_[0][0], y06 = +_[0][1], x12 = +_[1][0], y12 = +_[1][1]), reset3()) : x06 == null ? null : [[x06, y06], [x12, y12]];
    };
    projection3.scale = function(_) {
      return arguments.length ? (k2 = +_, reset3()) : k2;
    };
    projection3.translate = function(_) {
      return arguments.length ? (tx = +_[0], ty = +_[1], reset3()) : [tx, ty];
    };
    projection3.angle = function(_) {
      return arguments.length ? (alpha = _ % 360 * radians2, sa2 = sin2(alpha), ca3 = cos2(alpha), reset3()) : alpha * degrees3;
    };
    projection3.reflectX = function(_) {
      return arguments.length ? (sx = _ ? -1 : 1, reset3()) : sx < 0;
    };
    projection3.reflectY = function(_) {
      return arguments.length ? (sy = _ ? -1 : 1, reset3()) : sy < 0;
    };
    projection3.fitExtent = function(extent2, object2) {
      return fitExtent(projection3, extent2, object2);
    };
    projection3.fitSize = function(size, object2) {
      return fitSize(projection3, size, object2);
    };
    projection3.fitWidth = function(width2, object2) {
      return fitWidth(projection3, width2, object2);
    };
    projection3.fitHeight = function(height2, object2) {
      return fitHeight(projection3, height2, object2);
    };
    return projection3;
  }

  // node_modules/d3-geo/src/projection/naturalEarth1.js
  function naturalEarth1Raw(lambda, phi2) {
    var phi22 = phi2 * phi2, phi4 = phi22 * phi22;
    return [
      lambda * (0.8707 - 0.131979 * phi22 + phi4 * (-0.013791 + phi4 * (3971e-6 * phi22 - 1529e-6 * phi4))),
      phi2 * (1.007226 + phi22 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi22 - 5916e-6 * phi4)))
    ];
  }
  naturalEarth1Raw.invert = function(x5, y5) {
    var phi2 = y5, i2 = 25, delta;
    do {
      var phi22 = phi2 * phi2, phi4 = phi22 * phi22;
      phi2 -= delta = (phi2 * (1.007226 + phi22 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi22 - 5916e-6 * phi4))) - y5) / (1.007226 + phi22 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi22 - 5916e-6 * 11 * phi4)));
    } while (abs2(delta) > epsilon4 && --i2 > 0);
    return [
      x5 / (0.8707 + (phi22 = phi2 * phi2) * (-0.131979 + phi22 * (-0.013791 + phi22 * phi22 * phi22 * (3971e-6 - 1529e-6 * phi22)))),
      phi2
    ];
  };
  function naturalEarth1_default() {
    return projection(naturalEarth1Raw).scale(175.295);
  }

  // node_modules/d3-geo/src/projection/orthographic.js
  function orthographicRaw(x5, y5) {
    return [cos2(y5) * sin2(x5), sin2(y5)];
  }
  orthographicRaw.invert = azimuthalInvert(asin2);
  function orthographic_default() {
    return projection(orthographicRaw).scale(249.5).clipAngle(90 + epsilon4);
  }

  // node_modules/d3-geo/src/projection/stereographic.js
  function stereographicRaw(x5, y5) {
    var cy = cos2(y5), k2 = 1 + cos2(x5) * cy;
    return [cy * sin2(x5) / k2, sin2(y5) / k2];
  }
  stereographicRaw.invert = azimuthalInvert(function(z) {
    return 2 * atan(z);
  });
  function stereographic_default() {
    return projection(stereographicRaw).scale(250).clipAngle(142);
  }

  // node_modules/d3-geo/src/projection/transverseMercator.js
  function transverseMercatorRaw(lambda, phi2) {
    return [log4(tan((halfPi2 + phi2) / 2)), -lambda];
  }
  transverseMercatorRaw.invert = function(x5, y5) {
    return [-y5, 2 * atan(exp3(x5)) - halfPi2];
  };
  function transverseMercator_default() {
    var m4 = mercatorProjection(transverseMercatorRaw), center = m4.center, rotate2 = m4.rotate;
    m4.center = function(_) {
      return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);
    };
    m4.rotate = function(_) {
      return arguments.length ? rotate2([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate2(), [_[0], _[1], _[2] - 90]);
    };
    return rotate2([0, 0, 90]).scale(159.155);
  }

  // node_modules/d3-geo-projection/src/math.js
  var abs3 = Math.abs;
  var cos3 = Math.cos;
  var sin3 = Math.sin;
  var epsilon5 = 1e-6;
  var pi4 = Math.PI;
  var halfPi3 = pi4 / 2;
  var quarterPi2 = pi4 / 4;
  var sqrt22 = sqrt4(2);
  var sqrtPi = sqrt4(pi4);
  var tau4 = pi4 * 2;
  var degrees4 = 180 / pi4;
  var radians3 = pi4 / 180;
  function asin3(x5) {
    return x5 > 1 ? halfPi3 : x5 < -1 ? -halfPi3 : Math.asin(x5);
  }
  function sqrt4(x5) {
    return x5 > 0 ? Math.sqrt(x5) : 0;
  }

  // node_modules/d3-geo-projection/src/mollweide.js
  function mollweideBromleyTheta(cp, phi2) {
    var cpsinPhi = cp * sin3(phi2), i2 = 30, delta;
    do
      phi2 -= delta = (phi2 + sin3(phi2) - cpsinPhi) / (1 + cos3(phi2));
    while (abs3(delta) > epsilon5 && --i2 > 0);
    return phi2 / 2;
  }
  function mollweideBromleyRaw(cx, cy, cp) {
    function forward(lambda, phi2) {
      return [cx * lambda * cos3(phi2 = mollweideBromleyTheta(cp, phi2)), cy * sin3(phi2)];
    }
    forward.invert = function(x5, y5) {
      return y5 = asin3(y5 / cy), [x5 / (cx * cos3(y5)), asin3((2 * y5 + sin3(2 * y5)) / cp)];
    };
    return forward;
  }
  var mollweideRaw = mollweideBromleyRaw(sqrt22 / halfPi3, sqrt22, pi4);
  function mollweide_default() {
    return projection(mollweideRaw).scale(169.529);
  }

  // node_modules/vega-projection/build/vega-projection.module.js
  var defaultPath = path_default();
  var projectionProperties = [
    // standard properties in d3-geo
    "clipAngle",
    "clipExtent",
    "scale",
    "translate",
    "center",
    "rotate",
    "parallels",
    "precision",
    "reflectX",
    "reflectY",
    // extended properties in d3-geo-projections
    "coefficient",
    "distance",
    "fraction",
    "lobes",
    "parallel",
    "radius",
    "ratio",
    "spacing",
    "tilt"
  ];
  function create2(type3, constructor) {
    return function projection3() {
      const p2 = constructor();
      p2.type = type3;
      p2.path = path_default().projection(p2);
      p2.copy = p2.copy || function() {
        const c4 = projection3();
        projectionProperties.forEach((prop) => {
          if (p2[prop]) c4[prop](p2[prop]());
        });
        c4.path.pointRadius(p2.path.pointRadius());
        return c4;
      };
      return registerScale(p2);
    };
  }
  function projection2(type3, proj) {
    if (!type3 || typeof type3 !== "string") {
      throw new Error("Projection type must be a name string.");
    }
    type3 = type3.toLowerCase();
    if (arguments.length > 1) {
      projections[type3] = create2(type3, proj);
      return this;
    } else {
      return projections[type3] || null;
    }
  }
  function getProjectionPath(proj) {
    return proj && proj.path || defaultPath;
  }
  var projections = {
    // base d3-geo projection types
    albers: albers_default,
    albersusa: albersUsa_default,
    azimuthalequalarea: azimuthalEqualArea_default,
    azimuthalequidistant: azimuthalEquidistant_default,
    conicconformal: conicConformal_default,
    conicequalarea: conicEqualArea_default,
    conicequidistant: conicEquidistant_default,
    equalEarth: equalEarth_default,
    equirectangular: equirectangular_default,
    gnomonic: gnomonic_default,
    identity: identity_default4,
    mercator: mercator_default,
    mollweide: mollweide_default,
    naturalEarth1: naturalEarth1_default,
    orthographic: orthographic_default,
    stereographic: stereographic_default,
    transversemercator: transverseMercator_default
  };
  for (const key2 in projections) {
    projection2(key2, projections[key2]);
  }

  // node_modules/vega-geo/build/vega-geo.module.js
  function noop3() {
  }
  var cases = [[], [[[1, 1.5], [0.5, 1]]], [[[1.5, 1], [1, 1.5]]], [[[1.5, 1], [0.5, 1]]], [[[1, 0.5], [1.5, 1]]], [[[1, 1.5], [0.5, 1]], [[1, 0.5], [1.5, 1]]], [[[1, 0.5], [1, 1.5]]], [[[1, 0.5], [0.5, 1]]], [[[0.5, 1], [1, 0.5]]], [[[1, 1.5], [1, 0.5]]], [[[0.5, 1], [1, 0.5]], [[1.5, 1], [1, 1.5]]], [[[1.5, 1], [1, 0.5]]], [[[0.5, 1], [1.5, 1]]], [[[1, 1.5], [1.5, 1]]], [[[0.5, 1], [1, 1.5]]], []];
  function contours() {
    var dx = 1, dy = 1, smooth = smoothLinear;
    function contours2(values4, tz) {
      return tz.map((value3) => contour(values4, value3));
    }
    function contour(values4, value3) {
      var polygons = [], holes = [];
      isorings(values4, value3, (ring) => {
        smooth(ring, values4, value3);
        if (area2(ring) > 0) polygons.push([ring]);
        else holes.push(ring);
      });
      holes.forEach((hole) => {
        for (var i2 = 0, n2 = polygons.length, polygon; i2 < n2; ++i2) {
          if (contains((polygon = polygons[i2])[0], hole) !== -1) {
            polygon.push(hole);
            return;
          }
        }
      });
      return {
        type: "MultiPolygon",
        value: value3,
        coordinates: polygons
      };
    }
    function isorings(values4, value3, callback) {
      var fragmentByStart = [], fragmentByEnd = [], x5, y5, t04, t13, t22, t32;
      x5 = y5 = -1;
      t13 = values4[0] >= value3;
      cases[t13 << 1].forEach(stitch);
      while (++x5 < dx - 1) {
        t04 = t13, t13 = values4[x5 + 1] >= value3;
        cases[t04 | t13 << 1].forEach(stitch);
      }
      cases[t13 << 0].forEach(stitch);
      while (++y5 < dy - 1) {
        x5 = -1;
        t13 = values4[y5 * dx + dx] >= value3;
        t22 = values4[y5 * dx] >= value3;
        cases[t13 << 1 | t22 << 2].forEach(stitch);
        while (++x5 < dx - 1) {
          t04 = t13, t13 = values4[y5 * dx + dx + x5 + 1] >= value3;
          t32 = t22, t22 = values4[y5 * dx + x5 + 1] >= value3;
          cases[t04 | t13 << 1 | t22 << 2 | t32 << 3].forEach(stitch);
        }
        cases[t13 | t22 << 3].forEach(stitch);
      }
      x5 = -1;
      t22 = values4[y5 * dx] >= value3;
      cases[t22 << 2].forEach(stitch);
      while (++x5 < dx - 1) {
        t32 = t22, t22 = values4[y5 * dx + x5 + 1] >= value3;
        cases[t22 << 2 | t32 << 3].forEach(stitch);
      }
      cases[t22 << 3].forEach(stitch);
      function stitch(line4) {
        var start = [line4[0][0] + x5, line4[0][1] + y5], end = [line4[1][0] + x5, line4[1][1] + y5], startIndex = index4(start), endIndex = index4(end), f2, g2;
        if (f2 = fragmentByEnd[startIndex]) {
          if (g2 = fragmentByStart[endIndex]) {
            delete fragmentByEnd[f2.end];
            delete fragmentByStart[g2.start];
            if (f2 === g2) {
              f2.ring.push(end);
              callback(f2.ring);
            } else {
              fragmentByStart[f2.start] = fragmentByEnd[g2.end] = {
                start: f2.start,
                end: g2.end,
                ring: f2.ring.concat(g2.ring)
              };
            }
          } else {
            delete fragmentByEnd[f2.end];
            f2.ring.push(end);
            fragmentByEnd[f2.end = endIndex] = f2;
          }
        } else if (f2 = fragmentByStart[endIndex]) {
          if (g2 = fragmentByEnd[startIndex]) {
            delete fragmentByStart[f2.start];
            delete fragmentByEnd[g2.end];
            if (f2 === g2) {
              f2.ring.push(end);
              callback(f2.ring);
            } else {
              fragmentByStart[g2.start] = fragmentByEnd[f2.end] = {
                start: g2.start,
                end: f2.end,
                ring: g2.ring.concat(f2.ring)
              };
            }
          } else {
            delete fragmentByStart[f2.start];
            f2.ring.unshift(start);
            fragmentByStart[f2.start = startIndex] = f2;
          }
        } else {
          fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {
            start: startIndex,
            end: endIndex,
            ring: [start, end]
          };
        }
      }
    }
    function index4(point9) {
      return point9[0] * 2 + point9[1] * (dx + 1) * 4;
    }
    function smoothLinear(ring, values4, value3) {
      ring.forEach((point9) => {
        var x5 = point9[0], y5 = point9[1], xt = x5 | 0, yt = y5 | 0, v0, v1 = values4[yt * dx + xt];
        if (x5 > 0 && x5 < dx && xt === x5) {
          v0 = values4[yt * dx + xt - 1];
          point9[0] = x5 + (value3 - v0) / (v1 - v0) - 0.5;
        }
        if (y5 > 0 && y5 < dy && yt === y5) {
          v0 = values4[(yt - 1) * dx + xt];
          point9[1] = y5 + (value3 - v0) / (v1 - v0) - 0.5;
        }
      });
    }
    contours2.contour = contour;
    contours2.size = function(_) {
      if (!arguments.length) return [dx, dy];
      var _0 = Math.floor(_[0]), _1 = Math.floor(_[1]);
      if (!(_0 >= 0 && _1 >= 0)) error("invalid size");
      return dx = _0, dy = _1, contours2;
    };
    contours2.smooth = function(_) {
      return arguments.length ? (smooth = _ ? smoothLinear : noop3, contours2) : smooth === smoothLinear;
    };
    return contours2;
  }
  function area2(ring) {
    var i2 = 0, n2 = ring.length, area4 = ring[n2 - 1][1] * ring[0][0] - ring[n2 - 1][0] * ring[0][1];
    while (++i2 < n2) area4 += ring[i2 - 1][1] * ring[i2][0] - ring[i2 - 1][0] * ring[i2][1];
    return area4;
  }
  function contains(ring, hole) {
    var i2 = -1, n2 = hole.length, c4;
    while (++i2 < n2) if (c4 = ringContains(ring, hole[i2])) return c4;
    return 0;
  }
  function ringContains(ring, point9) {
    var x5 = point9[0], y5 = point9[1], contains3 = -1;
    for (var i2 = 0, n2 = ring.length, j2 = n2 - 1; i2 < n2; j2 = i2++) {
      var pi5 = ring[i2], xi = pi5[0], yi = pi5[1], pj = ring[j2], xj = pj[0], yj = pj[1];
      if (segmentContains(pi5, pj, point9)) return 0;
      if (yi > y5 !== yj > y5 && x5 < (xj - xi) * (y5 - yi) / (yj - yi) + xi) contains3 = -contains3;
    }
    return contains3;
  }
  function segmentContains(a4, b3, c4) {
    var i2;
    return collinear(a4, b3, c4) && within(a4[i2 = +(a4[0] === b3[0])], c4[i2], b3[i2]);
  }
  function collinear(a4, b3, c4) {
    return (b3[0] - a4[0]) * (c4[1] - a4[1]) === (c4[0] - a4[0]) * (b3[1] - a4[1]);
  }
  function within(p2, q2, r2) {
    return p2 <= q2 && q2 <= r2 || r2 <= q2 && q2 <= p2;
  }
  function quantize2(k2, nice3, zero6) {
    return function(values4) {
      var ex = extent(values4), start = zero6 ? Math.min(ex[0], 0) : ex[0], stop2 = ex[1], span2 = stop2 - start, step = nice3 ? tickStep(start, stop2, k2) : span2 / (k2 + 1);
      return range(start + step, stop2, step);
    };
  }
  function Isocontour(params2) {
    Transform.call(this, null, params2);
  }
  Isocontour.Definition = {
    "type": "Isocontour",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "thresholds",
      "type": "number",
      "array": true
    }, {
      "name": "levels",
      "type": "number"
    }, {
      "name": "nice",
      "type": "boolean",
      "default": false
    }, {
      "name": "resolve",
      "type": "enum",
      "values": ["shared", "independent"],
      "default": "independent"
    }, {
      "name": "zero",
      "type": "boolean",
      "default": true
    }, {
      "name": "smooth",
      "type": "boolean",
      "default": true
    }, {
      "name": "scale",
      "type": "number",
      "expr": true
    }, {
      "name": "translate",
      "type": "number",
      "array": true,
      "expr": true
    }, {
      "name": "as",
      "type": "string",
      "null": true,
      "default": "contour"
    }]
  };
  inherits(Isocontour, Transform, {
    transform(_, pulse2) {
      if (this.value && !pulse2.changed() && !_.modified()) {
        return pulse2.StopPropagation;
      }
      var out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), source4 = pulse2.materialize(pulse2.SOURCE).source, field3 = _.field || identity, contour = contours().smooth(_.smooth !== false), tz = _.thresholds || levels(source4, field3, _), as = _.as === null ? null : _.as || "contour", values4 = [];
      source4.forEach((t4) => {
        const grid = field3(t4);
        const paths = contour.size([grid.width, grid.height])(grid.values, isArray(tz) ? tz : tz(grid.values));
        transformPaths(paths, grid, t4, _);
        paths.forEach((p2) => {
          values4.push(rederive(t4, ingest$1(as != null ? {
            [as]: p2
          } : p2)));
        });
      });
      if (this.value) out.rem = this.value;
      this.value = out.source = out.add = values4;
      return out;
    }
  });
  function levels(values4, f2, _) {
    const q2 = quantize2(_.levels || 10, _.nice, _.zero !== false);
    return _.resolve !== "shared" ? q2 : q2(values4.map((t4) => max(f2(t4).values)));
  }
  function transformPaths(paths, grid, datum2, _) {
    let s2 = _.scale || grid.scale, t4 = _.translate || grid.translate;
    if (isFunction(s2)) s2 = s2(datum2, _);
    if (isFunction(t4)) t4 = t4(datum2, _);
    if ((s2 === 1 || s2 == null) && !t4) return;
    const sx = (isNumber(s2) ? s2 : s2[0]) || 1, sy = (isNumber(s2) ? s2 : s2[1]) || 1, tx = t4 && t4[0] || 0, ty = t4 && t4[1] || 0;
    paths.forEach(transform2(grid, sx, sy, tx, ty));
  }
  function transform2(grid, sx, sy, tx, ty) {
    const x12 = grid.x1 || 0, y12 = grid.y1 || 0, flip2 = sx * sy < 0;
    function transformPolygon(coordinates) {
      coordinates.forEach(transformRing);
    }
    function transformRing(coordinates) {
      if (flip2) coordinates.reverse();
      coordinates.forEach(transformPoint);
    }
    function transformPoint(coordinates) {
      coordinates[0] = (coordinates[0] - x12) * sx + tx;
      coordinates[1] = (coordinates[1] - y12) * sy + ty;
    }
    return function(geometry) {
      geometry.coordinates.forEach(transformPolygon);
      return geometry;
    };
  }
  function radius(bw, data3, f2) {
    const v3 = bw >= 0 ? bw : estimateBandwidth(data3, f2);
    return Math.round((Math.sqrt(4 * v3 * v3 + 1) - 1) / 2);
  }
  function number5(_) {
    return isFunction(_) ? _ : constant(+_);
  }
  function density2D() {
    var x5 = (d2) => d2[0], y5 = (d2) => d2[1], weight = one, bandwidth2 = [-1, -1], dx = 960, dy = 500, k2 = 2;
    function density(data3, counts) {
      const rx = radius(bandwidth2[0], data3, x5) >> k2, ry = radius(bandwidth2[1], data3, y5) >> k2, ox = rx ? rx + 2 : 0, oy = ry ? ry + 2 : 0, n2 = 2 * ox + (dx >> k2), m4 = 2 * oy + (dy >> k2), values0 = new Float32Array(n2 * m4), values1 = new Float32Array(n2 * m4);
      let values4 = values0;
      data3.forEach((d2) => {
        const xi = ox + (+x5(d2) >> k2), yi = oy + (+y5(d2) >> k2);
        if (xi >= 0 && xi < n2 && yi >= 0 && yi < m4) {
          values0[xi + yi * n2] += +weight(d2);
        }
      });
      if (rx > 0 && ry > 0) {
        blurX(n2, m4, values0, values1, rx);
        blurY(n2, m4, values1, values0, ry);
        blurX(n2, m4, values0, values1, rx);
        blurY(n2, m4, values1, values0, ry);
        blurX(n2, m4, values0, values1, rx);
        blurY(n2, m4, values1, values0, ry);
      } else if (rx > 0) {
        blurX(n2, m4, values0, values1, rx);
        blurX(n2, m4, values1, values0, rx);
        blurX(n2, m4, values0, values1, rx);
        values4 = values1;
      } else if (ry > 0) {
        blurY(n2, m4, values0, values1, ry);
        blurY(n2, m4, values1, values0, ry);
        blurY(n2, m4, values0, values1, ry);
        values4 = values1;
      }
      const s2 = counts ? Math.pow(2, -2 * k2) : 1 / sum(values4);
      for (let i2 = 0, sz2 = n2 * m4; i2 < sz2; ++i2) values4[i2] *= s2;
      return {
        values: values4,
        scale: 1 << k2,
        width: n2,
        height: m4,
        x1: ox,
        y1: oy,
        x2: ox + (dx >> k2),
        y2: oy + (dy >> k2)
      };
    }
    density.x = function(_) {
      return arguments.length ? (x5 = number5(_), density) : x5;
    };
    density.y = function(_) {
      return arguments.length ? (y5 = number5(_), density) : y5;
    };
    density.weight = function(_) {
      return arguments.length ? (weight = number5(_), density) : weight;
    };
    density.size = function(_) {
      if (!arguments.length) return [dx, dy];
      var _0 = +_[0], _1 = +_[1];
      if (!(_0 >= 0 && _1 >= 0)) error("invalid size");
      return dx = _0, dy = _1, density;
    };
    density.cellSize = function(_) {
      if (!arguments.length) return 1 << k2;
      if (!((_ = +_) >= 1)) error("invalid cell size");
      k2 = Math.floor(Math.log(_) / Math.LN2);
      return density;
    };
    density.bandwidth = function(_) {
      if (!arguments.length) return bandwidth2;
      _ = array(_);
      if (_.length === 1) _ = [+_[0], +_[0]];
      if (_.length !== 2) error("invalid bandwidth");
      return bandwidth2 = _, density;
    };
    return density;
  }
  function blurX(n2, m4, source4, target2, r2) {
    const w3 = (r2 << 1) + 1;
    for (let j2 = 0; j2 < m4; ++j2) {
      for (let i2 = 0, sr = 0; i2 < n2 + r2; ++i2) {
        if (i2 < n2) {
          sr += source4[i2 + j2 * n2];
        }
        if (i2 >= r2) {
          if (i2 >= w3) {
            sr -= source4[i2 - w3 + j2 * n2];
          }
          target2[i2 - r2 + j2 * n2] = sr / Math.min(i2 + 1, n2 - 1 + w3 - i2, w3);
        }
      }
    }
  }
  function blurY(n2, m4, source4, target2, r2) {
    const w3 = (r2 << 1) + 1;
    for (let i2 = 0; i2 < n2; ++i2) {
      for (let j2 = 0, sr = 0; j2 < m4 + r2; ++j2) {
        if (j2 < m4) {
          sr += source4[i2 + j2 * n2];
        }
        if (j2 >= r2) {
          if (j2 >= w3) {
            sr -= source4[i2 + (j2 - w3) * n2];
          }
          target2[i2 + (j2 - r2) * n2] = sr / Math.min(j2 + 1, m4 - 1 + w3 - j2, w3);
        }
      }
    }
  }
  function KDE2D(params2) {
    Transform.call(this, null, params2);
  }
  KDE2D.Definition = {
    "type": "KDE2D",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2,
      "required": true
    }, {
      "name": "x",
      "type": "field",
      "required": true
    }, {
      "name": "y",
      "type": "field",
      "required": true
    }, {
      "name": "weight",
      "type": "field"
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "cellSize",
      "type": "number"
    }, {
      "name": "bandwidth",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "counts",
      "type": "boolean",
      "default": false
    }, {
      "name": "as",
      "type": "string",
      "default": "grid"
    }]
  };
  var PARAMS = ["x", "y", "weight", "size", "cellSize", "bandwidth"];
  function params(obj, _) {
    PARAMS.forEach((param2) => _[param2] != null ? obj[param2](_[param2]) : 0);
    return obj;
  }
  inherits(KDE2D, Transform, {
    transform(_, pulse2) {
      if (this.value && !pulse2.changed() && !_.modified()) return pulse2.StopPropagation;
      var out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition3(source4, _.groupby), names = (_.groupby || []).map(accessorName), kde2 = params(density2D(), _), as = _.as || "grid", values4 = [];
      function set7(t4, vals2) {
        for (let i2 = 0; i2 < names.length; ++i2) t4[names[i2]] = vals2[i2];
        return t4;
      }
      values4 = groups.map((g2) => ingest$1(set7({
        [as]: kde2(g2, _.counts)
      }, g2.dims)));
      if (this.value) out.rem = this.value;
      this.value = out.source = out.add = values4;
      return out;
    }
  });
  function partition3(data3, groupby) {
    var groups = [], get6 = (f2) => f2(t4), map4, i2, n2, t4, k2, g2;
    if (groupby == null) {
      groups.push(data3);
    } else {
      for (map4 = {}, i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
        t4 = data3[i2];
        k2 = groupby.map(get6);
        g2 = map4[k2];
        if (!g2) {
          map4[k2] = g2 = [];
          g2.dims = k2;
          groups.push(g2);
        }
        g2.push(t4);
      }
    }
    return groups;
  }
  function Contour(params2) {
    Transform.call(this, null, params2);
  }
  Contour.Definition = {
    "type": "Contour",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2,
      "required": true
    }, {
      "name": "values",
      "type": "number",
      "array": true
    }, {
      "name": "x",
      "type": "field"
    }, {
      "name": "y",
      "type": "field"
    }, {
      "name": "weight",
      "type": "field"
    }, {
      "name": "cellSize",
      "type": "number"
    }, {
      "name": "bandwidth",
      "type": "number"
    }, {
      "name": "count",
      "type": "number"
    }, {
      "name": "nice",
      "type": "boolean",
      "default": false
    }, {
      "name": "thresholds",
      "type": "number",
      "array": true
    }, {
      "name": "smooth",
      "type": "boolean",
      "default": true
    }]
  };
  inherits(Contour, Transform, {
    transform(_, pulse2) {
      if (this.value && !pulse2.changed() && !_.modified()) {
        return pulse2.StopPropagation;
      }
      var out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS), contour = contours().smooth(_.smooth !== false), values4 = _.values, thresh = _.thresholds || quantize2(_.count || 10, _.nice, !!values4), size = _.size, grid, post2;
      if (!values4) {
        values4 = pulse2.materialize(pulse2.SOURCE).source;
        grid = params(density2D(), _)(values4, true);
        post2 = transform2(grid, grid.scale || 1, grid.scale || 1, 0, 0);
        size = [grid.width, grid.height];
        values4 = grid.values;
      }
      thresh = isArray(thresh) ? thresh : thresh(values4);
      values4 = contour.size(size)(values4, thresh);
      if (post2) values4.forEach(post2);
      if (this.value) out.rem = this.value;
      this.value = out.source = out.add = (values4 || []).map(ingest$1);
      return out;
    }
  });
  var Feature = "Feature";
  var FeatureCollection = "FeatureCollection";
  var MultiPoint = "MultiPoint";
  function GeoJSON(params2) {
    Transform.call(this, null, params2);
  }
  GeoJSON.Definition = {
    "type": "GeoJSON",
    "metadata": {},
    "params": [{
      "name": "fields",
      "type": "field",
      "array": true,
      "length": 2
    }, {
      "name": "geojson",
      "type": "field"
    }]
  };
  inherits(GeoJSON, Transform, {
    transform(_, pulse2) {
      var features = this._features, points2 = this._points, fields = _.fields, lon = fields && fields[0], lat = fields && fields[1], geojson = _.geojson || !fields && identity, flag2 = pulse2.ADD, mod;
      mod = _.modified() || pulse2.changed(pulse2.REM) || pulse2.modified(accessorFields(geojson)) || lon && pulse2.modified(accessorFields(lon)) || lat && pulse2.modified(accessorFields(lat));
      if (!this.value || mod) {
        flag2 = pulse2.SOURCE;
        this._features = features = [];
        this._points = points2 = [];
      }
      if (geojson) {
        pulse2.visit(flag2, (t4) => features.push(geojson(t4)));
      }
      if (lon && lat) {
        pulse2.visit(flag2, (t4) => {
          var x5 = lon(t4), y5 = lat(t4);
          if (x5 != null && y5 != null && (x5 = +x5) === x5 && (y5 = +y5) === y5) {
            points2.push([x5, y5]);
          }
        });
        features = features.concat({
          type: Feature,
          geometry: {
            type: MultiPoint,
            coordinates: points2
          }
        });
      }
      this.value = {
        type: FeatureCollection,
        features
      };
    }
  });
  function GeoPath(params2) {
    Transform.call(this, null, params2);
  }
  GeoPath.Definition = {
    "type": "GeoPath",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "projection",
      "type": "projection"
    }, {
      "name": "field",
      "type": "field"
    }, {
      "name": "pointRadius",
      "type": "number",
      "expr": true
    }, {
      "name": "as",
      "type": "string",
      "default": "path"
    }]
  };
  inherits(GeoPath, Transform, {
    transform(_, pulse2) {
      var out = pulse2.fork(pulse2.ALL), path3 = this.value, field3 = _.field || identity, as = _.as || "path", flag2 = out.SOURCE;
      if (!path3 || _.modified()) {
        this.value = path3 = getProjectionPath(_.projection);
        out.materialize().reflow();
      } else {
        flag2 = field3 === identity || pulse2.modified(field3.fields) ? out.ADD_MOD : out.ADD;
      }
      const prev = initPath(path3, _.pointRadius);
      out.visit(flag2, (t4) => t4[as] = path3(field3(t4)));
      path3.pointRadius(prev);
      return out.modifies(as);
    }
  });
  function initPath(path3, pointRadius) {
    const prev = path3.pointRadius();
    path3.context(null);
    if (pointRadius != null) {
      path3.pointRadius(pointRadius);
    }
    return prev;
  }
  function GeoPoint(params2) {
    Transform.call(this, null, params2);
  }
  GeoPoint.Definition = {
    "type": "GeoPoint",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "projection",
      "type": "projection",
      "required": true
    }, {
      "name": "fields",
      "type": "field",
      "array": true,
      "required": true,
      "length": 2
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 2,
      "default": ["x", "y"]
    }]
  };
  inherits(GeoPoint, Transform, {
    transform(_, pulse2) {
      var proj = _.projection, lon = _.fields[0], lat = _.fields[1], as = _.as || ["x", "y"], x5 = as[0], y5 = as[1], mod;
      function set7(t4) {
        const xy = proj([lon(t4), lat(t4)]);
        if (xy) {
          t4[x5] = xy[0];
          t4[y5] = xy[1];
        } else {
          t4[x5] = void 0;
          t4[y5] = void 0;
        }
      }
      if (_.modified()) {
        pulse2 = pulse2.materialize().reflow(true).visit(pulse2.SOURCE, set7);
      } else {
        mod = pulse2.modified(lon.fields) || pulse2.modified(lat.fields);
        pulse2.visit(mod ? pulse2.ADD_MOD : pulse2.ADD, set7);
      }
      return pulse2.modifies(as);
    }
  });
  function GeoShape(params2) {
    Transform.call(this, null, params2);
  }
  GeoShape.Definition = {
    "type": "GeoShape",
    "metadata": {
      "modifies": true,
      "nomod": true
    },
    "params": [{
      "name": "projection",
      "type": "projection"
    }, {
      "name": "field",
      "type": "field",
      "default": "datum"
    }, {
      "name": "pointRadius",
      "type": "number",
      "expr": true
    }, {
      "name": "as",
      "type": "string",
      "default": "shape"
    }]
  };
  inherits(GeoShape, Transform, {
    transform(_, pulse2) {
      var out = pulse2.fork(pulse2.ALL), shape2 = this.value, as = _.as || "shape", flag2 = out.ADD;
      if (!shape2 || _.modified()) {
        this.value = shape2 = shapeGenerator(getProjectionPath(_.projection), _.field || field("datum"), _.pointRadius);
        out.materialize().reflow();
        flag2 = out.SOURCE;
      }
      out.visit(flag2, (t4) => t4[as] = shape2);
      return out.modifies(as);
    }
  });
  function shapeGenerator(path3, field3, pointRadius) {
    const shape2 = pointRadius == null ? (_) => path3(field3(_)) : (_) => {
      var prev = path3.pointRadius(), value3 = path3.pointRadius(pointRadius)(field3(_));
      path3.pointRadius(prev);
      return value3;
    };
    shape2.context = (_) => {
      path3.context(_);
      return shape2;
    };
    return shape2;
  }
  function Graticule(params2) {
    Transform.call(this, [], params2);
    this.generator = graticule();
  }
  Graticule.Definition = {
    "type": "Graticule",
    "metadata": {
      "changes": true,
      "generates": true
    },
    "params": [{
      "name": "extent",
      "type": "array",
      "array": true,
      "length": 2,
      "content": {
        "type": "number",
        "array": true,
        "length": 2
      }
    }, {
      "name": "extentMajor",
      "type": "array",
      "array": true,
      "length": 2,
      "content": {
        "type": "number",
        "array": true,
        "length": 2
      }
    }, {
      "name": "extentMinor",
      "type": "array",
      "array": true,
      "length": 2,
      "content": {
        "type": "number",
        "array": true,
        "length": 2
      }
    }, {
      "name": "step",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "stepMajor",
      "type": "number",
      "array": true,
      "length": 2,
      "default": [90, 360]
    }, {
      "name": "stepMinor",
      "type": "number",
      "array": true,
      "length": 2,
      "default": [10, 10]
    }, {
      "name": "precision",
      "type": "number",
      "default": 2.5
    }]
  };
  inherits(Graticule, Transform, {
    transform(_, pulse2) {
      var src = this.value, gen = this.generator, t4;
      if (!src.length || _.modified()) {
        for (const prop in _) {
          if (isFunction(gen[prop])) {
            gen[prop](_[prop]);
          }
        }
      }
      t4 = gen();
      if (src.length) {
        pulse2.mod.push(replace(src[0], t4));
      } else {
        pulse2.add.push(ingest$1(t4));
      }
      src[0] = t4;
      return pulse2;
    }
  });
  function Heatmap(params2) {
    Transform.call(this, null, params2);
  }
  Heatmap.Definition = {
    "type": "heatmap",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "color",
      "type": "string",
      "expr": true
    }, {
      "name": "opacity",
      "type": "number",
      "expr": true
    }, {
      "name": "resolve",
      "type": "enum",
      "values": ["shared", "independent"],
      "default": "independent"
    }, {
      "name": "as",
      "type": "string",
      "default": "image"
    }]
  };
  inherits(Heatmap, Transform, {
    transform(_, pulse2) {
      if (!pulse2.changed() && !_.modified()) {
        return pulse2.StopPropagation;
      }
      var source4 = pulse2.materialize(pulse2.SOURCE).source, shared = _.resolve === "shared", field3 = _.field || identity, opacity2 = opacity_(_.opacity, _), color5 = color_(_.color, _), as = _.as || "image", obj = {
        $x: 0,
        $y: 0,
        $value: 0,
        $max: shared ? max(source4.map((t4) => max(field3(t4).values))) : 0
      };
      source4.forEach((t4) => {
        const v3 = field3(t4);
        const o2 = extend({}, t4, obj);
        if (!shared) o2.$max = max(v3.values || []);
        t4[as] = toCanvas(v3, o2, color5.dep ? color5 : constant(color5(o2)), opacity2.dep ? opacity2 : constant(opacity2(o2)));
      });
      return pulse2.reflow(true).modifies(as);
    }
  });
  function color_(color5, _) {
    let f2;
    if (isFunction(color5)) {
      f2 = (obj) => rgb(color5(obj, _));
      f2.dep = dependency(color5);
    } else {
      f2 = constant(rgb(color5 || "#888"));
    }
    return f2;
  }
  function opacity_(opacity2, _) {
    let f2;
    if (isFunction(opacity2)) {
      f2 = (obj) => opacity2(obj, _);
      f2.dep = dependency(opacity2);
    } else if (opacity2) {
      f2 = constant(opacity2);
    } else {
      f2 = (obj) => obj.$value / obj.$max || 0;
      f2.dep = true;
    }
    return f2;
  }
  function dependency(f2) {
    if (!isFunction(f2)) return false;
    const set7 = toSet(accessorFields(f2));
    return set7.$x || set7.$y || set7.$value || set7.$max;
  }
  function toCanvas(grid, obj, color5, opacity2) {
    const n2 = grid.width, m4 = grid.height, x12 = grid.x1 || 0, y12 = grid.y1 || 0, x22 = grid.x2 || n2, y22 = grid.y2 || m4, val = grid.values, value3 = val ? (i2) => val[i2] : zero, can = domCanvas(x22 - x12, y22 - y12), ctx = can.getContext("2d"), img = ctx.getImageData(0, 0, x22 - x12, y22 - y12), pix = img.data;
    for (let j2 = y12, k2 = 0; j2 < y22; ++j2) {
      obj.$y = j2 - y12;
      for (let i2 = x12, r2 = j2 * n2; i2 < x22; ++i2, k2 += 4) {
        obj.$x = i2 - x12;
        obj.$value = value3(i2 + r2);
        const v3 = color5(obj);
        pix[k2 + 0] = v3.r;
        pix[k2 + 1] = v3.g;
        pix[k2 + 2] = v3.b;
        pix[k2 + 3] = ~~(255 * opacity2(obj));
      }
    }
    ctx.putImageData(img, 0, 0);
    return can;
  }
  function Projection(params2) {
    Transform.call(this, null, params2);
    this.modified(true);
  }
  inherits(Projection, Transform, {
    transform(_, pulse2) {
      let proj = this.value;
      if (!proj || _.modified("type")) {
        this.value = proj = create3(_.type);
        projectionProperties.forEach((prop) => {
          if (_[prop] != null) set4(proj, prop, _[prop]);
        });
      } else {
        projectionProperties.forEach((prop) => {
          if (_.modified(prop)) set4(proj, prop, _[prop]);
        });
      }
      if (_.pointRadius != null) proj.path.pointRadius(_.pointRadius);
      if (_.fit) fit2(proj, _);
      return pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
    }
  });
  function fit2(proj, _) {
    const data3 = collectGeoJSON(_.fit);
    _.extent ? proj.fitExtent(_.extent, data3) : _.size ? proj.fitSize(_.size, data3) : 0;
  }
  function create3(type3) {
    const constructor = projection2((type3 || "mercator").toLowerCase());
    if (!constructor) error("Unrecognized projection type: " + type3);
    return constructor();
  }
  function set4(proj, key2, value3) {
    if (isFunction(proj[key2])) proj[key2](value3);
  }
  function collectGeoJSON(data3) {
    data3 = array(data3);
    return data3.length === 1 ? data3[0] : {
      type: FeatureCollection,
      features: data3.reduce((a4, f2) => a4.concat(featurize(f2)), [])
    };
  }
  function featurize(f2) {
    return f2.type === FeatureCollection ? f2.features : array(f2).filter((d2) => d2 != null).map((d2) => d2.type === Feature ? d2 : {
      type: Feature,
      geometry: d2
    });
  }

  // node_modules/vega-force/build/vega-force.module.js
  var vega_force_module_exports = {};
  __export(vega_force_module_exports, {
    force: () => Force
  });

  // node_modules/d3-force/src/center.js
  function center_default(x5, y5) {
    var nodes, strength = 1;
    if (x5 == null) x5 = 0;
    if (y5 == null) y5 = 0;
    function force() {
      var i2, n2 = nodes.length, node, sx = 0, sy = 0;
      for (i2 = 0; i2 < n2; ++i2) {
        node = nodes[i2], sx += node.x, sy += node.y;
      }
      for (sx = (sx / n2 - x5) * strength, sy = (sy / n2 - y5) * strength, i2 = 0; i2 < n2; ++i2) {
        node = nodes[i2], node.x -= sx, node.y -= sy;
      }
    }
    force.initialize = function(_) {
      nodes = _;
    };
    force.x = function(_) {
      return arguments.length ? (x5 = +_, force) : x5;
    };
    force.y = function(_) {
      return arguments.length ? (y5 = +_, force) : y5;
    };
    force.strength = function(_) {
      return arguments.length ? (strength = +_, force) : strength;
    };
    return force;
  }

  // node_modules/d3-quadtree/src/add.js
  function add_default(d2) {
    const x5 = +this._x.call(null, d2), y5 = +this._y.call(null, d2);
    return add4(this.cover(x5, y5), x5, y5, d2);
  }
  function add4(tree, x5, y5, d2) {
    if (isNaN(x5) || isNaN(y5)) return tree;
    var parent, node = tree._root, leaf = { data: d2 }, x06 = tree._x0, y06 = tree._y0, x12 = tree._x1, y12 = tree._y1, xm, ym, xp, yp, right, bottom, i2, j2;
    if (!node) return tree._root = leaf, tree;
    while (node.length) {
      if (right = x5 >= (xm = (x06 + x12) / 2)) x06 = xm;
      else x12 = xm;
      if (bottom = y5 >= (ym = (y06 + y12) / 2)) y06 = ym;
      else y12 = ym;
      if (parent = node, !(node = node[i2 = bottom << 1 | right])) return parent[i2] = leaf, tree;
    }
    xp = +tree._x.call(null, node.data);
    yp = +tree._y.call(null, node.data);
    if (x5 === xp && y5 === yp) return leaf.next = node, parent ? parent[i2] = leaf : tree._root = leaf, tree;
    do {
      parent = parent ? parent[i2] = new Array(4) : tree._root = new Array(4);
      if (right = x5 >= (xm = (x06 + x12) / 2)) x06 = xm;
      else x12 = xm;
      if (bottom = y5 >= (ym = (y06 + y12) / 2)) y06 = ym;
      else y12 = ym;
    } while ((i2 = bottom << 1 | right) === (j2 = (yp >= ym) << 1 | xp >= xm));
    return parent[j2] = node, parent[i2] = leaf, tree;
  }
  function addAll(data3) {
    var d2, i2, n2 = data3.length, x5, y5, xz = new Array(n2), yz = new Array(n2), x06 = Infinity, y06 = Infinity, x12 = -Infinity, y12 = -Infinity;
    for (i2 = 0; i2 < n2; ++i2) {
      if (isNaN(x5 = +this._x.call(null, d2 = data3[i2])) || isNaN(y5 = +this._y.call(null, d2))) continue;
      xz[i2] = x5;
      yz[i2] = y5;
      if (x5 < x06) x06 = x5;
      if (x5 > x12) x12 = x5;
      if (y5 < y06) y06 = y5;
      if (y5 > y12) y12 = y5;
    }
    if (x06 > x12 || y06 > y12) return this;
    this.cover(x06, y06).cover(x12, y12);
    for (i2 = 0; i2 < n2; ++i2) {
      add4(this, xz[i2], yz[i2], data3[i2]);
    }
    return this;
  }

  // node_modules/d3-quadtree/src/cover.js
  function cover_default(x5, y5) {
    if (isNaN(x5 = +x5) || isNaN(y5 = +y5)) return this;
    var x06 = this._x0, y06 = this._y0, x12 = this._x1, y12 = this._y1;
    if (isNaN(x06)) {
      x12 = (x06 = Math.floor(x5)) + 1;
      y12 = (y06 = Math.floor(y5)) + 1;
    } else {
      var z = x12 - x06 || 1, node = this._root, parent, i2;
      while (x06 > x5 || x5 >= x12 || y06 > y5 || y5 >= y12) {
        i2 = (y5 < y06) << 1 | x5 < x06;
        parent = new Array(4), parent[i2] = node, node = parent, z *= 2;
        switch (i2) {
          case 0:
            x12 = x06 + z, y12 = y06 + z;
            break;
          case 1:
            x06 = x12 - z, y12 = y06 + z;
            break;
          case 2:
            x12 = x06 + z, y06 = y12 - z;
            break;
          case 3:
            x06 = x12 - z, y06 = y12 - z;
            break;
        }
      }
      if (this._root && this._root.length) this._root = node;
    }
    this._x0 = x06;
    this._y0 = y06;
    this._x1 = x12;
    this._y1 = y12;
    return this;
  }

  // node_modules/d3-quadtree/src/data.js
  function data_default() {
    var data3 = [];
    this.visit(function(node) {
      if (!node.length) do
        data3.push(node.data);
      while (node = node.next);
    });
    return data3;
  }

  // node_modules/d3-quadtree/src/extent.js
  function extent_default(_) {
    return arguments.length ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
  }

  // node_modules/d3-quadtree/src/quad.js
  function quad_default(node, x06, y06, x12, y12) {
    this.node = node;
    this.x0 = x06;
    this.y0 = y06;
    this.x1 = x12;
    this.y1 = y12;
  }

  // node_modules/d3-quadtree/src/find.js
  function find_default(x5, y5, radius2) {
    var data3, x06 = this._x0, y06 = this._y0, x12, y12, x22, y22, x32 = this._x1, y32 = this._y1, quads = [], node = this._root, q2, i2;
    if (node) quads.push(new quad_default(node, x06, y06, x32, y32));
    if (radius2 == null) radius2 = Infinity;
    else {
      x06 = x5 - radius2, y06 = y5 - radius2;
      x32 = x5 + radius2, y32 = y5 + radius2;
      radius2 *= radius2;
    }
    while (q2 = quads.pop()) {
      if (!(node = q2.node) || (x12 = q2.x0) > x32 || (y12 = q2.y0) > y32 || (x22 = q2.x1) < x06 || (y22 = q2.y1) < y06) continue;
      if (node.length) {
        var xm = (x12 + x22) / 2, ym = (y12 + y22) / 2;
        quads.push(
          new quad_default(node[3], xm, ym, x22, y22),
          new quad_default(node[2], x12, ym, xm, y22),
          new quad_default(node[1], xm, y12, x22, ym),
          new quad_default(node[0], x12, y12, xm, ym)
        );
        if (i2 = (y5 >= ym) << 1 | x5 >= xm) {
          q2 = quads[quads.length - 1];
          quads[quads.length - 1] = quads[quads.length - 1 - i2];
          quads[quads.length - 1 - i2] = q2;
        }
      } else {
        var dx = x5 - +this._x.call(null, node.data), dy = y5 - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
        if (d2 < radius2) {
          var d3 = Math.sqrt(radius2 = d2);
          x06 = x5 - d3, y06 = y5 - d3;
          x32 = x5 + d3, y32 = y5 + d3;
          data3 = node.data;
        }
      }
    }
    return data3;
  }

  // node_modules/d3-quadtree/src/remove.js
  function remove_default(d2) {
    if (isNaN(x5 = +this._x.call(null, d2)) || isNaN(y5 = +this._y.call(null, d2))) return this;
    var parent, node = this._root, retainer, previous, next, x06 = this._x0, y06 = this._y0, x12 = this._x1, y12 = this._y1, x5, y5, xm, ym, right, bottom, i2, j2;
    if (!node) return this;
    if (node.length) while (true) {
      if (right = x5 >= (xm = (x06 + x12) / 2)) x06 = xm;
      else x12 = xm;
      if (bottom = y5 >= (ym = (y06 + y12) / 2)) y06 = ym;
      else y12 = ym;
      if (!(parent = node, node = node[i2 = bottom << 1 | right])) return this;
      if (!node.length) break;
      if (parent[i2 + 1 & 3] || parent[i2 + 2 & 3] || parent[i2 + 3 & 3]) retainer = parent, j2 = i2;
    }
    while (node.data !== d2) if (!(previous = node, node = node.next)) return this;
    if (next = node.next) delete node.next;
    if (previous) return next ? previous.next = next : delete previous.next, this;
    if (!parent) return this._root = next, this;
    next ? parent[i2] = next : delete parent[i2];
    if ((node = parent[0] || parent[1] || parent[2] || parent[3]) && node === (parent[3] || parent[2] || parent[1] || parent[0]) && !node.length) {
      if (retainer) retainer[j2] = node;
      else this._root = node;
    }
    return this;
  }
  function removeAll(data3) {
    for (var i2 = 0, n2 = data3.length; i2 < n2; ++i2) this.remove(data3[i2]);
    return this;
  }

  // node_modules/d3-quadtree/src/root.js
  function root_default() {
    return this._root;
  }

  // node_modules/d3-quadtree/src/size.js
  function size_default() {
    var size = 0;
    this.visit(function(node) {
      if (!node.length) do
        ++size;
      while (node = node.next);
    });
    return size;
  }

  // node_modules/d3-quadtree/src/visit.js
  function visit_default(callback) {
    var quads = [], q2, node = this._root, child, x06, y06, x12, y12;
    if (node) quads.push(new quad_default(node, this._x0, this._y0, this._x1, this._y1));
    while (q2 = quads.pop()) {
      if (!callback(node = q2.node, x06 = q2.x0, y06 = q2.y0, x12 = q2.x1, y12 = q2.y1) && node.length) {
        var xm = (x06 + x12) / 2, ym = (y06 + y12) / 2;
        if (child = node[3]) quads.push(new quad_default(child, xm, ym, x12, y12));
        if (child = node[2]) quads.push(new quad_default(child, x06, ym, xm, y12));
        if (child = node[1]) quads.push(new quad_default(child, xm, y06, x12, ym));
        if (child = node[0]) quads.push(new quad_default(child, x06, y06, xm, ym));
      }
    }
    return this;
  }

  // node_modules/d3-quadtree/src/visitAfter.js
  function visitAfter_default(callback) {
    var quads = [], next = [], q2;
    if (this._root) quads.push(new quad_default(this._root, this._x0, this._y0, this._x1, this._y1));
    while (q2 = quads.pop()) {
      var node = q2.node;
      if (node.length) {
        var child, x06 = q2.x0, y06 = q2.y0, x12 = q2.x1, y12 = q2.y1, xm = (x06 + x12) / 2, ym = (y06 + y12) / 2;
        if (child = node[0]) quads.push(new quad_default(child, x06, y06, xm, ym));
        if (child = node[1]) quads.push(new quad_default(child, xm, y06, x12, ym));
        if (child = node[2]) quads.push(new quad_default(child, x06, ym, xm, y12));
        if (child = node[3]) quads.push(new quad_default(child, xm, ym, x12, y12));
      }
      next.push(q2);
    }
    while (q2 = next.pop()) {
      callback(q2.node, q2.x0, q2.y0, q2.x1, q2.y1);
    }
    return this;
  }

  // node_modules/d3-quadtree/src/x.js
  function defaultX(d2) {
    return d2[0];
  }
  function x_default(_) {
    return arguments.length ? (this._x = _, this) : this._x;
  }

  // node_modules/d3-quadtree/src/y.js
  function defaultY(d2) {
    return d2[1];
  }
  function y_default(_) {
    return arguments.length ? (this._y = _, this) : this._y;
  }

  // node_modules/d3-quadtree/src/quadtree.js
  function quadtree(nodes, x5, y5) {
    var tree = new Quadtree(x5 == null ? defaultX : x5, y5 == null ? defaultY : y5, NaN, NaN, NaN, NaN);
    return nodes == null ? tree : tree.addAll(nodes);
  }
  function Quadtree(x5, y5, x06, y06, x12, y12) {
    this._x = x5;
    this._y = y5;
    this._x0 = x06;
    this._y0 = y06;
    this._x1 = x12;
    this._y1 = y12;
    this._root = void 0;
  }
  function leaf_copy(leaf) {
    var copy4 = { data: leaf.data }, next = copy4;
    while (leaf = leaf.next) next = next.next = { data: leaf.data };
    return copy4;
  }
  var treeProto = quadtree.prototype = Quadtree.prototype;
  treeProto.copy = function() {
    var copy4 = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child;
    if (!node) return copy4;
    if (!node.length) return copy4._root = leaf_copy(node), copy4;
    nodes = [{ source: node, target: copy4._root = new Array(4) }];
    while (node = nodes.pop()) {
      for (var i2 = 0; i2 < 4; ++i2) {
        if (child = node.source[i2]) {
          if (child.length) nodes.push({ source: child, target: node.target[i2] = new Array(4) });
          else node.target[i2] = leaf_copy(child);
        }
      }
    }
    return copy4;
  };
  treeProto.add = add_default;
  treeProto.addAll = addAll;
  treeProto.cover = cover_default;
  treeProto.data = data_default;
  treeProto.extent = extent_default;
  treeProto.find = find_default;
  treeProto.remove = remove_default;
  treeProto.removeAll = removeAll;
  treeProto.root = root_default;
  treeProto.size = size_default;
  treeProto.visit = visit_default;
  treeProto.visitAfter = visitAfter_default;
  treeProto.x = x_default;
  treeProto.y = y_default;

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

  // node_modules/d3-force/src/jiggle.js
  function jiggle_default(random2) {
    return (random2() - 0.5) * 1e-6;
  }

  // node_modules/d3-force/src/collide.js
  function x3(d2) {
    return d2.x + d2.vx;
  }
  function y3(d2) {
    return d2.y + d2.vy;
  }
  function collide_default(radius2) {
    var nodes, radii, random2, strength = 1, iterations2 = 1;
    if (typeof radius2 !== "function") radius2 = constant_default3(radius2 == null ? 1 : +radius2);
    function force() {
      var i2, n2 = nodes.length, tree, node, xi, yi, ri, ri2;
      for (var k2 = 0; k2 < iterations2; ++k2) {
        tree = quadtree(nodes, x3, y3).visitAfter(prepare2);
        for (i2 = 0; i2 < n2; ++i2) {
          node = nodes[i2];
          ri = radii[node.index], ri2 = ri * ri;
          xi = node.x + node.vx;
          yi = node.y + node.vy;
          tree.visit(apply3);
        }
      }
      function apply3(quad2, x06, y06, x12, y12) {
        var data3 = quad2.data, rj = quad2.r, r2 = ri + rj;
        if (data3) {
          if (data3.index > node.index) {
            var x5 = xi - data3.x - data3.vx, y5 = yi - data3.y - data3.vy, l2 = x5 * x5 + y5 * y5;
            if (l2 < r2 * r2) {
              if (x5 === 0) x5 = jiggle_default(random2), l2 += x5 * x5;
              if (y5 === 0) y5 = jiggle_default(random2), l2 += y5 * y5;
              l2 = (r2 - (l2 = Math.sqrt(l2))) / l2 * strength;
              node.vx += (x5 *= l2) * (r2 = (rj *= rj) / (ri2 + rj));
              node.vy += (y5 *= l2) * r2;
              data3.vx -= x5 * (r2 = 1 - r2);
              data3.vy -= y5 * r2;
            }
          }
          return;
        }
        return x06 > xi + r2 || x12 < xi - r2 || y06 > yi + r2 || y12 < yi - r2;
      }
    }
    function prepare2(quad2) {
      if (quad2.data) return quad2.r = radii[quad2.data.index];
      for (var i2 = quad2.r = 0; i2 < 4; ++i2) {
        if (quad2[i2] && quad2[i2].r > quad2.r) {
          quad2.r = quad2[i2].r;
        }
      }
    }
    function initialize3() {
      if (!nodes) return;
      var i2, n2 = nodes.length, node;
      radii = new Array(n2);
      for (i2 = 0; i2 < n2; ++i2) node = nodes[i2], radii[node.index] = +radius2(node, i2, nodes);
    }
    force.initialize = function(_nodes, _random) {
      nodes = _nodes;
      random2 = _random;
      initialize3();
    };
    force.iterations = function(_) {
      return arguments.length ? (iterations2 = +_, force) : iterations2;
    };
    force.strength = function(_) {
      return arguments.length ? (strength = +_, force) : strength;
    };
    force.radius = function(_) {
      return arguments.length ? (radius2 = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : radius2;
    };
    return force;
  }

  // node_modules/d3-force/src/link.js
  function index(d2) {
    return d2.index;
  }
  function find2(nodeById, nodeId) {
    var node = nodeById.get(nodeId);
    if (!node) throw new Error("node not found: " + nodeId);
    return node;
  }
  function link_default(links) {
    var id2 = index, strength = defaultStrength, strengths, distance = constant_default3(30), distances, nodes, count2, bias, random2, iterations2 = 1;
    if (links == null) links = [];
    function defaultStrength(link2) {
      return 1 / Math.min(count2[link2.source.index], count2[link2.target.index]);
    }
    function force(alpha) {
      for (var k2 = 0, n2 = links.length; k2 < iterations2; ++k2) {
        for (var i2 = 0, link2, source4, target2, x5, y5, l2, b3; i2 < n2; ++i2) {
          link2 = links[i2], source4 = link2.source, target2 = link2.target;
          x5 = target2.x + target2.vx - source4.x - source4.vx || jiggle_default(random2);
          y5 = target2.y + target2.vy - source4.y - source4.vy || jiggle_default(random2);
          l2 = Math.sqrt(x5 * x5 + y5 * y5);
          l2 = (l2 - distances[i2]) / l2 * alpha * strengths[i2];
          x5 *= l2, y5 *= l2;
          target2.vx -= x5 * (b3 = bias[i2]);
          target2.vy -= y5 * b3;
          source4.vx += x5 * (b3 = 1 - b3);
          source4.vy += y5 * b3;
        }
      }
    }
    function initialize3() {
      if (!nodes) return;
      var i2, n2 = nodes.length, m4 = links.length, nodeById = new Map(nodes.map((d2, i3) => [id2(d2, i3, nodes), d2])), link2;
      for (i2 = 0, count2 = new Array(n2); i2 < m4; ++i2) {
        link2 = links[i2], link2.index = i2;
        if (typeof link2.source !== "object") link2.source = find2(nodeById, link2.source);
        if (typeof link2.target !== "object") link2.target = find2(nodeById, link2.target);
        count2[link2.source.index] = (count2[link2.source.index] || 0) + 1;
        count2[link2.target.index] = (count2[link2.target.index] || 0) + 1;
      }
      for (i2 = 0, bias = new Array(m4); i2 < m4; ++i2) {
        link2 = links[i2], bias[i2] = count2[link2.source.index] / (count2[link2.source.index] + count2[link2.target.index]);
      }
      strengths = new Array(m4), initializeStrength();
      distances = new Array(m4), initializeDistance();
    }
    function initializeStrength() {
      if (!nodes) return;
      for (var i2 = 0, n2 = links.length; i2 < n2; ++i2) {
        strengths[i2] = +strength(links[i2], i2, links);
      }
    }
    function initializeDistance() {
      if (!nodes) return;
      for (var i2 = 0, n2 = links.length; i2 < n2; ++i2) {
        distances[i2] = +distance(links[i2], i2, links);
      }
    }
    force.initialize = function(_nodes, _random) {
      nodes = _nodes;
      random2 = _random;
      initialize3();
    };
    force.links = function(_) {
      return arguments.length ? (links = _, initialize3(), force) : links;
    };
    force.id = function(_) {
      return arguments.length ? (id2 = _, force) : id2;
    };
    force.iterations = function(_) {
      return arguments.length ? (iterations2 = +_, force) : iterations2;
    };
    force.strength = function(_) {
      return arguments.length ? (strength = typeof _ === "function" ? _ : constant_default3(+_), initializeStrength(), force) : strength;
    };
    force.distance = function(_) {
      return arguments.length ? (distance = typeof _ === "function" ? _ : constant_default3(+_), initializeDistance(), force) : distance;
    };
    return force;
  }

  // node_modules/d3-dispatch/src/dispatch.js
  var noop4 = { value: () => {
  } };
  function dispatch() {
    for (var i2 = 0, n2 = arguments.length, _ = {}, t4; i2 < n2; ++i2) {
      if (!(t4 = arguments[i2] + "") || t4 in _ || /[\s.]/.test(t4)) throw new Error("illegal type: " + t4);
      _[t4] = [];
    }
    return new Dispatch(_);
  }
  function Dispatch(_) {
    this._ = _;
  }
  function parseTypenames(typenames, types4) {
    return typenames.trim().split(/^|\s+/).map(function(t4) {
      var name4 = "", i2 = t4.indexOf(".");
      if (i2 >= 0) name4 = t4.slice(i2 + 1), t4 = t4.slice(0, i2);
      if (t4 && !types4.hasOwnProperty(t4)) throw new Error("unknown type: " + t4);
      return { type: t4, name: name4 };
    });
  }
  Dispatch.prototype = dispatch.prototype = {
    constructor: Dispatch,
    on: function(typename, callback) {
      var _ = this._, T = parseTypenames(typename + "", _), t4, i2 = -1, n2 = T.length;
      if (arguments.length < 2) {
        while (++i2 < n2) if ((t4 = (typename = T[i2]).type) && (t4 = get5(_[t4], typename.name))) return t4;
        return;
      }
      if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
      while (++i2 < n2) {
        if (t4 = (typename = T[i2]).type) _[t4] = set5(_[t4], typename.name, callback);
        else if (callback == null) for (t4 in _) _[t4] = set5(_[t4], typename.name, null);
      }
      return this;
    },
    copy: function() {
      var copy4 = {}, _ = this._;
      for (var t4 in _) copy4[t4] = _[t4].slice();
      return new Dispatch(copy4);
    },
    call: function(type3, that) {
      if ((n2 = arguments.length - 2) > 0) for (var args = new Array(n2), i2 = 0, n2, t4; i2 < n2; ++i2) args[i2] = arguments[i2 + 2];
      if (!this._.hasOwnProperty(type3)) throw new Error("unknown type: " + type3);
      for (t4 = this._[type3], i2 = 0, n2 = t4.length; i2 < n2; ++i2) t4[i2].value.apply(that, args);
    },
    apply: function(type3, that, args) {
      if (!this._.hasOwnProperty(type3)) throw new Error("unknown type: " + type3);
      for (var t4 = this._[type3], i2 = 0, n2 = t4.length; i2 < n2; ++i2) t4[i2].value.apply(that, args);
    }
  };
  function get5(type3, name4) {
    for (var i2 = 0, n2 = type3.length, c4; i2 < n2; ++i2) {
      if ((c4 = type3[i2]).name === name4) {
        return c4.value;
      }
    }
  }
  function set5(type3, name4, callback) {
    for (var i2 = 0, n2 = type3.length; i2 < n2; ++i2) {
      if (type3[i2].name === name4) {
        type3[i2] = noop4, type3 = type3.slice(0, i2).concat(type3.slice(i2 + 1));
        break;
      }
    }
    if (callback != null) type3.push({ name: name4, value: callback });
    return type3;
  }
  var dispatch_default = 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(f2) {
    setTimeout(f2, 17);
  };
  function now() {
    return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
  }
  function clearNow() {
    clockNow = 0;
  }
  function Timer() {
    this._call = this._time = this._next = null;
  }
  Timer.prototype = timer.prototype = {
    constructor: Timer,
    restart: function(callback, delay, time3) {
      if (typeof callback !== "function") throw new TypeError("callback is not a function");
      time3 = (time3 == null ? now() : +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 t4 = new Timer();
    t4.restart(callback, delay, time3);
    return t4;
  }
  function timerFlush() {
    now();
    ++frame;
    var t4 = taskHead, e4;
    while (t4) {
      if ((e4 = clockNow - t4._time) >= 0) t4._call.call(void 0, e4);
      t4 = t4._next;
    }
    --frame;
  }
  function wake() {
    clockNow = (clockLast = clock.now()) + clockSkew;
    frame = timeout = 0;
    try {
      timerFlush();
    } finally {
      frame = 0;
      nap();
      clockNow = 0;
    }
  }
  function poke() {
    var now2 = clock.now(), delay = now2 - clockLast;
    if (delay > pokeDelay) clockSkew -= delay, clockLast = now2;
  }
  function nap() {
    var t04, t13 = taskHead, t22, time3 = Infinity;
    while (t13) {
      if (t13._call) {
        if (time3 > t13._time) time3 = t13._time;
        t04 = t13, t13 = t13._next;
      } else {
        t22 = t13._next, t13._next = null;
        t13 = t04 ? t04._next = t22 : taskHead = t22;
      }
    }
    taskTail = t04;
    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/interval.js
  function interval_default(callback, delay, time3) {
    var t4 = new Timer(), total = delay;
    if (delay == null) return t4.restart(callback, delay, time3), t4;
    t4._restart = t4.restart;
    t4.restart = function(callback2, delay2, time4) {
      delay2 = +delay2, time4 = time4 == null ? now() : +time4;
      t4._restart(function tick2(elapsed) {
        elapsed += total;
        t4._restart(tick2, total += delay2, time4);
        callback2(elapsed);
      }, delay2, time4);
    };
    t4.restart(callback, delay, time3);
    return t4;
  }

  // node_modules/d3-force/src/lcg.js
  var a = 1664525;
  var c = 1013904223;
  var m = 4294967296;
  function lcg_default() {
    let s2 = 1;
    return () => (s2 = (a * s2 + c) % m) / m;
  }

  // node_modules/d3-force/src/simulation.js
  function x4(d2) {
    return d2.x;
  }
  function y4(d2) {
    return d2.y;
  }
  var initialRadius = 10;
  var initialAngle = Math.PI * (3 - Math.sqrt(5));
  function simulation_default(nodes) {
    var simulation2, alpha = 1, alphaMin = 1e-3, alphaDecay = 1 - Math.pow(alphaMin, 1 / 300), alphaTarget = 0, velocityDecay = 0.6, forces = /* @__PURE__ */ new Map(), stepper = timer(step), event2 = dispatch_default("tick", "end"), random2 = lcg_default();
    if (nodes == null) nodes = [];
    function step() {
      tick2();
      event2.call("tick", simulation2);
      if (alpha < alphaMin) {
        stepper.stop();
        event2.call("end", simulation2);
      }
    }
    function tick2(iterations2) {
      var i2, n2 = nodes.length, node;
      if (iterations2 === void 0) iterations2 = 1;
      for (var k2 = 0; k2 < iterations2; ++k2) {
        alpha += (alphaTarget - alpha) * alphaDecay;
        forces.forEach(function(force) {
          force(alpha);
        });
        for (i2 = 0; i2 < n2; ++i2) {
          node = nodes[i2];
          if (node.fx == null) node.x += node.vx *= velocityDecay;
          else node.x = node.fx, node.vx = 0;
          if (node.fy == null) node.y += node.vy *= velocityDecay;
          else node.y = node.fy, node.vy = 0;
        }
      }
      return simulation2;
    }
    function initializeNodes() {
      for (var i2 = 0, n2 = nodes.length, node; i2 < n2; ++i2) {
        node = nodes[i2], node.index = i2;
        if (node.fx != null) node.x = node.fx;
        if (node.fy != null) node.y = node.fy;
        if (isNaN(node.x) || isNaN(node.y)) {
          var radius2 = initialRadius * Math.sqrt(0.5 + i2), angle2 = i2 * initialAngle;
          node.x = radius2 * Math.cos(angle2);
          node.y = radius2 * Math.sin(angle2);
        }
        if (isNaN(node.vx) || isNaN(node.vy)) {
          node.vx = node.vy = 0;
        }
      }
    }
    function initializeForce(force) {
      if (force.initialize) force.initialize(nodes, random2);
      return force;
    }
    initializeNodes();
    return simulation2 = {
      tick: tick2,
      restart: function() {
        return stepper.restart(step), simulation2;
      },
      stop: function() {
        return stepper.stop(), simulation2;
      },
      nodes: function(_) {
        return arguments.length ? (nodes = _, initializeNodes(), forces.forEach(initializeForce), simulation2) : nodes;
      },
      alpha: function(_) {
        return arguments.length ? (alpha = +_, simulation2) : alpha;
      },
      alphaMin: function(_) {
        return arguments.length ? (alphaMin = +_, simulation2) : alphaMin;
      },
      alphaDecay: function(_) {
        return arguments.length ? (alphaDecay = +_, simulation2) : +alphaDecay;
      },
      alphaTarget: function(_) {
        return arguments.length ? (alphaTarget = +_, simulation2) : alphaTarget;
      },
      velocityDecay: function(_) {
        return arguments.length ? (velocityDecay = 1 - _, simulation2) : 1 - velocityDecay;
      },
      randomSource: function(_) {
        return arguments.length ? (random2 = _, forces.forEach(initializeForce), simulation2) : random2;
      },
      force: function(name4, _) {
        return arguments.length > 1 ? (_ == null ? forces.delete(name4) : forces.set(name4, initializeForce(_)), simulation2) : forces.get(name4);
      },
      find: function(x5, y5, radius2) {
        var i2 = 0, n2 = nodes.length, dx, dy, d2, node, closest;
        if (radius2 == null) radius2 = Infinity;
        else radius2 *= radius2;
        for (i2 = 0; i2 < n2; ++i2) {
          node = nodes[i2];
          dx = x5 - node.x;
          dy = y5 - node.y;
          d2 = dx * dx + dy * dy;
          if (d2 < radius2) closest = node, radius2 = d2;
        }
        return closest;
      },
      on: function(name4, _) {
        return arguments.length > 1 ? (event2.on(name4, _), simulation2) : event2.on(name4);
      }
    };
  }

  // node_modules/d3-force/src/manyBody.js
  function manyBody_default() {
    var nodes, node, random2, alpha, strength = constant_default3(-30), strengths, distanceMin2 = 1, distanceMax2 = Infinity, theta2 = 0.81;
    function force(_) {
      var i2, n2 = nodes.length, tree = quadtree(nodes, x4, y4).visitAfter(accumulate);
      for (alpha = _, i2 = 0; i2 < n2; ++i2) node = nodes[i2], tree.visit(apply3);
    }
    function initialize3() {
      if (!nodes) return;
      var i2, n2 = nodes.length, node2;
      strengths = new Array(n2);
      for (i2 = 0; i2 < n2; ++i2) node2 = nodes[i2], strengths[node2.index] = +strength(node2, i2, nodes);
    }
    function accumulate(quad2) {
      var strength2 = 0, q2, c4, weight = 0, x5, y5, i2;
      if (quad2.length) {
        for (x5 = y5 = i2 = 0; i2 < 4; ++i2) {
          if ((q2 = quad2[i2]) && (c4 = Math.abs(q2.value))) {
            strength2 += q2.value, weight += c4, x5 += c4 * q2.x, y5 += c4 * q2.y;
          }
        }
        quad2.x = x5 / weight;
        quad2.y = y5 / weight;
      } else {
        q2 = quad2;
        q2.x = q2.data.x;
        q2.y = q2.data.y;
        do
          strength2 += strengths[q2.data.index];
        while (q2 = q2.next);
      }
      quad2.value = strength2;
    }
    function apply3(quad2, x12, _, x22) {
      if (!quad2.value) return true;
      var x5 = quad2.x - node.x, y5 = quad2.y - node.y, w3 = x22 - x12, l2 = x5 * x5 + y5 * y5;
      if (w3 * w3 / theta2 < l2) {
        if (l2 < distanceMax2) {
          if (x5 === 0) x5 = jiggle_default(random2), l2 += x5 * x5;
          if (y5 === 0) y5 = jiggle_default(random2), l2 += y5 * y5;
          if (l2 < distanceMin2) l2 = Math.sqrt(distanceMin2 * l2);
          node.vx += x5 * quad2.value * alpha / l2;
          node.vy += y5 * quad2.value * alpha / l2;
        }
        return true;
      } else if (quad2.length || l2 >= distanceMax2) return;
      if (quad2.data !== node || quad2.next) {
        if (x5 === 0) x5 = jiggle_default(random2), l2 += x5 * x5;
        if (y5 === 0) y5 = jiggle_default(random2), l2 += y5 * y5;
        if (l2 < distanceMin2) l2 = Math.sqrt(distanceMin2 * l2);
      }
      do
        if (quad2.data !== node) {
          w3 = strengths[quad2.data.index] * alpha / l2;
          node.vx += x5 * w3;
          node.vy += y5 * w3;
        }
      while (quad2 = quad2.next);
    }
    force.initialize = function(_nodes, _random) {
      nodes = _nodes;
      random2 = _random;
      initialize3();
    };
    force.strength = function(_) {
      return arguments.length ? (strength = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : strength;
    };
    force.distanceMin = function(_) {
      return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
    };
    force.distanceMax = function(_) {
      return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
    };
    force.theta = function(_) {
      return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
    };
    return force;
  }

  // node_modules/d3-force/src/x.js
  function x_default2(x5) {
    var strength = constant_default3(0.1), nodes, strengths, xz;
    if (typeof x5 !== "function") x5 = constant_default3(x5 == null ? 0 : +x5);
    function force(alpha) {
      for (var i2 = 0, n2 = nodes.length, node; i2 < n2; ++i2) {
        node = nodes[i2], node.vx += (xz[i2] - node.x) * strengths[i2] * alpha;
      }
    }
    function initialize3() {
      if (!nodes) return;
      var i2, n2 = nodes.length;
      strengths = new Array(n2);
      xz = new Array(n2);
      for (i2 = 0; i2 < n2; ++i2) {
        strengths[i2] = isNaN(xz[i2] = +x5(nodes[i2], i2, nodes)) ? 0 : +strength(nodes[i2], i2, nodes);
      }
    }
    force.initialize = function(_) {
      nodes = _;
      initialize3();
    };
    force.strength = function(_) {
      return arguments.length ? (strength = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : strength;
    };
    force.x = function(_) {
      return arguments.length ? (x5 = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : x5;
    };
    return force;
  }

  // node_modules/d3-force/src/y.js
  function y_default2(y5) {
    var strength = constant_default3(0.1), nodes, strengths, yz;
    if (typeof y5 !== "function") y5 = constant_default3(y5 == null ? 0 : +y5);
    function force(alpha) {
      for (var i2 = 0, n2 = nodes.length, node; i2 < n2; ++i2) {
        node = nodes[i2], node.vy += (yz[i2] - node.y) * strengths[i2] * alpha;
      }
    }
    function initialize3() {
      if (!nodes) return;
      var i2, n2 = nodes.length;
      strengths = new Array(n2);
      yz = new Array(n2);
      for (i2 = 0; i2 < n2; ++i2) {
        strengths[i2] = isNaN(yz[i2] = +y5(nodes[i2], i2, nodes)) ? 0 : +strength(nodes[i2], i2, nodes);
      }
    }
    force.initialize = function(_) {
      nodes = _;
      initialize3();
    };
    force.strength = function(_) {
      return arguments.length ? (strength = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : strength;
    };
    force.y = function(_) {
      return arguments.length ? (y5 = typeof _ === "function" ? _ : constant_default3(+_), initialize3(), force) : y5;
    };
    return force;
  }

  // node_modules/vega-force/build/vega-force.module.js
  var ForceMap = {
    center: center_default,
    collide: collide_default,
    nbody: manyBody_default,
    link: link_default,
    x: x_default2,
    y: y_default2
  };
  var Forces = "forces";
  var ForceParams = ["alpha", "alphaMin", "alphaTarget", "velocityDecay", "forces"];
  var ForceConfig = ["static", "iterations"];
  var ForceOutput = ["x", "y", "vx", "vy"];
  function Force(params2) {
    Transform.call(this, null, params2);
  }
  Force.Definition = {
    "type": "Force",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "static",
      "type": "boolean",
      "default": false
    }, {
      "name": "restart",
      "type": "boolean",
      "default": false
    }, {
      "name": "iterations",
      "type": "number",
      "default": 300
    }, {
      "name": "alpha",
      "type": "number",
      "default": 1
    }, {
      "name": "alphaMin",
      "type": "number",
      "default": 1e-3
    }, {
      "name": "alphaTarget",
      "type": "number",
      "default": 0
    }, {
      "name": "velocityDecay",
      "type": "number",
      "default": 0.4
    }, {
      "name": "forces",
      "type": "param",
      "array": true,
      "params": [{
        "key": {
          "force": "center"
        },
        "params": [{
          "name": "x",
          "type": "number",
          "default": 0
        }, {
          "name": "y",
          "type": "number",
          "default": 0
        }]
      }, {
        "key": {
          "force": "collide"
        },
        "params": [{
          "name": "radius",
          "type": "number",
          "expr": true
        }, {
          "name": "strength",
          "type": "number",
          "default": 0.7
        }, {
          "name": "iterations",
          "type": "number",
          "default": 1
        }]
      }, {
        "key": {
          "force": "nbody"
        },
        "params": [{
          "name": "strength",
          "type": "number",
          "default": -30,
          "expr": true
        }, {
          "name": "theta",
          "type": "number",
          "default": 0.9
        }, {
          "name": "distanceMin",
          "type": "number",
          "default": 1
        }, {
          "name": "distanceMax",
          "type": "number"
        }]
      }, {
        "key": {
          "force": "link"
        },
        "params": [{
          "name": "links",
          "type": "data"
        }, {
          "name": "id",
          "type": "field"
        }, {
          "name": "distance",
          "type": "number",
          "default": 30,
          "expr": true
        }, {
          "name": "strength",
          "type": "number",
          "expr": true
        }, {
          "name": "iterations",
          "type": "number",
          "default": 1
        }]
      }, {
        "key": {
          "force": "x"
        },
        "params": [{
          "name": "strength",
          "type": "number",
          "default": 0.1
        }, {
          "name": "x",
          "type": "field"
        }]
      }, {
        "key": {
          "force": "y"
        },
        "params": [{
          "name": "strength",
          "type": "number",
          "default": 0.1
        }, {
          "name": "y",
          "type": "field"
        }]
      }]
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "modify": false,
      "default": ForceOutput
    }]
  };
  inherits(Force, Transform, {
    transform(_, pulse2) {
      var sim = this.value, change2 = pulse2.changed(pulse2.ADD_REM), params2 = _.modified(ForceParams), iters = _.iterations || 300;
      if (!sim) {
        this.value = sim = simulation(pulse2.source, _);
        sim.on("tick", rerun(pulse2.dataflow, this));
        if (!_.static) {
          change2 = true;
          sim.tick();
        }
        pulse2.modifies("index");
      } else {
        if (change2) {
          pulse2.modifies("index");
          sim.nodes(pulse2.source);
        }
        if (params2 || pulse2.changed(pulse2.MOD)) {
          setup(sim, _, 0, pulse2);
        }
      }
      if (params2 || change2 || _.modified(ForceConfig) || pulse2.changed() && _.restart) {
        sim.alpha(Math.max(sim.alpha(), _.alpha || 1)).alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters));
        if (_.static) {
          for (sim.stop(); --iters >= 0; ) sim.tick();
        } else {
          if (sim.stopped()) sim.restart();
          if (!change2) return pulse2.StopPropagation;
        }
      }
      return this.finish(_, pulse2);
    },
    finish(_, pulse2) {
      const dataflow = pulse2.dataflow;
      for (let args = this._argops, j2 = 0, m4 = args.length, arg; j2 < m4; ++j2) {
        arg = args[j2];
        if (arg.name !== Forces || arg.op._argval.force !== "link") {
          continue;
        }
        for (var ops2 = arg.op._argops, i2 = 0, n2 = ops2.length, op; i2 < n2; ++i2) {
          if (ops2[i2].name === "links" && (op = ops2[i2].op.source)) {
            dataflow.pulse(op, dataflow.changeset().reflow());
            break;
          }
        }
      }
      return pulse2.reflow(_.modified()).modifies(ForceOutput);
    }
  });
  function rerun(df, op) {
    return () => df.touch(op).run();
  }
  function simulation(nodes, _) {
    const sim = simulation_default(nodes), stop2 = sim.stop, restart = sim.restart;
    let stopped = false;
    sim.stopped = () => stopped;
    sim.restart = () => (stopped = false, restart());
    sim.stop = () => (stopped = true, stop2());
    return setup(sim, _, true).on("end", () => stopped = true);
  }
  function setup(sim, _, init2, pulse2) {
    var f2 = array(_.forces), i2, n2, p2, name4;
    for (i2 = 0, n2 = ForceParams.length; i2 < n2; ++i2) {
      p2 = ForceParams[i2];
      if (p2 !== Forces && _.modified(p2)) sim[p2](_[p2]);
    }
    for (i2 = 0, n2 = f2.length; i2 < n2; ++i2) {
      name4 = Forces + i2;
      p2 = init2 || _.modified(Forces, i2) ? getForce(f2[i2]) : pulse2 && modified(f2[i2], pulse2) ? sim.force(name4) : null;
      if (p2) sim.force(name4, p2);
    }
    for (n2 = sim.numForces || 0; i2 < n2; ++i2) {
      sim.force(Forces + i2, null);
    }
    sim.numForces = f2.length;
    return sim;
  }
  function modified(f2, pulse2) {
    var k2, v3;
    for (k2 in f2) {
      if (isFunction(v3 = f2[k2]) && pulse2.modified(accessorFields(v3))) return 1;
    }
    return 0;
  }
  function getForce(_) {
    var f2, p2;
    if (!has(ForceMap, _.force)) {
      error("Unrecognized force: " + _.force);
    }
    f2 = ForceMap[_.force]();
    for (p2 in _) {
      if (isFunction(f2[p2])) setForceParam(f2[p2], _[p2], _);
    }
    return f2;
  }
  function setForceParam(f2, v3, _) {
    f2(isFunction(v3) ? (d2) => v3(d2, _) : v3);
  }

  // node_modules/vega-hierarchy/build/vega-hierarchy.module.js
  var vega_hierarchy_module_exports = {};
  __export(vega_hierarchy_module_exports, {
    nest: () => Nest,
    pack: () => Pack,
    partition: () => Partition,
    stratify: () => Stratify,
    tree: () => Tree,
    treelinks: () => TreeLinks,
    treemap: () => Treemap
  });

  // node_modules/d3-hierarchy/src/cluster.js
  function defaultSeparation(a4, b3) {
    return a4.parent === b3.parent ? 1 : 2;
  }
  function meanX(children4) {
    return children4.reduce(meanXReduce, 0) / children4.length;
  }
  function meanXReduce(x5, c4) {
    return x5 + c4.x;
  }
  function maxY(children4) {
    return 1 + children4.reduce(maxYReduce, 0);
  }
  function maxYReduce(y5, c4) {
    return Math.max(y5, c4.y);
  }
  function leafLeft(node) {
    var children4;
    while (children4 = node.children) node = children4[0];
    return node;
  }
  function leafRight(node) {
    var children4;
    while (children4 = node.children) node = children4[children4.length - 1];
    return node;
  }
  function cluster_default() {
    var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = false;
    function cluster(root) {
      var previousNode, x5 = 0;
      root.eachAfter(function(node) {
        var children4 = node.children;
        if (children4) {
          node.x = meanX(children4);
          node.y = maxY(children4);
        } else {
          node.x = previousNode ? x5 += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });
      var left = leafLeft(root), right = leafRight(root), x06 = left.x - separation(left, right) / 2, x12 = right.x + separation(right, left) / 2;
      return root.eachAfter(nodeSize ? function(node) {
        node.x = (node.x - root.x) * dx;
        node.y = (root.y - node.y) * dy;
      } : function(node) {
        node.x = (node.x - x06) / (x12 - x06) * dx;
        node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
      });
    }
    cluster.separation = function(x5) {
      return arguments.length ? (separation = x5, cluster) : separation;
    };
    cluster.size = function(x5) {
      return arguments.length ? (nodeSize = false, dx = +x5[0], dy = +x5[1], cluster) : nodeSize ? null : [dx, dy];
    };
    cluster.nodeSize = function(x5) {
      return arguments.length ? (nodeSize = true, dx = +x5[0], dy = +x5[1], cluster) : nodeSize ? [dx, dy] : null;
    };
    return cluster;
  }

  // node_modules/d3-hierarchy/src/hierarchy/count.js
  function count(node) {
    var sum3 = 0, children4 = node.children, i2 = children4 && children4.length;
    if (!i2) sum3 = 1;
    else while (--i2 >= 0) sum3 += children4[i2].value;
    node.value = sum3;
  }
  function count_default() {
    return this.eachAfter(count);
  }

  // node_modules/d3-hierarchy/src/hierarchy/each.js
  function each_default(callback, that) {
    let index4 = -1;
    for (const node of this) {
      callback.call(that, node, ++index4, this);
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
  function eachBefore_default(callback, that) {
    var node = this, nodes = [node], children4, i2, index4 = -1;
    while (node = nodes.pop()) {
      callback.call(that, node, ++index4, this);
      if (children4 = node.children) {
        for (i2 = children4.length - 1; i2 >= 0; --i2) {
          nodes.push(children4[i2]);
        }
      }
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
  function eachAfter_default(callback, that) {
    var node = this, nodes = [node], next = [], children4, i2, n2, index4 = -1;
    while (node = nodes.pop()) {
      next.push(node);
      if (children4 = node.children) {
        for (i2 = 0, n2 = children4.length; i2 < n2; ++i2) {
          nodes.push(children4[i2]);
        }
      }
    }
    while (node = next.pop()) {
      callback.call(that, node, ++index4, this);
    }
    return this;
  }

  // node_modules/d3-hierarchy/src/hierarchy/find.js
  function find_default2(callback, that) {
    let index4 = -1;
    for (const node of this) {
      if (callback.call(that, node, ++index4, this)) {
        return node;
      }
    }
  }

  // node_modules/d3-hierarchy/src/hierarchy/sum.js
  function sum_default(value3) {
    return this.eachAfter(function(node) {
      var sum3 = +value3(node.data) || 0, children4 = node.children, i2 = children4 && children4.length;
      while (--i2 >= 0) sum3 += children4[i2].value;
      node.value = sum3;
    });
  }

  // node_modules/d3-hierarchy/src/hierarchy/sort.js
  function sort_default(compare4) {
    return this.eachBefore(function(node) {
      if (node.children) {
        node.children.sort(compare4);
      }
    });
  }

  // node_modules/d3-hierarchy/src/hierarchy/path.js
  function path_default2(end) {
    var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
    while (start !== ancestor) {
      start = start.parent;
      nodes.push(start);
    }
    var k2 = nodes.length;
    while (end !== ancestor) {
      nodes.splice(k2, 0, end);
      end = end.parent;
    }
    return nodes;
  }
  function leastCommonAncestor(a4, b3) {
    if (a4 === b3) return a4;
    var aNodes = a4.ancestors(), bNodes = b3.ancestors(), c4 = null;
    a4 = aNodes.pop();
    b3 = bNodes.pop();
    while (a4 === b3) {
      c4 = a4;
      a4 = aNodes.pop();
      b3 = bNodes.pop();
    }
    return c4;
  }

  // node_modules/d3-hierarchy/src/hierarchy/ancestors.js
  function ancestors_default() {
    var node = this, nodes = [node];
    while (node = node.parent) {
      nodes.push(node);
    }
    return nodes;
  }

  // node_modules/d3-hierarchy/src/hierarchy/descendants.js
  function descendants_default() {
    return Array.from(this);
  }

  // node_modules/d3-hierarchy/src/hierarchy/leaves.js
  function leaves_default() {
    var leaves = [];
    this.eachBefore(function(node) {
      if (!node.children) {
        leaves.push(node);
      }
    });
    return leaves;
  }

  // node_modules/d3-hierarchy/src/hierarchy/links.js
  function links_default() {
    var root = this, links = [];
    root.each(function(node) {
      if (node !== root) {
        links.push({ source: node.parent, target: node });
      }
    });
    return links;
  }

  // node_modules/d3-hierarchy/src/hierarchy/iterator.js
  function* iterator_default() {
    var node = this, current2, next = [node], children4, i2, n2;
    do {
      current2 = next.reverse(), next = [];
      while (node = current2.pop()) {
        yield node;
        if (children4 = node.children) {
          for (i2 = 0, n2 = children4.length; i2 < n2; ++i2) {
            next.push(children4[i2]);
          }
        }
      }
    } while (next.length);
  }

  // node_modules/d3-hierarchy/src/hierarchy/index.js
  function hierarchy(data3, children4) {
    if (data3 instanceof Map) {
      data3 = [void 0, data3];
      if (children4 === void 0) children4 = mapChildren;
    } else if (children4 === void 0) {
      children4 = objectChildren;
    }
    var root = new Node(data3), node, nodes = [root], child, childs, i2, n2;
    while (node = nodes.pop()) {
      if ((childs = children4(node.data)) && (n2 = (childs = Array.from(childs)).length)) {
        node.children = childs;
        for (i2 = n2 - 1; i2 >= 0; --i2) {
          nodes.push(child = childs[i2] = new Node(childs[i2]));
          child.parent = node;
          child.depth = node.depth + 1;
        }
      }
    }
    return root.eachBefore(computeHeight);
  }
  function node_copy() {
    return hierarchy(this).eachBefore(copyData);
  }
  function objectChildren(d2) {
    return d2.children;
  }
  function mapChildren(d2) {
    return Array.isArray(d2) ? d2[1] : null;
  }
  function copyData(node) {
    if (node.data.value !== void 0) node.value = node.data.value;
    node.data = node.data.data;
  }
  function computeHeight(node) {
    var height2 = 0;
    do
      node.height = height2;
    while ((node = node.parent) && node.height < ++height2);
  }
  function Node(data3) {
    this.data = data3;
    this.depth = this.height = 0;
    this.parent = null;
  }
  Node.prototype = hierarchy.prototype = {
    constructor: Node,
    count: count_default,
    each: each_default,
    eachAfter: eachAfter_default,
    eachBefore: eachBefore_default,
    find: find_default2,
    sum: sum_default,
    sort: sort_default,
    path: path_default2,
    ancestors: ancestors_default,
    descendants: descendants_default,
    leaves: leaves_default,
    links: links_default,
    copy: node_copy,
    [Symbol.iterator]: iterator_default
  };

  // node_modules/d3-hierarchy/src/accessors.js
  function optional(f2) {
    return f2 == null ? null : required(f2);
  }
  function required(f2) {
    if (typeof f2 !== "function") throw new Error();
    return f2;
  }

  // node_modules/d3-hierarchy/src/constant.js
  function constantZero() {
    return 0;
  }
  function constant_default4(x5) {
    return function() {
      return x5;
    };
  }

  // node_modules/d3-hierarchy/src/lcg.js
  var a2 = 1664525;
  var c2 = 1013904223;
  var m2 = 4294967296;
  function lcg_default2() {
    let s2 = 1;
    return () => (s2 = (a2 * s2 + c2) % m2) / m2;
  }

  // node_modules/d3-hierarchy/src/array.js
  function array_default3(x5) {
    return typeof x5 === "object" && "length" in x5 ? x5 : Array.from(x5);
  }
  function shuffle(array4, random2) {
    let m4 = array4.length, t4, i2;
    while (m4) {
      i2 = random2() * m4-- | 0;
      t4 = array4[m4];
      array4[m4] = array4[i2];
      array4[i2] = t4;
    }
    return array4;
  }

  // node_modules/d3-hierarchy/src/pack/enclose.js
  function packEncloseRandom(circles, random2) {
    var i2 = 0, n2 = (circles = shuffle(Array.from(circles), random2)).length, B3 = [], p2, e4;
    while (i2 < n2) {
      p2 = circles[i2];
      if (e4 && enclosesWeak(e4, p2)) ++i2;
      else e4 = encloseBasis(B3 = extendBasis(B3, p2)), i2 = 0;
    }
    return e4;
  }
  function extendBasis(B3, p2) {
    var i2, j2;
    if (enclosesWeakAll(p2, B3)) return [p2];
    for (i2 = 0; i2 < B3.length; ++i2) {
      if (enclosesNot(p2, B3[i2]) && enclosesWeakAll(encloseBasis2(B3[i2], p2), B3)) {
        return [B3[i2], p2];
      }
    }
    for (i2 = 0; i2 < B3.length - 1; ++i2) {
      for (j2 = i2 + 1; j2 < B3.length; ++j2) {
        if (enclosesNot(encloseBasis2(B3[i2], B3[j2]), p2) && enclosesNot(encloseBasis2(B3[i2], p2), B3[j2]) && enclosesNot(encloseBasis2(B3[j2], p2), B3[i2]) && enclosesWeakAll(encloseBasis3(B3[i2], B3[j2], p2), B3)) {
          return [B3[i2], B3[j2], p2];
        }
      }
    }
    throw new Error();
  }
  function enclosesNot(a4, b3) {
    var dr = a4.r - b3.r, dx = b3.x - a4.x, dy = b3.y - a4.y;
    return dr < 0 || dr * dr < dx * dx + dy * dy;
  }
  function enclosesWeak(a4, b3) {
    var dr = a4.r - b3.r + Math.max(a4.r, b3.r, 1) * 1e-9, dx = b3.x - a4.x, dy = b3.y - a4.y;
    return dr > 0 && dr * dr > dx * dx + dy * dy;
  }
  function enclosesWeakAll(a4, B3) {
    for (var i2 = 0; i2 < B3.length; ++i2) {
      if (!enclosesWeak(a4, B3[i2])) {
        return false;
      }
    }
    return true;
  }
  function encloseBasis(B3) {
    switch (B3.length) {
      case 1:
        return encloseBasis1(B3[0]);
      case 2:
        return encloseBasis2(B3[0], B3[1]);
      case 3:
        return encloseBasis3(B3[0], B3[1], B3[2]);
    }
  }
  function encloseBasis1(a4) {
    return {
      x: a4.x,
      y: a4.y,
      r: a4.r
    };
  }
  function encloseBasis2(a4, b3) {
    var x12 = a4.x, y12 = a4.y, r1 = a4.r, x22 = b3.x, y22 = b3.y, r2 = b3.r, x21 = x22 - x12, y21 = y22 - y12, r21 = r2 - r1, l2 = Math.sqrt(x21 * x21 + y21 * y21);
    return {
      x: (x12 + x22 + x21 / l2 * r21) / 2,
      y: (y12 + y22 + y21 / l2 * r21) / 2,
      r: (l2 + r1 + r2) / 2
    };
  }
  function encloseBasis3(a4, b3, c4) {
    var x12 = a4.x, y12 = a4.y, r1 = a4.r, x22 = b3.x, y22 = b3.y, r2 = b3.r, x32 = c4.x, y32 = c4.y, r3 = c4.r, a22 = x12 - x22, a32 = x12 - x32, b22 = y12 - y22, b32 = y12 - y32, c22 = r2 - r1, c32 = r3 - r1, d1 = x12 * x12 + y12 * y12 - r1 * r1, d2 = d1 - x22 * x22 - y22 * y22 + r2 * r2, d3 = d1 - x32 * x32 - y32 * y32 + r3 * r3, ab4 = a32 * b22 - a22 * b32, xa = (b22 * d3 - b32 * d2) / (ab4 * 2) - x12, xb = (b32 * c22 - b22 * c32) / ab4, ya = (a32 * d2 - a22 * d3) / (ab4 * 2) - y12, yb = (a22 * c32 - a32 * c22) / ab4, A5 = xb * xb + yb * yb - 1, B3 = 2 * (r1 + xa * xb + ya * yb), C3 = xa * xa + ya * ya - r1 * r1, r4 = -(Math.abs(A5) > 1e-6 ? (B3 + Math.sqrt(B3 * B3 - 4 * A5 * C3)) / (2 * A5) : C3 / B3);
    return {
      x: x12 + xa + xb * r4,
      y: y12 + ya + yb * r4,
      r: r4
    };
  }

  // node_modules/d3-hierarchy/src/pack/siblings.js
  function place(b3, a4, c4) {
    var dx = b3.x - a4.x, x5, a22, dy = b3.y - a4.y, y5, b22, d2 = dx * dx + dy * dy;
    if (d2) {
      a22 = a4.r + c4.r, a22 *= a22;
      b22 = b3.r + c4.r, b22 *= b22;
      if (a22 > b22) {
        x5 = (d2 + b22 - a22) / (2 * d2);
        y5 = Math.sqrt(Math.max(0, b22 / d2 - x5 * x5));
        c4.x = b3.x - x5 * dx - y5 * dy;
        c4.y = b3.y - x5 * dy + y5 * dx;
      } else {
        x5 = (d2 + a22 - b22) / (2 * d2);
        y5 = Math.sqrt(Math.max(0, a22 / d2 - x5 * x5));
        c4.x = a4.x + x5 * dx - y5 * dy;
        c4.y = a4.y + x5 * dy + y5 * dx;
      }
    } else {
      c4.x = a4.x + c4.r;
      c4.y = a4.y;
    }
  }
  function intersects(a4, b3) {
    var dr = a4.r + b3.r - 1e-6, dx = b3.x - a4.x, dy = b3.y - a4.y;
    return dr > 0 && dr * dr > dx * dx + dy * dy;
  }
  function score(node) {
    var a4 = node._, b3 = node.next._, ab4 = a4.r + b3.r, dx = (a4.x * b3.r + b3.x * a4.r) / ab4, dy = (a4.y * b3.r + b3.y * a4.r) / ab4;
    return dx * dx + dy * dy;
  }
  function Node2(circle2) {
    this._ = circle2;
    this.next = null;
    this.previous = null;
  }
  function packSiblingsRandom(circles, random2) {
    if (!(n2 = (circles = array_default3(circles)).length)) return 0;
    var a4, b3, c4, n2, aa2, ca3, i2, j2, k2, sj, sk;
    a4 = circles[0], a4.x = 0, a4.y = 0;
    if (!(n2 > 1)) return a4.r;
    b3 = circles[1], a4.x = -b3.r, b3.x = a4.r, b3.y = 0;
    if (!(n2 > 2)) return a4.r + b3.r;
    place(b3, a4, c4 = circles[2]);
    a4 = new Node2(a4), b3 = new Node2(b3), c4 = new Node2(c4);
    a4.next = c4.previous = b3;
    b3.next = a4.previous = c4;
    c4.next = b3.previous = a4;
    pack: for (i2 = 3; i2 < n2; ++i2) {
      place(a4._, b3._, c4 = circles[i2]), c4 = new Node2(c4);
      j2 = b3.next, k2 = a4.previous, sj = b3._.r, sk = a4._.r;
      do {
        if (sj <= sk) {
          if (intersects(j2._, c4._)) {
            b3 = j2, a4.next = b3, b3.previous = a4, --i2;
            continue pack;
          }
          sj += j2._.r, j2 = j2.next;
        } else {
          if (intersects(k2._, c4._)) {
            a4 = k2, a4.next = b3, b3.previous = a4, --i2;
            continue pack;
          }
          sk += k2._.r, k2 = k2.previous;
        }
      } while (j2 !== k2.next);
      c4.previous = a4, c4.next = b3, a4.next = b3.previous = b3 = c4;
      aa2 = score(a4);
      while ((c4 = c4.next) !== b3) {
        if ((ca3 = score(c4)) < aa2) {
          a4 = c4, aa2 = ca3;
        }
      }
      b3 = a4.next;
    }
    a4 = [b3._], c4 = b3;
    while ((c4 = c4.next) !== b3) a4.push(c4._);
    c4 = packEncloseRandom(a4, random2);
    for (i2 = 0; i2 < n2; ++i2) a4 = circles[i2], a4.x -= c4.x, a4.y -= c4.y;
    return c4.r;
  }

  // node_modules/d3-hierarchy/src/pack/index.js
  function defaultRadius(d2) {
    return Math.sqrt(d2.value);
  }
  function pack_default() {
    var radius2 = null, dx = 1, dy = 1, padding3 = constantZero;
    function pack(root) {
      const random2 = lcg_default2();
      root.x = dx / 2, root.y = dy / 2;
      if (radius2) {
        root.eachBefore(radiusLeaf(radius2)).eachAfter(packChildrenRandom(padding3, 0.5, random2)).eachBefore(translateChild(1));
      } else {
        root.eachBefore(radiusLeaf(defaultRadius)).eachAfter(packChildrenRandom(constantZero, 1, random2)).eachAfter(packChildrenRandom(padding3, root.r / Math.min(dx, dy), random2)).eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r)));
      }
      return root;
    }
    pack.radius = function(x5) {
      return arguments.length ? (radius2 = optional(x5), pack) : radius2;
    };
    pack.size = function(x5) {
      return arguments.length ? (dx = +x5[0], dy = +x5[1], pack) : [dx, dy];
    };
    pack.padding = function(x5) {
      return arguments.length ? (padding3 = typeof x5 === "function" ? x5 : constant_default4(+x5), pack) : padding3;
    };
    return pack;
  }
  function radiusLeaf(radius2) {
    return function(node) {
      if (!node.children) {
        node.r = Math.max(0, +radius2(node) || 0);
      }
    };
  }
  function packChildrenRandom(padding3, k2, random2) {
    return function(node) {
      if (children4 = node.children) {
        var children4, i2, n2 = children4.length, r2 = padding3(node) * k2 || 0, e4;
        if (r2) for (i2 = 0; i2 < n2; ++i2) children4[i2].r += r2;
        e4 = packSiblingsRandom(children4, random2);
        if (r2) for (i2 = 0; i2 < n2; ++i2) children4[i2].r -= r2;
        node.r = e4 + r2;
      }
    };
  }
  function translateChild(k2) {
    return function(node) {
      var parent = node.parent;
      node.r *= k2;
      if (parent) {
        node.x = parent.x + k2 * node.x;
        node.y = parent.y + k2 * node.y;
      }
    };
  }

  // node_modules/d3-hierarchy/src/treemap/round.js
  function round_default2(node) {
    node.x0 = Math.round(node.x0);
    node.y0 = Math.round(node.y0);
    node.x1 = Math.round(node.x1);
    node.y1 = Math.round(node.y1);
  }

  // node_modules/d3-hierarchy/src/treemap/dice.js
  function dice_default(parent, x06, y06, x12, y12) {
    var nodes = parent.children, node, i2 = -1, n2 = nodes.length, k2 = parent.value && (x12 - x06) / parent.value;
    while (++i2 < n2) {
      node = nodes[i2], node.y0 = y06, node.y1 = y12;
      node.x0 = x06, node.x1 = x06 += node.value * k2;
    }
  }

  // node_modules/d3-hierarchy/src/partition.js
  function partition_default() {
    var dx = 1, dy = 1, padding3 = 0, round = false;
    function partition6(root) {
      var n2 = root.height + 1;
      root.x0 = root.y0 = padding3;
      root.x1 = dx;
      root.y1 = dy / n2;
      root.eachBefore(positionNode(dy, n2));
      if (round) root.eachBefore(round_default2);
      return root;
    }
    function positionNode(dy2, n2) {
      return function(node) {
        if (node.children) {
          dice_default(node, node.x0, dy2 * (node.depth + 1) / n2, node.x1, dy2 * (node.depth + 2) / n2);
        }
        var x06 = node.x0, y06 = node.y0, x12 = node.x1 - padding3, y12 = node.y1 - padding3;
        if (x12 < x06) x06 = x12 = (x06 + x12) / 2;
        if (y12 < y06) y06 = y12 = (y06 + y12) / 2;
        node.x0 = x06;
        node.y0 = y06;
        node.x1 = x12;
        node.y1 = y12;
      };
    }
    partition6.round = function(x5) {
      return arguments.length ? (round = !!x5, partition6) : round;
    };
    partition6.size = function(x5) {
      return arguments.length ? (dx = +x5[0], dy = +x5[1], partition6) : [dx, dy];
    };
    partition6.padding = function(x5) {
      return arguments.length ? (padding3 = +x5, partition6) : padding3;
    };
    return partition6;
  }

  // node_modules/d3-hierarchy/src/stratify.js
  var preroot = { depth: -1 };
  var ambiguous = {};
  var imputed = {};
  function defaultId(d2) {
    return d2.id;
  }
  function defaultParentId(d2) {
    return d2.parentId;
  }
  function stratify_default() {
    var id2 = defaultId, parentId = defaultParentId, path3;
    function stratify(data3) {
      var nodes = Array.from(data3), currentId = id2, currentParentId = parentId, n2, d2, i2, root, parent, node, nodeId, nodeKey, nodeByKey = /* @__PURE__ */ new Map();
      if (path3 != null) {
        const I = nodes.map((d3, i3) => normalize2(path3(d3, i3, data3)));
        const P = I.map(parentof);
        const S = new Set(I).add("");
        for (const i3 of P) {
          if (!S.has(i3)) {
            S.add(i3);
            I.push(i3);
            P.push(parentof(i3));
            nodes.push(imputed);
          }
        }
        currentId = (_, i3) => I[i3];
        currentParentId = (_, i3) => P[i3];
      }
      for (i2 = 0, n2 = nodes.length; i2 < n2; ++i2) {
        d2 = nodes[i2], node = nodes[i2] = new Node(d2);
        if ((nodeId = currentId(d2, i2, data3)) != null && (nodeId += "")) {
          nodeKey = node.id = nodeId;
          nodeByKey.set(nodeKey, nodeByKey.has(nodeKey) ? ambiguous : node);
        }
        if ((nodeId = currentParentId(d2, i2, data3)) != null && (nodeId += "")) {
          node.parent = nodeId;
        }
      }
      for (i2 = 0; i2 < n2; ++i2) {
        node = nodes[i2];
        if (nodeId = node.parent) {
          parent = nodeByKey.get(nodeId);
          if (!parent) throw new Error("missing: " + nodeId);
          if (parent === ambiguous) throw new Error("ambiguous: " + nodeId);
          if (parent.children) parent.children.push(node);
          else parent.children = [node];
          node.parent = parent;
        } else {
          if (root) throw new Error("multiple roots");
          root = node;
        }
      }
      if (!root) throw new Error("no root");
      if (path3 != null) {
        while (root.data === imputed && root.children.length === 1) {
          root = root.children[0], --n2;
        }
        for (let i3 = nodes.length - 1; i3 >= 0; --i3) {
          node = nodes[i3];
          if (node.data !== imputed) break;
          node.data = null;
        }
      }
      root.parent = preroot;
      root.eachBefore(function(node2) {
        node2.depth = node2.parent.depth + 1;
        --n2;
      }).eachBefore(computeHeight);
      root.parent = null;
      if (n2 > 0) throw new Error("cycle");
      return root;
    }
    stratify.id = function(x5) {
      return arguments.length ? (id2 = optional(x5), stratify) : id2;
    };
    stratify.parentId = function(x5) {
      return arguments.length ? (parentId = optional(x5), stratify) : parentId;
    };
    stratify.path = function(x5) {
      return arguments.length ? (path3 = optional(x5), stratify) : path3;
    };
    return stratify;
  }
  function normalize2(path3) {
    path3 = `${path3}`;
    let i2 = path3.length;
    if (slash(path3, i2 - 1) && !slash(path3, i2 - 2)) path3 = path3.slice(0, -1);
    return path3[0] === "/" ? path3 : `/${path3}`;
  }
  function parentof(path3) {
    let i2 = path3.length;
    if (i2 < 2) return "";
    while (--i2 > 1) if (slash(path3, i2)) break;
    return path3.slice(0, i2);
  }
  function slash(path3, i2) {
    if (path3[i2] === "/") {
      let k2 = 0;
      while (i2 > 0 && path3[--i2] === "\\") ++k2;
      if ((k2 & 1) === 0) return true;
    }
    return false;
  }

  // node_modules/d3-hierarchy/src/tree.js
  function defaultSeparation2(a4, b3) {
    return a4.parent === b3.parent ? 1 : 2;
  }
  function nextLeft(v3) {
    var children4 = v3.children;
    return children4 ? children4[0] : v3.t;
  }
  function nextRight(v3) {
    var children4 = v3.children;
    return children4 ? children4[children4.length - 1] : v3.t;
  }
  function moveSubtree(wm, wp, shift) {
    var change2 = shift / (wp.i - wm.i);
    wp.c -= change2;
    wp.s += shift;
    wm.c += change2;
    wp.z += shift;
    wp.m += shift;
  }
  function executeShifts(v3) {
    var shift = 0, change2 = 0, children4 = v3.children, i2 = children4.length, w3;
    while (--i2 >= 0) {
      w3 = children4[i2];
      w3.z += shift;
      w3.m += shift;
      shift += w3.s + (change2 += w3.c);
    }
  }
  function nextAncestor(vim, v3, ancestor) {
    return vim.a.parent === v3.parent ? vim.a : ancestor;
  }
  function TreeNode(node, i2) {
    this._ = node;
    this.parent = null;
    this.children = null;
    this.A = null;
    this.a = this;
    this.z = 0;
    this.m = 0;
    this.c = 0;
    this.s = 0;
    this.t = null;
    this.i = i2;
  }
  TreeNode.prototype = Object.create(Node.prototype);
  function treeRoot(root) {
    var tree = new TreeNode(root, 0), node, nodes = [tree], child, children4, i2, n2;
    while (node = nodes.pop()) {
      if (children4 = node._.children) {
        node.children = new Array(n2 = children4.length);
        for (i2 = n2 - 1; i2 >= 0; --i2) {
          nodes.push(child = node.children[i2] = new TreeNode(children4[i2], i2));
          child.parent = node;
        }
      }
    }
    (tree.parent = new TreeNode(null, 0)).children = [tree];
    return tree;
  }
  function tree_default() {
    var separation = defaultSeparation2, dx = 1, dy = 1, nodeSize = null;
    function tree(root) {
      var t4 = treeRoot(root);
      t4.eachAfter(firstWalk), t4.parent.m = -t4.z;
      t4.eachBefore(secondWalk);
      if (nodeSize) root.eachBefore(sizeNode);
      else {
        var left = root, right = root, bottom = root;
        root.eachBefore(function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var s2 = left === right ? 1 : separation(left, right) / 2, tx = s2 - left.x, kx = dx / (right.x + s2 + tx), ky = dy / (bottom.depth || 1);
        root.eachBefore(function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }
      return root;
    }
    function firstWalk(v3) {
      var children4 = v3.children, siblings = v3.parent.children, w3 = v3.i ? siblings[v3.i - 1] : null;
      if (children4) {
        executeShifts(v3);
        var midpoint = (children4[0].z + children4[children4.length - 1].z) / 2;
        if (w3) {
          v3.z = w3.z + separation(v3._, w3._);
          v3.m = v3.z - midpoint;
        } else {
          v3.z = midpoint;
        }
      } else if (w3) {
        v3.z = w3.z + separation(v3._, w3._);
      }
      v3.parent.A = apportion(v3, w3, v3.parent.A || siblings[0]);
    }
    function secondWalk(v3) {
      v3._.x = v3.z + v3.parent.m;
      v3.m += v3.parent.m;
    }
    function apportion(v3, w3, ancestor) {
      if (w3) {
        var vip = v3, vop = v3, vim = w3, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
        while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
          vom = nextLeft(vom);
          vop = nextRight(vop);
          vop.a = v3;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            moveSubtree(nextAncestor(vim, v3, ancestor), v3, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !nextRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !nextLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v3;
        }
      }
      return ancestor;
    }
    function sizeNode(node) {
      node.x *= dx;
      node.y = node.depth * dy;
    }
    tree.separation = function(x5) {
      return arguments.length ? (separation = x5, tree) : separation;
    };
    tree.size = function(x5) {
      return arguments.length ? (nodeSize = false, dx = +x5[0], dy = +x5[1], tree) : nodeSize ? null : [dx, dy];
    };
    tree.nodeSize = function(x5) {
      return arguments.length ? (nodeSize = true, dx = +x5[0], dy = +x5[1], tree) : nodeSize ? [dx, dy] : null;
    };
    return tree;
  }

  // node_modules/d3-hierarchy/src/treemap/slice.js
  function slice_default(parent, x06, y06, x12, y12) {
    var nodes = parent.children, node, i2 = -1, n2 = nodes.length, k2 = parent.value && (y12 - y06) / parent.value;
    while (++i2 < n2) {
      node = nodes[i2], node.x0 = x06, node.x1 = x12;
      node.y0 = y06, node.y1 = y06 += node.value * k2;
    }
  }

  // node_modules/d3-hierarchy/src/treemap/squarify.js
  var phi = (1 + Math.sqrt(5)) / 2;
  function squarifyRatio(ratio, parent, x06, y06, x12, y12) {
    var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n2 = nodes.length, dx, dy, value3 = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
    while (i0 < n2) {
      dx = x12 - x06, dy = y12 - y06;
      do
        sumValue = nodes[i1++].value;
      while (!sumValue && i1 < n2);
      minValue = maxValue = sumValue;
      alpha = Math.max(dy / dx, dx / dy) / (value3 * ratio);
      beta = sumValue * sumValue * alpha;
      minRatio = Math.max(maxValue / beta, beta / minValue);
      for (; i1 < n2; ++i1) {
        sumValue += nodeValue = nodes[i1].value;
        if (nodeValue < minValue) minValue = nodeValue;
        if (nodeValue > maxValue) maxValue = nodeValue;
        beta = sumValue * sumValue * alpha;
        newRatio = Math.max(maxValue / beta, beta / minValue);
        if (newRatio > minRatio) {
          sumValue -= nodeValue;
          break;
        }
        minRatio = newRatio;
      }
      rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
      if (row.dice) dice_default(row, x06, y06, x12, value3 ? y06 += dy * sumValue / value3 : y12);
      else slice_default(row, x06, y06, value3 ? x06 += dx * sumValue / value3 : x12, y12);
      value3 -= sumValue, i0 = i1;
    }
    return rows;
  }
  var squarify_default = function custom9(ratio) {
    function squarify(parent, x06, y06, x12, y12) {
      squarifyRatio(ratio, parent, x06, y06, x12, y12);
    }
    squarify.ratio = function(x5) {
      return custom9((x5 = +x5) > 1 ? x5 : 1);
    };
    return squarify;
  }(phi);

  // node_modules/d3-hierarchy/src/treemap/index.js
  function treemap_default() {
    var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner2 = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
    function treemap(root) {
      root.x0 = root.y0 = 0;
      root.x1 = dx;
      root.y1 = dy;
      root.eachBefore(positionNode);
      paddingStack = [0];
      if (round) root.eachBefore(round_default2);
      return root;
    }
    function positionNode(node) {
      var p2 = paddingStack[node.depth], x06 = node.x0 + p2, y06 = node.y0 + p2, x12 = node.x1 - p2, y12 = node.y1 - p2;
      if (x12 < x06) x06 = x12 = (x06 + x12) / 2;
      if (y12 < y06) y06 = y12 = (y06 + y12) / 2;
      node.x0 = x06;
      node.y0 = y06;
      node.x1 = x12;
      node.y1 = y12;
      if (node.children) {
        p2 = paddingStack[node.depth + 1] = paddingInner2(node) / 2;
        x06 += paddingLeft(node) - p2;
        y06 += paddingTop(node) - p2;
        x12 -= paddingRight(node) - p2;
        y12 -= paddingBottom(node) - p2;
        if (x12 < x06) x06 = x12 = (x06 + x12) / 2;
        if (y12 < y06) y06 = y12 = (y06 + y12) / 2;
        tile(node, x06, y06, x12, y12);
      }
    }
    treemap.round = function(x5) {
      return arguments.length ? (round = !!x5, treemap) : round;
    };
    treemap.size = function(x5) {
      return arguments.length ? (dx = +x5[0], dy = +x5[1], treemap) : [dx, dy];
    };
    treemap.tile = function(x5) {
      return arguments.length ? (tile = required(x5), treemap) : tile;
    };
    treemap.padding = function(x5) {
      return arguments.length ? treemap.paddingInner(x5).paddingOuter(x5) : treemap.paddingInner();
    };
    treemap.paddingInner = function(x5) {
      return arguments.length ? (paddingInner2 = typeof x5 === "function" ? x5 : constant_default4(+x5), treemap) : paddingInner2;
    };
    treemap.paddingOuter = function(x5) {
      return arguments.length ? treemap.paddingTop(x5).paddingRight(x5).paddingBottom(x5).paddingLeft(x5) : treemap.paddingTop();
    };
    treemap.paddingTop = function(x5) {
      return arguments.length ? (paddingTop = typeof x5 === "function" ? x5 : constant_default4(+x5), treemap) : paddingTop;
    };
    treemap.paddingRight = function(x5) {
      return arguments.length ? (paddingRight = typeof x5 === "function" ? x5 : constant_default4(+x5), treemap) : paddingRight;
    };
    treemap.paddingBottom = function(x5) {
      return arguments.length ? (paddingBottom = typeof x5 === "function" ? x5 : constant_default4(+x5), treemap) : paddingBottom;
    };
    treemap.paddingLeft = function(x5) {
      return arguments.length ? (paddingLeft = typeof x5 === "function" ? x5 : constant_default4(+x5), treemap) : paddingLeft;
    };
    return treemap;
  }

  // node_modules/d3-hierarchy/src/treemap/binary.js
  function binary_default(parent, x06, y06, x12, y12) {
    var nodes = parent.children, i2, n2 = nodes.length, sum3, sums = new Array(n2 + 1);
    for (sums[0] = sum3 = i2 = 0; i2 < n2; ++i2) {
      sums[i2 + 1] = sum3 += nodes[i2].value;
    }
    partition6(0, n2, parent.value, x06, y06, x12, y12);
    function partition6(i3, j2, value3, x07, y07, x13, y13) {
      if (i3 >= j2 - 1) {
        var node = nodes[i3];
        node.x0 = x07, node.y0 = y07;
        node.x1 = x13, node.y1 = y13;
        return;
      }
      var valueOffset = sums[i3], valueTarget = value3 / 2 + valueOffset, k2 = i3 + 1, hi = j2 - 1;
      while (k2 < hi) {
        var mid = k2 + hi >>> 1;
        if (sums[mid] < valueTarget) k2 = mid + 1;
        else hi = mid;
      }
      if (valueTarget - sums[k2 - 1] < sums[k2] - valueTarget && i3 + 1 < k2) --k2;
      var valueLeft = sums[k2] - valueOffset, valueRight = value3 - valueLeft;
      if (x13 - x07 > y13 - y07) {
        var xk = value3 ? (x07 * valueRight + x13 * valueLeft) / value3 : x13;
        partition6(i3, k2, valueLeft, x07, y07, xk, y13);
        partition6(k2, j2, valueRight, xk, y07, x13, y13);
      } else {
        var yk = value3 ? (y07 * valueRight + y13 * valueLeft) / value3 : y13;
        partition6(i3, k2, valueLeft, x07, y07, x13, yk);
        partition6(k2, j2, valueRight, x07, yk, x13, y13);
      }
    }
  }

  // node_modules/d3-hierarchy/src/treemap/sliceDice.js
  function sliceDice_default(parent, x06, y06, x12, y12) {
    (parent.depth & 1 ? slice_default : dice_default)(parent, x06, y06, x12, y12);
  }

  // node_modules/d3-hierarchy/src/treemap/resquarify.js
  var resquarify_default = function custom10(ratio) {
    function resquarify(parent, x06, y06, x12, y12) {
      if ((rows = parent._squarify) && rows.ratio === ratio) {
        var rows, row, nodes, i2, j2 = -1, n2, m4 = rows.length, value3 = parent.value;
        while (++j2 < m4) {
          row = rows[j2], nodes = row.children;
          for (i2 = row.value = 0, n2 = nodes.length; i2 < n2; ++i2) row.value += nodes[i2].value;
          if (row.dice) dice_default(row, x06, y06, x12, value3 ? y06 += (y12 - y06) * row.value / value3 : y12);
          else slice_default(row, x06, y06, value3 ? x06 += (x12 - x06) * row.value / value3 : x12, y12);
          value3 -= row.value;
        }
      } else {
        parent._squarify = rows = squarifyRatio(ratio, parent, x06, y06, x12, y12);
        rows.ratio = ratio;
      }
    }
    resquarify.ratio = function(x5) {
      return custom10((x5 = +x5) > 1 ? x5 : 1);
    };
    return resquarify;
  }(phi);

  // node_modules/vega-hierarchy/build/vega-hierarchy.module.js
  function lookup3(tree, key2, filter3) {
    const map4 = {};
    tree.each((node) => {
      const t4 = node.data;
      if (filter3(t4)) map4[key2(t4)] = node;
    });
    tree.lookup = map4;
    return tree;
  }
  function Nest(params2) {
    Transform.call(this, null, params2);
  }
  Nest.Definition = {
    "type": "Nest",
    "metadata": {
      "treesource": true,
      "changes": true
    },
    "params": [{
      "name": "keys",
      "type": "field",
      "array": true
    }, {
      "name": "generate",
      "type": "boolean"
    }]
  };
  var children = (n2) => n2.values;
  inherits(Nest, Transform, {
    transform(_, pulse2) {
      if (!pulse2.source) {
        error("Nest transform requires an upstream data source.");
      }
      var gen = _.generate, mod = _.modified(), out = pulse2.clone(), tree = this.value;
      if (!tree || mod || pulse2.changed()) {
        if (tree) {
          tree.each((node) => {
            if (node.children && isTuple(node.data)) {
              out.rem.push(node.data);
            }
          });
        }
        this.value = tree = hierarchy({
          values: array(_.keys).reduce((n2, k2) => {
            n2.key(k2);
            return n2;
          }, nest()).entries(out.source)
        }, children);
        if (gen) {
          tree.each((node) => {
            if (node.children) {
              node = ingest$1(node.data);
              out.add.push(node);
              out.source.push(node);
            }
          });
        }
        lookup3(tree, tupleid, tupleid);
      }
      out.source.root = tree;
      return out;
    }
  });
  function nest() {
    const keys4 = [], nest2 = {
      entries: (array4) => entries3(apply3(array4, 0), 0),
      key: (d2) => (keys4.push(d2), nest2)
    };
    function apply3(array4, depth) {
      if (depth >= keys4.length) {
        return array4;
      }
      const n2 = array4.length, key2 = keys4[depth++], valuesByKey = {}, result = {};
      let i2 = -1, keyValue, value3, values4;
      while (++i2 < n2) {
        keyValue = key2(value3 = array4[i2]) + "";
        if (values4 = valuesByKey[keyValue]) {
          values4.push(value3);
        } else {
          valuesByKey[keyValue] = [value3];
        }
      }
      for (keyValue in valuesByKey) {
        result[keyValue] = apply3(valuesByKey[keyValue], depth);
      }
      return result;
    }
    function entries3(map4, depth) {
      if (++depth > keys4.length) return map4;
      const array4 = [];
      for (const key2 in map4) {
        array4.push({
          key: key2,
          values: entries3(map4[key2], depth)
        });
      }
      return array4;
    }
    return nest2;
  }
  function HierarchyLayout(params2) {
    Transform.call(this, null, params2);
  }
  var defaultSeparation3 = (a4, b3) => a4.parent === b3.parent ? 1 : 2;
  inherits(HierarchyLayout, Transform, {
    transform(_, pulse2) {
      if (!pulse2.source || !pulse2.source.root) {
        error(this.constructor.name + " transform requires a backing tree data source.");
      }
      const layout = this.layout(_.method), fields = this.fields, root = pulse2.source.root, as = _.as || fields;
      if (_.field) root.sum(_.field);
      else root.count();
      if (_.sort) root.sort(stableCompare(_.sort, (d2) => d2.data));
      setParams(layout, this.params, _);
      if (layout.separation) {
        layout.separation(_.separation !== false ? defaultSeparation3 : one);
      }
      try {
        this.value = layout(root);
      } catch (err) {
        error(err);
      }
      root.each((node) => setFields(node, fields, as));
      return pulse2.reflow(_.modified()).modifies(as).modifies("leaf");
    }
  });
  function setParams(layout, params2, _) {
    for (let p2, i2 = 0, n2 = params2.length; i2 < n2; ++i2) {
      p2 = params2[i2];
      if (p2 in _) layout[p2](_[p2]);
    }
  }
  function setFields(node, fields, as) {
    const t4 = node.data, n2 = fields.length - 1;
    for (let i2 = 0; i2 < n2; ++i2) {
      t4[as[i2]] = node[fields[i2]];
    }
    t4[as[n2]] = node.children ? node.children.length : 0;
  }
  var Output$3 = ["x", "y", "r", "depth", "children"];
  function Pack(params2) {
    HierarchyLayout.call(this, params2);
  }
  Pack.Definition = {
    "type": "Pack",
    "metadata": {
      "tree": true,
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "sort",
      "type": "compare"
    }, {
      "name": "padding",
      "type": "number",
      "default": 0
    }, {
      "name": "radius",
      "type": "field",
      "default": null
    }, {
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": Output$3.length,
      "default": Output$3
    }]
  };
  inherits(Pack, HierarchyLayout, {
    layout: pack_default,
    params: ["radius", "size", "padding"],
    fields: Output$3
  });
  var Output$2 = ["x0", "y0", "x1", "y1", "depth", "children"];
  function Partition(params2) {
    HierarchyLayout.call(this, params2);
  }
  Partition.Definition = {
    "type": "Partition",
    "metadata": {
      "tree": true,
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "sort",
      "type": "compare"
    }, {
      "name": "padding",
      "type": "number",
      "default": 0
    }, {
      "name": "round",
      "type": "boolean",
      "default": false
    }, {
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": Output$2.length,
      "default": Output$2
    }]
  };
  inherits(Partition, HierarchyLayout, {
    layout: partition_default,
    params: ["size", "round", "padding"],
    fields: Output$2
  });
  function Stratify(params2) {
    Transform.call(this, null, params2);
  }
  Stratify.Definition = {
    "type": "Stratify",
    "metadata": {
      "treesource": true
    },
    "params": [{
      "name": "key",
      "type": "field",
      "required": true
    }, {
      "name": "parentKey",
      "type": "field",
      "required": true
    }]
  };
  inherits(Stratify, Transform, {
    transform(_, pulse2) {
      if (!pulse2.source) {
        error("Stratify transform requires an upstream data source.");
      }
      let tree = this.value;
      const mod = _.modified(), out = pulse2.fork(pulse2.ALL).materialize(pulse2.SOURCE), run2 = !tree || mod || pulse2.changed(pulse2.ADD_REM) || pulse2.modified(_.key.fields) || pulse2.modified(_.parentKey.fields);
      out.source = out.source.slice();
      if (run2) {
        tree = out.source.length ? lookup3(stratify_default().id(_.key).parentId(_.parentKey)(out.source), _.key, truthy) : lookup3(stratify_default()([{}]), _.key, _.key);
      }
      out.source.root = this.value = tree;
      return out;
    }
  });
  var Layouts = {
    tidy: tree_default,
    cluster: cluster_default
  };
  var Output$1 = ["x", "y", "depth", "children"];
  function Tree(params2) {
    HierarchyLayout.call(this, params2);
  }
  Tree.Definition = {
    "type": "Tree",
    "metadata": {
      "tree": true,
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "sort",
      "type": "compare"
    }, {
      "name": "method",
      "type": "enum",
      "default": "tidy",
      "values": ["tidy", "cluster"]
    }, {
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "nodeSize",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "separation",
      "type": "boolean",
      "default": true
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": Output$1.length,
      "default": Output$1
    }]
  };
  inherits(Tree, HierarchyLayout, {
    /**
     * Tree layout generator. Supports both 'tidy' and 'cluster' layouts.
     */
    layout(method2) {
      const m4 = method2 || "tidy";
      if (has(Layouts, m4)) return Layouts[m4]();
      else error("Unrecognized Tree layout method: " + m4);
    },
    params: ["size", "nodeSize"],
    fields: Output$1
  });
  function TreeLinks(params2) {
    Transform.call(this, [], params2);
  }
  TreeLinks.Definition = {
    "type": "TreeLinks",
    "metadata": {
      "tree": true,
      "generates": true,
      "changes": true
    },
    "params": []
  };
  inherits(TreeLinks, Transform, {
    transform(_, pulse2) {
      const links = this.value, tree = pulse2.source && pulse2.source.root, out = pulse2.fork(pulse2.NO_SOURCE), lut = {};
      if (!tree) error("TreeLinks transform requires a tree data source.");
      if (pulse2.changed(pulse2.ADD_REM)) {
        out.rem = links;
        pulse2.visit(pulse2.SOURCE, (t4) => lut[tupleid(t4)] = 1);
        tree.each((node) => {
          const t4 = node.data, p2 = node.parent && node.parent.data;
          if (p2 && lut[tupleid(t4)] && lut[tupleid(p2)]) {
            out.add.push(ingest$1({
              source: p2,
              target: t4
            }));
          }
        });
        this.value = out.add;
      } else if (pulse2.changed(pulse2.MOD)) {
        pulse2.visit(pulse2.MOD, (t4) => lut[tupleid(t4)] = 1);
        links.forEach((link2) => {
          if (lut[tupleid(link2.source)] || lut[tupleid(link2.target)]) {
            out.mod.push(link2);
          }
        });
      }
      return out;
    }
  });
  var Tiles = {
    binary: binary_default,
    dice: dice_default,
    slice: slice_default,
    slicedice: sliceDice_default,
    squarify: squarify_default,
    resquarify: resquarify_default
  };
  var Output2 = ["x0", "y0", "x1", "y1", "depth", "children"];
  function Treemap(params2) {
    HierarchyLayout.call(this, params2);
  }
  Treemap.Definition = {
    "type": "Treemap",
    "metadata": {
      "tree": true,
      "modifies": true
    },
    "params": [{
      "name": "field",
      "type": "field"
    }, {
      "name": "sort",
      "type": "compare"
    }, {
      "name": "method",
      "type": "enum",
      "default": "squarify",
      "values": ["squarify", "resquarify", "binary", "dice", "slice", "slicedice"]
    }, {
      "name": "padding",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingInner",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingOuter",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingTop",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingRight",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingBottom",
      "type": "number",
      "default": 0
    }, {
      "name": "paddingLeft",
      "type": "number",
      "default": 0
    }, {
      "name": "ratio",
      "type": "number",
      "default": 1.618033988749895
    }, {
      "name": "round",
      "type": "boolean",
      "default": false
    }, {
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": Output2.length,
      "default": Output2
    }]
  };
  inherits(Treemap, HierarchyLayout, {
    /**
     * Treemap layout generator. Adds 'method' and 'ratio' parameters
     * to configure the underlying tile method.
     */
    layout() {
      const x5 = treemap_default();
      x5.ratio = (_) => {
        const t4 = x5.tile();
        if (t4.ratio) x5.tile(t4.ratio(_));
      };
      x5.method = (_) => {
        if (has(Tiles, _)) x5.tile(Tiles[_]);
        else error("Unrecognized Treemap layout method: " + _);
      };
      return x5;
    },
    params: ["method", "ratio", "size", "round", "padding", "paddingInner", "paddingOuter", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],
    fields: Output2
  });

  // node_modules/vega-label/build/vega-label.module.js
  var vega_label_module_exports = {};
  __export(vega_label_module_exports, {
    label: () => Label
  });
  var ALPHA_MASK = 4278190080;
  function baseBitmaps($2, data3) {
    const bitmap = $2.bitmap();
    (data3 || []).forEach((d2) => bitmap.set($2(d2.boundary[0]), $2(d2.boundary[3])));
    return [bitmap, void 0];
  }
  function markBitmaps($2, baseMark, avoidMarks, labelInside, isGroupArea) {
    const width2 = $2.width, height2 = $2.height, border = labelInside || isGroupArea, context3 = domCanvas(width2, height2).getContext("2d"), baseMarkContext = domCanvas(width2, height2).getContext("2d"), strokeContext = border && domCanvas(width2, height2).getContext("2d");
    avoidMarks.forEach((items) => draw2(context3, items, false));
    draw2(baseMarkContext, baseMark, false);
    if (border) {
      draw2(strokeContext, baseMark, true);
    }
    const buffer = getBuffer(context3, width2, height2), baseMarkBuffer = getBuffer(baseMarkContext, width2, height2), strokeBuffer = border && getBuffer(strokeContext, width2, height2), layer1 = $2.bitmap(), layer2 = border && $2.bitmap();
    let x5, y5, u5, v3, index4, alpha, strokeAlpha, baseMarkAlpha;
    for (y5 = 0; y5 < height2; ++y5) {
      for (x5 = 0; x5 < width2; ++x5) {
        index4 = y5 * width2 + x5;
        alpha = buffer[index4] & ALPHA_MASK;
        baseMarkAlpha = baseMarkBuffer[index4] & ALPHA_MASK;
        strokeAlpha = border && strokeBuffer[index4] & ALPHA_MASK;
        if (alpha || strokeAlpha || baseMarkAlpha) {
          u5 = $2(x5);
          v3 = $2(y5);
          if (!isGroupArea && (alpha || baseMarkAlpha)) layer1.set(u5, v3);
          if (border && (alpha || strokeAlpha)) layer2.set(u5, v3);
        }
      }
    }
    return [layer1, layer2];
  }
  function getBuffer(context3, width2, height2) {
    return new Uint32Array(context3.getImageData(0, 0, width2, height2).data.buffer);
  }
  function draw2(context3, items, interior) {
    if (!items.length) return;
    const type3 = items[0].mark.marktype;
    if (type3 === "group") {
      items.forEach((group2) => {
        group2.items.forEach((mark) => draw2(context3, mark.items, interior));
      });
    } else {
      Marks[type3].draw(context3, {
        items: interior ? items.map(prepare) : items
      });
    }
  }
  function prepare(source4) {
    const item = rederive(source4, {});
    if (item.stroke && item.strokeOpacity !== 0 || item.fill && item.fillOpacity !== 0) {
      return {
        ...item,
        strokeOpacity: 1,
        stroke: "#000",
        fillOpacity: 0
      };
    }
    return item;
  }
  var DIV = 5;
  var MOD2 = 31;
  var SIZE = 32;
  var RIGHT0 = new Uint32Array(SIZE + 1);
  var RIGHT1 = new Uint32Array(SIZE + 1);
  RIGHT1[0] = 0;
  RIGHT0[0] = ~RIGHT1[0];
  for (let i2 = 1; i2 <= SIZE; ++i2) {
    RIGHT1[i2] = RIGHT1[i2 - 1] << 1 | 1;
    RIGHT0[i2] = ~RIGHT1[i2];
  }
  function Bitmap(w3, h3) {
    const array4 = new Uint32Array(~~((w3 * h3 + SIZE) / SIZE));
    function _set(index4, mask) {
      array4[index4] |= mask;
    }
    function _clear(index4, mask) {
      array4[index4] &= mask;
    }
    return {
      array: array4,
      get: (x5, y5) => {
        const index4 = y5 * w3 + x5;
        return array4[index4 >>> DIV] & 1 << (index4 & MOD2);
      },
      set: (x5, y5) => {
        const index4 = y5 * w3 + x5;
        _set(index4 >>> DIV, 1 << (index4 & MOD2));
      },
      clear: (x5, y5) => {
        const index4 = y5 * w3 + x5;
        _clear(index4 >>> DIV, ~(1 << (index4 & MOD2)));
      },
      getRange: (x5, y5, x22, y22) => {
        let r2 = y22, start, end, indexStart, indexEnd;
        for (; r2 >= y5; --r2) {
          start = r2 * w3 + x5;
          end = r2 * w3 + x22;
          indexStart = start >>> DIV;
          indexEnd = end >>> DIV;
          if (indexStart === indexEnd) {
            if (array4[indexStart] & RIGHT0[start & MOD2] & RIGHT1[(end & MOD2) + 1]) {
              return true;
            }
          } else {
            if (array4[indexStart] & RIGHT0[start & MOD2]) return true;
            if (array4[indexEnd] & RIGHT1[(end & MOD2) + 1]) return true;
            for (let i2 = indexStart + 1; i2 < indexEnd; ++i2) {
              if (array4[i2]) return true;
            }
          }
        }
        return false;
      },
      setRange: (x5, y5, x22, y22) => {
        let start, end, indexStart, indexEnd, i2;
        for (; y5 <= y22; ++y5) {
          start = y5 * w3 + x5;
          end = y5 * w3 + x22;
          indexStart = start >>> DIV;
          indexEnd = end >>> DIV;
          if (indexStart === indexEnd) {
            _set(indexStart, RIGHT0[start & MOD2] & RIGHT1[(end & MOD2) + 1]);
          } else {
            _set(indexStart, RIGHT0[start & MOD2]);
            _set(indexEnd, RIGHT1[(end & MOD2) + 1]);
            for (i2 = indexStart + 1; i2 < indexEnd; ++i2) _set(i2, 4294967295);
          }
        }
      },
      clearRange: (x5, y5, x22, y22) => {
        let start, end, indexStart, indexEnd, i2;
        for (; y5 <= y22; ++y5) {
          start = y5 * w3 + x5;
          end = y5 * w3 + x22;
          indexStart = start >>> DIV;
          indexEnd = end >>> DIV;
          if (indexStart === indexEnd) {
            _clear(indexStart, RIGHT1[start & MOD2] | RIGHT0[(end & MOD2) + 1]);
          } else {
            _clear(indexStart, RIGHT1[start & MOD2]);
            _clear(indexEnd, RIGHT0[(end & MOD2) + 1]);
            for (i2 = indexStart + 1; i2 < indexEnd; ++i2) _clear(i2, 0);
          }
        }
      },
      outOfBounds: (x5, y5, x22, y22) => x5 < 0 || y5 < 0 || y22 >= h3 || x22 >= w3
    };
  }
  function scaler(width2, height2, padding3) {
    const ratio = Math.max(1, Math.sqrt(width2 * height2 / 1e6)), w3 = ~~((width2 + 2 * padding3 + ratio) / ratio), h3 = ~~((height2 + 2 * padding3 + ratio) / ratio), scale7 = (_) => ~~((_ + padding3) / ratio);
    scale7.invert = (_) => _ * ratio - padding3;
    scale7.bitmap = () => Bitmap(w3, h3);
    scale7.ratio = ratio;
    scale7.padding = padding3;
    scale7.width = width2;
    scale7.height = height2;
    return scale7;
  }
  function placeAreaLabelNaive($2, bitmaps, avoidBaseMark, markIndex) {
    const width2 = $2.width, height2 = $2.height;
    return function(d2) {
      const items = d2.datum.datum.items[markIndex].items, n2 = items.length, textHeight = d2.datum.fontSize, textWidth = textMetrics.width(d2.datum, d2.datum.text);
      let maxAreaWidth = 0, x12, x22, y12, y22, x5, y5, areaWidth;
      for (let i2 = 0; i2 < n2; ++i2) {
        x12 = items[i2].x;
        y12 = items[i2].y;
        x22 = items[i2].x2 === void 0 ? x12 : items[i2].x2;
        y22 = items[i2].y2 === void 0 ? y12 : items[i2].y2;
        x5 = (x12 + x22) / 2;
        y5 = (y12 + y22) / 2;
        areaWidth = Math.abs(x22 - x12 + y22 - y12);
        if (areaWidth >= maxAreaWidth) {
          maxAreaWidth = areaWidth;
          d2.x = x5;
          d2.y = y5;
        }
      }
      x5 = textWidth / 2;
      y5 = textHeight / 2;
      x12 = d2.x - x5;
      x22 = d2.x + x5;
      y12 = d2.y - y5;
      y22 = d2.y + y5;
      d2.align = "center";
      if (x12 < 0 && x22 <= width2) {
        d2.align = "left";
      } else if (0 <= x12 && width2 < x22) {
        d2.align = "right";
      }
      d2.baseline = "middle";
      if (y12 < 0 && y22 <= height2) {
        d2.baseline = "top";
      } else if (0 <= y12 && height2 < y22) {
        d2.baseline = "bottom";
      }
      return true;
    };
  }
  function outOfBounds(x5, y5, textWidth, textHeight, width2, height2) {
    let r2 = textWidth / 2;
    return x5 - r2 < 0 || x5 + r2 > width2 || y5 - (r2 = textHeight / 2) < 0 || y5 + r2 > height2;
  }
  function collision($2, x5, y5, textHeight, textWidth, h3, bm0, bm1) {
    const w3 = textWidth * h3 / (textHeight * 2), x12 = $2(x5 - w3), x22 = $2(x5 + w3), y12 = $2(y5 - (h3 = h3 / 2)), y22 = $2(y5 + h3);
    return bm0.outOfBounds(x12, y12, x22, y22) || bm0.getRange(x12, y12, x22, y22) || bm1 && bm1.getRange(x12, y12, x22, y22);
  }
  function placeAreaLabelReducedSearch($2, bitmaps, avoidBaseMark, markIndex) {
    const width2 = $2.width, height2 = $2.height, bm0 = bitmaps[0], bm1 = bitmaps[1];
    function tryLabel(_x3, _y3, maxSize, textWidth, textHeight) {
      const x5 = $2.invert(_x3), y5 = $2.invert(_y3);
      let lo = maxSize, hi = height2, mid;
      if (!outOfBounds(x5, y5, textWidth, textHeight, width2, height2) && !collision($2, x5, y5, textHeight, textWidth, lo, bm0, bm1) && !collision($2, x5, y5, textHeight, textWidth, textHeight, bm0, null)) {
        while (hi - lo >= 1) {
          mid = (lo + hi) / 2;
          if (collision($2, x5, y5, textHeight, textWidth, mid, bm0, bm1)) {
            hi = mid;
          } else {
            lo = mid;
          }
        }
        if (lo > maxSize) {
          return [x5, y5, lo, true];
        }
      }
    }
    return function(d2) {
      const items = d2.datum.datum.items[markIndex].items, n2 = items.length, textHeight = d2.datum.fontSize, textWidth = textMetrics.width(d2.datum, d2.datum.text);
      let maxSize = avoidBaseMark ? textHeight : 0, labelPlaced = false, labelPlaced2 = false, maxAreaWidth = 0, x12, x22, y12, y22, x5, y5, _x3, _y3, _x1, _xMid, _x22, _y1, _yMid, _y22, areaWidth, result, swapTmp;
      for (let i2 = 0; i2 < n2; ++i2) {
        x12 = items[i2].x;
        y12 = items[i2].y;
        x22 = items[i2].x2 === void 0 ? x12 : items[i2].x2;
        y22 = items[i2].y2 === void 0 ? y12 : items[i2].y2;
        if (x12 > x22) {
          swapTmp = x12;
          x12 = x22;
          x22 = swapTmp;
        }
        if (y12 > y22) {
          swapTmp = y12;
          y12 = y22;
          y22 = swapTmp;
        }
        _x1 = $2(x12);
        _x22 = $2(x22);
        _xMid = ~~((_x1 + _x22) / 2);
        _y1 = $2(y12);
        _y22 = $2(y22);
        _yMid = ~~((_y1 + _y22) / 2);
        for (_x3 = _xMid; _x3 >= _x1; --_x3) {
          for (_y3 = _yMid; _y3 >= _y1; --_y3) {
            result = tryLabel(_x3, _y3, maxSize, textWidth, textHeight);
            if (result) {
              [d2.x, d2.y, maxSize, labelPlaced] = result;
            }
          }
        }
        for (_x3 = _xMid; _x3 <= _x22; ++_x3) {
          for (_y3 = _yMid; _y3 <= _y22; ++_y3) {
            result = tryLabel(_x3, _y3, maxSize, textWidth, textHeight);
            if (result) {
              [d2.x, d2.y, maxSize, labelPlaced] = result;
            }
          }
        }
        if (!labelPlaced && !avoidBaseMark) {
          areaWidth = Math.abs(x22 - x12 + y22 - y12);
          x5 = (x12 + x22) / 2;
          y5 = (y12 + y22) / 2;
          if (areaWidth >= maxAreaWidth && !outOfBounds(x5, y5, textWidth, textHeight, width2, height2) && !collision($2, x5, y5, textHeight, textWidth, textHeight, bm0, null)) {
            maxAreaWidth = areaWidth;
            d2.x = x5;
            d2.y = y5;
            labelPlaced2 = true;
          }
        }
      }
      if (labelPlaced || labelPlaced2) {
        x5 = textWidth / 2;
        y5 = textHeight / 2;
        bm0.setRange($2(d2.x - x5), $2(d2.y - y5), $2(d2.x + x5), $2(d2.y + y5));
        d2.align = "center";
        d2.baseline = "middle";
        return true;
      } else {
        return false;
      }
    };
  }
  var X_DIR = [-1, -1, 1, 1];
  var Y_DIR = [-1, 1, -1, 1];
  function placeAreaLabelFloodFill($2, bitmaps, avoidBaseMark, markIndex) {
    const width2 = $2.width, height2 = $2.height, bm0 = bitmaps[0], bm1 = bitmaps[1], bm2 = $2.bitmap();
    return function(d2) {
      const items = d2.datum.datum.items[markIndex].items, n2 = items.length, textHeight = d2.datum.fontSize, textWidth = textMetrics.width(d2.datum, d2.datum.text), stack2 = [];
      let maxSize = avoidBaseMark ? textHeight : 0, labelPlaced = false, labelPlaced2 = false, maxAreaWidth = 0, x12, x22, y12, y22, x5, y5, _x3, _y3, lo, hi, mid, areaWidth;
      for (let i2 = 0; i2 < n2; ++i2) {
        x12 = items[i2].x;
        y12 = items[i2].y;
        x22 = items[i2].x2 === void 0 ? x12 : items[i2].x2;
        y22 = items[i2].y2 === void 0 ? y12 : items[i2].y2;
        stack2.push([$2((x12 + x22) / 2), $2((y12 + y22) / 2)]);
        while (stack2.length) {
          [_x3, _y3] = stack2.pop();
          if (bm0.get(_x3, _y3) || bm1.get(_x3, _y3) || bm2.get(_x3, _y3)) continue;
          bm2.set(_x3, _y3);
          for (let j2 = 0; j2 < 4; ++j2) {
            x5 = _x3 + X_DIR[j2];
            y5 = _y3 + Y_DIR[j2];
            if (!bm2.outOfBounds(x5, y5, x5, y5)) stack2.push([x5, y5]);
          }
          x5 = $2.invert(_x3);
          y5 = $2.invert(_y3);
          lo = maxSize;
          hi = height2;
          if (!outOfBounds(x5, y5, textWidth, textHeight, width2, height2) && !collision($2, x5, y5, textHeight, textWidth, lo, bm0, bm1) && !collision($2, x5, y5, textHeight, textWidth, textHeight, bm0, null)) {
            while (hi - lo >= 1) {
              mid = (lo + hi) / 2;
              if (collision($2, x5, y5, textHeight, textWidth, mid, bm0, bm1)) {
                hi = mid;
              } else {
                lo = mid;
              }
            }
            if (lo > maxSize) {
              d2.x = x5;
              d2.y = y5;
              maxSize = lo;
              labelPlaced = true;
            }
          }
        }
        if (!labelPlaced && !avoidBaseMark) {
          areaWidth = Math.abs(x22 - x12 + y22 - y12);
          x5 = (x12 + x22) / 2;
          y5 = (y12 + y22) / 2;
          if (areaWidth >= maxAreaWidth && !outOfBounds(x5, y5, textWidth, textHeight, width2, height2) && !collision($2, x5, y5, textHeight, textWidth, textHeight, bm0, null)) {
            maxAreaWidth = areaWidth;
            d2.x = x5;
            d2.y = y5;
            labelPlaced2 = true;
          }
        }
      }
      if (labelPlaced || labelPlaced2) {
        x5 = textWidth / 2;
        y5 = textHeight / 2;
        bm0.setRange($2(d2.x - x5), $2(d2.y - y5), $2(d2.x + x5), $2(d2.y + y5));
        d2.align = "center";
        d2.baseline = "middle";
        return true;
      } else {
        return false;
      }
    };
  }
  var Aligns = ["right", "center", "left"];
  var Baselines = ["bottom", "middle", "top"];
  function placeMarkLabel($2, bitmaps, anchors, offsets2) {
    const width2 = $2.width, height2 = $2.height, bm0 = bitmaps[0], bm1 = bitmaps[1], n2 = offsets2.length;
    return function(d2) {
      const boundary = d2.boundary, textHeight = d2.datum.fontSize;
      if (boundary[2] < 0 || boundary[5] < 0 || boundary[0] > width2 || boundary[3] > height2) {
        return false;
      }
      let textWidth = d2.textWidth ?? 0, dx, dy, isInside, sizeFactor, insideFactor, x12, x22, y12, y22, xc, yc, _x1, _x22, _y1, _y22;
      for (let i2 = 0; i2 < n2; ++i2) {
        dx = (anchors[i2] & 3) - 1;
        dy = (anchors[i2] >>> 2 & 3) - 1;
        isInside = dx === 0 && dy === 0 || offsets2[i2] < 0;
        sizeFactor = dx && dy ? Math.SQRT1_2 : 1;
        insideFactor = offsets2[i2] < 0 ? -1 : 1;
        x12 = boundary[1 + dx] + offsets2[i2] * dx * sizeFactor;
        yc = boundary[4 + dy] + insideFactor * textHeight * dy / 2 + offsets2[i2] * dy * sizeFactor;
        y12 = yc - textHeight / 2;
        y22 = yc + textHeight / 2;
        _x1 = $2(x12);
        _y1 = $2(y12);
        _y22 = $2(y22);
        if (!textWidth) {
          if (!test(_x1, _x1, _y1, _y22, bm0, bm1, x12, x12, y12, y22, boundary, isInside)) {
            continue;
          } else {
            textWidth = textMetrics.width(d2.datum, d2.datum.text);
          }
        }
        xc = x12 + insideFactor * textWidth * dx / 2;
        x12 = xc - textWidth / 2;
        x22 = xc + textWidth / 2;
        _x1 = $2(x12);
        _x22 = $2(x22);
        if (test(_x1, _x22, _y1, _y22, bm0, bm1, x12, x22, y12, y22, boundary, isInside)) {
          d2.x = !dx ? xc : dx * insideFactor < 0 ? x22 : x12;
          d2.y = !dy ? yc : dy * insideFactor < 0 ? y22 : y12;
          d2.align = Aligns[dx * insideFactor + 1];
          d2.baseline = Baselines[dy * insideFactor + 1];
          bm0.setRange(_x1, _y1, _x22, _y22);
          return true;
        }
      }
      return false;
    };
  }
  function test(_x1, _x22, _y1, _y22, bm0, bm1, x12, x22, y12, y22, boundary, isInside) {
    return !(bm0.outOfBounds(_x1, _y1, _x22, _y22) || (isInside && bm1 || bm0).getRange(_x1, _y1, _x22, _y22));
  }
  var TOP = 0;
  var MIDDLE = 4;
  var BOTTOM = 8;
  var LEFT = 0;
  var CENTER = 1;
  var RIGHT = 2;
  var anchorCode = {
    "top-left": TOP + LEFT,
    "top": TOP + CENTER,
    "top-right": TOP + RIGHT,
    "left": MIDDLE + LEFT,
    "middle": MIDDLE + CENTER,
    "right": MIDDLE + RIGHT,
    "bottom-left": BOTTOM + LEFT,
    "bottom": BOTTOM + CENTER,
    "bottom-right": BOTTOM + RIGHT
  };
  var placeAreaLabel = {
    "naive": placeAreaLabelNaive,
    "reduced-search": placeAreaLabelReducedSearch,
    "floodfill": placeAreaLabelFloodFill
  };
  function labelLayout(texts, size, compare4, offset4, anchor, avoidMarks, avoidBaseMark, lineAnchor, markIndex, padding3, method2) {
    if (!texts.length) return texts;
    const positions = Math.max(offset4.length, anchor.length), offsets2 = getOffsets(offset4, positions), anchors = getAnchors(anchor, positions), marktype = markType(texts[0].datum), grouptype = marktype === "group" && texts[0].datum.items[markIndex].marktype, isGroupArea = grouptype === "area", boundary = markBoundary(marktype, grouptype, lineAnchor, markIndex), infPadding = padding3 === null || padding3 === Infinity, isNaiveGroupArea = isGroupArea && method2 === "naive";
    let maxTextWidth = -1, maxTextHeight = -1;
    const data3 = texts.map((d2) => {
      const textWidth = infPadding ? textMetrics.width(d2, d2.text) : void 0;
      maxTextWidth = Math.max(maxTextWidth, textWidth);
      maxTextHeight = Math.max(maxTextHeight, d2.fontSize);
      return {
        datum: d2,
        opacity: 0,
        x: void 0,
        y: void 0,
        align: void 0,
        baseline: void 0,
        boundary: boundary(d2),
        textWidth
      };
    });
    padding3 = padding3 === null || padding3 === Infinity ? Math.max(maxTextWidth, maxTextHeight) + Math.max(...offset4) : padding3;
    const $2 = scaler(size[0], size[1], padding3);
    let bitmaps;
    if (!isNaiveGroupArea) {
      if (compare4) {
        data3.sort((a4, b3) => compare4(a4.datum, b3.datum));
      }
      let labelInside = false;
      for (let i2 = 0; i2 < anchors.length && !labelInside; ++i2) {
        labelInside = anchors[i2] === 5 || offsets2[i2] < 0;
      }
      const baseMark = (marktype && avoidBaseMark || isGroupArea) && texts.map((d2) => d2.datum);
      bitmaps = avoidMarks.length || baseMark ? markBitmaps($2, baseMark || [], avoidMarks, labelInside, isGroupArea) : baseBitmaps($2, avoidBaseMark && data3);
    }
    const place2 = isGroupArea ? placeAreaLabel[method2]($2, bitmaps, avoidBaseMark, markIndex) : placeMarkLabel($2, bitmaps, anchors, offsets2);
    data3.forEach((d2) => d2.opacity = +place2(d2));
    return data3;
  }
  function getOffsets(_, count2) {
    const offsets2 = new Float64Array(count2), n2 = _.length;
    for (let i2 = 0; i2 < n2; ++i2) offsets2[i2] = _[i2] || 0;
    for (let i2 = n2; i2 < count2; ++i2) offsets2[i2] = offsets2[n2 - 1];
    return offsets2;
  }
  function getAnchors(_, count2) {
    const anchors = new Int8Array(count2), n2 = _.length;
    for (let i2 = 0; i2 < n2; ++i2) anchors[i2] |= anchorCode[_[i2]];
    for (let i2 = n2; i2 < count2; ++i2) anchors[i2] = anchors[n2 - 1];
    return anchors;
  }
  function markType(item) {
    return item && item.mark && item.mark.marktype;
  }
  function markBoundary(marktype, grouptype, lineAnchor, markIndex) {
    const xy = (d2) => [d2.x, d2.x, d2.x, d2.y, d2.y, d2.y];
    if (!marktype) {
      return xy;
    } else if (marktype === "line" || marktype === "area") {
      return (d2) => xy(d2.datum);
    } else if (grouptype === "line") {
      return (d2) => {
        const items = d2.datum.items[markIndex].items;
        return xy(items.length ? items[lineAnchor === "start" ? 0 : items.length - 1] : {
          x: NaN,
          y: NaN
        });
      };
    } else {
      return (d2) => {
        const b3 = d2.datum.bounds;
        return [b3.x1, (b3.x1 + b3.x2) / 2, b3.x2, b3.y1, (b3.y1 + b3.y2) / 2, b3.y2];
      };
    }
  }
  var Output3 = ["x", "y", "opacity", "align", "baseline"];
  var Anchors = ["top-left", "left", "bottom-left", "top", "bottom", "top-right", "right", "bottom-right"];
  function Label(params2) {
    Transform.call(this, null, params2);
  }
  Label.Definition = {
    type: "Label",
    metadata: {
      modifies: true
    },
    params: [{
      name: "size",
      type: "number",
      array: true,
      length: 2,
      required: true
    }, {
      name: "sort",
      type: "compare"
    }, {
      name: "anchor",
      type: "string",
      array: true,
      default: Anchors
    }, {
      name: "offset",
      type: "number",
      array: true,
      default: [1]
    }, {
      name: "padding",
      type: "number",
      default: 0,
      null: true
    }, {
      name: "lineAnchor",
      type: "string",
      values: ["start", "end"],
      default: "end"
    }, {
      name: "markIndex",
      type: "number",
      default: 0
    }, {
      name: "avoidBaseMark",
      type: "boolean",
      default: true
    }, {
      name: "avoidMarks",
      type: "data",
      array: true
    }, {
      name: "method",
      type: "string",
      default: "naive"
    }, {
      name: "as",
      type: "string",
      array: true,
      length: Output3.length,
      default: Output3
    }]
  };
  inherits(Label, Transform, {
    transform(_, pulse2) {
      function modp(param2) {
        const p2 = _[param2];
        return isFunction(p2) && pulse2.modified(p2.fields);
      }
      const mod = _.modified();
      if (!(mod || pulse2.changed(pulse2.ADD_REM) || modp("sort"))) return;
      if (!_.size || _.size.length !== 2) {
        error("Size parameter should be specified as a [width, height] array.");
      }
      const as = _.as || Output3;
      labelLayout(pulse2.materialize(pulse2.SOURCE).source || [], _.size, _.sort, array(_.offset == null ? 1 : _.offset), array(_.anchor || Anchors), _.avoidMarks || [], _.avoidBaseMark !== false, _.lineAnchor || "end", _.markIndex || 0, _.padding === void 0 ? 0 : _.padding, _.method || "naive").forEach((l2) => {
        const t4 = l2.datum;
        t4[as[0]] = l2.x;
        t4[as[1]] = l2.y;
        t4[as[2]] = l2.opacity;
        t4[as[3]] = l2.align;
        t4[as[4]] = l2.baseline;
      });
      return pulse2.reflow(mod).modifies(as);
    }
  });

  // node_modules/vega-regression/build/vega-regression.module.js
  var vega_regression_module_exports = {};
  __export(vega_regression_module_exports, {
    loess: () => Loess,
    regression: () => Regression
  });
  function partition4(data3, groupby) {
    var groups = [], get6 = function(f2) {
      return f2(t4);
    }, map4, i2, n2, t4, k2, g2;
    if (groupby == null) {
      groups.push(data3);
    } else {
      for (map4 = {}, i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
        t4 = data3[i2];
        k2 = groupby.map(get6);
        g2 = map4[k2];
        if (!g2) {
          map4[k2] = g2 = [];
          g2.dims = k2;
          groups.push(g2);
        }
        g2.push(t4);
      }
    }
    return groups;
  }
  function Loess(params2) {
    Transform.call(this, null, params2);
  }
  Loess.Definition = {
    "type": "Loess",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "x",
      "type": "field",
      "required": true
    }, {
      "name": "y",
      "type": "field",
      "required": true
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "bandwidth",
      "type": "number",
      "default": 0.3
    }, {
      "name": "as",
      "type": "string",
      "array": true
    }]
  };
  inherits(Loess, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
      if (!this.value || pulse2.changed() || _.modified()) {
        const source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition4(source4, _.groupby), names = (_.groupby || []).map(accessorName), m4 = names.length, as = _.as || [accessorName(_.x), accessorName(_.y)], values4 = [];
        groups.forEach((g2) => {
          loess(g2, _.x, _.y, _.bandwidth || 0.3).forEach((p2) => {
            const t4 = {};
            for (let i2 = 0; i2 < m4; ++i2) {
              t4[names[i2]] = g2.dims[i2];
            }
            t4[as[0]] = p2[0];
            t4[as[1]] = p2[1];
            values4.push(ingest$1(t4));
          });
        });
        if (this.value) out.rem = this.value;
        this.value = out.add = out.source = values4;
      }
      return out;
    }
  });
  var Methods2 = {
    constant: constant2,
    linear,
    log: log2,
    exp: exp2,
    pow: pow2,
    quad,
    poly
  };
  var degreesOfFreedom = (method2, order) => method2 === "poly" ? order : method2 === "quad" ? 2 : 1;
  function Regression(params2) {
    Transform.call(this, null, params2);
  }
  Regression.Definition = {
    "type": "Regression",
    "metadata": {
      "generates": true
    },
    "params": [{
      "name": "x",
      "type": "field",
      "required": true
    }, {
      "name": "y",
      "type": "field",
      "required": true
    }, {
      "name": "groupby",
      "type": "field",
      "array": true
    }, {
      "name": "method",
      "type": "string",
      "default": "linear",
      "values": Object.keys(Methods2)
    }, {
      "name": "order",
      "type": "number",
      "default": 3
    }, {
      "name": "extent",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "params",
      "type": "boolean",
      "default": false
    }, {
      "name": "as",
      "type": "string",
      "array": true
    }]
  };
  inherits(Regression, Transform, {
    transform(_, pulse2) {
      const out = pulse2.fork(pulse2.NO_SOURCE | pulse2.NO_FIELDS);
      if (!this.value || pulse2.changed() || _.modified()) {
        const source4 = pulse2.materialize(pulse2.SOURCE).source, groups = partition4(source4, _.groupby), names = (_.groupby || []).map(accessorName), method2 = _.method || "linear", order = _.order == null ? 3 : _.order, dof = degreesOfFreedom(method2, order), as = _.as || [accessorName(_.x), accessorName(_.y)], fit3 = Methods2[method2], values4 = [];
        let domain4 = _.extent;
        if (!has(Methods2, method2)) {
          error("Invalid regression method: " + method2);
        }
        if (domain4 != null) {
          if (method2 === "log" && domain4[0] <= 0) {
            pulse2.dataflow.warn("Ignoring extent with values <= 0 for log regression.");
            domain4 = null;
          }
        }
        groups.forEach((g2) => {
          const n2 = g2.length;
          if (n2 <= dof) {
            pulse2.dataflow.warn("Skipping regression with more parameters than data points.");
            return;
          }
          const model = fit3(g2, _.x, _.y, order);
          if (_.params) {
            values4.push(ingest$1({
              keys: g2.dims,
              coef: model.coef,
              rSquared: model.rSquared
            }));
            return;
          }
          const dom = domain4 || extent(g2, _.x), add6 = (p2) => {
            const t4 = {};
            for (let i2 = 0; i2 < names.length; ++i2) {
              t4[names[i2]] = g2.dims[i2];
            }
            t4[as[0]] = p2[0];
            t4[as[1]] = p2[1];
            values4.push(ingest$1(t4));
          };
          if (method2 === "linear" || method2 === "constant") {
            dom.forEach((x5) => add6([x5, model.predict(x5)]));
          } else {
            sampleCurve(model.predict, dom, 25, 200).forEach(add6);
          }
        });
        if (this.value) out.rem = this.value;
        this.value = out.add = out.source = values4;
      }
      return out;
    }
  });

  // node_modules/vega-voronoi/build/vega-voronoi.module.js
  var vega_voronoi_module_exports = {};
  __export(vega_voronoi_module_exports, {
    voronoi: () => Voronoi2
  });

  // node_modules/robust-predicates/esm/util.js
  var epsilon6 = 11102230246251565e-32;
  var splitter = 134217729;
  var resulterrbound = (3 + 8 * epsilon6) * epsilon6;
  function sum2(elen, e4, flen, f2, h3) {
    let Q, Qnew, hh, bvirt;
    let enow = e4[0];
    let fnow = f2[0];
    let eindex = 0;
    let findex = 0;
    if (fnow > enow === fnow > -enow) {
      Q = enow;
      enow = e4[++eindex];
    } else {
      Q = fnow;
      fnow = f2[++findex];
    }
    let hindex = 0;
    if (eindex < elen && findex < flen) {
      if (fnow > enow === fnow > -enow) {
        Qnew = enow + Q;
        hh = Q - (Qnew - enow);
        enow = e4[++eindex];
      } else {
        Qnew = fnow + Q;
        hh = Q - (Qnew - fnow);
        fnow = f2[++findex];
      }
      Q = Qnew;
      if (hh !== 0) {
        h3[hindex++] = hh;
      }
      while (eindex < elen && findex < flen) {
        if (fnow > enow === fnow > -enow) {
          Qnew = Q + enow;
          bvirt = Qnew - Q;
          hh = Q - (Qnew - bvirt) + (enow - bvirt);
          enow = e4[++eindex];
        } else {
          Qnew = Q + fnow;
          bvirt = Qnew - Q;
          hh = Q - (Qnew - bvirt) + (fnow - bvirt);
          fnow = f2[++findex];
        }
        Q = Qnew;
        if (hh !== 0) {
          h3[hindex++] = hh;
        }
      }
    }
    while (eindex < elen) {
      Qnew = Q + enow;
      bvirt = Qnew - Q;
      hh = Q - (Qnew - bvirt) + (enow - bvirt);
      enow = e4[++eindex];
      Q = Qnew;
      if (hh !== 0) {
        h3[hindex++] = hh;
      }
    }
    while (findex < flen) {
      Qnew = Q + fnow;
      bvirt = Qnew - Q;
      hh = Q - (Qnew - bvirt) + (fnow - bvirt);
      fnow = f2[++findex];
      Q = Qnew;
      if (hh !== 0) {
        h3[hindex++] = hh;
      }
    }
    if (Q !== 0 || hindex === 0) {
      h3[hindex++] = Q;
    }
    return hindex;
  }
  function estimate(elen, e4) {
    let Q = e4[0];
    for (let i2 = 1; i2 < elen; i2++) Q += e4[i2];
    return Q;
  }
  function vec(n2) {
    return new Float64Array(n2);
  }

  // node_modules/robust-predicates/esm/orient2d.js
  var ccwerrboundA = (3 + 16 * epsilon6) * epsilon6;
  var ccwerrboundB = (2 + 12 * epsilon6) * epsilon6;
  var ccwerrboundC = (9 + 64 * epsilon6) * epsilon6 * epsilon6;
  var B2 = vec(4);
  var C1 = vec(8);
  var C22 = vec(12);
  var D2 = vec(16);
  var u = vec(4);
  function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) {
    let acxtail, acytail, bcxtail, bcytail;
    let bvirt, c4, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t13, t04, u32;
    const acx = ax - cx;
    const bcx = bx - cx;
    const acy = ay - cy;
    const bcy = by - cy;
    s1 = acx * bcy;
    c4 = splitter * acx;
    ahi = c4 - (c4 - acx);
    alo = acx - ahi;
    c4 = splitter * bcy;
    bhi = c4 - (c4 - bcy);
    blo = bcy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t13 = acy * bcx;
    c4 = splitter * acy;
    ahi = c4 - (c4 - acy);
    alo = acy - ahi;
    c4 = splitter * bcx;
    bhi = c4 - (c4 - bcx);
    blo = bcx - bhi;
    t04 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t04;
    bvirt = s0 - _i;
    B2[0] = s0 - (_i + bvirt) + (bvirt - t04);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t13;
    bvirt = _0 - _i;
    B2[1] = _0 - (_i + bvirt) + (bvirt - t13);
    u32 = _j + _i;
    bvirt = u32 - _j;
    B2[2] = _j - (u32 - bvirt) + (_i - bvirt);
    B2[3] = u32;
    let det = estimate(4, B2);
    let errbound = ccwerrboundB * detsum;
    if (det >= errbound || -det >= errbound) {
      return det;
    }
    bvirt = ax - acx;
    acxtail = ax - (acx + bvirt) + (bvirt - cx);
    bvirt = bx - bcx;
    bcxtail = bx - (bcx + bvirt) + (bvirt - cx);
    bvirt = ay - acy;
    acytail = ay - (acy + bvirt) + (bvirt - cy);
    bvirt = by - bcy;
    bcytail = by - (bcy + bvirt) + (bvirt - cy);
    if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) {
      return det;
    }
    errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det);
    det += acx * bcytail + bcy * acxtail - (acy * bcxtail + bcx * acytail);
    if (det >= errbound || -det >= errbound) return det;
    s1 = acxtail * bcy;
    c4 = splitter * acxtail;
    ahi = c4 - (c4 - acxtail);
    alo = acxtail - ahi;
    c4 = splitter * bcy;
    bhi = c4 - (c4 - bcy);
    blo = bcy - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t13 = acytail * bcx;
    c4 = splitter * acytail;
    ahi = c4 - (c4 - acytail);
    alo = acytail - ahi;
    c4 = splitter * bcx;
    bhi = c4 - (c4 - bcx);
    blo = bcx - bhi;
    t04 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t04;
    bvirt = s0 - _i;
    u[0] = s0 - (_i + bvirt) + (bvirt - t04);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t13;
    bvirt = _0 - _i;
    u[1] = _0 - (_i + bvirt) + (bvirt - t13);
    u32 = _j + _i;
    bvirt = u32 - _j;
    u[2] = _j - (u32 - bvirt) + (_i - bvirt);
    u[3] = u32;
    const C1len = sum2(4, B2, 4, u, C1);
    s1 = acx * bcytail;
    c4 = splitter * acx;
    ahi = c4 - (c4 - acx);
    alo = acx - ahi;
    c4 = splitter * bcytail;
    bhi = c4 - (c4 - bcytail);
    blo = bcytail - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t13 = acy * bcxtail;
    c4 = splitter * acy;
    ahi = c4 - (c4 - acy);
    alo = acy - ahi;
    c4 = splitter * bcxtail;
    bhi = c4 - (c4 - bcxtail);
    blo = bcxtail - bhi;
    t04 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t04;
    bvirt = s0 - _i;
    u[0] = s0 - (_i + bvirt) + (bvirt - t04);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t13;
    bvirt = _0 - _i;
    u[1] = _0 - (_i + bvirt) + (bvirt - t13);
    u32 = _j + _i;
    bvirt = u32 - _j;
    u[2] = _j - (u32 - bvirt) + (_i - bvirt);
    u[3] = u32;
    const C2len = sum2(C1len, C1, 4, u, C22);
    s1 = acxtail * bcytail;
    c4 = splitter * acxtail;
    ahi = c4 - (c4 - acxtail);
    alo = acxtail - ahi;
    c4 = splitter * bcytail;
    bhi = c4 - (c4 - bcytail);
    blo = bcytail - bhi;
    s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo);
    t13 = acytail * bcxtail;
    c4 = splitter * acytail;
    ahi = c4 - (c4 - acytail);
    alo = acytail - ahi;
    c4 = splitter * bcxtail;
    bhi = c4 - (c4 - bcxtail);
    blo = bcxtail - bhi;
    t04 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
    _i = s0 - t04;
    bvirt = s0 - _i;
    u[0] = s0 - (_i + bvirt) + (bvirt - t04);
    _j = s1 + _i;
    bvirt = _j - s1;
    _0 = s1 - (_j - bvirt) + (_i - bvirt);
    _i = _0 - t13;
    bvirt = _0 - _i;
    u[1] = _0 - (_i + bvirt) + (bvirt - t13);
    u32 = _j + _i;
    bvirt = u32 - _j;
    u[2] = _j - (u32 - bvirt) + (_i - bvirt);
    u[3] = u32;
    const Dlen = sum2(C2len, C22, 4, u, D2);
    return D2[Dlen - 1];
  }
  function orient2d(ax, ay, bx, by, cx, cy) {
    const detleft = (ay - cy) * (bx - cx);
    const detright = (ax - cx) * (by - cy);
    const det = detleft - detright;
    const detsum = Math.abs(detleft + detright);
    if (Math.abs(det) >= ccwerrboundA * detsum) return det;
    return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum);
  }

  // node_modules/robust-predicates/esm/orient3d.js
  var o3derrboundA = (7 + 56 * epsilon6) * epsilon6;
  var o3derrboundB = (3 + 28 * epsilon6) * epsilon6;
  var o3derrboundC = (26 + 288 * epsilon6) * epsilon6 * epsilon6;
  var bc = vec(4);
  var ca = vec(4);
  var ab = vec(4);
  var at_b = vec(4);
  var at_c = vec(4);
  var bt_c = vec(4);
  var bt_a = vec(4);
  var ct_a = vec(4);
  var ct_b = vec(4);
  var bct = vec(8);
  var cat = vec(8);
  var abt = vec(8);
  var u2 = vec(4);
  var _8 = vec(8);
  var _8b = vec(8);
  var _16 = vec(8);
  var _12 = vec(12);
  var fin = vec(192);
  var fin2 = vec(192);

  // node_modules/robust-predicates/esm/incircle.js
  var iccerrboundA = (10 + 96 * epsilon6) * epsilon6;
  var iccerrboundB = (4 + 48 * epsilon6) * epsilon6;
  var iccerrboundC = (44 + 576 * epsilon6) * epsilon6 * epsilon6;
  var bc2 = vec(4);
  var ca2 = vec(4);
  var ab2 = vec(4);
  var aa = vec(4);
  var bb = vec(4);
  var cc = vec(4);
  var u3 = vec(4);
  var v = vec(4);
  var axtbc = vec(8);
  var aytbc = vec(8);
  var bxtca = vec(8);
  var bytca = vec(8);
  var cxtab = vec(8);
  var cytab = vec(8);
  var abt2 = vec(8);
  var bct2 = vec(8);
  var cat2 = vec(8);
  var abtt = vec(4);
  var bctt = vec(4);
  var catt = vec(4);
  var _82 = vec(8);
  var _162 = vec(16);
  var _16b = vec(16);
  var _16c = vec(16);
  var _32 = vec(32);
  var _32b = vec(32);
  var _48 = vec(48);
  var _64 = vec(64);
  var fin3 = vec(1152);
  var fin22 = vec(1152);

  // node_modules/robust-predicates/esm/insphere.js
  var isperrboundA = (16 + 224 * epsilon6) * epsilon6;
  var isperrboundB = (5 + 72 * epsilon6) * epsilon6;
  var isperrboundC = (71 + 1408 * epsilon6) * epsilon6 * epsilon6;
  var ab3 = vec(4);
  var bc3 = vec(4);
  var cd = vec(4);
  var de = vec(4);
  var ea2 = vec(4);
  var ac = vec(4);
  var bd = vec(4);
  var ce = vec(4);
  var da = vec(4);
  var eb = vec(4);
  var abc = vec(24);
  var bcd = vec(24);
  var cde = vec(24);
  var dea = vec(24);
  var eab = vec(24);
  var abd = vec(24);
  var bce = vec(24);
  var cda = vec(24);
  var deb = vec(24);
  var eac = vec(24);
  var adet = vec(1152);
  var bdet = vec(1152);
  var cdet = vec(1152);
  var ddet = vec(1152);
  var edet = vec(1152);
  var abdet = vec(2304);
  var cddet = vec(2304);
  var cdedet = vec(3456);
  var deter = vec(5760);
  var _83 = vec(8);
  var _8b2 = vec(8);
  var _8c = vec(8);
  var _163 = vec(16);
  var _24 = vec(24);
  var _482 = vec(48);
  var _48b = vec(48);
  var _96 = vec(96);
  var _192 = vec(192);
  var _384x = vec(384);
  var _384y = vec(384);
  var _384z = vec(384);
  var _768 = vec(768);
  var xdet = vec(96);
  var ydet = vec(96);
  var zdet = vec(96);
  var fin4 = vec(1152);

  // node_modules/delaunator/index.js
  var EPSILON2 = Math.pow(2, -52);
  var EDGE_STACK = new Uint32Array(512);
  var Delaunator = class _Delaunator {
    static from(points2, getX = defaultGetX, getY = defaultGetY) {
      const n2 = points2.length;
      const coords = new Float64Array(n2 * 2);
      for (let i2 = 0; i2 < n2; i2++) {
        const p2 = points2[i2];
        coords[2 * i2] = getX(p2);
        coords[2 * i2 + 1] = getY(p2);
      }
      return new _Delaunator(coords);
    }
    constructor(coords) {
      const n2 = coords.length >> 1;
      if (n2 > 0 && typeof coords[0] !== "number") throw new Error("Expected coords to contain numbers.");
      this.coords = coords;
      const maxTriangles = Math.max(2 * n2 - 5, 0);
      this._triangles = new Uint32Array(maxTriangles * 3);
      this._halfedges = new Int32Array(maxTriangles * 3);
      this._hashSize = Math.ceil(Math.sqrt(n2));
      this._hullPrev = new Uint32Array(n2);
      this._hullNext = new Uint32Array(n2);
      this._hullTri = new Uint32Array(n2);
      this._hullHash = new Int32Array(this._hashSize);
      this._ids = new Uint32Array(n2);
      this._dists = new Float64Array(n2);
      this.update();
    }
    update() {
      const { coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash } = this;
      const n2 = coords.length >> 1;
      let minX = Infinity;
      let minY = Infinity;
      let maxX = -Infinity;
      let maxY2 = -Infinity;
      for (let i3 = 0; i3 < n2; i3++) {
        const x5 = coords[2 * i3];
        const y5 = coords[2 * i3 + 1];
        if (x5 < minX) minX = x5;
        if (y5 < minY) minY = y5;
        if (x5 > maxX) maxX = x5;
        if (y5 > maxY2) maxY2 = y5;
        this._ids[i3] = i3;
      }
      const cx = (minX + maxX) / 2;
      const cy = (minY + maxY2) / 2;
      let i0, i1, i2;
      for (let i3 = 0, minDist = Infinity; i3 < n2; i3++) {
        const d2 = dist(cx, cy, coords[2 * i3], coords[2 * i3 + 1]);
        if (d2 < minDist) {
          i0 = i3;
          minDist = d2;
        }
      }
      const i0x = coords[2 * i0];
      const i0y = coords[2 * i0 + 1];
      for (let i3 = 0, minDist = Infinity; i3 < n2; i3++) {
        if (i3 === i0) continue;
        const d2 = dist(i0x, i0y, coords[2 * i3], coords[2 * i3 + 1]);
        if (d2 < minDist && d2 > 0) {
          i1 = i3;
          minDist = d2;
        }
      }
      let i1x = coords[2 * i1];
      let i1y = coords[2 * i1 + 1];
      let minRadius = Infinity;
      for (let i3 = 0; i3 < n2; i3++) {
        if (i3 === i0 || i3 === i1) continue;
        const r2 = circumradius(i0x, i0y, i1x, i1y, coords[2 * i3], coords[2 * i3 + 1]);
        if (r2 < minRadius) {
          i2 = i3;
          minRadius = r2;
        }
      }
      let i2x = coords[2 * i2];
      let i2y = coords[2 * i2 + 1];
      if (minRadius === Infinity) {
        for (let i3 = 0; i3 < n2; i3++) {
          this._dists[i3] = coords[2 * i3] - coords[0] || coords[2 * i3 + 1] - coords[1];
        }
        quicksort(this._ids, this._dists, 0, n2 - 1);
        const hull = new Uint32Array(n2);
        let j2 = 0;
        for (let i3 = 0, d0 = -Infinity; i3 < n2; i3++) {
          const id2 = this._ids[i3];
          const d2 = this._dists[id2];
          if (d2 > d0) {
            hull[j2++] = id2;
            d0 = d2;
          }
        }
        this.hull = hull.subarray(0, j2);
        this.triangles = new Uint32Array(0);
        this.halfedges = new Uint32Array(0);
        return;
      }
      if (orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0) {
        const i3 = i1;
        const x5 = i1x;
        const y5 = i1y;
        i1 = i2;
        i1x = i2x;
        i1y = i2y;
        i2 = i3;
        i2x = x5;
        i2y = y5;
      }
      const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
      this._cx = center.x;
      this._cy = center.y;
      for (let i3 = 0; i3 < n2; i3++) {
        this._dists[i3] = dist(coords[2 * i3], coords[2 * i3 + 1], center.x, center.y);
      }
      quicksort(this._ids, this._dists, 0, n2 - 1);
      this._hullStart = i0;
      let hullSize = 3;
      hullNext[i0] = hullPrev[i2] = i1;
      hullNext[i1] = hullPrev[i0] = i2;
      hullNext[i2] = hullPrev[i1] = i0;
      hullTri[i0] = 0;
      hullTri[i1] = 1;
      hullTri[i2] = 2;
      hullHash.fill(-1);
      hullHash[this._hashKey(i0x, i0y)] = i0;
      hullHash[this._hashKey(i1x, i1y)] = i1;
      hullHash[this._hashKey(i2x, i2y)] = i2;
      this.trianglesLen = 0;
      this._addTriangle(i0, i1, i2, -1, -1, -1);
      for (let k2 = 0, xp, yp; k2 < this._ids.length; k2++) {
        const i3 = this._ids[k2];
        const x5 = coords[2 * i3];
        const y5 = coords[2 * i3 + 1];
        if (k2 > 0 && Math.abs(x5 - xp) <= EPSILON2 && Math.abs(y5 - yp) <= EPSILON2) continue;
        xp = x5;
        yp = y5;
        if (i3 === i0 || i3 === i1 || i3 === i2) continue;
        let start = 0;
        for (let j2 = 0, key2 = this._hashKey(x5, y5); j2 < this._hashSize; j2++) {
          start = hullHash[(key2 + j2) % this._hashSize];
          if (start !== -1 && start !== hullNext[start]) break;
        }
        start = hullPrev[start];
        let e4 = start, q2;
        while (q2 = hullNext[e4], orient2d(x5, y5, coords[2 * e4], coords[2 * e4 + 1], coords[2 * q2], coords[2 * q2 + 1]) >= 0) {
          e4 = q2;
          if (e4 === start) {
            e4 = -1;
            break;
          }
        }
        if (e4 === -1) continue;
        let t4 = this._addTriangle(e4, i3, hullNext[e4], -1, -1, hullTri[e4]);
        hullTri[i3] = this._legalize(t4 + 2);
        hullTri[e4] = t4;
        hullSize++;
        let n3 = hullNext[e4];
        while (q2 = hullNext[n3], orient2d(x5, y5, coords[2 * n3], coords[2 * n3 + 1], coords[2 * q2], coords[2 * q2 + 1]) < 0) {
          t4 = this._addTriangle(n3, i3, q2, hullTri[i3], -1, hullTri[n3]);
          hullTri[i3] = this._legalize(t4 + 2);
          hullNext[n3] = n3;
          hullSize--;
          n3 = q2;
        }
        if (e4 === start) {
          while (q2 = hullPrev[e4], orient2d(x5, y5, coords[2 * q2], coords[2 * q2 + 1], coords[2 * e4], coords[2 * e4 + 1]) < 0) {
            t4 = this._addTriangle(q2, i3, e4, -1, hullTri[e4], hullTri[q2]);
            this._legalize(t4 + 2);
            hullTri[q2] = t4;
            hullNext[e4] = e4;
            hullSize--;
            e4 = q2;
          }
        }
        this._hullStart = hullPrev[i3] = e4;
        hullNext[e4] = hullPrev[n3] = i3;
        hullNext[i3] = n3;
        hullHash[this._hashKey(x5, y5)] = i3;
        hullHash[this._hashKey(coords[2 * e4], coords[2 * e4 + 1])] = e4;
      }
      this.hull = new Uint32Array(hullSize);
      for (let i3 = 0, e4 = this._hullStart; i3 < hullSize; i3++) {
        this.hull[i3] = e4;
        e4 = hullNext[e4];
      }
      this.triangles = this._triangles.subarray(0, this.trianglesLen);
      this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
    }
    _hashKey(x5, y5) {
      return Math.floor(pseudoAngle(x5 - this._cx, y5 - this._cy) * this._hashSize) % this._hashSize;
    }
    _legalize(a4) {
      const { _triangles: triangles, _halfedges: halfedges, coords } = this;
      let i2 = 0;
      let ar = 0;
      while (true) {
        const b3 = halfedges[a4];
        const a0 = a4 - a4 % 3;
        ar = a0 + (a4 + 2) % 3;
        if (b3 === -1) {
          if (i2 === 0) break;
          a4 = EDGE_STACK[--i2];
          continue;
        }
        const b0 = b3 - b3 % 3;
        const al = a0 + (a4 + 1) % 3;
        const bl2 = b0 + (b3 + 2) % 3;
        const p02 = triangles[ar];
        const pr = triangles[a4];
        const pl = triangles[al];
        const p1 = triangles[bl2];
        const illegal = inCircle(
          coords[2 * p02],
          coords[2 * p02 + 1],
          coords[2 * pr],
          coords[2 * pr + 1],
          coords[2 * pl],
          coords[2 * pl + 1],
          coords[2 * p1],
          coords[2 * p1 + 1]
        );
        if (illegal) {
          triangles[a4] = p1;
          triangles[b3] = p02;
          const hbl = halfedges[bl2];
          if (hbl === -1) {
            let e4 = this._hullStart;
            do {
              if (this._hullTri[e4] === bl2) {
                this._hullTri[e4] = a4;
                break;
              }
              e4 = this._hullPrev[e4];
            } while (e4 !== this._hullStart);
          }
          this._link(a4, hbl);
          this._link(b3, halfedges[ar]);
          this._link(ar, bl2);
          const br2 = b0 + (b3 + 1) % 3;
          if (i2 < EDGE_STACK.length) {
            EDGE_STACK[i2++] = br2;
          }
        } else {
          if (i2 === 0) break;
          a4 = EDGE_STACK[--i2];
        }
      }
      return ar;
    }
    _link(a4, b3) {
      this._halfedges[a4] = b3;
      if (b3 !== -1) this._halfedges[b3] = a4;
    }
    // add a new triangle given vertex indices and adjacent half-edge ids
    _addTriangle(i0, i1, i2, a4, b3, c4) {
      const t4 = this.trianglesLen;
      this._triangles[t4] = i0;
      this._triangles[t4 + 1] = i1;
      this._triangles[t4 + 2] = i2;
      this._link(t4, a4);
      this._link(t4 + 1, b3);
      this._link(t4 + 2, c4);
      this.trianglesLen += 3;
      return t4;
    }
  };
  function pseudoAngle(dx, dy) {
    const p2 = dx / (Math.abs(dx) + Math.abs(dy));
    return (dy > 0 ? 3 - p2 : 1 + p2) / 4;
  }
  function dist(ax, ay, bx, by) {
    const dx = ax - bx;
    const dy = ay - by;
    return dx * dx + dy * dy;
  }
  function inCircle(ax, ay, bx, by, cx, cy, px2, py2) {
    const dx = ax - px2;
    const dy = ay - py2;
    const ex = bx - px2;
    const ey = by - py2;
    const fx = cx - px2;
    const fy = cy - py2;
    const ap = dx * dx + dy * dy;
    const bp = ex * ex + ey * ey;
    const cp = fx * fx + fy * fy;
    return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0;
  }
  function circumradius(ax, ay, bx, by, cx, cy) {
    const dx = bx - ax;
    const dy = by - ay;
    const ex = cx - ax;
    const ey = cy - ay;
    const bl2 = dx * dx + dy * dy;
    const cl = ex * ex + ey * ey;
    const d2 = 0.5 / (dx * ey - dy * ex);
    const x5 = (ey * bl2 - dy * cl) * d2;
    const y5 = (dx * cl - ex * bl2) * d2;
    return x5 * x5 + y5 * y5;
  }
  function circumcenter(ax, ay, bx, by, cx, cy) {
    const dx = bx - ax;
    const dy = by - ay;
    const ex = cx - ax;
    const ey = cy - ay;
    const bl2 = dx * dx + dy * dy;
    const cl = ex * ex + ey * ey;
    const d2 = 0.5 / (dx * ey - dy * ex);
    const x5 = ax + (ey * bl2 - dy * cl) * d2;
    const y5 = ay + (dx * cl - ex * bl2) * d2;
    return { x: x5, y: y5 };
  }
  function quicksort(ids, dists, left, right) {
    if (right - left <= 20) {
      for (let i2 = left + 1; i2 <= right; i2++) {
        const temp2 = ids[i2];
        const tempDist = dists[temp2];
        let j2 = i2 - 1;
        while (j2 >= left && dists[ids[j2]] > tempDist) ids[j2 + 1] = ids[j2--];
        ids[j2 + 1] = temp2;
      }
    } else {
      const median2 = left + right >> 1;
      let i2 = left + 1;
      let j2 = right;
      swap2(ids, median2, i2);
      if (dists[ids[left]] > dists[ids[right]]) swap2(ids, left, right);
      if (dists[ids[i2]] > dists[ids[right]]) swap2(ids, i2, right);
      if (dists[ids[left]] > dists[ids[i2]]) swap2(ids, left, i2);
      const temp2 = ids[i2];
      const tempDist = dists[temp2];
      while (true) {
        do
          i2++;
        while (dists[ids[i2]] < tempDist);
        do
          j2--;
        while (dists[ids[j2]] > tempDist);
        if (j2 < i2) break;
        swap2(ids, i2, j2);
      }
      ids[left + 1] = ids[j2];
      ids[j2] = temp2;
      if (right - i2 + 1 >= j2 - left) {
        quicksort(ids, dists, i2, right);
        quicksort(ids, dists, left, j2 - 1);
      } else {
        quicksort(ids, dists, left, j2 - 1);
        quicksort(ids, dists, i2, right);
      }
    }
  }
  function swap2(arr, i2, j2) {
    const tmp = arr[i2];
    arr[i2] = arr[j2];
    arr[j2] = tmp;
  }
  function defaultGetX(p2) {
    return p2[0];
  }
  function defaultGetY(p2) {
    return p2[1];
  }

  // node_modules/d3-delaunay/src/path.js
  var epsilon7 = 1e-6;
  var Path2 = class {
    constructor() {
      this._x0 = this._y0 = // start of current subpath
      this._x1 = this._y1 = null;
      this._ = "";
    }
    moveTo(x5, y5) {
      this._ += `M${this._x0 = this._x1 = +x5},${this._y0 = this._y1 = +y5}`;
    }
    closePath() {
      if (this._x1 !== null) {
        this._x1 = this._x0, this._y1 = this._y0;
        this._ += "Z";
      }
    }
    lineTo(x5, y5) {
      this._ += `L${this._x1 = +x5},${this._y1 = +y5}`;
    }
    arc(x5, y5, r2) {
      x5 = +x5, y5 = +y5, r2 = +r2;
      const x06 = x5 + r2;
      const y06 = y5;
      if (r2 < 0) throw new Error("negative radius");
      if (this._x1 === null) this._ += `M${x06},${y06}`;
      else if (Math.abs(this._x1 - x06) > epsilon7 || Math.abs(this._y1 - y06) > epsilon7) this._ += "L" + x06 + "," + y06;
      if (!r2) return;
      this._ += `A${r2},${r2},0,1,1,${x5 - r2},${y5}A${r2},${r2},0,1,1,${this._x1 = x06},${this._y1 = y06}`;
    }
    rect(x5, y5, w3, h3) {
      this._ += `M${this._x0 = this._x1 = +x5},${this._y0 = this._y1 = +y5}h${+w3}v${+h3}h${-w3}Z`;
    }
    value() {
      return this._ || null;
    }
  };

  // node_modules/d3-delaunay/src/polygon.js
  var Polygon = class {
    constructor() {
      this._ = [];
    }
    moveTo(x5, y5) {
      this._.push([x5, y5]);
    }
    closePath() {
      this._.push(this._[0].slice());
    }
    lineTo(x5, y5) {
      this._.push([x5, y5]);
    }
    value() {
      return this._.length ? this._ : null;
    }
  };

  // node_modules/d3-delaunay/src/voronoi.js
  var Voronoi = class {
    constructor(delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {
      if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error("invalid bounds");
      this.delaunay = delaunay;
      this._circumcenters = new Float64Array(delaunay.points.length * 2);
      this.vectors = new Float64Array(delaunay.points.length * 2);
      this.xmax = xmax, this.xmin = xmin;
      this.ymax = ymax, this.ymin = ymin;
      this._init();
    }
    update() {
      this.delaunay.update();
      this._init();
      return this;
    }
    _init() {
      const { delaunay: { points: points2, hull, triangles }, vectors } = this;
      let bx, by;
      const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
      for (let i2 = 0, j2 = 0, n2 = triangles.length, x5, y5; i2 < n2; i2 += 3, j2 += 2) {
        const t13 = triangles[i2] * 2;
        const t22 = triangles[i2 + 1] * 2;
        const t32 = triangles[i2 + 2] * 2;
        const x13 = points2[t13];
        const y13 = points2[t13 + 1];
        const x22 = points2[t22];
        const y22 = points2[t22 + 1];
        const x32 = points2[t32];
        const y32 = points2[t32 + 1];
        const dx = x22 - x13;
        const dy = y22 - y13;
        const ex = x32 - x13;
        const ey = y32 - y13;
        const ab4 = (dx * ey - dy * ex) * 2;
        if (Math.abs(ab4) < 1e-9) {
          if (bx === void 0) {
            bx = by = 0;
            for (const i3 of hull) bx += points2[i3 * 2], by += points2[i3 * 2 + 1];
            bx /= hull.length, by /= hull.length;
          }
          const a4 = 1e9 * Math.sign((bx - x13) * ey - (by - y13) * ex);
          x5 = (x13 + x32) / 2 - a4 * ey;
          y5 = (y13 + y32) / 2 + a4 * ex;
        } else {
          const d2 = 1 / ab4;
          const bl2 = dx * dx + dy * dy;
          const cl = ex * ex + ey * ey;
          x5 = x13 + (ey * bl2 - dy * cl) * d2;
          y5 = y13 + (dx * cl - ex * bl2) * d2;
        }
        circumcenters[j2] = x5;
        circumcenters[j2 + 1] = y5;
      }
      let h3 = hull[hull.length - 1];
      let p02, p1 = h3 * 4;
      let x06, x12 = points2[2 * h3];
      let y06, y12 = points2[2 * h3 + 1];
      vectors.fill(0);
      for (let i2 = 0; i2 < hull.length; ++i2) {
        h3 = hull[i2];
        p02 = p1, x06 = x12, y06 = y12;
        p1 = h3 * 4, x12 = points2[2 * h3], y12 = points2[2 * h3 + 1];
        vectors[p02 + 2] = vectors[p1] = y06 - y12;
        vectors[p02 + 3] = vectors[p1 + 1] = x12 - x06;
      }
    }
    render(context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const { delaunay: { halfedges, inedges, hull }, circumcenters, vectors } = this;
      if (hull.length <= 1) return null;
      for (let i2 = 0, n2 = halfedges.length; i2 < n2; ++i2) {
        const j2 = halfedges[i2];
        if (j2 < i2) continue;
        const ti = Math.floor(i2 / 3) * 2;
        const tj = Math.floor(j2 / 3) * 2;
        const xi = circumcenters[ti];
        const yi = circumcenters[ti + 1];
        const xj = circumcenters[tj];
        const yj = circumcenters[tj + 1];
        this._renderSegment(xi, yi, xj, yj, context3);
      }
      let h0, h1 = hull[hull.length - 1];
      for (let i2 = 0; i2 < hull.length; ++i2) {
        h0 = h1, h1 = hull[i2];
        const t4 = Math.floor(inedges[h1] / 3) * 2;
        const x5 = circumcenters[t4];
        const y5 = circumcenters[t4 + 1];
        const v3 = h0 * 4;
        const p2 = this._project(x5, y5, vectors[v3 + 2], vectors[v3 + 3]);
        if (p2) this._renderSegment(x5, y5, p2[0], p2[1], context3);
      }
      return buffer && buffer.value();
    }
    renderBounds(context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      context3.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);
      return buffer && buffer.value();
    }
    renderCell(i2, context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const points2 = this._clip(i2);
      if (points2 === null || !points2.length) return;
      context3.moveTo(points2[0], points2[1]);
      let n2 = points2.length;
      while (points2[0] === points2[n2 - 2] && points2[1] === points2[n2 - 1] && n2 > 1) n2 -= 2;
      for (let i3 = 2; i3 < n2; i3 += 2) {
        if (points2[i3] !== points2[i3 - 2] || points2[i3 + 1] !== points2[i3 - 1])
          context3.lineTo(points2[i3], points2[i3 + 1]);
      }
      context3.closePath();
      return buffer && buffer.value();
    }
    *cellPolygons() {
      const { delaunay: { points: points2 } } = this;
      for (let i2 = 0, n2 = points2.length / 2; i2 < n2; ++i2) {
        const cell2 = this.cellPolygon(i2);
        if (cell2) cell2.index = i2, yield cell2;
      }
    }
    cellPolygon(i2) {
      const polygon = new Polygon();
      this.renderCell(i2, polygon);
      return polygon.value();
    }
    _renderSegment(x06, y06, x12, y12, context3) {
      let S;
      const c0 = this._regioncode(x06, y06);
      const c1 = this._regioncode(x12, y12);
      if (c0 === 0 && c1 === 0) {
        context3.moveTo(x06, y06);
        context3.lineTo(x12, y12);
      } else if (S = this._clipSegment(x06, y06, x12, y12, c0, c1)) {
        context3.moveTo(S[0], S[1]);
        context3.lineTo(S[2], S[3]);
      }
    }
    contains(i2, x5, y5) {
      if ((x5 = +x5, x5 !== x5) || (y5 = +y5, y5 !== y5)) return false;
      return this.delaunay._step(i2, x5, y5) === i2;
    }
    *neighbors(i2) {
      const ci = this._clip(i2);
      if (ci) for (const j2 of this.delaunay.neighbors(i2)) {
        const cj = this._clip(j2);
        if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {
          for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {
            if (ci[ai] === cj[aj] && ci[ai + 1] === cj[aj + 1] && ci[(ai + 2) % li] === cj[(aj + lj - 2) % lj] && ci[(ai + 3) % li] === cj[(aj + lj - 1) % lj]) {
              yield j2;
              break loop;
            }
          }
        }
      }
    }
    _cell(i2) {
      const { circumcenters, delaunay: { inedges, halfedges, triangles } } = this;
      const e0 = inedges[i2];
      if (e0 === -1) return null;
      const points2 = [];
      let e4 = e0;
      do {
        const t4 = Math.floor(e4 / 3);
        points2.push(circumcenters[t4 * 2], circumcenters[t4 * 2 + 1]);
        e4 = e4 % 3 === 2 ? e4 - 2 : e4 + 1;
        if (triangles[e4] !== i2) break;
        e4 = halfedges[e4];
      } while (e4 !== e0 && e4 !== -1);
      return points2;
    }
    _clip(i2) {
      if (i2 === 0 && this.delaunay.hull.length === 1) {
        return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
      }
      const points2 = this._cell(i2);
      if (points2 === null) return null;
      const { vectors: V } = this;
      const v3 = i2 * 4;
      return this._simplify(V[v3] || V[v3 + 1] ? this._clipInfinite(i2, points2, V[v3], V[v3 + 1], V[v3 + 2], V[v3 + 3]) : this._clipFinite(i2, points2));
    }
    _clipFinite(i2, points2) {
      const n2 = points2.length;
      let P = null;
      let x06, y06, x12 = points2[n2 - 2], y12 = points2[n2 - 1];
      let c0, c1 = this._regioncode(x12, y12);
      let e0, e1 = 0;
      for (let j2 = 0; j2 < n2; j2 += 2) {
        x06 = x12, y06 = y12, x12 = points2[j2], y12 = points2[j2 + 1];
        c0 = c1, c1 = this._regioncode(x12, y12);
        if (c0 === 0 && c1 === 0) {
          e0 = e1, e1 = 0;
          if (P) P.push(x12, y12);
          else P = [x12, y12];
        } else {
          let S, sx0, sy0, sx1, sy1;
          if (c0 === 0) {
            if ((S = this._clipSegment(x06, y06, x12, y12, c0, c1)) === null) continue;
            [sx0, sy0, sx1, sy1] = S;
          } else {
            if ((S = this._clipSegment(x12, y12, x06, y06, c1, c0)) === null) continue;
            [sx1, sy1, sx0, sy0] = S;
            e0 = e1, e1 = this._edgecode(sx0, sy0);
            if (e0 && e1) this._edge(i2, e0, e1, P, P.length);
            if (P) P.push(sx0, sy0);
            else P = [sx0, sy0];
          }
          e0 = e1, e1 = this._edgecode(sx1, sy1);
          if (e0 && e1) this._edge(i2, e0, e1, P, P.length);
          if (P) P.push(sx1, sy1);
          else P = [sx1, sy1];
        }
      }
      if (P) {
        e0 = e1, e1 = this._edgecode(P[0], P[1]);
        if (e0 && e1) this._edge(i2, e0, e1, P, P.length);
      } else if (this.contains(i2, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
        return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];
      }
      return P;
    }
    _clipSegment(x06, y06, x12, y12, c0, c1) {
      const flip2 = c0 < c1;
      if (flip2) [x06, y06, x12, y12, c0, c1] = [x12, y12, x06, y06, c1, c0];
      while (true) {
        if (c0 === 0 && c1 === 0) return flip2 ? [x12, y12, x06, y06] : [x06, y06, x12, y12];
        if (c0 & c1) return null;
        let x5, y5, c4 = c0 || c1;
        if (c4 & 8) x5 = x06 + (x12 - x06) * (this.ymax - y06) / (y12 - y06), y5 = this.ymax;
        else if (c4 & 4) x5 = x06 + (x12 - x06) * (this.ymin - y06) / (y12 - y06), y5 = this.ymin;
        else if (c4 & 2) y5 = y06 + (y12 - y06) * (this.xmax - x06) / (x12 - x06), x5 = this.xmax;
        else y5 = y06 + (y12 - y06) * (this.xmin - x06) / (x12 - x06), x5 = this.xmin;
        if (c0) x06 = x5, y06 = y5, c0 = this._regioncode(x06, y06);
        else x12 = x5, y12 = y5, c1 = this._regioncode(x12, y12);
      }
    }
    _clipInfinite(i2, points2, vx0, vy0, vxn, vyn) {
      let P = Array.from(points2), p2;
      if (p2 = this._project(P[0], P[1], vx0, vy0)) P.unshift(p2[0], p2[1]);
      if (p2 = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p2[0], p2[1]);
      if (P = this._clipFinite(i2, P)) {
        for (let j2 = 0, n2 = P.length, c0, c1 = this._edgecode(P[n2 - 2], P[n2 - 1]); j2 < n2; j2 += 2) {
          c0 = c1, c1 = this._edgecode(P[j2], P[j2 + 1]);
          if (c0 && c1) j2 = this._edge(i2, c0, c1, P, j2), n2 = P.length;
        }
      } else if (this.contains(i2, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {
        P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];
      }
      return P;
    }
    _edge(i2, e0, e1, P, j2) {
      while (e0 !== e1) {
        let x5, y5;
        switch (e0) {
          case 5:
            e0 = 4;
            continue;
          // top-left
          case 4:
            e0 = 6, x5 = this.xmax, y5 = this.ymin;
            break;
          // top
          case 6:
            e0 = 2;
            continue;
          // top-right
          case 2:
            e0 = 10, x5 = this.xmax, y5 = this.ymax;
            break;
          // right
          case 10:
            e0 = 8;
            continue;
          // bottom-right
          case 8:
            e0 = 9, x5 = this.xmin, y5 = this.ymax;
            break;
          // bottom
          case 9:
            e0 = 1;
            continue;
          // bottom-left
          case 1:
            e0 = 5, x5 = this.xmin, y5 = this.ymin;
            break;
        }
        if ((P[j2] !== x5 || P[j2 + 1] !== y5) && this.contains(i2, x5, y5)) {
          P.splice(j2, 0, x5, y5), j2 += 2;
        }
      }
      return j2;
    }
    _project(x06, y06, vx, vy) {
      let t4 = Infinity, c4, x5, y5;
      if (vy < 0) {
        if (y06 <= this.ymin) return null;
        if ((c4 = (this.ymin - y06) / vy) < t4) y5 = this.ymin, x5 = x06 + (t4 = c4) * vx;
      } else if (vy > 0) {
        if (y06 >= this.ymax) return null;
        if ((c4 = (this.ymax - y06) / vy) < t4) y5 = this.ymax, x5 = x06 + (t4 = c4) * vx;
      }
      if (vx > 0) {
        if (x06 >= this.xmax) return null;
        if ((c4 = (this.xmax - x06) / vx) < t4) x5 = this.xmax, y5 = y06 + (t4 = c4) * vy;
      } else if (vx < 0) {
        if (x06 <= this.xmin) return null;
        if ((c4 = (this.xmin - x06) / vx) < t4) x5 = this.xmin, y5 = y06 + (t4 = c4) * vy;
      }
      return [x5, y5];
    }
    _edgecode(x5, y5) {
      return (x5 === this.xmin ? 1 : x5 === this.xmax ? 2 : 0) | (y5 === this.ymin ? 4 : y5 === this.ymax ? 8 : 0);
    }
    _regioncode(x5, y5) {
      return (x5 < this.xmin ? 1 : x5 > this.xmax ? 2 : 0) | (y5 < this.ymin ? 4 : y5 > this.ymax ? 8 : 0);
    }
    _simplify(P) {
      if (P && P.length > 4) {
        for (let i2 = 0; i2 < P.length; i2 += 2) {
          const j2 = (i2 + 2) % P.length, k2 = (i2 + 4) % P.length;
          if (P[i2] === P[j2] && P[j2] === P[k2] || P[i2 + 1] === P[j2 + 1] && P[j2 + 1] === P[k2 + 1]) {
            P.splice(j2, 2), i2 -= 2;
          }
        }
        if (!P.length) P = null;
      }
      return P;
    }
  };

  // node_modules/d3-delaunay/src/delaunay.js
  var tau5 = 2 * Math.PI;
  var pow5 = Math.pow;
  function pointX(p2) {
    return p2[0];
  }
  function pointY(p2) {
    return p2[1];
  }
  function collinear2(d2) {
    const { triangles, coords } = d2;
    for (let i2 = 0; i2 < triangles.length; i2 += 3) {
      const a4 = 2 * triangles[i2], b3 = 2 * triangles[i2 + 1], c4 = 2 * triangles[i2 + 2], cross2 = (coords[c4] - coords[a4]) * (coords[b3 + 1] - coords[a4 + 1]) - (coords[b3] - coords[a4]) * (coords[c4 + 1] - coords[a4 + 1]);
      if (cross2 > 1e-10) return false;
    }
    return true;
  }
  function jitter(x5, y5, r2) {
    return [x5 + Math.sin(x5 + y5) * r2, y5 + Math.cos(x5 - y5) * r2];
  }
  var Delaunay = class _Delaunay {
    static from(points2, fx = pointX, fy = pointY, that) {
      return new _Delaunay("length" in points2 ? flatArray(points2, fx, fy, that) : Float64Array.from(flatIterable(points2, fx, fy, that)));
    }
    constructor(points2) {
      this._delaunator = new Delaunator(points2);
      this.inedges = new Int32Array(points2.length / 2);
      this._hullIndex = new Int32Array(points2.length / 2);
      this.points = this._delaunator.coords;
      this._init();
    }
    update() {
      this._delaunator.update();
      this._init();
      return this;
    }
    _init() {
      const d2 = this._delaunator, points2 = this.points;
      if (d2.hull && d2.hull.length > 2 && collinear2(d2)) {
        this.collinear = Int32Array.from({ length: points2.length / 2 }, (_, i2) => i2).sort((i2, j2) => points2[2 * i2] - points2[2 * j2] || points2[2 * i2 + 1] - points2[2 * j2 + 1]);
        const e4 = this.collinear[0], f2 = this.collinear[this.collinear.length - 1], bounds2 = [points2[2 * e4], points2[2 * e4 + 1], points2[2 * f2], points2[2 * f2 + 1]], r2 = 1e-8 * Math.hypot(bounds2[3] - bounds2[1], bounds2[2] - bounds2[0]);
        for (let i2 = 0, n2 = points2.length / 2; i2 < n2; ++i2) {
          const p2 = jitter(points2[2 * i2], points2[2 * i2 + 1], r2);
          points2[2 * i2] = p2[0];
          points2[2 * i2 + 1] = p2[1];
        }
        this._delaunator = new Delaunator(points2);
      } else {
        delete this.collinear;
      }
      const halfedges = this.halfedges = this._delaunator.halfedges;
      const hull = this.hull = this._delaunator.hull;
      const triangles = this.triangles = this._delaunator.triangles;
      const inedges = this.inedges.fill(-1);
      const hullIndex = this._hullIndex.fill(-1);
      for (let e4 = 0, n2 = halfedges.length; e4 < n2; ++e4) {
        const p2 = triangles[e4 % 3 === 2 ? e4 - 2 : e4 + 1];
        if (halfedges[e4] === -1 || inedges[p2] === -1) inedges[p2] = e4;
      }
      for (let i2 = 0, n2 = hull.length; i2 < n2; ++i2) {
        hullIndex[hull[i2]] = i2;
      }
      if (hull.length <= 2 && hull.length > 0) {
        this.triangles = new Int32Array(3).fill(-1);
        this.halfedges = new Int32Array(3).fill(-1);
        this.triangles[0] = hull[0];
        inedges[hull[0]] = 1;
        if (hull.length === 2) {
          inedges[hull[1]] = 0;
          this.triangles[1] = hull[1];
          this.triangles[2] = hull[1];
        }
      }
    }
    voronoi(bounds2) {
      return new Voronoi(this, bounds2);
    }
    *neighbors(i2) {
      const { inedges, hull, _hullIndex, halfedges, triangles, collinear: collinear3 } = this;
      if (collinear3) {
        const l2 = collinear3.indexOf(i2);
        if (l2 > 0) yield collinear3[l2 - 1];
        if (l2 < collinear3.length - 1) yield collinear3[l2 + 1];
        return;
      }
      const e0 = inedges[i2];
      if (e0 === -1) return;
      let e4 = e0, p02 = -1;
      do {
        yield p02 = triangles[e4];
        e4 = e4 % 3 === 2 ? e4 - 2 : e4 + 1;
        if (triangles[e4] !== i2) return;
        e4 = halfedges[e4];
        if (e4 === -1) {
          const p2 = hull[(_hullIndex[i2] + 1) % hull.length];
          if (p2 !== p02) yield p2;
          return;
        }
      } while (e4 !== e0);
    }
    find(x5, y5, i2 = 0) {
      if ((x5 = +x5, x5 !== x5) || (y5 = +y5, y5 !== y5)) return -1;
      const i0 = i2;
      let c4;
      while ((c4 = this._step(i2, x5, y5)) >= 0 && c4 !== i2 && c4 !== i0) i2 = c4;
      return c4;
    }
    _step(i2, x5, y5) {
      const { inedges, hull, _hullIndex, halfedges, triangles, points: points2 } = this;
      if (inedges[i2] === -1 || !points2.length) return (i2 + 1) % (points2.length >> 1);
      let c4 = i2;
      let dc = pow5(x5 - points2[i2 * 2], 2) + pow5(y5 - points2[i2 * 2 + 1], 2);
      const e0 = inedges[i2];
      let e4 = e0;
      do {
        let t4 = triangles[e4];
        const dt = pow5(x5 - points2[t4 * 2], 2) + pow5(y5 - points2[t4 * 2 + 1], 2);
        if (dt < dc) dc = dt, c4 = t4;
        e4 = e4 % 3 === 2 ? e4 - 2 : e4 + 1;
        if (triangles[e4] !== i2) break;
        e4 = halfedges[e4];
        if (e4 === -1) {
          e4 = hull[(_hullIndex[i2] + 1) % hull.length];
          if (e4 !== t4) {
            if (pow5(x5 - points2[e4 * 2], 2) + pow5(y5 - points2[e4 * 2 + 1], 2) < dc) return e4;
          }
          break;
        }
      } while (e4 !== e0);
      return c4;
    }
    render(context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const { points: points2, halfedges, triangles } = this;
      for (let i2 = 0, n2 = halfedges.length; i2 < n2; ++i2) {
        const j2 = halfedges[i2];
        if (j2 < i2) continue;
        const ti = triangles[i2] * 2;
        const tj = triangles[j2] * 2;
        context3.moveTo(points2[ti], points2[ti + 1]);
        context3.lineTo(points2[tj], points2[tj + 1]);
      }
      this.renderHull(context3);
      return buffer && buffer.value();
    }
    renderPoints(context3, r2) {
      if (r2 === void 0 && (!context3 || typeof context3.moveTo !== "function")) r2 = context3, context3 = null;
      r2 = r2 == void 0 ? 2 : +r2;
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const { points: points2 } = this;
      for (let i2 = 0, n2 = points2.length; i2 < n2; i2 += 2) {
        const x5 = points2[i2], y5 = points2[i2 + 1];
        context3.moveTo(x5 + r2, y5);
        context3.arc(x5, y5, r2, 0, tau5);
      }
      return buffer && buffer.value();
    }
    renderHull(context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const { hull, points: points2 } = this;
      const h3 = hull[0] * 2, n2 = hull.length;
      context3.moveTo(points2[h3], points2[h3 + 1]);
      for (let i2 = 1; i2 < n2; ++i2) {
        const h4 = 2 * hull[i2];
        context3.lineTo(points2[h4], points2[h4 + 1]);
      }
      context3.closePath();
      return buffer && buffer.value();
    }
    hullPolygon() {
      const polygon = new Polygon();
      this.renderHull(polygon);
      return polygon.value();
    }
    renderTriangle(i2, context3) {
      const buffer = context3 == null ? context3 = new Path2() : void 0;
      const { points: points2, triangles } = this;
      const t04 = triangles[i2 *= 3] * 2;
      const t13 = triangles[i2 + 1] * 2;
      const t22 = triangles[i2 + 2] * 2;
      context3.moveTo(points2[t04], points2[t04 + 1]);
      context3.lineTo(points2[t13], points2[t13 + 1]);
      context3.lineTo(points2[t22], points2[t22 + 1]);
      context3.closePath();
      return buffer && buffer.value();
    }
    *trianglePolygons() {
      const { triangles } = this;
      for (let i2 = 0, n2 = triangles.length / 3; i2 < n2; ++i2) {
        yield this.trianglePolygon(i2);
      }
    }
    trianglePolygon(i2) {
      const polygon = new Polygon();
      this.renderTriangle(i2, polygon);
      return polygon.value();
    }
  };
  function flatArray(points2, fx, fy, that) {
    const n2 = points2.length;
    const array4 = new Float64Array(n2 * 2);
    for (let i2 = 0; i2 < n2; ++i2) {
      const p2 = points2[i2];
      array4[i2 * 2] = fx.call(that, p2, i2, points2);
      array4[i2 * 2 + 1] = fy.call(that, p2, i2, points2);
    }
    return array4;
  }
  function* flatIterable(points2, fx, fy, that) {
    let i2 = 0;
    for (const p2 of points2) {
      yield fx.call(that, p2, i2, points2);
      yield fy.call(that, p2, i2, points2);
      ++i2;
    }
  }

  // node_modules/vega-voronoi/build/vega-voronoi.module.js
  function Voronoi2(params2) {
    Transform.call(this, null, params2);
  }
  Voronoi2.Definition = {
    "type": "Voronoi",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "x",
      "type": "field",
      "required": true
    }, {
      "name": "y",
      "type": "field",
      "required": true
    }, {
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "extent",
      "type": "array",
      "array": true,
      "length": 2,
      "default": [[-1e5, -1e5], [1e5, 1e5]],
      "content": {
        "type": "number",
        "array": true,
        "length": 2
      }
    }, {
      "name": "as",
      "type": "string",
      "default": "path"
    }]
  };
  var defaultExtent = [-1e5, -1e5, 1e5, 1e5];
  inherits(Voronoi2, Transform, {
    transform(_, pulse2) {
      const as = _.as || "path", data3 = pulse2.source;
      if (!data3 || !data3.length) return pulse2;
      let s2 = _.size;
      s2 = s2 ? [0, 0, s2[0], s2[1]] : (s2 = _.extent) ? [s2[0][0], s2[0][1], s2[1][0], s2[1][1]] : defaultExtent;
      const voronoi = this.value = Delaunay.from(data3, _.x, _.y).voronoi(s2);
      for (let i2 = 0, n2 = data3.length; i2 < n2; ++i2) {
        const polygon = voronoi.cellPolygon(i2);
        data3[i2][as] = polygon && !isPoint(polygon) ? toPathString(polygon) : null;
      }
      return pulse2.reflow(_.modified()).modifies(as);
    }
  });
  function toPathString(p2) {
    const x5 = p2[0][0], y5 = p2[0][1];
    let n2 = p2.length - 1;
    for (; p2[n2][0] === x5 && p2[n2][1] === y5; --n2) ;
    return "M" + p2.slice(0, n2 + 1).join("L") + "Z";
  }
  function isPoint(p2) {
    return p2.length === 2 && p2[0][0] === p2[1][0] && p2[0][1] === p2[1][1];
  }

  // node_modules/vega-wordcloud/build/vega-wordcloud.module.js
  var vega_wordcloud_module_exports = {};
  __export(vega_wordcloud_module_exports, {
    wordcloud: () => Wordcloud
  });
  var cloudRadians = Math.PI / 180;
  var cw = 1 << 11 >> 5;
  var ch = 1 << 11;
  function cloud() {
    var size = [256, 256], text4, font3, fontSize2, fontStyle, fontWeight2, rotate2, padding3, spiral = archimedeanSpiral, words = [], random2 = Math.random, cloud2 = {};
    cloud2.layout = function() {
      var contextAndRatio = getContext2(domCanvas()), board = zeroArray((size[0] >> 5) * size[1]), bounds2 = null, n2 = words.length, i2 = -1, tags = [], data3 = words.map((d3) => ({
        text: text4(d3),
        font: font3(d3),
        style: fontStyle(d3),
        weight: fontWeight2(d3),
        rotate: rotate2(d3),
        size: ~~(fontSize2(d3) + 1e-14),
        padding: padding3(d3),
        xoff: 0,
        yoff: 0,
        x1: 0,
        y1: 0,
        x0: 0,
        y0: 0,
        hasText: false,
        sprite: null,
        datum: d3
      })).sort((a4, b3) => b3.size - a4.size);
      while (++i2 < n2) {
        var d2 = data3[i2];
        d2.x = size[0] * (random2() + 0.5) >> 1;
        d2.y = size[1] * (random2() + 0.5) >> 1;
        cloudSprite(contextAndRatio, d2, data3, i2);
        if (d2.hasText && place2(board, d2, bounds2)) {
          tags.push(d2);
          if (bounds2) cloudBounds(bounds2, d2);
          else bounds2 = [{
            x: d2.x + d2.x0,
            y: d2.y + d2.y0
          }, {
            x: d2.x + d2.x1,
            y: d2.y + d2.y1
          }];
          d2.x -= size[0] >> 1;
          d2.y -= size[1] >> 1;
        }
      }
      return tags;
    };
    function getContext2(canvas) {
      canvas.width = canvas.height = 1;
      var ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
      canvas.width = (cw << 5) / ratio;
      canvas.height = ch / ratio;
      var context3 = canvas.getContext("2d");
      context3.fillStyle = context3.strokeStyle = "red";
      context3.textAlign = "center";
      return {
        context: context3,
        ratio
      };
    }
    function place2(board, tag, bounds2) {
      var startX = tag.x, startY = tag.y, maxDelta = Math.hypot(size[0], size[1]), s2 = spiral(size), dt = random2() < 0.5 ? 1 : -1, t4 = -dt, dxdy, dx, dy;
      while (dxdy = s2(t4 += dt)) {
        dx = ~~dxdy[0];
        dy = ~~dxdy[1];
        if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
        tag.x = startX + dx;
        tag.y = startY + dy;
        if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
        if (!bounds2 || !cloudCollide(tag, board, size[0])) {
          if (!bounds2 || collideRects(tag, bounds2)) {
            var sprite = tag.sprite, w3 = tag.width >> 5, sw = size[0] >> 5, lx2 = tag.x - (w3 << 4), sx = lx2 & 127, msx = 32 - sx, h3 = tag.y1 - tag.y0, x5 = (tag.y + tag.y0) * sw + (lx2 >> 5), last;
            for (var j2 = 0; j2 < h3; j2++) {
              last = 0;
              for (var i2 = 0; i2 <= w3; i2++) {
                board[x5 + i2] |= last << msx | (i2 < w3 ? (last = sprite[j2 * w3 + i2]) >>> sx : 0);
              }
              x5 += sw;
            }
            tag.sprite = null;
            return true;
          }
        }
      }
      return false;
    }
    cloud2.words = function(_) {
      if (arguments.length) {
        words = _;
        return cloud2;
      } else {
        return words;
      }
    };
    cloud2.size = function(_) {
      if (arguments.length) {
        size = [+_[0], +_[1]];
        return cloud2;
      } else {
        return size;
      }
    };
    cloud2.font = function(_) {
      if (arguments.length) {
        font3 = functor(_);
        return cloud2;
      } else {
        return font3;
      }
    };
    cloud2.fontStyle = function(_) {
      if (arguments.length) {
        fontStyle = functor(_);
        return cloud2;
      } else {
        return fontStyle;
      }
    };
    cloud2.fontWeight = function(_) {
      if (arguments.length) {
        fontWeight2 = functor(_);
        return cloud2;
      } else {
        return fontWeight2;
      }
    };
    cloud2.rotate = function(_) {
      if (arguments.length) {
        rotate2 = functor(_);
        return cloud2;
      } else {
        return rotate2;
      }
    };
    cloud2.text = function(_) {
      if (arguments.length) {
        text4 = functor(_);
        return cloud2;
      } else {
        return text4;
      }
    };
    cloud2.spiral = function(_) {
      if (arguments.length) {
        spiral = spirals[_] || _;
        return cloud2;
      } else {
        return spiral;
      }
    };
    cloud2.fontSize = function(_) {
      if (arguments.length) {
        fontSize2 = functor(_);
        return cloud2;
      } else {
        return fontSize2;
      }
    };
    cloud2.padding = function(_) {
      if (arguments.length) {
        padding3 = functor(_);
        return cloud2;
      } else {
        return padding3;
      }
    };
    cloud2.random = function(_) {
      if (arguments.length) {
        random2 = _;
        return cloud2;
      } else {
        return random2;
      }
    };
    return cloud2;
  }
  function cloudSprite(contextAndRatio, d2, data3, di) {
    if (d2.sprite) return;
    var c4 = contextAndRatio.context, ratio = contextAndRatio.ratio;
    c4.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
    var x5 = 0, y5 = 0, maxh = 0, n2 = data3.length, w3, w32, h3, i2, j2;
    --di;
    while (++di < n2) {
      d2 = data3[di];
      c4.save();
      c4.font = d2.style + " " + d2.weight + " " + ~~((d2.size + 1) / ratio) + "px " + d2.font;
      w3 = c4.measureText(d2.text + "m").width * ratio;
      h3 = d2.size << 1;
      if (d2.rotate) {
        var sr = Math.sin(d2.rotate * cloudRadians), cr2 = Math.cos(d2.rotate * cloudRadians), wcr = w3 * cr2, wsr = w3 * sr, hcr = h3 * cr2, hsr = h3 * sr;
        w3 = Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 31 >> 5 << 5;
        h3 = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
      } else {
        w3 = w3 + 31 >> 5 << 5;
      }
      if (h3 > maxh) maxh = h3;
      if (x5 + w3 >= cw << 5) {
        x5 = 0;
        y5 += maxh;
        maxh = 0;
      }
      if (y5 + h3 >= ch) break;
      c4.translate((x5 + (w3 >> 1)) / ratio, (y5 + (h3 >> 1)) / ratio);
      if (d2.rotate) c4.rotate(d2.rotate * cloudRadians);
      c4.fillText(d2.text, 0, 0);
      if (d2.padding) {
        c4.lineWidth = 2 * d2.padding;
        c4.strokeText(d2.text, 0, 0);
      }
      c4.restore();
      d2.width = w3;
      d2.height = h3;
      d2.xoff = x5;
      d2.yoff = y5;
      d2.x1 = w3 >> 1;
      d2.y1 = h3 >> 1;
      d2.x0 = -d2.x1;
      d2.y0 = -d2.y1;
      d2.hasText = true;
      x5 += w3;
    }
    var pixels = c4.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data, sprite = [];
    while (--di >= 0) {
      d2 = data3[di];
      if (!d2.hasText) continue;
      w3 = d2.width;
      w32 = w3 >> 5;
      h3 = d2.y1 - d2.y0;
      for (i2 = 0; i2 < h3 * w32; i2++) sprite[i2] = 0;
      x5 = d2.xoff;
      if (x5 == null) return;
      y5 = d2.yoff;
      var seen = 0, seenRow = -1;
      for (j2 = 0; j2 < h3; j2++) {
        for (i2 = 0; i2 < w3; i2++) {
          var k2 = w32 * j2 + (i2 >> 5), m4 = pixels[(y5 + j2) * (cw << 5) + (x5 + i2) << 2] ? 1 << 31 - i2 % 32 : 0;
          sprite[k2] |= m4;
          seen |= m4;
        }
        if (seen) seenRow = j2;
        else {
          d2.y0++;
          h3--;
          j2--;
          y5++;
        }
      }
      d2.y1 = d2.y0 + seenRow;
      d2.sprite = sprite.slice(0, (d2.y1 - d2.y0) * w32);
    }
  }
  function cloudCollide(tag, board, sw) {
    sw >>= 5;
    var sprite = tag.sprite, w3 = tag.width >> 5, lx2 = tag.x - (w3 << 4), sx = lx2 & 127, msx = 32 - sx, h3 = tag.y1 - tag.y0, x5 = (tag.y + tag.y0) * sw + (lx2 >> 5), last;
    for (var j2 = 0; j2 < h3; j2++) {
      last = 0;
      for (var i2 = 0; i2 <= w3; i2++) {
        if ((last << msx | (i2 < w3 ? (last = sprite[j2 * w3 + i2]) >>> sx : 0)) & board[x5 + i2]) return true;
      }
      x5 += sw;
    }
    return false;
  }
  function cloudBounds(bounds2, d2) {
    var b0 = bounds2[0], b1 = bounds2[1];
    if (d2.x + d2.x0 < b0.x) b0.x = d2.x + d2.x0;
    if (d2.y + d2.y0 < b0.y) b0.y = d2.y + d2.y0;
    if (d2.x + d2.x1 > b1.x) b1.x = d2.x + d2.x1;
    if (d2.y + d2.y1 > b1.y) b1.y = d2.y + d2.y1;
  }
  function collideRects(a4, b3) {
    return a4.x + a4.x1 > b3[0].x && a4.x + a4.x0 < b3[1].x && a4.y + a4.y1 > b3[0].y && a4.y + a4.y0 < b3[1].y;
  }
  function archimedeanSpiral(size) {
    var e4 = size[0] / size[1];
    return function(t4) {
      return [e4 * (t4 *= 0.1) * Math.cos(t4), t4 * Math.sin(t4)];
    };
  }
  function rectangularSpiral(size) {
    var dy = 4, dx = dy * size[0] / size[1], x5 = 0, y5 = 0;
    return function(t4) {
      var sign3 = t4 < 0 ? -1 : 1;
      switch (Math.sqrt(1 + 4 * sign3 * t4) - sign3 & 3) {
        case 0:
          x5 += dx;
          break;
        case 1:
          y5 += dy;
          break;
        case 2:
          x5 -= dx;
          break;
        default:
          y5 -= dy;
          break;
      }
      return [x5, y5];
    };
  }
  function zeroArray(n2) {
    var a4 = [], i2 = -1;
    while (++i2 < n2) a4[i2] = 0;
    return a4;
  }
  function functor(d2) {
    return typeof d2 === "function" ? d2 : function() {
      return d2;
    };
  }
  var spirals = {
    archimedean: archimedeanSpiral,
    rectangular: rectangularSpiral
  };
  var Output4 = ["x", "y", "font", "fontSize", "fontStyle", "fontWeight", "angle"];
  var Params2 = ["text", "font", "rotate", "fontSize", "fontStyle", "fontWeight"];
  function Wordcloud(params2) {
    Transform.call(this, cloud(), params2);
  }
  Wordcloud.Definition = {
    "type": "Wordcloud",
    "metadata": {
      "modifies": true
    },
    "params": [{
      "name": "size",
      "type": "number",
      "array": true,
      "length": 2
    }, {
      "name": "font",
      "type": "string",
      "expr": true,
      "default": "sans-serif"
    }, {
      "name": "fontStyle",
      "type": "string",
      "expr": true,
      "default": "normal"
    }, {
      "name": "fontWeight",
      "type": "string",
      "expr": true,
      "default": "normal"
    }, {
      "name": "fontSize",
      "type": "number",
      "expr": true,
      "default": 14
    }, {
      "name": "fontSizeRange",
      "type": "number",
      "array": "nullable",
      "default": [10, 50]
    }, {
      "name": "rotate",
      "type": "number",
      "expr": true,
      "default": 0
    }, {
      "name": "text",
      "type": "field"
    }, {
      "name": "spiral",
      "type": "string",
      "values": ["archimedean", "rectangular"]
    }, {
      "name": "padding",
      "type": "number",
      "expr": true
    }, {
      "name": "as",
      "type": "string",
      "array": true,
      "length": 7,
      "default": Output4
    }]
  };
  inherits(Wordcloud, Transform, {
    transform(_, pulse2) {
      if (_.size && !(_.size[0] && _.size[1])) {
        error("Wordcloud size dimensions must be non-zero.");
      }
      function modp(param2) {
        const p2 = _[param2];
        return isFunction(p2) && pulse2.modified(p2.fields);
      }
      const mod = _.modified();
      if (!(mod || pulse2.changed(pulse2.ADD_REM) || Params2.some(modp))) return;
      const data3 = pulse2.materialize(pulse2.SOURCE).source, layout = this.value, as = _.as || Output4;
      let fontSize2 = _.fontSize || 14, range7;
      isFunction(fontSize2) ? range7 = _.fontSizeRange : fontSize2 = constant(fontSize2);
      if (range7) {
        const fsize = fontSize2, sizeScale = scale("sqrt")().domain(extent(data3, fsize)).range(range7);
        fontSize2 = (x5) => sizeScale(fsize(x5));
      }
      data3.forEach((t4) => {
        t4[as[0]] = NaN;
        t4[as[1]] = NaN;
        t4[as[3]] = 0;
      });
      const words = layout.words(data3).text(_.text).size(_.size || [500, 500]).padding(_.padding || 1).spiral(_.spiral || "archimedean").rotate(_.rotate || 0).font(_.font || "sans-serif").fontStyle(_.fontStyle || "normal").fontWeight(_.fontWeight || "normal").fontSize(fontSize2).random(random).layout();
      const size = layout.size(), dx = size[0] >> 1, dy = size[1] >> 1, n2 = words.length;
      for (let i2 = 0, w3, t4; i2 < n2; ++i2) {
        w3 = words[i2];
        t4 = w3.datum;
        t4[as[0]] = w3.x + dx;
        t4[as[1]] = w3.y + dy;
        t4[as[2]] = w3.font;
        t4[as[3]] = w3.size;
        t4[as[4]] = w3.style;
        t4[as[5]] = w3.weight;
        t4[as[6]] = w3.rotate;
      }
      return pulse2.reflow(mod).modifies(as);
    }
  });

  // node_modules/vega-crossfilter/build/vega-crossfilter.module.js
  var vega_crossfilter_module_exports = {};
  __export(vega_crossfilter_module_exports, {
    crossfilter: () => CrossFilter,
    resolvefilter: () => ResolveFilter
  });
  var array8 = (n2) => new Uint8Array(n2);
  var array16 = (n2) => new Uint16Array(n2);
  var array32 = (n2) => new Uint32Array(n2);
  function Bitmaps() {
    let width2 = 8, data3 = [], seen = array32(0), curr = array2(0, width2), prev = array2(0, width2);
    return {
      data: () => data3,
      seen: () => seen = lengthen(seen, data3.length),
      add(array4) {
        for (let i2 = 0, j2 = data3.length, n2 = array4.length, t4; i2 < n2; ++i2) {
          t4 = array4[i2];
          t4._index = j2++;
          data3.push(t4);
        }
      },
      remove(num, map4) {
        const n2 = data3.length, copy4 = Array(n2 - num), reindex = data3;
        let t4, i2, j2;
        for (i2 = 0; !map4[i2] && i2 < n2; ++i2) {
          copy4[i2] = data3[i2];
          reindex[i2] = i2;
        }
        for (j2 = i2; i2 < n2; ++i2) {
          t4 = data3[i2];
          if (!map4[i2]) {
            reindex[i2] = j2;
            curr[j2] = curr[i2];
            prev[j2] = prev[i2];
            copy4[j2] = t4;
            t4._index = j2++;
          } else {
            reindex[i2] = -1;
          }
          curr[i2] = 0;
        }
        data3 = copy4;
        return reindex;
      },
      size: () => data3.length,
      curr: () => curr,
      prev: () => prev,
      reset: (k2) => prev[k2] = curr[k2],
      all: () => width2 < 257 ? 255 : width2 < 65537 ? 65535 : 4294967295,
      set(k2, one4) {
        curr[k2] |= one4;
      },
      clear(k2, one4) {
        curr[k2] &= ~one4;
      },
      resize(n2, m4) {
        const k2 = curr.length;
        if (n2 > k2 || m4 > width2) {
          width2 = Math.max(m4, width2);
          curr = array2(n2, width2, curr);
          prev = array2(n2, width2);
        }
      }
    };
  }
  function lengthen(array4, length3, copy4) {
    if (array4.length >= length3) return array4;
    copy4 = copy4 || new array4.constructor(length3);
    copy4.set(array4);
    return copy4;
  }
  function array2(n2, m4, array4) {
    const copy4 = (m4 < 257 ? array8 : m4 < 65537 ? array16 : array32)(n2);
    if (array4) copy4.set(array4);
    return copy4;
  }
  function Dimension(index4, i2, query) {
    const bit = 1 << i2;
    return {
      one: bit,
      zero: ~bit,
      range: query.slice(),
      bisect: index4.bisect,
      index: index4.index,
      size: index4.size,
      onAdd(added, curr) {
        const dim = this, range7 = dim.bisect(dim.range, added.value), idx = added.index, lo = range7[0], hi = range7[1], n1 = idx.length;
        let i3;
        for (i3 = 0; i3 < lo; ++i3) curr[idx[i3]] |= bit;
        for (i3 = hi; i3 < n1; ++i3) curr[idx[i3]] |= bit;
        return dim;
      }
    };
  }
  function SortedIndex() {
    let index4 = array32(0), value3 = [], size = 0;
    function insert2(key2, data3, base) {
      if (!data3.length) return [];
      const n0 = size, n1 = data3.length, addi = array32(n1);
      let addv = Array(n1), oldv, oldi, i2;
      for (i2 = 0; i2 < n1; ++i2) {
        addv[i2] = key2(data3[i2]);
        addi[i2] = i2;
      }
      addv = sort(addv, addi);
      if (n0) {
        oldv = value3;
        oldi = index4;
        value3 = Array(n0 + n1);
        index4 = array32(n0 + n1);
        merge3(base, oldv, oldi, n0, addv, addi, n1, value3, index4);
      } else {
        if (base > 0) for (i2 = 0; i2 < n1; ++i2) {
          addi[i2] += base;
        }
        value3 = addv;
        index4 = addi;
      }
      size = n0 + n1;
      return {
        index: addi,
        value: addv
      };
    }
    function remove2(num, map4) {
      const n2 = size;
      let idx, i2, j2;
      for (i2 = 0; !map4[index4[i2]] && i2 < n2; ++i2) ;
      for (j2 = i2; i2 < n2; ++i2) {
        if (!map4[idx = index4[i2]]) {
          index4[j2] = idx;
          value3[j2] = value3[i2];
          ++j2;
        }
      }
      size = n2 - num;
    }
    function reindex(map4) {
      for (let i2 = 0, n2 = size; i2 < n2; ++i2) {
        index4[i2] = map4[index4[i2]];
      }
    }
    function bisect2(range7, array4) {
      let n2;
      if (array4) {
        n2 = array4.length;
      } else {
        array4 = value3;
        n2 = size;
      }
      return [bisectLeft(array4, range7[0], 0, n2), bisectRight(array4, range7[1], 0, n2)];
    }
    return {
      insert: insert2,
      remove: remove2,
      bisect: bisect2,
      reindex,
      index: () => index4,
      size: () => size
    };
  }
  function sort(values4, index4) {
    values4.sort.call(index4, (a4, b3) => {
      const x5 = values4[a4], y5 = values4[b3];
      return x5 < y5 ? -1 : x5 > y5 ? 1 : 0;
    });
    return permute(values4, index4);
  }
  function merge3(base, value0, index0, n0, value1, index1, n1, value3, index4) {
    let i0 = 0, i1 = 0, i2;
    for (i2 = 0; i0 < n0 && i1 < n1; ++i2) {
      if (value0[i0] < value1[i1]) {
        value3[i2] = value0[i0];
        index4[i2] = index0[i0++];
      } else {
        value3[i2] = value1[i1];
        index4[i2] = index1[i1++] + base;
      }
    }
    for (; i0 < n0; ++i0, ++i2) {
      value3[i2] = value0[i0];
      index4[i2] = index0[i0];
    }
    for (; i1 < n1; ++i1, ++i2) {
      value3[i2] = value1[i1];
      index4[i2] = index1[i1] + base;
    }
  }
  function CrossFilter(params2) {
    Transform.call(this, Bitmaps(), params2);
    this._indices = null;
    this._dims = null;
  }
  CrossFilter.Definition = {
    "type": "CrossFilter",
    "metadata": {},
    "params": [{
      "name": "fields",
      "type": "field",
      "array": true,
      "required": true
    }, {
      "name": "query",
      "type": "array",
      "array": true,
      "required": true,
      "content": {
        "type": "number",
        "array": true,
        "length": 2
      }
    }]
  };
  inherits(CrossFilter, Transform, {
    transform(_, pulse2) {
      if (!this._dims) {
        return this.init(_, pulse2);
      } else {
        var init2 = _.modified("fields") || _.fields.some((f2) => pulse2.modified(f2.fields));
        return init2 ? this.reinit(_, pulse2) : this.eval(_, pulse2);
      }
    },
    init(_, pulse2) {
      const fields = _.fields, query = _.query, indices = this._indices = {}, dims = this._dims = [], m4 = query.length;
      let i2 = 0, key2, index4;
      for (; i2 < m4; ++i2) {
        key2 = fields[i2].fname;
        index4 = indices[key2] || (indices[key2] = SortedIndex());
        dims.push(Dimension(index4, i2, query[i2]));
      }
      return this.eval(_, pulse2);
    },
    reinit(_, pulse2) {
      const output3 = pulse2.materialize().fork(), fields = _.fields, query = _.query, indices = this._indices, dims = this._dims, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), out = output3.rem = output3.add, mod = output3.mod, m4 = query.length, adds = {};
      let add6, index4, key2, mods, remMap, modMap, i2, n2, f2;
      prev.set(curr);
      if (pulse2.rem.length) {
        remMap = this.remove(_, pulse2, output3);
      }
      if (pulse2.add.length) {
        bits.add(pulse2.add);
      }
      if (pulse2.mod.length) {
        modMap = {};
        for (mods = pulse2.mod, i2 = 0, n2 = mods.length; i2 < n2; ++i2) {
          modMap[mods[i2]._index] = 1;
        }
      }
      for (i2 = 0; i2 < m4; ++i2) {
        f2 = fields[i2];
        if (!dims[i2] || _.modified("fields", i2) || pulse2.modified(f2.fields)) {
          key2 = f2.fname;
          if (!(add6 = adds[key2])) {
            indices[key2] = index4 = SortedIndex();
            adds[key2] = add6 = index4.insert(f2, pulse2.source, 0);
          }
          dims[i2] = Dimension(index4, i2, query[i2]).onAdd(add6, curr);
        }
      }
      for (i2 = 0, n2 = bits.data().length; i2 < n2; ++i2) {
        if (remMap[i2]) {
          continue;
        } else if (prev[i2] !== curr[i2]) {
          out.push(i2);
        } else if (modMap[i2] && curr[i2] !== all) {
          mod.push(i2);
        }
      }
      bits.mask = (1 << m4) - 1;
      return output3;
    },
    eval(_, pulse2) {
      const output3 = pulse2.materialize().fork(), m4 = this._dims.length;
      let mask = 0;
      if (pulse2.rem.length) {
        this.remove(_, pulse2, output3);
        mask |= (1 << m4) - 1;
      }
      if (_.modified("query") && !_.modified("fields")) {
        mask |= this.update(_, pulse2, output3);
      }
      if (pulse2.add.length) {
        this.insert(_, pulse2, output3);
        mask |= (1 << m4) - 1;
      }
      if (pulse2.mod.length) {
        this.modify(pulse2, output3);
        mask |= (1 << m4) - 1;
      }
      this.value.mask = mask;
      return output3;
    },
    insert(_, pulse2, output3) {
      const tuples = pulse2.add, bits = this.value, dims = this._dims, indices = this._indices, fields = _.fields, adds = {}, out = output3.add, n2 = bits.size() + tuples.length, m4 = dims.length;
      let k2 = bits.size(), j2, key2, add6;
      bits.resize(n2, m4);
      bits.add(tuples);
      const curr = bits.curr(), prev = bits.prev(), all = bits.all();
      for (j2 = 0; j2 < m4; ++j2) {
        key2 = fields[j2].fname;
        add6 = adds[key2] || (adds[key2] = indices[key2].insert(fields[j2], tuples, k2));
        dims[j2].onAdd(add6, curr);
      }
      for (; k2 < n2; ++k2) {
        prev[k2] = all;
        if (curr[k2] !== all) out.push(k2);
      }
    },
    modify(pulse2, output3) {
      const out = output3.mod, bits = this.value, curr = bits.curr(), all = bits.all(), tuples = pulse2.mod;
      let i2, n2, k2;
      for (i2 = 0, n2 = tuples.length; i2 < n2; ++i2) {
        k2 = tuples[i2]._index;
        if (curr[k2] !== all) out.push(k2);
      }
    },
    remove(_, pulse2, output3) {
      const indices = this._indices, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), map4 = {}, out = output3.rem, tuples = pulse2.rem;
      let i2, n2, k2, f2;
      for (i2 = 0, n2 = tuples.length; i2 < n2; ++i2) {
        k2 = tuples[i2]._index;
        map4[k2] = 1;
        prev[k2] = f2 = curr[k2];
        curr[k2] = all;
        if (f2 !== all) out.push(k2);
      }
      for (k2 in indices) {
        indices[k2].remove(n2, map4);
      }
      this.reindex(pulse2, n2, map4);
      return map4;
    },
    // reindex filters and indices after propagation completes
    reindex(pulse2, num, map4) {
      const indices = this._indices, bits = this.value;
      pulse2.runAfter(() => {
        const indexMap = bits.remove(num, map4);
        for (const key2 in indices) indices[key2].reindex(indexMap);
      });
    },
    update(_, pulse2, output3) {
      const dims = this._dims, query = _.query, stamp = pulse2.stamp, m4 = dims.length;
      let mask = 0, i2, q2;
      output3.filters = 0;
      for (q2 = 0; q2 < m4; ++q2) {
        if (_.modified("query", q2)) {
          i2 = q2;
          ++mask;
        }
      }
      if (mask === 1) {
        mask = dims[i2].one;
        this.incrementOne(dims[i2], query[i2], output3.add, output3.rem);
      } else {
        for (q2 = 0, mask = 0; q2 < m4; ++q2) {
          if (!_.modified("query", q2)) continue;
          mask |= dims[q2].one;
          this.incrementAll(dims[q2], query[q2], stamp, output3.add);
          output3.rem = output3.add;
        }
      }
      return mask;
    },
    incrementAll(dim, query, stamp, out) {
      const bits = this.value, seen = bits.seen(), curr = bits.curr(), prev = bits.prev(), index4 = dim.index(), old = dim.bisect(dim.range), range7 = dim.bisect(query), lo1 = range7[0], hi1 = range7[1], lo0 = old[0], hi0 = old[1], one4 = dim.one;
      let i2, j2, k2;
      if (lo1 < lo0) {
        for (i2 = lo1, j2 = Math.min(lo0, hi1); i2 < j2; ++i2) {
          k2 = index4[i2];
          if (seen[k2] !== stamp) {
            prev[k2] = curr[k2];
            seen[k2] = stamp;
            out.push(k2);
          }
          curr[k2] ^= one4;
        }
      } else if (lo1 > lo0) {
        for (i2 = lo0, j2 = Math.min(lo1, hi0); i2 < j2; ++i2) {
          k2 = index4[i2];
          if (seen[k2] !== stamp) {
            prev[k2] = curr[k2];
            seen[k2] = stamp;
            out.push(k2);
          }
          curr[k2] ^= one4;
        }
      }
      if (hi1 > hi0) {
        for (i2 = Math.max(lo1, hi0), j2 = hi1; i2 < j2; ++i2) {
          k2 = index4[i2];
          if (seen[k2] !== stamp) {
            prev[k2] = curr[k2];
            seen[k2] = stamp;
            out.push(k2);
          }
          curr[k2] ^= one4;
        }
      } else if (hi1 < hi0) {
        for (i2 = Math.max(lo0, hi1), j2 = hi0; i2 < j2; ++i2) {
          k2 = index4[i2];
          if (seen[k2] !== stamp) {
            prev[k2] = curr[k2];
            seen[k2] = stamp;
            out.push(k2);
          }
          curr[k2] ^= one4;
        }
      }
      dim.range = query.slice();
    },
    incrementOne(dim, query, add6, rem2) {
      const bits = this.value, curr = bits.curr(), index4 = dim.index(), old = dim.bisect(dim.range), range7 = dim.bisect(query), lo1 = range7[0], hi1 = range7[1], lo0 = old[0], hi0 = old[1], one4 = dim.one;
      let i2, j2, k2;
      if (lo1 < lo0) {
        for (i2 = lo1, j2 = Math.min(lo0, hi1); i2 < j2; ++i2) {
          k2 = index4[i2];
          curr[k2] ^= one4;
          add6.push(k2);
        }
      } else if (lo1 > lo0) {
        for (i2 = lo0, j2 = Math.min(lo1, hi0); i2 < j2; ++i2) {
          k2 = index4[i2];
          curr[k2] ^= one4;
          rem2.push(k2);
        }
      }
      if (hi1 > hi0) {
        for (i2 = Math.max(lo1, hi0), j2 = hi1; i2 < j2; ++i2) {
          k2 = index4[i2];
          curr[k2] ^= one4;
          add6.push(k2);
        }
      } else if (hi1 < hi0) {
        for (i2 = Math.max(lo0, hi1), j2 = hi0; i2 < j2; ++i2) {
          k2 = index4[i2];
          curr[k2] ^= one4;
          rem2.push(k2);
        }
      }
      dim.range = query.slice();
    }
  });
  function ResolveFilter(params2) {
    Transform.call(this, null, params2);
  }
  ResolveFilter.Definition = {
    "type": "ResolveFilter",
    "metadata": {},
    "params": [{
      "name": "ignore",
      "type": "number",
      "required": true,
      "description": "A bit mask indicating which filters to ignore."
    }, {
      "name": "filter",
      "type": "object",
      "required": true,
      "description": "Per-tuple filter bitmaps from a CrossFilter transform."
    }]
  };
  inherits(ResolveFilter, Transform, {
    transform(_, pulse2) {
      const ignore = ~(_.ignore || 0), bitmap = _.filter, mask = bitmap.mask;
      if ((mask & ignore) === 0) return pulse2.StopPropagation;
      const output3 = pulse2.fork(pulse2.ALL), data3 = bitmap.data(), curr = bitmap.curr(), prev = bitmap.prev(), pass2 = (k2) => !(curr[k2] & ignore) ? data3[k2] : null;
      output3.filter(output3.MOD, pass2);
      if (!(mask & mask - 1)) {
        output3.filter(output3.ADD, pass2);
        output3.filter(output3.REM, (k2) => (curr[k2] & ignore) === mask ? data3[k2] : null);
      } else {
        output3.filter(output3.ADD, (k2) => {
          const c4 = curr[k2] & ignore, f2 = !c4 && c4 ^ prev[k2] & ignore;
          return f2 ? data3[k2] : null;
        });
        output3.filter(output3.REM, (k2) => {
          const c4 = curr[k2] & ignore, f2 = c4 && !(c4 ^ (c4 ^ prev[k2] & ignore));
          return f2 ? data3[k2] : null;
        });
      }
      return output3.filter(output3.SOURCE, (t4) => pass2(t4._index));
    }
  });

  // node_modules/vega-expression/build/vega-expression.module.js
  var RawCode = "RawCode";
  var Literal = "Literal";
  var Property = "Property";
  var Identifier2 = "Identifier";
  var ArrayExpression = "ArrayExpression";
  var BinaryExpression = "BinaryExpression";
  var CallExpression = "CallExpression";
  var ConditionalExpression = "ConditionalExpression";
  var LogicalExpression = "LogicalExpression";
  var MemberExpression = "MemberExpression";
  var ObjectExpression = "ObjectExpression";
  var UnaryExpression = "UnaryExpression";
  function ASTNode(type3) {
    this.type = type3;
  }
  ASTNode.prototype.visit = function(visitor) {
    let c4, i2, n2;
    if (visitor(this)) return 1;
    for (c4 = children2(this), i2 = 0, n2 = c4.length; i2 < n2; ++i2) {
      if (c4[i2].visit(visitor)) return 1;
    }
  };
  function children2(node) {
    switch (node.type) {
      case ArrayExpression:
        return node.elements;
      case BinaryExpression:
      case LogicalExpression:
        return [node.left, node.right];
      case CallExpression:
        return [node.callee].concat(node.arguments);
      case ConditionalExpression:
        return [node.test, node.consequent, node.alternate];
      case MemberExpression:
        return [node.object, node.property];
      case ObjectExpression:
        return node.properties;
      case Property:
        return [node.key, node.value];
      case UnaryExpression:
        return [node.argument];
      case Identifier2:
      case Literal:
      case RawCode:
      default:
        return [];
    }
  }
  var TokenName;
  var source2;
  var index2;
  var length;
  var lookahead;
  var TokenBooleanLiteral = 1;
  var TokenEOF = 2;
  var TokenIdentifier = 3;
  var TokenKeyword = 4;
  var TokenNullLiteral = 5;
  var TokenNumericLiteral = 6;
  var TokenPunctuator = 7;
  var TokenStringLiteral = 8;
  var TokenRegularExpression = 9;
  TokenName = {};
  TokenName[TokenBooleanLiteral] = "Boolean";
  TokenName[TokenEOF] = "<end>";
  TokenName[TokenIdentifier] = "Identifier";
  TokenName[TokenKeyword] = "Keyword";
  TokenName[TokenNullLiteral] = "Null";
  TokenName[TokenNumericLiteral] = "Numeric";
  TokenName[TokenPunctuator] = "Punctuator";
  TokenName[TokenStringLiteral] = "String";
  TokenName[TokenRegularExpression] = "RegularExpression";
  var SyntaxArrayExpression = "ArrayExpression";
  var SyntaxBinaryExpression = "BinaryExpression";
  var SyntaxCallExpression = "CallExpression";
  var SyntaxConditionalExpression = "ConditionalExpression";
  var SyntaxIdentifier = "Identifier";
  var SyntaxLiteral = "Literal";
  var SyntaxLogicalExpression = "LogicalExpression";
  var SyntaxMemberExpression = "MemberExpression";
  var SyntaxObjectExpression = "ObjectExpression";
  var SyntaxProperty = "Property";
  var SyntaxUnaryExpression = "UnaryExpression";
  var MessageUnexpectedToken = "Unexpected token %0";
  var MessageUnexpectedNumber = "Unexpected number";
  var MessageUnexpectedString = "Unexpected string";
  var MessageUnexpectedIdentifier = "Unexpected identifier";
  var MessageUnexpectedReserved = "Unexpected reserved word";
  var MessageUnexpectedEOS = "Unexpected end of input";
  var MessageInvalidRegExp = "Invalid regular expression";
  var MessageUnterminatedRegExp = "Invalid regular expression: missing /";
  var MessageStrictOctalLiteral = "Octal literals are not allowed in strict mode.";
  var MessageStrictDuplicateProperty = "Duplicate data property in object literal not allowed in strict mode";
  var ILLEGAL = "ILLEGAL";
  var DISABLED = "Disabled.";
  var RegexNonAsciiIdentifierStart = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]");
  var RegexNonAsciiIdentifierPart = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]");
  function assert(condition, message) {
    if (!condition) {
      throw new Error("ASSERT: " + message);
    }
  }
  function isDecimalDigit(ch2) {
    return ch2 >= 48 && ch2 <= 57;
  }
  function isHexDigit(ch2) {
    return "0123456789abcdefABCDEF".includes(ch2);
  }
  function isOctalDigit(ch2) {
    return "01234567".includes(ch2);
  }
  function isWhiteSpace(ch2) {
    return ch2 === 32 || ch2 === 9 || ch2 === 11 || ch2 === 12 || ch2 === 160 || ch2 >= 5760 && [5760, 6158, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].includes(ch2);
  }
  function isLineTerminator(ch2) {
    return ch2 === 10 || ch2 === 13 || ch2 === 8232 || ch2 === 8233;
  }
  function isIdentifierStart(ch2) {
    return ch2 === 36 || ch2 === 95 || // $ (dollar) and _ (underscore)
    ch2 >= 65 && ch2 <= 90 || // A..Z
    ch2 >= 97 && ch2 <= 122 || // a..z
    ch2 === 92 || // \ (backslash)
    ch2 >= 128 && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch2));
  }
  function isIdentifierPart(ch2) {
    return ch2 === 36 || ch2 === 95 || // $ (dollar) and _ (underscore)
    ch2 >= 65 && ch2 <= 90 || // A..Z
    ch2 >= 97 && ch2 <= 122 || // a..z
    ch2 >= 48 && ch2 <= 57 || // 0..9
    ch2 === 92 || // \ (backslash)
    ch2 >= 128 && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch2));
  }
  var keywords = {
    "if": 1,
    "in": 1,
    "do": 1,
    "var": 1,
    "for": 1,
    "new": 1,
    "try": 1,
    "let": 1,
    "this": 1,
    "else": 1,
    "case": 1,
    "void": 1,
    "with": 1,
    "enum": 1,
    "while": 1,
    "break": 1,
    "catch": 1,
    "throw": 1,
    "const": 1,
    "yield": 1,
    "class": 1,
    "super": 1,
    "return": 1,
    "typeof": 1,
    "delete": 1,
    "switch": 1,
    "export": 1,
    "import": 1,
    "public": 1,
    "static": 1,
    "default": 1,
    "finally": 1,
    "extends": 1,
    "package": 1,
    "private": 1,
    "function": 1,
    "continue": 1,
    "debugger": 1,
    "interface": 1,
    "protected": 1,
    "instanceof": 1,
    "implements": 1
  };
  function skipComment() {
    while (index2 < length) {
      const ch2 = source2.charCodeAt(index2);
      if (isWhiteSpace(ch2) || isLineTerminator(ch2)) {
        ++index2;
      } else {
        break;
      }
    }
  }
  function scanHexEscape(prefix) {
    var i2, len, ch2, code = 0;
    len = prefix === "u" ? 4 : 2;
    for (i2 = 0; i2 < len; ++i2) {
      if (index2 < length && isHexDigit(source2[index2])) {
        ch2 = source2[index2++];
        code = code * 16 + "0123456789abcdef".indexOf(ch2.toLowerCase());
      } else {
        throwError({}, MessageUnexpectedToken, ILLEGAL);
      }
    }
    return String.fromCharCode(code);
  }
  function scanUnicodeCodePointEscape() {
    var ch2, code, cu1, cu2;
    ch2 = source2[index2];
    code = 0;
    if (ch2 === "}") {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    while (index2 < length) {
      ch2 = source2[index2++];
      if (!isHexDigit(ch2)) {
        break;
      }
      code = code * 16 + "0123456789abcdef".indexOf(ch2.toLowerCase());
    }
    if (code > 1114111 || ch2 !== "}") {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    if (code <= 65535) {
      return String.fromCharCode(code);
    }
    cu1 = (code - 65536 >> 10) + 55296;
    cu2 = (code - 65536 & 1023) + 56320;
    return String.fromCharCode(cu1, cu2);
  }
  function getEscapedIdentifier() {
    var ch2, id2;
    ch2 = source2.charCodeAt(index2++);
    id2 = String.fromCharCode(ch2);
    if (ch2 === 92) {
      if (source2.charCodeAt(index2) !== 117) {
        throwError({}, MessageUnexpectedToken, ILLEGAL);
      }
      ++index2;
      ch2 = scanHexEscape("u");
      if (!ch2 || ch2 === "\\" || !isIdentifierStart(ch2.charCodeAt(0))) {
        throwError({}, MessageUnexpectedToken, ILLEGAL);
      }
      id2 = ch2;
    }
    while (index2 < length) {
      ch2 = source2.charCodeAt(index2);
      if (!isIdentifierPart(ch2)) {
        break;
      }
      ++index2;
      id2 += String.fromCharCode(ch2);
      if (ch2 === 92) {
        id2 = id2.substr(0, id2.length - 1);
        if (source2.charCodeAt(index2) !== 117) {
          throwError({}, MessageUnexpectedToken, ILLEGAL);
        }
        ++index2;
        ch2 = scanHexEscape("u");
        if (!ch2 || ch2 === "\\" || !isIdentifierPart(ch2.charCodeAt(0))) {
          throwError({}, MessageUnexpectedToken, ILLEGAL);
        }
        id2 += ch2;
      }
    }
    return id2;
  }
  function getIdentifier() {
    var start, ch2;
    start = index2++;
    while (index2 < length) {
      ch2 = source2.charCodeAt(index2);
      if (ch2 === 92) {
        index2 = start;
        return getEscapedIdentifier();
      }
      if (isIdentifierPart(ch2)) {
        ++index2;
      } else {
        break;
      }
    }
    return source2.slice(start, index2);
  }
  function scanIdentifier() {
    var start, id2, type3;
    start = index2;
    id2 = source2.charCodeAt(index2) === 92 ? getEscapedIdentifier() : getIdentifier();
    if (id2.length === 1) {
      type3 = TokenIdentifier;
    } else if (keywords.hasOwnProperty(id2)) {
      type3 = TokenKeyword;
    } else if (id2 === "null") {
      type3 = TokenNullLiteral;
    } else if (id2 === "true" || id2 === "false") {
      type3 = TokenBooleanLiteral;
    } else {
      type3 = TokenIdentifier;
    }
    return {
      type: type3,
      value: id2,
      start,
      end: index2
    };
  }
  function scanPunctuator() {
    var start = index2, code = source2.charCodeAt(index2), code2, ch1 = source2[index2], ch2, ch3, ch4;
    switch (code) {
      // Check for most common single-character punctuators.
      case 46:
      // . dot
      case 40:
      // ( open bracket
      case 41:
      // ) close bracket
      case 59:
      // ; semicolon
      case 44:
      // , comma
      case 123:
      // { open curly brace
      case 125:
      // } close curly brace
      case 91:
      // [
      case 93:
      // ]
      case 58:
      // :
      case 63:
      // ?
      case 126:
        ++index2;
        return {
          type: TokenPunctuator,
          value: String.fromCharCode(code),
          start,
          end: index2
        };
      default:
        code2 = source2.charCodeAt(index2 + 1);
        if (code2 === 61) {
          switch (code) {
            case 43:
            // +
            case 45:
            // -
            case 47:
            // /
            case 60:
            // <
            case 62:
            // >
            case 94:
            // ^
            case 124:
            // |
            case 37:
            // %
            case 38:
            // &
            case 42:
              index2 += 2;
              return {
                type: TokenPunctuator,
                value: String.fromCharCode(code) + String.fromCharCode(code2),
                start,
                end: index2
              };
            case 33:
            // !
            case 61:
              index2 += 2;
              if (source2.charCodeAt(index2) === 61) {
                ++index2;
              }
              return {
                type: TokenPunctuator,
                value: source2.slice(start, index2),
                start,
                end: index2
              };
          }
        }
    }
    ch4 = source2.substr(index2, 4);
    if (ch4 === ">>>=") {
      index2 += 4;
      return {
        type: TokenPunctuator,
        value: ch4,
        start,
        end: index2
      };
    }
    ch3 = ch4.substr(0, 3);
    if (ch3 === ">>>" || ch3 === "<<=" || ch3 === ">>=") {
      index2 += 3;
      return {
        type: TokenPunctuator,
        value: ch3,
        start,
        end: index2
      };
    }
    ch2 = ch3.substr(0, 2);
    if (ch1 === ch2[1] && "+-<>&|".includes(ch1) || ch2 === "=>") {
      index2 += 2;
      return {
        type: TokenPunctuator,
        value: ch2,
        start,
        end: index2
      };
    }
    if (ch2 === "//") {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    if ("<>=!+-*%&|^/".includes(ch1)) {
      ++index2;
      return {
        type: TokenPunctuator,
        value: ch1,
        start,
        end: index2
      };
    }
    throwError({}, MessageUnexpectedToken, ILLEGAL);
  }
  function scanHexLiteral(start) {
    let number8 = "";
    while (index2 < length) {
      if (!isHexDigit(source2[index2])) {
        break;
      }
      number8 += source2[index2++];
    }
    if (number8.length === 0) {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    if (isIdentifierStart(source2.charCodeAt(index2))) {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    return {
      type: TokenNumericLiteral,
      value: parseInt("0x" + number8, 16),
      start,
      end: index2
    };
  }
  function scanOctalLiteral(start) {
    let number8 = "0" + source2[index2++];
    while (index2 < length) {
      if (!isOctalDigit(source2[index2])) {
        break;
      }
      number8 += source2[index2++];
    }
    if (isIdentifierStart(source2.charCodeAt(index2)) || isDecimalDigit(source2.charCodeAt(index2))) {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    return {
      type: TokenNumericLiteral,
      value: parseInt(number8, 8),
      octal: true,
      start,
      end: index2
    };
  }
  function scanNumericLiteral() {
    var number8, start, ch2;
    ch2 = source2[index2];
    assert(isDecimalDigit(ch2.charCodeAt(0)) || ch2 === ".", "Numeric literal must start with a decimal digit or a decimal point");
    start = index2;
    number8 = "";
    if (ch2 !== ".") {
      number8 = source2[index2++];
      ch2 = source2[index2];
      if (number8 === "0") {
        if (ch2 === "x" || ch2 === "X") {
          ++index2;
          return scanHexLiteral(start);
        }
        if (isOctalDigit(ch2)) {
          return scanOctalLiteral(start);
        }
        if (ch2 && isDecimalDigit(ch2.charCodeAt(0))) {
          throwError({}, MessageUnexpectedToken, ILLEGAL);
        }
      }
      while (isDecimalDigit(source2.charCodeAt(index2))) {
        number8 += source2[index2++];
      }
      ch2 = source2[index2];
    }
    if (ch2 === ".") {
      number8 += source2[index2++];
      while (isDecimalDigit(source2.charCodeAt(index2))) {
        number8 += source2[index2++];
      }
      ch2 = source2[index2];
    }
    if (ch2 === "e" || ch2 === "E") {
      number8 += source2[index2++];
      ch2 = source2[index2];
      if (ch2 === "+" || ch2 === "-") {
        number8 += source2[index2++];
      }
      if (isDecimalDigit(source2.charCodeAt(index2))) {
        while (isDecimalDigit(source2.charCodeAt(index2))) {
          number8 += source2[index2++];
        }
      } else {
        throwError({}, MessageUnexpectedToken, ILLEGAL);
      }
    }
    if (isIdentifierStart(source2.charCodeAt(index2))) {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    return {
      type: TokenNumericLiteral,
      value: parseFloat(number8),
      start,
      end: index2
    };
  }
  function scanStringLiteral() {
    var str = "", quote, start, ch2, code, octal = false;
    quote = source2[index2];
    assert(quote === "'" || quote === '"', "String literal must starts with a quote");
    start = index2;
    ++index2;
    while (index2 < length) {
      ch2 = source2[index2++];
      if (ch2 === quote) {
        quote = "";
        break;
      } else if (ch2 === "\\") {
        ch2 = source2[index2++];
        if (!ch2 || !isLineTerminator(ch2.charCodeAt(0))) {
          switch (ch2) {
            case "u":
            case "x":
              if (source2[index2] === "{") {
                ++index2;
                str += scanUnicodeCodePointEscape();
              } else {
                str += scanHexEscape(ch2);
              }
              break;
            case "n":
              str += "\n";
              break;
            case "r":
              str += "\r";
              break;
            case "t":
              str += "	";
              break;
            case "b":
              str += "\b";
              break;
            case "f":
              str += "\f";
              break;
            case "v":
              str += "\v";
              break;
            default:
              if (isOctalDigit(ch2)) {
                code = "01234567".indexOf(ch2);
                if (code !== 0) {
                  octal = true;
                }
                if (index2 < length && isOctalDigit(source2[index2])) {
                  octal = true;
                  code = code * 8 + "01234567".indexOf(source2[index2++]);
                  if ("0123".includes(ch2) && index2 < length && isOctalDigit(source2[index2])) {
                    code = code * 8 + "01234567".indexOf(source2[index2++]);
                  }
                }
                str += String.fromCharCode(code);
              } else {
                str += ch2;
              }
              break;
          }
        } else {
          if (ch2 === "\r" && source2[index2] === "\n") {
            ++index2;
          }
        }
      } else if (isLineTerminator(ch2.charCodeAt(0))) {
        break;
      } else {
        str += ch2;
      }
    }
    if (quote !== "") {
      throwError({}, MessageUnexpectedToken, ILLEGAL);
    }
    return {
      type: TokenStringLiteral,
      value: str,
      octal,
      start,
      end: index2
    };
  }
  function testRegExp(pattern, flags) {
    let tmp = pattern;
    if (flags.includes("u")) {
      tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, ($0, $1) => {
        if (parseInt($1, 16) <= 1114111) {
          return "x";
        }
        throwError({}, MessageInvalidRegExp);
      }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
    }
    try {
      new RegExp(tmp);
    } catch (e4) {
      throwError({}, MessageInvalidRegExp);
    }
    try {
      return new RegExp(pattern, flags);
    } catch (exception) {
      return null;
    }
  }
  function scanRegExpBody() {
    var ch2, str, classMarker, terminated, body;
    ch2 = source2[index2];
    assert(ch2 === "/", "Regular expression literal must start with a slash");
    str = source2[index2++];
    classMarker = false;
    terminated = false;
    while (index2 < length) {
      ch2 = source2[index2++];
      str += ch2;
      if (ch2 === "\\") {
        ch2 = source2[index2++];
        if (isLineTerminator(ch2.charCodeAt(0))) {
          throwError({}, MessageUnterminatedRegExp);
        }
        str += ch2;
      } else if (isLineTerminator(ch2.charCodeAt(0))) {
        throwError({}, MessageUnterminatedRegExp);
      } else if (classMarker) {
        if (ch2 === "]") {
          classMarker = false;
        }
      } else {
        if (ch2 === "/") {
          terminated = true;
          break;
        } else if (ch2 === "[") {
          classMarker = true;
        }
      }
    }
    if (!terminated) {
      throwError({}, MessageUnterminatedRegExp);
    }
    body = str.substr(1, str.length - 2);
    return {
      value: body,
      literal: str
    };
  }
  function scanRegExpFlags() {
    var ch2, str, flags;
    str = "";
    flags = "";
    while (index2 < length) {
      ch2 = source2[index2];
      if (!isIdentifierPart(ch2.charCodeAt(0))) {
        break;
      }
      ++index2;
      if (ch2 === "\\" && index2 < length) {
        throwError({}, MessageUnexpectedToken, ILLEGAL);
      } else {
        flags += ch2;
        str += ch2;
      }
    }
    if (flags.search(/[^gimuy]/g) >= 0) {
      throwError({}, MessageInvalidRegExp, flags);
    }
    return {
      value: flags,
      literal: str
    };
  }
  function scanRegExp() {
    var start, body, flags, value3;
    lookahead = null;
    skipComment();
    start = index2;
    body = scanRegExpBody();
    flags = scanRegExpFlags();
    value3 = testRegExp(body.value, flags.value);
    return {
      literal: body.literal + flags.literal,
      value: value3,
      regex: {
        pattern: body.value,
        flags: flags.value
      },
      start,
      end: index2
    };
  }
  function isIdentifierName(token) {
    return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral;
  }
  function advance() {
    skipComment();
    if (index2 >= length) {
      return {
        type: TokenEOF,
        start: index2,
        end: index2
      };
    }
    const ch2 = source2.charCodeAt(index2);
    if (isIdentifierStart(ch2)) {
      return scanIdentifier();
    }
    if (ch2 === 40 || ch2 === 41 || ch2 === 59) {
      return scanPunctuator();
    }
    if (ch2 === 39 || ch2 === 34) {
      return scanStringLiteral();
    }
    if (ch2 === 46) {
      if (isDecimalDigit(source2.charCodeAt(index2 + 1))) {
        return scanNumericLiteral();
      }
      return scanPunctuator();
    }
    if (isDecimalDigit(ch2)) {
      return scanNumericLiteral();
    }
    return scanPunctuator();
  }
  function lex() {
    const token = lookahead;
    index2 = token.end;
    lookahead = advance();
    index2 = token.end;
    return token;
  }
  function peek2() {
    const pos = index2;
    lookahead = advance();
    index2 = pos;
  }
  function finishArrayExpression(elements) {
    const node = new ASTNode(SyntaxArrayExpression);
    node.elements = elements;
    return node;
  }
  function finishBinaryExpression(operator2, left, right) {
    const node = new ASTNode(operator2 === "||" || operator2 === "&&" ? SyntaxLogicalExpression : SyntaxBinaryExpression);
    node.operator = operator2;
    node.left = left;
    node.right = right;
    return node;
  }
  function finishCallExpression(callee, args) {
    const node = new ASTNode(SyntaxCallExpression);
    node.callee = callee;
    node.arguments = args;
    return node;
  }
  function finishConditionalExpression(test2, consequent, alternate) {
    const node = new ASTNode(SyntaxConditionalExpression);
    node.test = test2;
    node.consequent = consequent;
    node.alternate = alternate;
    return node;
  }
  function finishIdentifier(name4) {
    const node = new ASTNode(SyntaxIdentifier);
    node.name = name4;
    return node;
  }
  function finishLiteral(token) {
    const node = new ASTNode(SyntaxLiteral);
    node.value = token.value;
    node.raw = source2.slice(token.start, token.end);
    if (token.regex) {
      if (node.raw === "//") {
        node.raw = "/(?:)/";
      }
      node.regex = token.regex;
    }
    return node;
  }
  function finishMemberExpression(accessor2, object2, property2) {
    const node = new ASTNode(SyntaxMemberExpression);
    node.computed = accessor2 === "[";
    node.object = object2;
    node.property = property2;
    if (!node.computed) property2.member = true;
    return node;
  }
  function finishObjectExpression(properties) {
    const node = new ASTNode(SyntaxObjectExpression);
    node.properties = properties;
    return node;
  }
  function finishProperty(kind, key2, value3) {
    const node = new ASTNode(SyntaxProperty);
    node.key = key2;
    node.value = value3;
    node.kind = kind;
    return node;
  }
  function finishUnaryExpression(operator2, argument) {
    const node = new ASTNode(SyntaxUnaryExpression);
    node.operator = operator2;
    node.argument = argument;
    node.prefix = true;
    return node;
  }
  function throwError(token, messageFormat) {
    var error3, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace(/%(\d)/g, (whole, index4) => {
      assert(index4 < args.length, "Message reference must be in range");
      return args[index4];
    });
    error3 = new Error(msg);
    error3.index = index2;
    error3.description = msg;
    throw error3;
  }
  function throwUnexpected(token) {
    if (token.type === TokenEOF) {
      throwError(token, MessageUnexpectedEOS);
    }
    if (token.type === TokenNumericLiteral) {
      throwError(token, MessageUnexpectedNumber);
    }
    if (token.type === TokenStringLiteral) {
      throwError(token, MessageUnexpectedString);
    }
    if (token.type === TokenIdentifier) {
      throwError(token, MessageUnexpectedIdentifier);
    }
    if (token.type === TokenKeyword) {
      throwError(token, MessageUnexpectedReserved);
    }
    throwError(token, MessageUnexpectedToken, token.value);
  }
  function expect(value3) {
    const token = lex();
    if (token.type !== TokenPunctuator || token.value !== value3) {
      throwUnexpected(token);
    }
  }
  function match(value3) {
    return lookahead.type === TokenPunctuator && lookahead.value === value3;
  }
  function matchKeyword(keyword) {
    return lookahead.type === TokenKeyword && lookahead.value === keyword;
  }
  function parseArrayInitialiser() {
    const elements = [];
    index2 = lookahead.start;
    expect("[");
    while (!match("]")) {
      if (match(",")) {
        lex();
        elements.push(null);
      } else {
        elements.push(parseConditionalExpression());
        if (!match("]")) {
          expect(",");
        }
      }
    }
    lex();
    return finishArrayExpression(elements);
  }
  function parseObjectPropertyKey() {
    index2 = lookahead.start;
    const token = lex();
    if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) {
      if (token.octal) {
        throwError(token, MessageStrictOctalLiteral);
      }
      return finishLiteral(token);
    }
    return finishIdentifier(token.value);
  }
  function parseObjectProperty() {
    var token, key2, id2, value3;
    index2 = lookahead.start;
    token = lookahead;
    if (token.type === TokenIdentifier) {
      id2 = parseObjectPropertyKey();
      expect(":");
      value3 = parseConditionalExpression();
      return finishProperty("init", id2, value3);
    }
    if (token.type === TokenEOF || token.type === TokenPunctuator) {
      throwUnexpected(token);
    } else {
      key2 = parseObjectPropertyKey();
      expect(":");
      value3 = parseConditionalExpression();
      return finishProperty("init", key2, value3);
    }
  }
  function parseObjectInitialiser() {
    var properties = [], property2, name4, key2, map4 = {}, toString2 = String;
    index2 = lookahead.start;
    expect("{");
    while (!match("}")) {
      property2 = parseObjectProperty();
      if (property2.key.type === SyntaxIdentifier) {
        name4 = property2.key.name;
      } else {
        name4 = toString2(property2.key.value);
      }
      key2 = "$" + name4;
      if (Object.prototype.hasOwnProperty.call(map4, key2)) {
        throwError({}, MessageStrictDuplicateProperty);
      } else {
        map4[key2] = true;
      }
      properties.push(property2);
      if (!match("}")) {
        expect(",");
      }
    }
    expect("}");
    return finishObjectExpression(properties);
  }
  function parseGroupExpression() {
    expect("(");
    const expr2 = parseExpression();
    expect(")");
    return expr2;
  }
  var legalKeywords = {
    "if": 1
  };
  function parsePrimaryExpression() {
    var type3, token, expr2;
    if (match("(")) {
      return parseGroupExpression();
    }
    if (match("[")) {
      return parseArrayInitialiser();
    }
    if (match("{")) {
      return parseObjectInitialiser();
    }
    type3 = lookahead.type;
    index2 = lookahead.start;
    if (type3 === TokenIdentifier || legalKeywords[lookahead.value]) {
      expr2 = finishIdentifier(lex().value);
    } else if (type3 === TokenStringLiteral || type3 === TokenNumericLiteral) {
      if (lookahead.octal) {
        throwError(lookahead, MessageStrictOctalLiteral);
      }
      expr2 = finishLiteral(lex());
    } else if (type3 === TokenKeyword) {
      throw new Error(DISABLED);
    } else if (type3 === TokenBooleanLiteral) {
      token = lex();
      token.value = token.value === "true";
      expr2 = finishLiteral(token);
    } else if (type3 === TokenNullLiteral) {
      token = lex();
      token.value = null;
      expr2 = finishLiteral(token);
    } else if (match("/") || match("/=")) {
      expr2 = finishLiteral(scanRegExp());
      peek2();
    } else {
      throwUnexpected(lex());
    }
    return expr2;
  }
  function parseArguments() {
    const args = [];
    expect("(");
    if (!match(")")) {
      while (index2 < length) {
        args.push(parseConditionalExpression());
        if (match(")")) {
          break;
        }
        expect(",");
      }
    }
    expect(")");
    return args;
  }
  function parseNonComputedProperty() {
    index2 = lookahead.start;
    const token = lex();
    if (!isIdentifierName(token)) {
      throwUnexpected(token);
    }
    return finishIdentifier(token.value);
  }
  function parseNonComputedMember() {
    expect(".");
    return parseNonComputedProperty();
  }
  function parseComputedMember() {
    expect("[");
    const expr2 = parseExpression();
    expect("]");
    return expr2;
  }
  function parseLeftHandSideExpressionAllowCall() {
    var expr2, args, property2;
    expr2 = parsePrimaryExpression();
    for (; ; ) {
      if (match(".")) {
        property2 = parseNonComputedMember();
        expr2 = finishMemberExpression(".", expr2, property2);
      } else if (match("(")) {
        args = parseArguments();
        expr2 = finishCallExpression(expr2, args);
      } else if (match("[")) {
        property2 = parseComputedMember();
        expr2 = finishMemberExpression("[", expr2, property2);
      } else {
        break;
      }
    }
    return expr2;
  }
  function parsePostfixExpression() {
    const expr2 = parseLeftHandSideExpressionAllowCall();
    if (lookahead.type === TokenPunctuator) {
      if (match("++") || match("--")) {
        throw new Error(DISABLED);
      }
    }
    return expr2;
  }
  function parseUnaryExpression() {
    var token, expr2;
    if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) {
      expr2 = parsePostfixExpression();
    } else if (match("++") || match("--")) {
      throw new Error(DISABLED);
    } else if (match("+") || match("-") || match("~") || match("!")) {
      token = lex();
      expr2 = parseUnaryExpression();
      expr2 = finishUnaryExpression(token.value, expr2);
    } else if (matchKeyword("delete") || matchKeyword("void") || matchKeyword("typeof")) {
      throw new Error(DISABLED);
    } else {
      expr2 = parsePostfixExpression();
    }
    return expr2;
  }
  function binaryPrecedence(token) {
    let prec = 0;
    if (token.type !== TokenPunctuator && token.type !== TokenKeyword) {
      return 0;
    }
    switch (token.value) {
      case "||":
        prec = 1;
        break;
      case "&&":
        prec = 2;
        break;
      case "|":
        prec = 3;
        break;
      case "^":
        prec = 4;
        break;
      case "&":
        prec = 5;
        break;
      case "==":
      case "!=":
      case "===":
      case "!==":
        prec = 6;
        break;
      case "<":
      case ">":
      case "<=":
      case ">=":
      case "instanceof":
      case "in":
        prec = 7;
        break;
      case "<<":
      case ">>":
      case ">>>":
        prec = 8;
        break;
      case "+":
      case "-":
        prec = 9;
        break;
      case "*":
      case "/":
      case "%":
        prec = 11;
        break;
    }
    return prec;
  }
  function parseBinaryExpression() {
    var marker, markers, expr2, token, prec, stack2, right, operator2, left, i2;
    marker = lookahead;
    left = parseUnaryExpression();
    token = lookahead;
    prec = binaryPrecedence(token);
    if (prec === 0) {
      return left;
    }
    token.prec = prec;
    lex();
    markers = [marker, lookahead];
    right = parseUnaryExpression();
    stack2 = [left, token, right];
    while ((prec = binaryPrecedence(lookahead)) > 0) {
      while (stack2.length > 2 && prec <= stack2[stack2.length - 2].prec) {
        right = stack2.pop();
        operator2 = stack2.pop().value;
        left = stack2.pop();
        markers.pop();
        expr2 = finishBinaryExpression(operator2, left, right);
        stack2.push(expr2);
      }
      token = lex();
      token.prec = prec;
      stack2.push(token);
      markers.push(lookahead);
      expr2 = parseUnaryExpression();
      stack2.push(expr2);
    }
    i2 = stack2.length - 1;
    expr2 = stack2[i2];
    markers.pop();
    while (i2 > 1) {
      markers.pop();
      expr2 = finishBinaryExpression(stack2[i2 - 1].value, stack2[i2 - 2], expr2);
      i2 -= 2;
    }
    return expr2;
  }
  function parseConditionalExpression() {
    var expr2, consequent, alternate;
    expr2 = parseBinaryExpression();
    if (match("?")) {
      lex();
      consequent = parseConditionalExpression();
      expect(":");
      alternate = parseConditionalExpression();
      expr2 = finishConditionalExpression(expr2, consequent, alternate);
    }
    return expr2;
  }
  function parseExpression() {
    const expr2 = parseConditionalExpression();
    if (match(",")) {
      throw new Error(DISABLED);
    }
    return expr2;
  }
  function parser(code) {
    source2 = code;
    index2 = 0;
    length = source2.length;
    lookahead = null;
    peek2();
    const expr2 = parseExpression();
    if (lookahead.type !== TokenEOF) {
      throw new Error("Unexpect token after expression.");
    }
    return expr2;
  }
  var Constants = {
    NaN: "NaN",
    E: "Math.E",
    LN2: "Math.LN2",
    LN10: "Math.LN10",
    LOG2E: "Math.LOG2E",
    LOG10E: "Math.LOG10E",
    PI: "Math.PI",
    SQRT1_2: "Math.SQRT1_2",
    SQRT2: "Math.SQRT2",
    MIN_VALUE: "Number.MIN_VALUE",
    MAX_VALUE: "Number.MAX_VALUE"
  };
  function Functions(codegen2) {
    function fncall(name4, args, cast, type3) {
      let obj = codegen2(args[0]);
      if (cast) {
        obj = cast + "(" + obj + ")";
        if (cast.lastIndexOf("new ", 0) === 0) obj = "(" + obj + ")";
      }
      return obj + "." + name4 + (type3 < 0 ? "" : type3 === 0 ? "()" : "(" + args.slice(1).map(codegen2).join(",") + ")");
    }
    function fn(name4, cast, type3) {
      return (args) => fncall(name4, args, cast, type3);
    }
    const DATE2 = "new Date", STRING = "String", REGEXP = "RegExp";
    return {
      // MATH functions
      isNaN: "Number.isNaN",
      isFinite: "Number.isFinite",
      abs: "Math.abs",
      acos: "Math.acos",
      asin: "Math.asin",
      atan: "Math.atan",
      atan2: "Math.atan2",
      ceil: "Math.ceil",
      cos: "Math.cos",
      exp: "Math.exp",
      floor: "Math.floor",
      hypot: "Math.hypot",
      log: "Math.log",
      max: "Math.max",
      min: "Math.min",
      pow: "Math.pow",
      random: "Math.random",
      round: "Math.round",
      sin: "Math.sin",
      sqrt: "Math.sqrt",
      tan: "Math.tan",
      clamp: function(args) {
        if (args.length < 3) error("Missing arguments to clamp function.");
        if (args.length > 3) error("Too many arguments to clamp function.");
        const a4 = args.map(codegen2);
        return "Math.max(" + a4[1] + ", Math.min(" + a4[2] + "," + a4[0] + "))";
      },
      // DATE functions
      now: "Date.now",
      utc: "Date.UTC",
      datetime: DATE2,
      date: fn("getDate", DATE2, 0),
      day: fn("getDay", DATE2, 0),
      year: fn("getFullYear", DATE2, 0),
      month: fn("getMonth", DATE2, 0),
      hours: fn("getHours", DATE2, 0),
      minutes: fn("getMinutes", DATE2, 0),
      seconds: fn("getSeconds", DATE2, 0),
      milliseconds: fn("getMilliseconds", DATE2, 0),
      time: fn("getTime", DATE2, 0),
      timezoneoffset: fn("getTimezoneOffset", DATE2, 0),
      utcdate: fn("getUTCDate", DATE2, 0),
      utcday: fn("getUTCDay", DATE2, 0),
      utcyear: fn("getUTCFullYear", DATE2, 0),
      utcmonth: fn("getUTCMonth", DATE2, 0),
      utchours: fn("getUTCHours", DATE2, 0),
      utcminutes: fn("getUTCMinutes", DATE2, 0),
      utcseconds: fn("getUTCSeconds", DATE2, 0),
      utcmilliseconds: fn("getUTCMilliseconds", DATE2, 0),
      // sequence functions
      length: fn("length", null, -1),
      // STRING functions
      parseFloat: "parseFloat",
      parseInt: "parseInt",
      upper: fn("toUpperCase", STRING, 0),
      lower: fn("toLowerCase", STRING, 0),
      substring: fn("substring", STRING),
      split: fn("split", STRING),
      trim: fn("trim", STRING, 0),
      // base64 encode/decode
      btoa: "btoa",
      atob: "atob",
      // REGEXP functions
      regexp: REGEXP,
      test: fn("test", REGEXP),
      // Control Flow functions
      if: function(args) {
        if (args.length < 3) error("Missing arguments to if function.");
        if (args.length > 3) error("Too many arguments to if function.");
        const a4 = args.map(codegen2);
        return "(" + a4[0] + "?" + a4[1] + ":" + a4[2] + ")";
      }
    };
  }
  function stripQuotes(s2) {
    const n2 = s2 && s2.length - 1;
    return n2 && (s2[0] === '"' && s2[n2] === '"' || s2[0] === "'" && s2[n2] === "'") ? s2.slice(1, -1) : s2;
  }
  function codegen(opt) {
    opt = opt || {};
    const allowed = opt.allowed ? toSet(opt.allowed) : {}, forbidden = opt.forbidden ? toSet(opt.forbidden) : {}, constants3 = opt.constants || Constants, functions = (opt.functions || Functions)(visit2), globalvar = opt.globalvar, fieldvar = opt.fieldvar, outputGlobal = isFunction(globalvar) ? globalvar : (id2) => `${globalvar}["${id2}"]`;
    let globals = {}, fields = {}, memberDepth = 0;
    function visit2(ast) {
      if (isString(ast)) return ast;
      const generator = Generators[ast.type];
      if (generator == null) error("Unsupported type: " + ast.type);
      return generator(ast);
    }
    const Generators = {
      Literal: (n2) => n2.raw,
      Identifier: (n2) => {
        const id2 = n2.name;
        if (memberDepth > 0) {
          return id2;
        } else if (has(forbidden, id2)) {
          return error("Illegal identifier: " + id2);
        } else if (has(constants3, id2)) {
          return constants3[id2];
        } else if (has(allowed, id2)) {
          return id2;
        } else {
          globals[id2] = 1;
          return outputGlobal(id2);
        }
      },
      MemberExpression: (n2) => {
        const d2 = !n2.computed, o2 = visit2(n2.object);
        if (d2) memberDepth += 1;
        const p2 = visit2(n2.property);
        if (o2 === fieldvar) {
          fields[stripQuotes(p2)] = 1;
        }
        if (d2) memberDepth -= 1;
        return o2 + (d2 ? "." + p2 : "[" + p2 + "]");
      },
      CallExpression: (n2) => {
        if (n2.callee.type !== "Identifier") {
          error("Illegal callee type: " + n2.callee.type);
        }
        const callee = n2.callee.name, args = n2.arguments, fn = has(functions, callee) && functions[callee];
        if (!fn) error("Unrecognized function: " + callee);
        return isFunction(fn) ? fn(args) : fn + "(" + args.map(visit2).join(",") + ")";
      },
      ArrayExpression: (n2) => "[" + n2.elements.map(visit2).join(",") + "]",
      BinaryExpression: (n2) => "(" + visit2(n2.left) + " " + n2.operator + " " + visit2(n2.right) + ")",
      UnaryExpression: (n2) => "(" + n2.operator + visit2(n2.argument) + ")",
      ConditionalExpression: (n2) => "(" + visit2(n2.test) + "?" + visit2(n2.consequent) + ":" + visit2(n2.alternate) + ")",
      LogicalExpression: (n2) => "(" + visit2(n2.left) + n2.operator + visit2(n2.right) + ")",
      ObjectExpression: (n2) => "{" + n2.properties.map(visit2).join(",") + "}",
      Property: (n2) => {
        memberDepth += 1;
        const k2 = visit2(n2.key);
        memberDepth -= 1;
        return k2 + ":" + visit2(n2.value);
      }
    };
    function codegen2(ast) {
      const result = {
        code: visit2(ast),
        globals: Object.keys(globals),
        fields: Object.keys(fields)
      };
      globals = {};
      fields = {};
      return result;
    }
    codegen2.functions = functions;
    codegen2.constants = constants3;
    return codegen2;
  }

  // node_modules/vega-selections/build/vega-selection.module.js
  var SELECTION_GETTER = Symbol("vega_selection_getter");
  function getter2(f2) {
    if (!f2.getter || !f2.getter[SELECTION_GETTER]) {
      f2.getter = field(f2.field);
      f2.getter[SELECTION_GETTER] = true;
    }
    return f2.getter;
  }
  var Intersect = "intersect";
  var Union = "union";
  var VlMulti = "vlMulti";
  var VlPoint = "vlPoint";
  var Or = "or";
  var And = "and";
  var SelectionId = "_vgsid_";
  var $selectionId = field(SelectionId);
  var TYPE_ENUM = "E";
  var TYPE_RANGE_INC = "R";
  var TYPE_RANGE_EXC = "R-E";
  var TYPE_RANGE_LE = "R-LE";
  var TYPE_RANGE_RE = "R-RE";
  var TYPE_PRED_LT = "E-LT";
  var TYPE_PRED_LTE = "E-LTE";
  var TYPE_PRED_GT = "E-GT";
  var TYPE_PRED_GTE = "E-GTE";
  var TYPE_PRED_VALID = "E-VALID";
  var TYPE_PRED_ONE_OF = "E-ONE";
  var UNIT_INDEX = "index:unit";
  function testPoint(datum2, entry2) {
    var fields = entry2.fields, values4 = entry2.values, n2 = fields.length, i2 = 0, dval, f2;
    for (; i2 < n2; ++i2) {
      f2 = fields[i2];
      dval = getter2(f2)(datum2);
      if (isDate(dval)) dval = toNumber(dval);
      if (isDate(values4[i2])) values4[i2] = toNumber(values4[i2]);
      if (isArray(values4[i2]) && isDate(values4[i2][0])) values4[i2] = values4[i2].map(toNumber);
      if (f2.type === TYPE_ENUM) {
        if (isArray(values4[i2]) ? !values4[i2].includes(dval) : dval !== values4[i2]) {
          return false;
        }
      } else {
        if (f2.type === TYPE_RANGE_INC) {
          if (!inrange(dval, values4[i2])) return false;
        } else if (f2.type === TYPE_RANGE_RE) {
          if (!inrange(dval, values4[i2], true, false)) return false;
        } else if (f2.type === TYPE_RANGE_EXC) {
          if (!inrange(dval, values4[i2], false, false)) return false;
        } else if (f2.type === TYPE_RANGE_LE) {
          if (!inrange(dval, values4[i2], false, true)) return false;
        } else if (f2.type === TYPE_PRED_LT) {
          if (dval >= values4[i2]) return false;
        } else if (f2.type === TYPE_PRED_LTE) {
          if (dval > values4[i2]) return false;
        } else if (f2.type === TYPE_PRED_GT) {
          if (dval <= values4[i2]) return false;
        } else if (f2.type === TYPE_PRED_GTE) {
          if (dval < values4[i2]) return false;
        } else if (f2.type === TYPE_PRED_VALID) {
          if (dval === null || isNaN(dval)) return false;
        } else if (f2.type === TYPE_PRED_ONE_OF) {
          if (values4[i2].indexOf(dval) === -1) return false;
        }
      }
    }
    return true;
  }
  function selectionTest(name4, datum2, op) {
    var data3 = this.context.data[name4], entries3 = data3 ? data3.values.value : [], unitIdx = data3 ? data3[UNIT_INDEX] && data3[UNIT_INDEX].value : void 0, intersect5 = op === Intersect, n2 = entries3.length, i2 = 0, entry2, miss, count2, unit2, b3;
    for (; i2 < n2; ++i2) {
      entry2 = entries3[i2];
      if (unitIdx && intersect5) {
        miss = miss || {};
        count2 = miss[unit2 = entry2.unit] || 0;
        if (count2 === -1) continue;
        b3 = testPoint(datum2, entry2);
        miss[unit2] = b3 ? -1 : ++count2;
        if (b3 && unitIdx.size === 1) return true;
        if (!b3 && count2 === unitIdx.get(unit2).count) return false;
      } else {
        b3 = testPoint(datum2, entry2);
        if (intersect5 ^ b3) return b3;
      }
    }
    return n2 && intersect5;
  }
  var bisect = bisector($selectionId);
  var bisectLeft2 = bisect.left;
  var bisectRight2 = bisect.right;
  function selectionIdTest(name4, datum2, op) {
    const data3 = this.context.data[name4], entries3 = data3 ? data3.values.value : [], unitIdx = data3 ? data3[UNIT_INDEX] && data3[UNIT_INDEX].value : void 0, intersect5 = op === Intersect, value3 = $selectionId(datum2), index4 = bisectLeft2(entries3, value3);
    if (index4 === entries3.length) return false;
    if ($selectionId(entries3[index4]) !== value3) return false;
    if (unitIdx && intersect5) {
      if (unitIdx.size === 1) return true;
      if (bisectRight2(entries3, value3) - index4 < unitIdx.size) return false;
    }
    return true;
  }
  function selectionTuples(array4, base) {
    return array4.map((x5) => extend(base.fields ? {
      values: base.fields.map((f2) => getter2(f2)(x5.datum))
    } : {
      [SelectionId]: $selectionId(x5.datum)
    }, base));
  }
  function selectionResolve(name4, op, isMulti, vl5) {
    var data3 = this.context.data[name4], entries3 = data3 ? data3.values.value : [], resolved = {}, multiRes = {}, types4 = {}, entry2, fields, values4, unit2, field3, value3, res, resUnit, type3, union2, n2 = entries3.length, i2 = 0, j2, m4;
    for (; i2 < n2; ++i2) {
      entry2 = entries3[i2];
      unit2 = entry2.unit;
      fields = entry2.fields;
      values4 = entry2.values;
      if (fields && values4) {
        for (j2 = 0, m4 = fields.length; j2 < m4; ++j2) {
          field3 = fields[j2];
          res = resolved[field3.field] || (resolved[field3.field] = {});
          resUnit = res[unit2] || (res[unit2] = []);
          types4[field3.field] = type3 = field3.type.charAt(0);
          union2 = ops[`${type3}_union`];
          res[unit2] = union2(resUnit, array(values4[j2]));
        }
        if (isMulti) {
          resUnit = multiRes[unit2] || (multiRes[unit2] = []);
          resUnit.push(array(values4).reduce((obj, curr, j3) => (obj[fields[j3].field] = curr, obj), {}));
        }
      } else {
        field3 = SelectionId;
        value3 = $selectionId(entry2);
        res = resolved[field3] || (resolved[field3] = {});
        resUnit = res[unit2] || (res[unit2] = []);
        resUnit.push(value3);
        if (isMulti) {
          resUnit = multiRes[unit2] || (multiRes[unit2] = []);
          resUnit.push({
            [SelectionId]: value3
          });
        }
      }
    }
    op = op || Union;
    if (resolved[SelectionId]) {
      resolved[SelectionId] = ops[`${SelectionId}_${op}`](...Object.values(resolved[SelectionId]));
    } else {
      Object.keys(resolved).forEach((field4) => {
        resolved[field4] = Object.keys(resolved[field4]).map((unit3) => resolved[field4][unit3]).reduce((acc, curr) => acc === void 0 ? curr : ops[`${types4[field4]}_${op}`](acc, curr));
      });
    }
    entries3 = Object.keys(multiRes);
    if (isMulti && entries3.length) {
      const key2 = vl5 ? VlPoint : VlMulti;
      resolved[key2] = op === Union ? {
        [Or]: entries3.reduce((acc, k2) => (acc.push(...multiRes[k2]), acc), [])
      } : {
        [And]: entries3.map((k2) => ({
          [Or]: multiRes[k2]
        }))
      };
    }
    return resolved;
  }
  var ops = {
    [`${SelectionId}_union`]: union,
    [`${SelectionId}_intersect`]: intersection,
    E_union: function(base, value3) {
      if (!base.length) return value3;
      var i2 = 0, n2 = value3.length;
      for (; i2 < n2; ++i2) if (!base.includes(value3[i2])) base.push(value3[i2]);
      return base;
    },
    E_intersect: function(base, value3) {
      return !base.length ? value3 : base.filter((v3) => value3.includes(v3));
    },
    R_union: function(base, value3) {
      var lo = toNumber(value3[0]), hi = toNumber(value3[1]);
      if (lo > hi) {
        lo = value3[1];
        hi = value3[0];
      }
      if (!base.length) return [lo, hi];
      if (base[0] > lo) base[0] = lo;
      if (base[1] < hi) base[1] = hi;
      return base;
    },
    R_intersect: function(base, value3) {
      var lo = toNumber(value3[0]), hi = toNumber(value3[1]);
      if (lo > hi) {
        lo = value3[1];
        hi = value3[0];
      }
      if (!base.length) return [lo, hi];
      if (hi < base[0] || base[1] < lo) {
        return [];
      } else {
        if (base[0] < lo) base[0] = lo;
        if (base[1] > hi) base[1] = hi;
      }
      return base;
    }
  };
  var DataPrefix = ":";
  var IndexPrefix = "@";
  function selectionVisitor(name4, args, scope, params2) {
    if (args[0].type !== Literal) error("First argument to selection functions must be a string literal.");
    const data3 = args[0].value, op = args.length >= 2 && peek(args).value, field3 = "unit", indexName = IndexPrefix + field3, dataName = DataPrefix + data3;
    if (op === Intersect && !has(params2, indexName)) {
      params2[indexName] = scope.getData(data3).indataRef(scope, field3);
    }
    if (!has(params2, dataName)) {
      params2[dataName] = scope.getData(data3).tuplesRef();
    }
  }

  // node_modules/vega-functions/build/vega-functions.module.js
  function data(name4) {
    const data3 = this.context.data[name4];
    return data3 ? data3.values.value : [];
  }
  function indata(name4, field3, value3) {
    const index4 = this.context.data[name4]["index:" + field3], entry2 = index4 ? index4.value.get(value3) : void 0;
    return entry2 ? entry2.count : entry2;
  }
  function setdata(name4, tuples) {
    const df = this.context.dataflow, data3 = this.context.data[name4], input = data3.input;
    df.pulse(input, df.changeset().remove(truthy).insert(tuples));
    return 1;
  }
  function encode(item, name4, retval) {
    if (item) {
      const df = this.context.dataflow, target2 = item.mark.source;
      df.pulse(target2, df.changeset().encode(item, name4));
    }
    return retval !== void 0 ? retval : item;
  }
  var wrap = (method2) => function(value3, spec) {
    const locale4 = this.context.dataflow.locale();
    return value3 === null ? "null" : locale4[method2](spec)(value3);
  };
  var format4 = wrap("format");
  var timeFormat2 = wrap("timeFormat");
  var utcFormat2 = wrap("utcFormat");
  var timeParse2 = wrap("timeParse");
  var utcParse2 = wrap("utcParse");
  var dateObj = new Date(2e3, 0, 1);
  function time2(month, day, specifier) {
    if (!Number.isInteger(month) || !Number.isInteger(day)) return "";
    dateObj.setYear(2e3);
    dateObj.setMonth(month);
    dateObj.setDate(day);
    return timeFormat2.call(this, dateObj, specifier);
  }
  function monthFormat(month) {
    return time2.call(this, month, 1, "%B");
  }
  function monthAbbrevFormat(month) {
    return time2.call(this, month, 1, "%b");
  }
  function dayFormat(day) {
    return time2.call(this, 0, 2 + day, "%A");
  }
  function dayAbbrevFormat(day) {
    return time2.call(this, 0, 2 + day, "%a");
  }
  var DataPrefix2 = ":";
  var IndexPrefix2 = "@";
  var ScalePrefix = "%";
  var SignalPrefix = "$";
  function dataVisitor(name4, args, scope, params2) {
    if (args[0].type !== Literal) {
      error("First argument to data functions must be a string literal.");
    }
    const data3 = args[0].value, dataName = DataPrefix2 + data3;
    if (!has(dataName, params2)) {
      try {
        params2[dataName] = scope.getData(data3).tuplesRef();
      } catch (err) {
      }
    }
  }
  function indataVisitor(name4, args, scope, params2) {
    if (args[0].type !== Literal) error("First argument to indata must be a string literal.");
    if (args[1].type !== Literal) error("Second argument to indata must be a string literal.");
    const data3 = args[0].value, field3 = args[1].value, indexName = IndexPrefix2 + field3;
    if (!has(indexName, params2)) {
      params2[indexName] = scope.getData(data3).indataRef(scope, field3);
    }
  }
  function scaleVisitor(name4, args, scope, params2) {
    if (args[0].type === Literal) {
      addScaleDependency(scope, params2, args[0].value);
    } else {
      for (name4 in scope.scales) {
        addScaleDependency(scope, params2, name4);
      }
    }
  }
  function addScaleDependency(scope, params2, name4) {
    const scaleName = ScalePrefix + name4;
    if (!has(params2, scaleName)) {
      try {
        params2[scaleName] = scope.scaleRef(name4);
      } catch (err) {
      }
    }
  }
  function getScale(nameOrFunction, ctx) {
    if (isString(nameOrFunction)) {
      const maybeScale = ctx.scales[nameOrFunction];
      return maybeScale && isRegisteredScale(maybeScale.value) ? maybeScale.value : void 0;
    } else if (isFunction(nameOrFunction)) {
      return isRegisteredScale(nameOrFunction) ? nameOrFunction : void 0;
    }
    return void 0;
  }
  function internalScaleFunctions(codegen2, fnctx, visitors) {
    fnctx.__bandwidth = (s2) => s2 && s2.bandwidth ? s2.bandwidth() : 0;
    visitors._bandwidth = scaleVisitor;
    visitors._range = scaleVisitor;
    visitors._scale = scaleVisitor;
    const ref2 = (arg) => "_[" + (arg.type === Literal ? $(ScalePrefix + arg.value) : $(ScalePrefix) + "+" + codegen2(arg)) + "]";
    return {
      _bandwidth: (args) => `this.__bandwidth(${ref2(args[0])})`,
      _range: (args) => `${ref2(args[0])}.range()`,
      _scale: (args) => `${ref2(args[0])}(${codegen2(args[1])})`
    };
  }
  function geoMethod(methodName, globalMethod) {
    return function(projection3, geojson, group2) {
      if (projection3) {
        const p2 = getScale(projection3, (group2 || this).context);
        return p2 && p2.path[methodName](geojson);
      } else {
        return globalMethod(geojson);
      }
    };
  }
  var geoArea = geoMethod("area", area_default2);
  var geoBounds = geoMethod("bounds", bounds_default);
  var geoCentroid = geoMethod("centroid", centroid_default);
  function geoScale(projection3, group2) {
    const p2 = getScale(projection3, (group2 || this).context);
    return p2 && p2.scale();
  }
  function inScope(item) {
    const group2 = this.context.group;
    let value3 = false;
    if (group2) while (item) {
      if (item === group2) {
        value3 = true;
        break;
      }
      item = item.mark.group;
    }
    return value3;
  }
  function log5(df, method2, args) {
    try {
      df[method2].apply(df, ["EXPRESSION"].concat([].slice.call(args)));
    } catch (err) {
      df.warn(err);
    }
    return args[args.length - 1];
  }
  function warn() {
    return log5(this.context.dataflow, "warn", arguments);
  }
  function info() {
    return log5(this.context.dataflow, "info", arguments);
  }
  function debug() {
    return log5(this.context.dataflow, "debug", arguments);
  }
  function channel_luminance_value(channelValue) {
    const val = channelValue / 255;
    if (val <= 0.03928) {
      return val / 12.92;
    }
    return Math.pow((val + 0.055) / 1.055, 2.4);
  }
  function luminance(color5) {
    const c4 = rgb(color5), r2 = channel_luminance_value(c4.r), g2 = channel_luminance_value(c4.g), b3 = channel_luminance_value(c4.b);
    return 0.2126 * r2 + 0.7152 * g2 + 0.0722 * b3;
  }
  function contrast(color1, color22) {
    const lum1 = luminance(color1), lum2 = luminance(color22), lumL = Math.max(lum1, lum2), lumD = Math.min(lum1, lum2);
    return (lumL + 0.05) / (lumD + 0.05);
  }
  function merge4() {
    const args = [].slice.call(arguments);
    args.unshift({});
    return extend(...args);
  }
  function equal(a4, b3) {
    return a4 === b3 || a4 !== a4 && b3 !== b3 ? true : isArray(a4) ? isArray(b3) && a4.length === b3.length ? equalArray(a4, b3) : false : isObject(a4) && isObject(b3) ? equalObject(a4, b3) : false;
  }
  function equalArray(a4, b3) {
    for (let i2 = 0, n2 = a4.length; i2 < n2; ++i2) {
      if (!equal(a4[i2], b3[i2])) return false;
    }
    return true;
  }
  function equalObject(a4, b3) {
    for (const key2 in a4) {
      if (!equal(a4[key2], b3[key2])) return false;
    }
    return true;
  }
  function removePredicate(props) {
    return (_) => equalObject(props, _);
  }
  function modify(name4, insert2, remove2, toggle2, modify2, values4) {
    const df = this.context.dataflow, data3 = this.context.data[name4], input = data3.input, stamp = df.stamp();
    let changes = data3.changes, predicate, key2;
    if (df._trigger === false || !(input.value.length || insert2 || toggle2)) {
      return 0;
    }
    if (!changes || changes.stamp < stamp) {
      data3.changes = changes = df.changeset();
      changes.stamp = stamp;
      df.runAfter(() => {
        data3.modified = true;
        df.pulse(input, changes).run();
      }, true, 1);
    }
    if (remove2) {
      predicate = remove2 === true ? truthy : isArray(remove2) || isTuple(remove2) ? remove2 : removePredicate(remove2);
      changes.remove(predicate);
    }
    if (insert2) {
      changes.insert(insert2);
    }
    if (toggle2) {
      predicate = removePredicate(toggle2);
      if (input.value.some(predicate)) {
        changes.remove(predicate);
      } else {
        changes.insert(toggle2);
      }
    }
    if (modify2) {
      for (key2 in values4) {
        changes.modify(modify2, key2, values4[key2]);
      }
    }
    return 1;
  }
  function pinchDistance(event2) {
    const t4 = event2.touches, dx = t4[0].clientX - t4[1].clientX, dy = t4[0].clientY - t4[1].clientY;
    return Math.hypot(dx, dy);
  }
  function pinchAngle(event2) {
    const t4 = event2.touches;
    return Math.atan2(t4[0].clientY - t4[1].clientY, t4[0].clientX - t4[1].clientX);
  }
  var accessors = {};
  function pluck(data3, name4) {
    const accessor2 = accessors[name4] || (accessors[name4] = field(name4));
    return isArray(data3) ? data3.map(accessor2) : accessor2(data3);
  }
  function array3(seq) {
    return isArray(seq) || ArrayBuffer.isView(seq) ? seq : null;
  }
  function sequence2(seq) {
    return array3(seq) || (isString(seq) ? seq : null);
  }
  function join2(seq) {
    for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return array3(seq).join(...args);
  }
  function indexof(seq) {
    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }
    return sequence2(seq).indexOf(...args);
  }
  function lastindexof(seq) {
    for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
      args[_key3 - 1] = arguments[_key3];
    }
    return sequence2(seq).lastIndexOf(...args);
  }
  function slice3(seq) {
    for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
      args[_key4 - 1] = arguments[_key4];
    }
    return sequence2(seq).slice(...args);
  }
  function replace2(str, pattern, repl) {
    if (isFunction(repl)) error("Function argument passed to replace.");
    if (!isString(pattern) && !isRegExp(pattern)) error("Please pass a string or RegExp argument to replace.");
    return String(str).replace(pattern, repl);
  }
  function reverse(seq) {
    return array3(seq).slice().reverse();
  }
  function sort2(seq) {
    return array3(seq).slice().sort(ascending);
  }
  function bandspace(count2, paddingInner2, paddingOuter2) {
    return bandSpace(count2 || 0, paddingInner2 || 0, paddingOuter2 || 0);
  }
  function bandwidth(name4, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return s2 && s2.bandwidth ? s2.bandwidth() : 0;
  }
  function copy3(name4, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return s2 ? s2.copy() : void 0;
  }
  function domain(name4, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return s2 ? s2.domain() : [];
  }
  function invert(name4, range7, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return !s2 ? void 0 : isArray(range7) ? (s2.invertRange || s2.invert)(range7) : (s2.invert || s2.invertExtent)(range7);
  }
  function range3(name4, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return s2 && s2.range ? s2.range() : [];
  }
  function scale4(name4, value3, group2) {
    const s2 = getScale(name4, (group2 || this).context);
    return s2 ? s2(value3) : void 0;
  }
  function scaleGradient(scale7, p02, p1, count2, group2) {
    scale7 = getScale(scale7, (group2 || this).context);
    const gradient4 = Gradient(p02, p1);
    let stops = scale7.domain(), min4 = stops[0], max4 = peek(stops), fraction = identity;
    if (!(max4 - min4)) {
      scale7 = (scale7.interpolator ? scale("sequential")().interpolator(scale7.interpolator()) : scale("linear")().interpolate(scale7.interpolate()).range(scale7.range())).domain([min4 = 0, max4 = 1]);
    } else {
      fraction = scaleFraction(scale7, min4, max4);
    }
    if (scale7.ticks) {
      stops = scale7.ticks(+count2 || 15);
      if (min4 !== stops[0]) stops.unshift(min4);
      if (max4 !== peek(stops)) stops.push(max4);
    }
    stops.forEach((_) => gradient4.stop(fraction(_), scale7(_)));
    return gradient4;
  }
  function geoShape(projection3, geojson, group2) {
    const p2 = getScale(projection3, (group2 || this).context);
    return function(context3) {
      return p2 ? p2.path.context(context3)(geojson) : "";
    };
  }
  function pathShape(path3) {
    let p2 = null;
    return function(context3) {
      return context3 ? pathRender(context3, p2 = p2 || parse4(path3)) : path3;
    };
  }
  var datum = (d2) => d2.data;
  function treeNodes(name4, context3) {
    const tree = data.call(context3, name4);
    return tree.root && tree.root.lookup || {};
  }
  function treePath(name4, source4, target2) {
    const nodes = treeNodes(name4, this), s2 = nodes[source4], t4 = nodes[target2];
    return s2 && t4 ? s2.path(t4).map(datum) : void 0;
  }
  function treeAncestors(name4, node) {
    const n2 = treeNodes(name4, this)[node];
    return n2 ? n2.ancestors().map(datum) : void 0;
  }
  var _window = () => typeof window !== "undefined" && window || null;
  function screen() {
    const w3 = _window();
    return w3 ? w3.screen : {};
  }
  function windowSize() {
    const w3 = _window();
    return w3 ? [w3.innerWidth, w3.innerHeight] : [void 0, void 0];
  }
  function containerSize() {
    const view = this.context.dataflow, el = view.container && view.container();
    return el ? [el.clientWidth, el.clientHeight] : [void 0, void 0];
  }
  function intersect4(b3, opt, group2) {
    if (!b3) return [];
    const [u5, v3] = b3, box = new Bounds().set(u5[0], u5[1], v3[0], v3[1]), scene = group2 || this.context.dataflow.scenegraph().root;
    return intersect2(scene, box, filter2(opt));
  }
  function filter2(opt) {
    let p2 = null;
    if (opt) {
      const types4 = array(opt.marktype), names = array(opt.markname);
      p2 = (_) => (!types4.length || types4.some((t4) => _.marktype === t4)) && (!names.length || names.some((s2) => _.name === s2));
    }
    return p2;
  }
  function lassoAppend(lasso, x5, y5) {
    let minDist = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 5;
    lasso = array(lasso);
    const last = lasso[lasso.length - 1];
    return last === void 0 || Math.hypot(last[0] - x5, last[1] - y5) > minDist ? [...lasso, [x5, y5]] : lasso;
  }
  function lassoPath(lasso) {
    return array(lasso).reduce((svg, _ref, i2) => {
      let [x5, y5] = _ref;
      return svg += i2 == 0 ? `M ${x5},${y5} ` : i2 === lasso.length - 1 ? " Z" : `L ${x5},${y5} `;
    }, "");
  }
  function intersectLasso(markname, pixelLasso, unit2) {
    const {
      x: x5,
      y: y5,
      mark
    } = unit2;
    const bb2 = new Bounds().set(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);
    for (const [px2, py2] of pixelLasso) {
      if (px2 < bb2.x1) bb2.x1 = px2;
      if (px2 > bb2.x2) bb2.x2 = px2;
      if (py2 < bb2.y1) bb2.y1 = py2;
      if (py2 > bb2.y2) bb2.y2 = py2;
    }
    bb2.translate(x5, y5);
    const intersection2 = intersect4([[bb2.x1, bb2.y1], [bb2.x2, bb2.y2]], markname, mark);
    return intersection2.filter((tuple) => pointInPolygon(tuple.x, tuple.y, pixelLasso));
  }
  function pointInPolygon(testx, testy, polygon) {
    let intersections = 0;
    for (let i2 = 0, j2 = polygon.length - 1; i2 < polygon.length; j2 = i2++) {
      const [prevX, prevY] = polygon[j2];
      const [x5, y5] = polygon[i2];
      if (y5 > testy != prevY > testy && testx < (prevX - x5) * (testy - y5) / (prevY - y5) + x5) {
        intersections++;
      }
    }
    return intersections & 1;
  }
  var functionContext = {
    random() {
      return random();
    },
    // override default
    cumulativeNormal,
    cumulativeLogNormal,
    cumulativeUniform,
    densityNormal,
    densityLogNormal,
    densityUniform,
    quantileNormal,
    quantileLogNormal,
    quantileUniform,
    sampleNormal,
    sampleLogNormal,
    sampleUniform,
    isArray,
    isBoolean,
    isDate,
    isDefined(_) {
      return _ !== void 0;
    },
    isNumber,
    isObject,
    isRegExp,
    isString,
    isTuple,
    isValid(_) {
      return _ != null && _ === _;
    },
    toBoolean,
    toDate(_) {
      return toDate(_);
    },
    // suppress extra arguments
    toNumber,
    toString,
    indexof,
    join: join2,
    lastindexof,
    replace: replace2,
    reverse,
    sort: sort2,
    slice: slice3,
    flush,
    lerp,
    merge: merge4,
    pad,
    peek,
    pluck,
    span,
    inrange,
    truncate,
    rgb,
    lab,
    hcl,
    hsl,
    luminance,
    contrast,
    sequence: range,
    format: format4,
    utcFormat: utcFormat2,
    utcParse: utcParse2,
    utcOffset,
    utcSequence,
    timeFormat: timeFormat2,
    timeParse: timeParse2,
    timeOffset,
    timeSequence,
    timeUnitSpecifier,
    monthFormat,
    monthAbbrevFormat,
    dayFormat,
    dayAbbrevFormat,
    quarter,
    utcquarter,
    week,
    utcweek,
    dayofyear,
    utcdayofyear,
    warn,
    info,
    debug,
    extent(_) {
      return extent(_);
    },
    // suppress extra arguments
    inScope,
    intersect: intersect4,
    clampRange,
    pinchDistance,
    pinchAngle,
    screen,
    containerSize,
    windowSize,
    bandspace,
    setdata,
    pathShape,
    panLinear,
    panLog,
    panPow,
    panSymlog,
    zoomLinear,
    zoomLog,
    zoomPow,
    zoomSymlog,
    encode,
    modify,
    lassoAppend,
    lassoPath,
    intersectLasso
  };
  var eventFunctions = ["view", "item", "group", "xy", "x", "y"];
  var eventPrefix = "event.vega.";
  var thisPrefix = "this.";
  var astVisitors = {};
  var codegenParams = {
    forbidden: ["_"],
    allowed: ["datum", "event", "item"],
    fieldvar: "datum",
    globalvar: (id2) => `_[${$(SignalPrefix + id2)}]`,
    functions: buildFunctions,
    constants: Constants,
    visitors: astVisitors
  };
  var codeGenerator = codegen(codegenParams);
  function buildFunctions(codegen2) {
    const fn = Functions(codegen2);
    eventFunctions.forEach((name4) => fn[name4] = eventPrefix + name4);
    for (const name4 in functionContext) {
      fn[name4] = thisPrefix + name4;
    }
    extend(fn, internalScaleFunctions(codegen2, functionContext, astVisitors));
    return fn;
  }
  function expressionFunction(name4, fn, visitor) {
    if (arguments.length === 1) {
      return functionContext[name4];
    }
    functionContext[name4] = fn;
    if (visitor) astVisitors[name4] = visitor;
    if (codeGenerator) codeGenerator.functions[name4] = thisPrefix + name4;
    return this;
  }
  expressionFunction("bandwidth", bandwidth, scaleVisitor);
  expressionFunction("copy", copy3, scaleVisitor);
  expressionFunction("domain", domain, scaleVisitor);
  expressionFunction("range", range3, scaleVisitor);
  expressionFunction("invert", invert, scaleVisitor);
  expressionFunction("scale", scale4, scaleVisitor);
  expressionFunction("gradient", scaleGradient, scaleVisitor);
  expressionFunction("geoArea", geoArea, scaleVisitor);
  expressionFunction("geoBounds", geoBounds, scaleVisitor);
  expressionFunction("geoCentroid", geoCentroid, scaleVisitor);
  expressionFunction("geoShape", geoShape, scaleVisitor);
  expressionFunction("geoScale", geoScale, scaleVisitor);
  expressionFunction("indata", indata, indataVisitor);
  expressionFunction("data", data, dataVisitor);
  expressionFunction("treePath", treePath, dataVisitor);
  expressionFunction("treeAncestors", treeAncestors, dataVisitor);
  expressionFunction("vlSelectionTest", selectionTest, selectionVisitor);
  expressionFunction("vlSelectionIdTest", selectionIdTest, selectionVisitor);
  expressionFunction("vlSelectionResolve", selectionResolve, selectionVisitor);
  expressionFunction("vlSelectionTuples", selectionTuples);
  function parser2(expr2, scope) {
    const params2 = {};
    let ast;
    try {
      expr2 = isString(expr2) ? expr2 : $(expr2) + "";
      ast = parser(expr2);
    } catch (err) {
      error("Expression parse error: " + expr2);
    }
    ast.visit((node) => {
      if (node.type !== CallExpression) return;
      const name4 = node.callee.name, visit2 = codegenParams.visitors[name4];
      if (visit2) visit2(name4, node.arguments, scope, params2);
    });
    const gen = codeGenerator(ast);
    gen.globals.forEach((name4) => {
      const signalName = SignalPrefix + name4;
      if (!has(params2, signalName) && scope.getSignal(name4)) {
        params2[signalName] = scope.signalRef(name4);
      }
    });
    return {
      $expr: extend({
        code: gen.code
      }, scope.options.ast ? {
        ast
      } : null),
      $fields: gen.fields,
      $params: params2
    };
  }

  // node_modules/vega-runtime/build/vega-runtime.module.js
  function parse5(spec) {
    const ctx = this, operators = spec.operators || [];
    if (spec.background) {
      ctx.background = spec.background;
    }
    if (spec.eventConfig) {
      ctx.eventConfig = spec.eventConfig;
    }
    if (spec.locale) {
      ctx.locale = spec.locale;
    }
    operators.forEach((entry2) => ctx.parseOperator(entry2));
    operators.forEach((entry2) => ctx.parseOperatorParameters(entry2));
    (spec.streams || []).forEach((entry2) => ctx.parseStream(entry2));
    (spec.updates || []).forEach((entry2) => ctx.parseUpdate(entry2));
    return ctx.resolve();
  }
  var Skip = toSet(["rule"]);
  var Swap = toSet(["group", "image", "rect"]);
  function adjustSpatial(encode2, marktype) {
    let code = "";
    if (Skip[marktype]) return code;
    if (encode2.x2) {
      if (encode2.x) {
        if (Swap[marktype]) {
          code += "if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;";
        }
        code += "o.width=o.x2-o.x;";
      } else {
        code += "o.x=o.x2-(o.width||0);";
      }
    }
    if (encode2.xc) {
      code += "o.x=o.xc-(o.width||0)/2;";
    }
    if (encode2.y2) {
      if (encode2.y) {
        if (Swap[marktype]) {
          code += "if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;";
        }
        code += "o.height=o.y2-o.y;";
      } else {
        code += "o.y=o.y2-(o.height||0);";
      }
    }
    if (encode2.yc) {
      code += "o.y=o.yc-(o.height||0)/2;";
    }
    return code;
  }
  function canonicalType(type3) {
    return (type3 + "").toLowerCase();
  }
  function isOperator(type3) {
    return canonicalType(type3) === "operator";
  }
  function isCollect(type3) {
    return canonicalType(type3) === "collect";
  }
  function expression(ctx, args, code) {
    if (!code.endsWith(";")) {
      code = "return(" + code + ");";
    }
    const fn = Function(...args.concat(code));
    return ctx && ctx.functions ? fn.bind(ctx.functions) : fn;
  }
  function _compare(u5, v3, lt, gt) {
    return `((u = ${u5}) < (v = ${v3}) || u == null) && v != null ? ${lt}
  : (u > v || v == null) && u != null ? ${gt}
  : ((v = v instanceof Date ? +v : v), (u = u instanceof Date ? +u : u)) !== u && v === v ? ${lt}
  : v !== v && u === u ? ${gt} : `;
  }
  var expressionCodegen = {
    /**
     * Parse an expression used to update an operator value.
     */
    operator: (ctx, expr2) => expression(ctx, ["_"], expr2.code),
    /**
     * Parse an expression provided as an operator parameter value.
     */
    parameter: (ctx, expr2) => expression(ctx, ["datum", "_"], expr2.code),
    /**
     * Parse an expression applied to an event stream.
     */
    event: (ctx, expr2) => expression(ctx, ["event"], expr2.code),
    /**
     * Parse an expression used to handle an event-driven operator update.
     */
    handler: (ctx, expr2) => {
      const code = `var datum=event.item&&event.item.datum;return ${expr2.code};`;
      return expression(ctx, ["_", "event"], code);
    },
    /**
     * Parse an expression that performs visual encoding.
     */
    encode: (ctx, encode2) => {
      const {
        marktype,
        channels
      } = encode2;
      let code = "var o=item,datum=o.datum,m=0,$;";
      for (const name4 in channels) {
        const o2 = "o[" + $(name4) + "]";
        code += `$=${channels[name4].code};if(${o2}!==$)${o2}=$,m=1;`;
      }
      code += adjustSpatial(channels, marktype);
      code += "return m;";
      return expression(ctx, ["item", "_"], code);
    },
    /**
     * Optimized code generators for access and comparison.
     */
    codegen: {
      get(path3) {
        const ref2 = `[${path3.map($).join("][")}]`;
        const get6 = Function("_", `return _${ref2};`);
        get6.path = ref2;
        return get6;
      },
      comparator(fields, orders) {
        let t4;
        const map4 = (f2, i2) => {
          const o2 = orders[i2];
          let u5, v3;
          if (f2.path) {
            u5 = `a${f2.path}`;
            v3 = `b${f2.path}`;
          } else {
            (t4 = t4 || {})["f" + i2] = f2;
            u5 = `this.f${i2}(a)`;
            v3 = `this.f${i2}(b)`;
          }
          return _compare(u5, v3, -o2, o2);
        };
        const fn = Function("a", "b", "var u, v; return " + fields.map(map4).join("") + "0;");
        return t4 ? fn.bind(t4) : fn;
      }
    }
  };
  function parseOperator(spec) {
    const ctx = this;
    if (isOperator(spec.type) || !spec.type) {
      ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);
    } else {
      ctx.transform(spec, spec.type);
    }
  }
  function parseOperatorParameters(spec) {
    const ctx = this;
    if (spec.params) {
      const op = ctx.get(spec.id);
      if (!op) error("Invalid operator id: " + spec.id);
      ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));
    }
  }
  function parseParameters(spec, params2) {
    params2 = params2 || {};
    const ctx = this;
    for (const key2 in spec) {
      const value3 = spec[key2];
      params2[key2] = isArray(value3) ? value3.map((v3) => parseParameter(v3, ctx, params2)) : parseParameter(value3, ctx, params2);
    }
    return params2;
  }
  function parseParameter(spec, ctx, params2) {
    if (!spec || !isObject(spec)) return spec;
    for (let i2 = 0, n2 = PARSERS.length, p2; i2 < n2; ++i2) {
      p2 = PARSERS[i2];
      if (has(spec, p2.key)) {
        return p2.parse(spec, ctx, params2);
      }
    }
    return spec;
  }
  var PARSERS = [{
    key: "$ref",
    parse: getOperator
  }, {
    key: "$key",
    parse: getKey
  }, {
    key: "$expr",
    parse: getExpression
  }, {
    key: "$field",
    parse: getField2
  }, {
    key: "$encode",
    parse: getEncode
  }, {
    key: "$compare",
    parse: getCompare
  }, {
    key: "$context",
    parse: getContext
  }, {
    key: "$subflow",
    parse: getSubflow
  }, {
    key: "$tupleid",
    parse: getTupleId
  }];
  function getOperator(_, ctx) {
    return ctx.get(_.$ref) || error("Operator not defined: " + _.$ref);
  }
  function getExpression(_, ctx, params2) {
    if (_.$params) {
      ctx.parseParameters(_.$params, params2);
    }
    const k2 = "e:" + _.$expr.code;
    return ctx.fn[k2] || (ctx.fn[k2] = accessor(ctx.parameterExpression(_.$expr), _.$fields));
  }
  function getKey(_, ctx) {
    const k2 = "k:" + _.$key + "_" + !!_.$flat;
    return ctx.fn[k2] || (ctx.fn[k2] = key(_.$key, _.$flat, ctx.expr.codegen));
  }
  function getField2(_, ctx) {
    if (!_.$field) return null;
    const k2 = "f:" + _.$field + "_" + _.$name;
    return ctx.fn[k2] || (ctx.fn[k2] = field(_.$field, _.$name, ctx.expr.codegen));
  }
  function getCompare(_, ctx) {
    const k2 = "c:" + _.$compare + "_" + _.$order, c4 = array(_.$compare).map((_2) => _2 && _2.$tupleid ? tupleid : _2);
    return ctx.fn[k2] || (ctx.fn[k2] = compare(c4, _.$order, ctx.expr.codegen));
  }
  function getEncode(_, ctx) {
    const spec = _.$encode, encode2 = {};
    for (const name4 in spec) {
      const enc = spec[name4];
      encode2[name4] = accessor(ctx.encodeExpression(enc.$expr), enc.$fields);
      encode2[name4].output = enc.$output;
    }
    return encode2;
  }
  function getContext(_, ctx) {
    return ctx;
  }
  function getSubflow(_, ctx) {
    const spec = _.$subflow;
    return function(dataflow, key2, parent) {
      const subctx = ctx.fork().parse(spec), op = subctx.get(spec.operators[0].id), p2 = subctx.signals.parent;
      if (p2) p2.set(parent);
      op.detachSubflow = () => ctx.detach(subctx);
      return op;
    };
  }
  function getTupleId() {
    return tupleid;
  }
  function parseStream(spec) {
    var ctx = this, filter3 = spec.filter != null ? ctx.eventExpression(spec.filter) : void 0, stream2 = spec.stream != null ? ctx.get(spec.stream) : void 0, args;
    if (spec.source) {
      stream2 = ctx.events(spec.source, spec.type, filter3);
    } else if (spec.merge) {
      args = spec.merge.map((_) => ctx.get(_));
      stream2 = args[0].merge.apply(args[0], args.slice(1));
    }
    if (spec.between) {
      args = spec.between.map((_) => ctx.get(_));
      stream2 = stream2.between(args[0], args[1]);
    }
    if (spec.filter) {
      stream2 = stream2.filter(filter3);
    }
    if (spec.throttle != null) {
      stream2 = stream2.throttle(+spec.throttle);
    }
    if (spec.debounce != null) {
      stream2 = stream2.debounce(+spec.debounce);
    }
    if (stream2 == null) {
      error("Invalid stream definition: " + JSON.stringify(spec));
    }
    if (spec.consume) stream2.consume(true);
    ctx.stream(spec, stream2);
  }
  function parseUpdate(spec) {
    var ctx = this, srcid = isObject(srcid = spec.source) ? srcid.$ref : srcid, source4 = ctx.get(srcid), target2 = null, update3 = spec.update, params2 = void 0;
    if (!source4) error("Source not defined: " + spec.source);
    target2 = spec.target && spec.target.$expr ? ctx.eventExpression(spec.target.$expr) : ctx.get(spec.target);
    if (update3 && update3.$expr) {
      if (update3.$params) {
        params2 = ctx.parseParameters(update3.$params);
      }
      update3 = ctx.handlerExpression(update3.$expr);
    }
    ctx.update(spec, source4, target2, update3, params2);
  }
  var SKIP3 = {
    skip: true
  };
  function getState(options) {
    var ctx = this, state = {};
    if (options.signals) {
      var signals = state.signals = {};
      Object.keys(ctx.signals).forEach((key2) => {
        const op = ctx.signals[key2];
        if (options.signals(key2, op)) {
          signals[key2] = op.value;
        }
      });
    }
    if (options.data) {
      var data3 = state.data = {};
      Object.keys(ctx.data).forEach((key2) => {
        const dataset = ctx.data[key2];
        if (options.data(key2, dataset)) {
          data3[key2] = dataset.input.value;
        }
      });
    }
    if (ctx.subcontext && options.recurse !== false) {
      state.subcontext = ctx.subcontext.map((ctx2) => ctx2.getState(options));
    }
    return state;
  }
  function setState(state) {
    var ctx = this, df = ctx.dataflow, data3 = state.data, signals = state.signals;
    Object.keys(signals || {}).forEach((key2) => {
      df.update(ctx.signals[key2], signals[key2], SKIP3);
    });
    Object.keys(data3 || {}).forEach((key2) => {
      df.pulse(ctx.data[key2].input, df.changeset().remove(truthy).insert(data3[key2]));
    });
    (state.subcontext || []).forEach((substate, i2) => {
      const subctx = ctx.subcontext[i2];
      if (subctx) subctx.setState(substate);
    });
  }
  function context2(df, transforms2, functions, expr2) {
    return new Context(df, transforms2, functions, expr2);
  }
  function Context(df, transforms2, functions, expr2) {
    this.dataflow = df;
    this.transforms = transforms2;
    this.events = df.events.bind(df);
    this.expr = expr2 || expressionCodegen, this.signals = {};
    this.scales = {};
    this.nodes = {};
    this.data = {};
    this.fn = {};
    if (functions) {
      this.functions = Object.create(functions);
      this.functions.context = this;
    }
  }
  function Subcontext(ctx) {
    this.dataflow = ctx.dataflow;
    this.transforms = ctx.transforms;
    this.events = ctx.events;
    this.expr = ctx.expr;
    this.signals = Object.create(ctx.signals);
    this.scales = Object.create(ctx.scales);
    this.nodes = Object.create(ctx.nodes);
    this.data = Object.create(ctx.data);
    this.fn = Object.create(ctx.fn);
    if (ctx.functions) {
      this.functions = Object.create(ctx.functions);
      this.functions.context = this;
    }
  }
  Context.prototype = Subcontext.prototype = {
    fork() {
      const ctx = new Subcontext(this);
      (this.subcontext || (this.subcontext = [])).push(ctx);
      return ctx;
    },
    detach(ctx) {
      this.subcontext = this.subcontext.filter((c4) => c4 !== ctx);
      const keys4 = Object.keys(ctx.nodes);
      for (const key2 of keys4) ctx.nodes[key2]._targets = null;
      for (const key2 of keys4) ctx.nodes[key2].detach();
      ctx.nodes = null;
    },
    get(id2) {
      return this.nodes[id2];
    },
    set(id2, node) {
      return this.nodes[id2] = node;
    },
    add(spec, op) {
      const ctx = this, df = ctx.dataflow, data3 = spec.value;
      ctx.set(spec.id, op);
      if (isCollect(spec.type) && data3) {
        if (data3.$ingest) {
          df.ingest(op, data3.$ingest, data3.$format);
        } else if (data3.$request) {
          df.preload(op, data3.$request, data3.$format);
        } else {
          df.pulse(op, df.changeset().insert(data3));
        }
      }
      if (spec.root) {
        ctx.root = op;
      }
      if (spec.parent) {
        let p2 = ctx.get(spec.parent.$ref);
        if (p2) {
          df.connect(p2, [op]);
          op.targets().add(p2);
        } else {
          (ctx.unresolved = ctx.unresolved || []).push(() => {
            p2 = ctx.get(spec.parent.$ref);
            df.connect(p2, [op]);
            op.targets().add(p2);
          });
        }
      }
      if (spec.signal) {
        ctx.signals[spec.signal] = op;
      }
      if (spec.scale) {
        ctx.scales[spec.scale] = op;
      }
      if (spec.data) {
        for (const name4 in spec.data) {
          const data4 = ctx.data[name4] || (ctx.data[name4] = {});
          spec.data[name4].forEach((role) => data4[role] = op);
        }
      }
    },
    resolve() {
      (this.unresolved || []).forEach((fn) => fn());
      delete this.unresolved;
      return this;
    },
    operator(spec, update3) {
      this.add(spec, this.dataflow.add(spec.value, update3));
    },
    transform(spec, type3) {
      this.add(spec, this.dataflow.add(this.transforms[canonicalType(type3)]));
    },
    stream(spec, stream2) {
      this.set(spec.id, stream2);
    },
    update(spec, stream2, target2, update3, params2) {
      this.dataflow.on(stream2, target2, update3, params2, spec.options);
    },
    // expression parsing
    operatorExpression(expr2) {
      return this.expr.operator(this, expr2);
    },
    parameterExpression(expr2) {
      return this.expr.parameter(this, expr2);
    },
    eventExpression(expr2) {
      return this.expr.event(this, expr2);
    },
    handlerExpression(expr2) {
      return this.expr.handler(this, expr2);
    },
    encodeExpression(encode2) {
      return this.expr.encode(this, encode2);
    },
    // parse methods
    parse: parse5,
    parseOperator,
    parseOperatorParameters,
    parseParameters,
    parseStream,
    parseUpdate,
    // state methods
    getState,
    setState
  };

  // node_modules/vega-view/build/vega-view.module.js
  function initializeAria(view) {
    const el = view.container();
    if (el) {
      el.setAttribute("role", "graphics-document");
      el.setAttribute("aria-roleDescription", "visualization");
      ariaLabel(el, view.description());
    }
  }
  function ariaLabel(el, desc) {
    if (el) desc == null ? el.removeAttribute("aria-label") : el.setAttribute("aria-label", desc);
  }
  function background2(view) {
    view.add(null, (_) => {
      view._background = _.bg;
      view._resize = 1;
      return _.bg;
    }, {
      bg: view._signals.background
    });
  }
  var Default = "default";
  function cursor(view) {
    const cursor3 = view._signals.cursor || (view._signals.cursor = view.add({
      user: Default,
      item: null
    }));
    view.on(view.events("view", "pointermove"), cursor3, (_, event2) => {
      const value3 = cursor3.value, user = value3 ? isString(value3) ? value3 : value3.user : Default, item = event2.item && event2.item.cursor || null;
      return value3 && user === value3.user && item == value3.item ? value3 : {
        user,
        item
      };
    });
    view.add(null, function(_) {
      let user = _.cursor, item = this.value;
      if (!isString(user)) {
        item = user.item;
        user = user.user;
      }
      setCursor(view, user && user !== Default ? user : item || user);
      return item;
    }, {
      cursor: cursor3
    });
  }
  function setCursor(view, cursor3) {
    const el = view.globalCursor() ? typeof document !== "undefined" && document.body : view.container();
    if (el) {
      return cursor3 == null ? el.style.removeProperty("cursor") : el.style.cursor = cursor3;
    }
  }
  function dataref(view, name4) {
    var data3 = view._runtime.data;
    if (!has(data3, name4)) {
      error("Unrecognized data set: " + name4);
    }
    return data3[name4];
  }
  function data2(name4, values4) {
    return arguments.length < 2 ? dataref(this, name4).values.value : change.call(this, name4, changeset().remove(truthy).insert(values4));
  }
  function change(name4, changes) {
    if (!isChangeSet(changes)) {
      error("Second argument to changes must be a changeset.");
    }
    const dataset = dataref(this, name4);
    dataset.modified = true;
    return this.pulse(dataset.input, changes);
  }
  function insert(name4, _) {
    return change.call(this, name4, changeset().insert(_));
  }
  function remove(name4, _) {
    return change.call(this, name4, changeset().remove(_));
  }
  function width(view) {
    var padding3 = view.padding();
    return Math.max(0, view._viewWidth + padding3.left + padding3.right);
  }
  function height(view) {
    var padding3 = view.padding();
    return Math.max(0, view._viewHeight + padding3.top + padding3.bottom);
  }
  function offset3(view) {
    var padding3 = view.padding(), origin = view._origin;
    return [padding3.left + origin[0], padding3.top + origin[1]];
  }
  function resizeRenderer(view) {
    var origin = offset3(view), w3 = width(view), h3 = height(view);
    view._renderer.background(view.background());
    view._renderer.resize(w3, h3, origin);
    view._handler.origin(origin);
    view._resizeListeners.forEach((handler) => {
      try {
        handler(w3, h3);
      } catch (error3) {
        view.error(error3);
      }
    });
  }
  function eventExtend(view, event2, item) {
    var r2 = view._renderer, el = r2 && r2.canvas(), p2, e4, translate4;
    if (el) {
      translate4 = offset3(view);
      e4 = event2.changedTouches ? event2.changedTouches[0] : event2;
      p2 = point6(e4, el);
      p2[0] -= translate4[0];
      p2[1] -= translate4[1];
    }
    event2.dataflow = view;
    event2.item = item;
    event2.vega = extension(view, item, p2);
    return event2;
  }
  function extension(view, item, point9) {
    const itemGroup = item ? item.mark.marktype === "group" ? item : item.mark.group : null;
    function group2(name4) {
      var g2 = itemGroup, i2;
      if (name4) for (i2 = item; i2; i2 = i2.mark.group) {
        if (i2.mark.name === name4) {
          g2 = i2;
          break;
        }
      }
      return g2 && g2.mark && g2.mark.interactive ? g2 : {};
    }
    function xy(item2) {
      if (!item2) return point9;
      if (isString(item2)) item2 = group2(item2);
      const p2 = point9.slice();
      while (item2) {
        p2[0] -= item2.x || 0;
        p2[1] -= item2.y || 0;
        item2 = item2.mark && item2.mark.group;
      }
      return p2;
    }
    return {
      view: constant(view),
      item: constant(item || {}),
      group: group2,
      xy,
      x: (item2) => xy(item2)[0],
      y: (item2) => xy(item2)[1]
    };
  }
  var VIEW = "view";
  var TIMER = "timer";
  var WINDOW = "window";
  var NO_TRAP = {
    trap: false
  };
  function initializeEventConfig(config) {
    const events3 = extend({
      defaults: {}
    }, config);
    const unpack = (obj, keys4) => {
      keys4.forEach((k2) => {
        if (isArray(obj[k2])) obj[k2] = toSet(obj[k2]);
      });
    };
    unpack(events3.defaults, ["prevent", "allow"]);
    unpack(events3, ["view", "window", "selector"]);
    return events3;
  }
  function trackEventListener(view, sources, type3, handler) {
    view._eventListeners.push({
      type: type3,
      sources: array(sources),
      handler
    });
  }
  function prevent(view, type3) {
    var def2 = view._eventConfig.defaults, prevent2 = def2.prevent, allow = def2.allow;
    return prevent2 === false || allow === true ? false : prevent2 === true || allow === false ? true : prevent2 ? prevent2[type3] : allow ? !allow[type3] : view.preventDefault();
  }
  function permit(view, key2, type3) {
    const rule4 = view._eventConfig && view._eventConfig[key2];
    if (rule4 === false || isObject(rule4) && !rule4[type3]) {
      view.warn(`Blocked ${key2} ${type3} event listener.`);
      return false;
    }
    return true;
  }
  function events2(source4, type3, filter3) {
    var view = this, s2 = new EventStream(filter3), send = function(e4, item) {
      view.runAsync(null, () => {
        if (source4 === VIEW && prevent(view, type3)) {
          e4.preventDefault();
        }
        s2.receive(eventExtend(view, e4, item));
      });
    }, sources;
    if (source4 === TIMER) {
      if (permit(view, "timer", type3)) {
        view.timer(send, type3);
      }
    } else if (source4 === VIEW) {
      if (permit(view, "view", type3)) {
        view.addEventListener(type3, send, NO_TRAP);
      }
    } else {
      if (source4 === WINDOW) {
        if (permit(view, "window", type3) && typeof window !== "undefined") {
          sources = [window];
        }
      } else if (typeof document !== "undefined") {
        if (permit(view, "selector", type3)) {
          sources = Array.from(document.querySelectorAll(source4));
        }
      }
      if (!sources) {
        view.warn("Can not resolve event source: " + source4);
      } else {
        for (var i2 = 0, n2 = sources.length; i2 < n2; ++i2) {
          sources[i2].addEventListener(type3, send);
        }
        trackEventListener(view, sources, type3, send);
      }
    }
    return s2;
  }
  function itemFilter(event2) {
    return event2.item;
  }
  function markTarget(event2) {
    return event2.item.mark.source;
  }
  function invoke(name4) {
    return function(_, event2) {
      return event2.vega.view().changeset().encode(event2.item, name4);
    };
  }
  function hover(hoverSet, leaveSet) {
    hoverSet = [hoverSet || "hover"];
    leaveSet = [leaveSet || "update", hoverSet[0]];
    this.on(this.events("view", "pointerover", itemFilter), markTarget, invoke(hoverSet));
    this.on(this.events("view", "pointerout", itemFilter), markTarget, invoke(leaveSet));
    return this;
  }
  function finalize() {
    var tooltip2 = this._tooltip, timers = this._timers, handlers = this._handler.handlers(), listeners = this._eventListeners, n2, m4, e4, h3, t4;
    n2 = timers.length;
    while (--n2 >= 0) {
      timers[n2].stop();
    }
    n2 = listeners.length;
    while (--n2 >= 0) {
      e4 = listeners[n2];
      m4 = e4.sources.length;
      while (--m4 >= 0) {
        e4.sources[m4].removeEventListener(e4.type, e4.handler);
      }
    }
    if (tooltip2) {
      tooltip2.call(this, this._handler, null, null, null);
    }
    n2 = handlers.length;
    while (--n2 >= 0) {
      t4 = handlers[n2].type;
      h3 = handlers[n2].handler;
      this._handler.off(t4, h3);
    }
    return this;
  }
  function element2(tag, attr2, text4) {
    const el = document.createElement(tag);
    for (const key2 in attr2) el.setAttribute(key2, attr2[key2]);
    if (text4 != null) el.textContent = text4;
    return el;
  }
  var BindClass = "vega-bind";
  var NameClass = "vega-bind-name";
  var RadioClass = "vega-bind-radio";
  function bind2(view, el, binding) {
    if (!el) return;
    const param2 = binding.param;
    let bind3 = binding.state;
    if (!bind3) {
      bind3 = binding.state = {
        elements: null,
        active: false,
        set: null,
        update: (value3) => {
          if (value3 != view.signal(param2.signal)) {
            view.runAsync(null, () => {
              bind3.source = true;
              view.signal(param2.signal, value3);
            });
          }
        }
      };
      if (param2.debounce) {
        bind3.update = debounce(param2.debounce, bind3.update);
      }
    }
    const create4 = param2.input == null && param2.element ? target : generate;
    create4(bind3, el, param2, view);
    if (!bind3.active) {
      view.on(view._signals[param2.signal], null, () => {
        bind3.source ? bind3.source = false : bind3.set(view.signal(param2.signal));
      });
      bind3.active = true;
    }
    return bind3;
  }
  function target(bind3, node, param2, view) {
    const type3 = param2.event || "input";
    const handler = () => bind3.update(node.value);
    view.signal(param2.signal, node.value);
    node.addEventListener(type3, handler);
    trackEventListener(view, node, type3, handler);
    bind3.set = (value3) => {
      node.value = value3;
      node.dispatchEvent(event(type3));
    };
  }
  function event(type3) {
    return typeof Event !== "undefined" ? new Event(type3) : {
      type: type3
    };
  }
  function generate(bind3, el, param2, view) {
    const value3 = view.signal(param2.signal);
    const div = element2("div", {
      "class": BindClass
    });
    const wrapper = param2.input === "radio" ? div : div.appendChild(element2("label"));
    wrapper.appendChild(element2("span", {
      "class": NameClass
    }, param2.name || param2.signal));
    el.appendChild(div);
    let input = form;
    switch (param2.input) {
      case "checkbox":
        input = checkbox;
        break;
      case "select":
        input = select;
        break;
      case "radio":
        input = radio;
        break;
      case "range":
        input = range4;
        break;
    }
    input(bind3, wrapper, param2, value3);
  }
  function form(bind3, el, param2, value3) {
    const node = element2("input");
    for (const key2 in param2) {
      if (key2 !== "signal" && key2 !== "element") {
        node.setAttribute(key2 === "input" ? "type" : key2, param2[key2]);
      }
    }
    node.setAttribute("name", param2.signal);
    node.value = value3;
    el.appendChild(node);
    node.addEventListener("input", () => bind3.update(node.value));
    bind3.elements = [node];
    bind3.set = (value4) => node.value = value4;
  }
  function checkbox(bind3, el, param2, value3) {
    const attr2 = {
      type: "checkbox",
      name: param2.signal
    };
    if (value3) attr2.checked = true;
    const node = element2("input", attr2);
    el.appendChild(node);
    node.addEventListener("change", () => bind3.update(node.checked));
    bind3.elements = [node];
    bind3.set = (value4) => node.checked = !!value4 || null;
  }
  function select(bind3, el, param2, value3) {
    const node = element2("select", {
      name: param2.signal
    }), labels3 = param2.labels || [];
    param2.options.forEach((option, i2) => {
      const attr2 = {
        value: option
      };
      if (valuesEqual(option, value3)) attr2.selected = true;
      node.appendChild(element2("option", attr2, (labels3[i2] || option) + ""));
    });
    el.appendChild(node);
    node.addEventListener("change", () => {
      bind3.update(param2.options[node.selectedIndex]);
    });
    bind3.elements = [node];
    bind3.set = (value4) => {
      for (let i2 = 0, n2 = param2.options.length; i2 < n2; ++i2) {
        if (valuesEqual(param2.options[i2], value4)) {
          node.selectedIndex = i2;
          return;
        }
      }
    };
  }
  function radio(bind3, el, param2, value3) {
    const group2 = element2("span", {
      "class": RadioClass
    }), labels3 = param2.labels || [];
    el.appendChild(group2);
    bind3.elements = param2.options.map((option, i2) => {
      const attr2 = {
        type: "radio",
        name: param2.signal,
        value: option
      };
      if (valuesEqual(option, value3)) attr2.checked = true;
      const input = element2("input", attr2);
      input.addEventListener("change", () => bind3.update(option));
      const label = element2("label", {}, (labels3[i2] || option) + "");
      label.prepend(input);
      group2.appendChild(label);
      return input;
    });
    bind3.set = (value4) => {
      const nodes = bind3.elements, n2 = nodes.length;
      for (let i2 = 0; i2 < n2; ++i2) {
        if (valuesEqual(nodes[i2].value, value4)) nodes[i2].checked = true;
      }
    };
  }
  function range4(bind3, el, param2, value3) {
    value3 = value3 !== void 0 ? value3 : (+param2.max + +param2.min) / 2;
    const max4 = param2.max != null ? param2.max : Math.max(100, +value3) || 100, min4 = param2.min || Math.min(0, max4, +value3) || 0, step = param2.step || tickStep(min4, max4, 100);
    const node = element2("input", {
      type: "range",
      name: param2.signal,
      min: min4,
      max: max4,
      step
    });
    node.value = value3;
    const span2 = element2("span", {}, +value3);
    el.appendChild(node);
    el.appendChild(span2);
    const update3 = () => {
      span2.textContent = node.value;
      bind3.update(+node.value);
    };
    node.addEventListener("input", update3);
    node.addEventListener("change", update3);
    bind3.elements = [node];
    bind3.set = (value4) => {
      node.value = value4;
      span2.textContent = value4;
    };
  }
  function valuesEqual(a4, b3) {
    return a4 === b3 || a4 + "" === b3 + "";
  }
  function initializeRenderer(view, r2, el, constructor, scaleFactor, opt) {
    r2 = r2 || new constructor(view.loader());
    return r2.initialize(el, width(view), height(view), offset3(view), scaleFactor, opt).background(view.background());
  }
  function trap(view, fn) {
    return !fn ? null : function() {
      try {
        fn.apply(this, arguments);
      } catch (error3) {
        view.error(error3);
      }
    };
  }
  function initializeHandler(view, prevHandler, el, constructor) {
    const handler = new constructor(view.loader(), trap(view, view.tooltip())).scene(view.scenegraph().root).initialize(el, offset3(view), view);
    if (prevHandler) {
      prevHandler.handlers().forEach((h3) => {
        handler.on(h3.type, h3.handler);
      });
    }
    return handler;
  }
  function initialize2(el, elBind) {
    const view = this, type3 = view._renderType, config = view._eventConfig.bind, module5 = renderModule(type3);
    el = view._el = el ? lookup4(view, el, true) : null;
    initializeAria(view);
    if (!module5) view.error("Unrecognized renderer type: " + type3);
    const Handler3 = module5.handler || CanvasHandler, Renderer2 = el ? module5.renderer : module5.headless;
    view._renderer = !Renderer2 ? null : initializeRenderer(view, view._renderer, el, Renderer2);
    view._handler = initializeHandler(view, view._handler, el, Handler3);
    view._redraw = true;
    if (el && config !== "none") {
      elBind = elBind ? view._elBind = lookup4(view, elBind, true) : el.appendChild(element2("form", {
        "class": "vega-bindings"
      }));
      view._bind.forEach((_) => {
        if (_.param.element && config !== "container") {
          _.element = lookup4(view, _.param.element, !!_.param.input);
        }
      });
      view._bind.forEach((_) => {
        bind2(view, _.element || elBind, _);
      });
    }
    return view;
  }
  function lookup4(view, el, clear2) {
    if (typeof el === "string") {
      if (typeof document !== "undefined") {
        el = document.querySelector(el);
        if (!el) {
          view.error("Signal bind element not found: " + el);
          return null;
        }
      } else {
        view.error("DOM document instance not found.");
        return null;
      }
    }
    if (el && clear2) {
      try {
        el.textContent = "";
      } catch (e4) {
        el = null;
        view.error(e4);
      }
    }
    return el;
  }
  var number6 = (_) => +_ || 0;
  var paddingObject = (_) => ({
    top: _,
    bottom: _,
    left: _,
    right: _
  });
  function padding(_) {
    return isObject(_) ? {
      top: number6(_.top),
      bottom: number6(_.bottom),
      left: number6(_.left),
      right: number6(_.right)
    } : paddingObject(number6(_));
  }
  async function renderHeadless(view, type3, scaleFactor, opt) {
    const module5 = renderModule(type3), ctr = module5 && module5.headless;
    if (!ctr) error("Unrecognized renderer type: " + type3);
    await view.runAsync();
    return initializeRenderer(view, null, null, ctr, scaleFactor, opt).renderAsync(view._scenegraph.root);
  }
  async function renderToImageURL(type3, scaleFactor) {
    if (type3 !== RenderType.Canvas && type3 !== RenderType.SVG && type3 !== RenderType.PNG) {
      error("Unrecognized image type: " + type3);
    }
    const r2 = await renderHeadless(this, type3, scaleFactor);
    return type3 === RenderType.SVG ? toBlobURL(r2.svg(), "image/svg+xml") : r2.canvas().toDataURL("image/png");
  }
  function toBlobURL(data3, mime) {
    const blob = new Blob([data3], {
      type: mime
    });
    return window.URL.createObjectURL(blob);
  }
  async function renderToCanvas(scaleFactor, opt) {
    const r2 = await renderHeadless(this, RenderType.Canvas, scaleFactor, opt);
    return r2.canvas();
  }
  async function renderToSVG(scaleFactor) {
    const r2 = await renderHeadless(this, RenderType.SVG, scaleFactor);
    return r2.svg();
  }
  function runtime(view, spec, expr2) {
    return context2(view, transforms, functionContext, expr2).parse(spec);
  }
  function scale5(name4) {
    var scales2 = this._runtime.scales;
    if (!has(scales2, name4)) {
      error("Unrecognized scale or projection: " + name4);
    }
    return scales2[name4].value;
  }
  var Width = "width";
  var Height = "height";
  var Padding2 = "padding";
  var Skip2 = {
    skip: true
  };
  function viewWidth(view, width2) {
    var a4 = view.autosize(), p2 = view.padding();
    return width2 - (a4 && a4.contains === Padding2 ? p2.left + p2.right : 0);
  }
  function viewHeight(view, height2) {
    var a4 = view.autosize(), p2 = view.padding();
    return height2 - (a4 && a4.contains === Padding2 ? p2.top + p2.bottom : 0);
  }
  function initializeResize(view) {
    var s2 = view._signals, w3 = s2[Width], h3 = s2[Height], p2 = s2[Padding2];
    function resetSize() {
      view._autosize = view._resize = 1;
    }
    view._resizeWidth = view.add(null, (_) => {
      view._width = _.size;
      view._viewWidth = viewWidth(view, _.size);
      resetSize();
    }, {
      size: w3
    });
    view._resizeHeight = view.add(null, (_) => {
      view._height = _.size;
      view._viewHeight = viewHeight(view, _.size);
      resetSize();
    }, {
      size: h3
    });
    const resizePadding = view.add(null, resetSize, {
      pad: p2
    });
    view._resizeWidth.rank = w3.rank + 1;
    view._resizeHeight.rank = h3.rank + 1;
    resizePadding.rank = p2.rank + 1;
  }
  function resizeView(viewWidth2, viewHeight2, width2, height2, origin, auto) {
    this.runAfter((view) => {
      let rerun2 = 0;
      view._autosize = 0;
      if (view.width() !== width2) {
        rerun2 = 1;
        view.signal(Width, width2, Skip2);
        view._resizeWidth.skip(true);
      }
      if (view.height() !== height2) {
        rerun2 = 1;
        view.signal(Height, height2, Skip2);
        view._resizeHeight.skip(true);
      }
      if (view._viewWidth !== viewWidth2) {
        view._resize = 1;
        view._viewWidth = viewWidth2;
      }
      if (view._viewHeight !== viewHeight2) {
        view._resize = 1;
        view._viewHeight = viewHeight2;
      }
      if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) {
        view._resize = 1;
        view._origin = origin;
      }
      if (rerun2) view.run("enter");
      if (auto) view.runAfter((v3) => v3.resize());
    }, false, 1);
  }
  function getState2(options) {
    return this._runtime.getState(options || {
      data: dataTest,
      signals: signalTest,
      recurse: true
    });
  }
  function dataTest(name4, data3) {
    return data3.modified && isArray(data3.input.value) && !name4.startsWith("_:vega:_");
  }
  function signalTest(name4, op) {
    return !(name4 === "parent" || op instanceof transforms.proxy);
  }
  function setState2(state) {
    this.runAsync(null, (v3) => {
      v3._trigger = false;
      v3._runtime.setState(state);
    }, (v3) => {
      v3._trigger = true;
    });
    return this;
  }
  function timer2(callback, delay) {
    function tick2(elapsed) {
      callback({
        timestamp: Date.now(),
        elapsed
      });
    }
    this._timers.push(interval_default(tick2, delay));
  }
  function defaultTooltip2(handler, event2, item, value3) {
    const el = handler.element();
    if (el) el.setAttribute("title", formatTooltip(value3));
  }
  function formatTooltip(value3) {
    return value3 == null ? "" : isArray(value3) ? formatArray(value3) : isObject(value3) && !isDate(value3) ? formatObject(value3) : value3 + "";
  }
  function formatObject(obj) {
    return Object.keys(obj).map((key2) => {
      const v3 = obj[key2];
      return key2 + ": " + (isArray(v3) ? formatArray(v3) : formatValue2(v3));
    }).join("\n");
  }
  function formatArray(value3) {
    return "[" + value3.map(formatValue2).join(", ") + "]";
  }
  function formatValue2(value3) {
    return isArray(value3) ? "[\u2026]" : isObject(value3) && !isDate(value3) ? "{\u2026}" : value3;
  }
  function watchPixelRatio() {
    if (this.renderer() === "canvas" && this._renderer._canvas) {
      let remove2 = null;
      const updatePixelRatio = () => {
        if (remove2 != null) {
          remove2();
        }
        const media = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
        media.addEventListener("change", updatePixelRatio);
        remove2 = () => {
          media.removeEventListener("change", updatePixelRatio);
        };
        this._renderer._canvas.getContext("2d").pixelRatio = window.devicePixelRatio || 1;
        this._redraw = true;
        this._resize = 1;
        this.resize().runAsync();
      };
      updatePixelRatio();
    }
  }
  function View(spec, options) {
    const view = this;
    options = options || {};
    Dataflow.call(view);
    if (options.loader) view.loader(options.loader);
    if (options.logger) view.logger(options.logger);
    if (options.logLevel != null) view.logLevel(options.logLevel);
    if (options.locale || spec.locale) {
      const loc = extend({}, spec.locale, options.locale);
      view.locale(locale3(loc.number, loc.time));
    }
    view._el = null;
    view._elBind = null;
    view._renderType = options.renderer || RenderType.Canvas;
    view._scenegraph = new Scenegraph();
    const root = view._scenegraph.root;
    view._renderer = null;
    view._tooltip = options.tooltip || defaultTooltip2, view._redraw = true;
    view._handler = new CanvasHandler().scene(root);
    view._globalCursor = false;
    view._preventDefault = false;
    view._timers = [];
    view._eventListeners = [];
    view._resizeListeners = [];
    view._eventConfig = initializeEventConfig(spec.eventConfig);
    view.globalCursor(view._eventConfig.globalCursor);
    const ctx = runtime(view, spec, options.expr);
    view._runtime = ctx;
    view._signals = ctx.signals;
    view._bind = (spec.bindings || []).map((_) => ({
      state: null,
      param: extend({}, _)
    }));
    if (ctx.root) ctx.root.set(root);
    root.source = ctx.data.root.input;
    view.pulse(ctx.data.root.input, view.changeset().insert(root.items));
    view._width = view.width();
    view._height = view.height();
    view._viewWidth = viewWidth(view, view._width);
    view._viewHeight = viewHeight(view, view._height);
    view._origin = [0, 0];
    view._resize = 0;
    view._autosize = 1;
    initializeResize(view);
    background2(view);
    cursor(view);
    view.description(spec.description);
    if (options.hover) view.hover();
    if (options.container) view.initialize(options.container, options.bind);
    if (options.watchPixelRatio) view._watchPixelRatio();
  }
  function lookupSignal(view, name4) {
    return has(view._signals, name4) ? view._signals[name4] : error("Unrecognized signal name: " + $(name4));
  }
  function findOperatorHandler(op, handler) {
    const h3 = (op._targets || []).filter((op2) => op2._update && op2._update.handler === handler);
    return h3.length ? h3[0] : null;
  }
  function addOperatorListener(view, name4, op, handler) {
    let h3 = findOperatorHandler(op, handler);
    if (!h3) {
      h3 = trap(view, () => handler(name4, op.value));
      h3.handler = handler;
      view.on(op, null, h3);
    }
    return view;
  }
  function removeOperatorListener(view, op, handler) {
    const h3 = findOperatorHandler(op, handler);
    if (h3) op._targets.remove(h3);
    return view;
  }
  inherits(View, Dataflow, {
    // -- DATAFLOW / RENDERING ----
    async evaluate(encode2, prerun, postrun) {
      await Dataflow.prototype.evaluate.call(this, encode2, prerun);
      if (this._redraw || this._resize) {
        try {
          if (this._renderer) {
            if (this._resize) {
              this._resize = 0;
              resizeRenderer(this);
            }
            await this._renderer.renderAsync(this._scenegraph.root);
          }
          this._redraw = false;
        } catch (e4) {
          this.error(e4);
        }
      }
      if (postrun) asyncCallback(this, postrun);
      return this;
    },
    dirty(item) {
      this._redraw = true;
      this._renderer && this._renderer.dirty(item);
    },
    // -- GET / SET ----
    description(text4) {
      if (arguments.length) {
        const desc = text4 != null ? text4 + "" : null;
        if (desc !== this._desc) ariaLabel(this._el, this._desc = desc);
        return this;
      }
      return this._desc;
    },
    container() {
      return this._el;
    },
    scenegraph() {
      return this._scenegraph;
    },
    origin() {
      return this._origin.slice();
    },
    signal(name4, value3, options) {
      const op = lookupSignal(this, name4);
      return arguments.length === 1 ? op.value : this.update(op, value3, options);
    },
    width(_) {
      return arguments.length ? this.signal("width", _) : this.signal("width");
    },
    height(_) {
      return arguments.length ? this.signal("height", _) : this.signal("height");
    },
    padding(_) {
      return arguments.length ? this.signal("padding", padding(_)) : padding(this.signal("padding"));
    },
    autosize(_) {
      return arguments.length ? this.signal("autosize", _) : this.signal("autosize");
    },
    background(_) {
      return arguments.length ? this.signal("background", _) : this.signal("background");
    },
    renderer(type3) {
      if (!arguments.length) return this._renderType;
      if (!renderModule(type3)) error("Unrecognized renderer type: " + type3);
      if (type3 !== this._renderType) {
        this._renderType = type3;
        this._resetRenderer();
      }
      return this;
    },
    tooltip(handler) {
      if (!arguments.length) return this._tooltip;
      if (handler !== this._tooltip) {
        this._tooltip = handler;
        this._resetRenderer();
      }
      return this;
    },
    loader(loader2) {
      if (!arguments.length) return this._loader;
      if (loader2 !== this._loader) {
        Dataflow.prototype.loader.call(this, loader2);
        this._resetRenderer();
      }
      return this;
    },
    resize() {
      this._autosize = 1;
      return this.touch(lookupSignal(this, "autosize"));
    },
    _resetRenderer() {
      if (this._renderer) {
        this._renderer = null;
        this.initialize(this._el, this._elBind);
      }
    },
    // -- SIZING ----
    _resizeView: resizeView,
    // -- EVENT HANDLING ----
    addEventListener(type3, handler, options) {
      let callback = handler;
      if (!(options && options.trap === false)) {
        callback = trap(this, handler);
        callback.raw = handler;
      }
      this._handler.on(type3, callback);
      return this;
    },
    removeEventListener(type3, handler) {
      var handlers = this._handler.handlers(type3), i2 = handlers.length, h3, t4;
      while (--i2 >= 0) {
        t4 = handlers[i2].type;
        h3 = handlers[i2].handler;
        if (type3 === t4 && (handler === h3 || handler === h3.raw)) {
          this._handler.off(t4, h3);
          break;
        }
      }
      return this;
    },
    addResizeListener(handler) {
      const l2 = this._resizeListeners;
      if (!l2.includes(handler)) {
        l2.push(handler);
      }
      return this;
    },
    removeResizeListener(handler) {
      var l2 = this._resizeListeners, i2 = l2.indexOf(handler);
      if (i2 >= 0) {
        l2.splice(i2, 1);
      }
      return this;
    },
    addSignalListener(name4, handler) {
      return addOperatorListener(this, name4, lookupSignal(this, name4), handler);
    },
    removeSignalListener(name4, handler) {
      return removeOperatorListener(this, lookupSignal(this, name4), handler);
    },
    addDataListener(name4, handler) {
      return addOperatorListener(this, name4, dataref(this, name4).values, handler);
    },
    removeDataListener(name4, handler) {
      return removeOperatorListener(this, dataref(this, name4).values, handler);
    },
    globalCursor(_) {
      if (arguments.length) {
        if (this._globalCursor !== !!_) {
          const prev = setCursor(this, null);
          this._globalCursor = !!_;
          if (prev) setCursor(this, prev);
        }
        return this;
      } else {
        return this._globalCursor;
      }
    },
    preventDefault(_) {
      if (arguments.length) {
        this._preventDefault = _;
        return this;
      } else {
        return this._preventDefault;
      }
    },
    timer: timer2,
    events: events2,
    finalize,
    hover,
    // -- DATA ----
    data: data2,
    change,
    insert,
    remove,
    // -- SCALES --
    scale: scale5,
    // -- INITIALIZATION ----
    initialize: initialize2,
    // -- HEADLESS RENDERING ----
    toImageURL: renderToImageURL,
    toCanvas: renderToCanvas,
    toSVG: renderToSVG,
    // -- SAVE / RESTORE STATE ----
    getState: getState2,
    setState: setState2,
    // RE-RENDER ON ZOOM
    _watchPixelRatio: watchPixelRatio
  });

  // node_modules/vega-event-selector/build/vega-event-selector.module.js
  var VIEW2 = "view";
  var LBRACK = "[";
  var RBRACK = "]";
  var LBRACE = "{";
  var RBRACE = "}";
  var COLON = ":";
  var COMMA = ",";
  var NAME = "@";
  var GT = ">";
  var ILLEGAL2 = /[[\]{}]/;
  var DEFAULT_MARKS = {
    "*": 1,
    arc: 1,
    area: 1,
    group: 1,
    image: 1,
    line: 1,
    path: 1,
    rect: 1,
    rule: 1,
    shape: 1,
    symbol: 1,
    text: 1,
    trail: 1
  };
  var DEFAULT_SOURCE;
  var MARKS;
  function eventSelector(selector, source4, marks) {
    DEFAULT_SOURCE = source4 || VIEW2;
    MARKS = marks || DEFAULT_MARKS;
    return parseMerge(selector.trim()).map(parseSelector);
  }
  function isMarkType(type3) {
    return MARKS[type3];
  }
  function find3(s2, i2, endChar, pushChar, popChar) {
    const n2 = s2.length;
    let count2 = 0, c4;
    for (; i2 < n2; ++i2) {
      c4 = s2[i2];
      if (!count2 && c4 === endChar) return i2;
      else if (popChar && popChar.indexOf(c4) >= 0) --count2;
      else if (pushChar && pushChar.indexOf(c4) >= 0) ++count2;
    }
    return i2;
  }
  function parseMerge(s2) {
    const output3 = [], n2 = s2.length;
    let start = 0, i2 = 0;
    while (i2 < n2) {
      i2 = find3(s2, i2, COMMA, LBRACK + LBRACE, RBRACK + RBRACE);
      output3.push(s2.substring(start, i2).trim());
      start = ++i2;
    }
    if (output3.length === 0) {
      throw "Empty event selector: " + s2;
    }
    return output3;
  }
  function parseSelector(s2) {
    return s2[0] === "[" ? parseBetween(s2) : parseStream2(s2);
  }
  function parseBetween(s2) {
    const n2 = s2.length;
    let i2 = 1, b3;
    i2 = find3(s2, i2, RBRACK, LBRACK, RBRACK);
    if (i2 === n2) {
      throw "Empty between selector: " + s2;
    }
    b3 = parseMerge(s2.substring(1, i2));
    if (b3.length !== 2) {
      throw "Between selector must have two elements: " + s2;
    }
    s2 = s2.slice(i2 + 1).trim();
    if (s2[0] !== GT) {
      throw "Expected '>' after between selector: " + s2;
    }
    b3 = b3.map(parseSelector);
    const stream2 = parseSelector(s2.slice(1).trim());
    if (stream2.between) {
      return {
        between: b3,
        stream: stream2
      };
    } else {
      stream2.between = b3;
    }
    return stream2;
  }
  function parseStream2(s2) {
    const stream2 = {
      source: DEFAULT_SOURCE
    }, source4 = [];
    let throttle = [0, 0], markname = 0, start = 0, n2 = s2.length, i2 = 0, j2, filter3;
    if (s2[n2 - 1] === RBRACE) {
      i2 = s2.lastIndexOf(LBRACE);
      if (i2 >= 0) {
        try {
          throttle = parseThrottle(s2.substring(i2 + 1, n2 - 1));
        } catch (e4) {
          throw "Invalid throttle specification: " + s2;
        }
        s2 = s2.slice(0, i2).trim();
        n2 = s2.length;
      } else throw "Unmatched right brace: " + s2;
      i2 = 0;
    }
    if (!n2) throw s2;
    if (s2[0] === NAME) markname = ++i2;
    j2 = find3(s2, i2, COLON);
    if (j2 < n2) {
      source4.push(s2.substring(start, j2).trim());
      start = i2 = ++j2;
    }
    i2 = find3(s2, i2, LBRACK);
    if (i2 === n2) {
      source4.push(s2.substring(start, n2).trim());
    } else {
      source4.push(s2.substring(start, i2).trim());
      filter3 = [];
      start = ++i2;
      if (start === n2) throw "Unmatched left bracket: " + s2;
    }
    while (i2 < n2) {
      i2 = find3(s2, i2, RBRACK);
      if (i2 === n2) throw "Unmatched left bracket: " + s2;
      filter3.push(s2.substring(start, i2).trim());
      if (i2 < n2 - 1 && s2[++i2] !== LBRACK) throw "Expected left bracket: " + s2;
      start = ++i2;
    }
    if (!(n2 = source4.length) || ILLEGAL2.test(source4[n2 - 1])) {
      throw "Invalid event selector: " + s2;
    }
    if (n2 > 1) {
      stream2.type = source4[1];
      if (markname) {
        stream2.markname = source4[0].slice(1);
      } else if (isMarkType(source4[0])) {
        stream2.marktype = source4[0];
      } else {
        stream2.source = source4[0];
      }
    } else {
      stream2.type = source4[0];
    }
    if (stream2.type.slice(-1) === "!") {
      stream2.consume = true;
      stream2.type = stream2.type.slice(0, -1);
    }
    if (filter3 != null) stream2.filter = filter3;
    if (throttle[0]) stream2.throttle = throttle[0];
    if (throttle[1]) stream2.debounce = throttle[1];
    return stream2;
  }
  function parseThrottle(s2) {
    const a4 = s2.split(COMMA);
    if (!s2.length || a4.length > 2) throw s2;
    return a4.map((_) => {
      const x5 = +_;
      if (x5 !== x5) throw s2;
      return x5;
    });
  }

  // node_modules/vega-parser/build/vega-parser.module.js
  function parseAutosize(spec) {
    return isObject(spec) ? spec : {
      type: spec || "pad"
    };
  }
  var number7 = (_) => +_ || 0;
  var paddingObject2 = (_) => ({
    top: _,
    bottom: _,
    left: _,
    right: _
  });
  function parsePadding(spec) {
    return !isObject(spec) ? paddingObject2(number7(spec)) : spec.signal ? spec : {
      top: number7(spec.top),
      bottom: number7(spec.bottom),
      left: number7(spec.left),
      right: number7(spec.right)
    };
  }
  var encoder = (_) => isObject(_) && !isArray(_) ? extend({}, _) : {
    value: _
  };
  function addEncode(object2, name4, value3, set7) {
    if (value3 != null) {
      const isEncoder = isObject(value3) && !isArray(value3) || isArray(value3) && value3.length && isObject(value3[0]);
      if (isEncoder) {
        object2.update[name4] = value3;
      } else {
        object2[set7 || "enter"][name4] = {
          value: value3
        };
      }
      return 1;
    } else {
      return 0;
    }
  }
  function addEncoders(object2, enter, update3) {
    for (const name4 in enter) {
      addEncode(object2, name4, enter[name4]);
    }
    for (const name4 in update3) {
      addEncode(object2, name4, update3[name4], "update");
    }
  }
  function extendEncode(encode2, extra, skip) {
    for (const name4 in extra) {
      if (skip && has(skip, name4)) continue;
      encode2[name4] = extend(encode2[name4] || {}, extra[name4]);
    }
    return encode2;
  }
  function has2(key2, encode2) {
    return encode2 && (encode2.enter && encode2.enter[key2] || encode2.update && encode2.update[key2]);
  }
  var MarkRole = "mark";
  var FrameRole2 = "frame";
  var ScopeRole2 = "scope";
  var AxisRole2 = "axis";
  var AxisDomainRole = "axis-domain";
  var AxisGridRole = "axis-grid";
  var AxisLabelRole = "axis-label";
  var AxisTickRole = "axis-tick";
  var AxisTitleRole = "axis-title";
  var LegendRole2 = "legend";
  var LegendBandRole = "legend-band";
  var LegendEntryRole = "legend-entry";
  var LegendGradientRole = "legend-gradient";
  var LegendLabelRole = "legend-label";
  var LegendSymbolRole = "legend-symbol";
  var LegendTitleRole = "legend-title";
  var TitleRole2 = "title";
  var TitleTextRole = "title-text";
  var TitleSubtitleRole = "title-subtitle";
  function applyDefaults(encode2, type3, role, style2, config) {
    const defaults2 = {}, enter = {};
    let update3, key2, skip, props;
    key2 = "lineBreak";
    if (type3 === "text" && config[key2] != null && !has2(key2, encode2)) {
      applyDefault(defaults2, key2, config[key2]);
    }
    if (role == "legend" || String(role).startsWith("axis")) {
      role = null;
    }
    props = role === FrameRole2 ? config.group : role === MarkRole ? extend({}, config.mark, config[type3]) : null;
    for (key2 in props) {
      skip = has2(key2, encode2) || (key2 === "fill" || key2 === "stroke") && (has2("fill", encode2) || has2("stroke", encode2));
      if (!skip) applyDefault(defaults2, key2, props[key2]);
    }
    array(style2).forEach((name4) => {
      const props2 = config.style && config.style[name4];
      for (const key3 in props2) {
        if (!has2(key3, encode2)) {
          applyDefault(defaults2, key3, props2[key3]);
        }
      }
    });
    encode2 = extend({}, encode2);
    for (key2 in defaults2) {
      props = defaults2[key2];
      if (props.signal) {
        (update3 = update3 || {})[key2] = props;
      } else {
        enter[key2] = props;
      }
    }
    encode2.enter = extend(enter, encode2.enter);
    if (update3) encode2.update = extend(update3, encode2.update);
    return encode2;
  }
  function applyDefault(defaults2, key2, value3) {
    defaults2[key2] = value3 && value3.signal ? {
      signal: value3.signal
    } : {
      value: value3
    };
  }
  var scaleRef = (scale7) => isString(scale7) ? $(scale7) : scale7.signal ? `(${scale7.signal})` : field2(scale7);
  function entry$1(enc) {
    if (enc.gradient != null) {
      return gradient2(enc);
    }
    let value3 = enc.signal ? `(${enc.signal})` : enc.color ? color3(enc.color) : enc.field != null ? field2(enc.field) : enc.value !== void 0 ? $(enc.value) : void 0;
    if (enc.scale != null) {
      value3 = scale6(enc, value3);
    }
    if (value3 === void 0) {
      value3 = null;
    }
    if (enc.exponent != null) {
      value3 = `pow(${value3},${property(enc.exponent)})`;
    }
    if (enc.mult != null) {
      value3 += `*${property(enc.mult)}`;
    }
    if (enc.offset != null) {
      value3 += `+${property(enc.offset)}`;
    }
    if (enc.round) {
      value3 = `round(${value3})`;
    }
    return value3;
  }
  var _color = (type3, x5, y5, z) => `(${type3}(${[x5, y5, z].map(entry$1).join(",")})+'')`;
  function color3(enc) {
    return enc.c ? _color("hcl", enc.h, enc.c, enc.l) : enc.h || enc.s ? _color("hsl", enc.h, enc.s, enc.l) : enc.l || enc.a ? _color("lab", enc.l, enc.a, enc.b) : enc.r || enc.g || enc.b ? _color("rgb", enc.r, enc.g, enc.b) : null;
  }
  function gradient2(enc) {
    const args = [enc.start, enc.stop, enc.count].map((_) => _ == null ? null : $(_));
    while (args.length && peek(args) == null) args.pop();
    args.unshift(scaleRef(enc.gradient));
    return `gradient(${args.join(",")})`;
  }
  function property(property2) {
    return isObject(property2) ? "(" + entry$1(property2) + ")" : property2;
  }
  function field2(ref2) {
    return resolveField(isObject(ref2) ? ref2 : {
      datum: ref2
    });
  }
  function resolveField(ref2) {
    let object2, level, field3;
    if (ref2.signal) {
      object2 = "datum";
      field3 = ref2.signal;
    } else if (ref2.group || ref2.parent) {
      level = Math.max(1, ref2.level || 1);
      object2 = "item";
      while (level-- > 0) {
        object2 += ".mark.group";
      }
      if (ref2.parent) {
        field3 = ref2.parent;
        object2 += ".datum";
      } else {
        field3 = ref2.group;
      }
    } else if (ref2.datum) {
      object2 = "datum";
      field3 = ref2.datum;
    } else {
      error("Invalid field reference: " + $(ref2));
    }
    if (!ref2.signal) {
      field3 = isString(field3) ? splitAccessPath(field3).map($).join("][") : resolveField(field3);
    }
    return object2 + "[" + field3 + "]";
  }
  function scale6(enc, value3) {
    const scale7 = scaleRef(enc.scale);
    if (enc.range != null) {
      value3 = `lerp(_range(${scale7}), ${+enc.range})`;
    } else {
      if (value3 !== void 0) value3 = `_scale(${scale7}, ${value3})`;
      if (enc.band) {
        value3 = (value3 ? value3 + "+" : "") + `_bandwidth(${scale7})` + (+enc.band === 1 ? "" : "*" + property(enc.band));
        if (enc.extra) {
          value3 = `(datum.extra ? _scale(${scale7}, datum.extra.value) : ${value3})`;
        }
      }
      if (value3 == null) value3 = "0";
    }
    return value3;
  }
  function rule2(enc) {
    let code = "";
    enc.forEach((rule4) => {
      const value3 = entry$1(rule4);
      code += rule4.test ? `(${rule4.test})?${value3}:` : value3;
    });
    if (peek(code) === ":") {
      code += "null";
    }
    return code;
  }
  function parseEncode(encode2, type3, role, style2, scope, params2) {
    const enc = {};
    params2 = params2 || {};
    params2.encoders = {
      $encode: enc
    };
    encode2 = applyDefaults(encode2, type3, role, style2, scope.config);
    for (const key2 in encode2) {
      enc[key2] = parseBlock(encode2[key2], type3, params2, scope);
    }
    return params2;
  }
  function parseBlock(block, marktype, params2, scope) {
    const channels = {}, fields = {};
    for (const name4 in block) {
      if (block[name4] != null) {
        channels[name4] = parse$1(expr(block[name4]), scope, params2, fields);
      }
    }
    return {
      $expr: {
        marktype,
        channels
      },
      $fields: Object.keys(fields),
      $output: Object.keys(block)
    };
  }
  function expr(enc) {
    return isArray(enc) ? rule2(enc) : entry$1(enc);
  }
  function parse$1(code, scope, params2, fields) {
    const expr2 = parser2(code, scope);
    expr2.$fields.forEach((name4) => fields[name4] = 1);
    extend(params2, expr2.$params);
    return expr2.$expr;
  }
  var OUTER = "outer";
  var OUTER_INVALID = ["value", "update", "init", "react", "bind"];
  function outerError(prefix, name4) {
    error(prefix + ' for "outer" push: ' + $(name4));
  }
  function parseSignal(signal, scope) {
    const name4 = signal.name;
    if (signal.push === OUTER) {
      if (!scope.signals[name4]) outerError("No prior signal definition", name4);
      OUTER_INVALID.forEach((prop) => {
        if (signal[prop] !== void 0) outerError("Invalid property ", prop);
      });
    } else {
      const op = scope.addSignal(name4, signal.value);
      if (signal.react === false) op.react = false;
      if (signal.bind) scope.addBinding(name4, signal.bind);
    }
  }
  function Entry(type3, value3, params2, parent) {
    this.id = -1;
    this.type = type3;
    this.value = value3;
    this.params = params2;
    if (parent) this.parent = parent;
  }
  function entry(type3, value3, params2, parent) {
    return new Entry(type3, value3, params2, parent);
  }
  function operator(value3, params2) {
    return entry("operator", value3, params2);
  }
  function ref(op) {
    const ref2 = {
      $ref: op.id
    };
    if (op.id < 0) (op.refs = op.refs || []).push(ref2);
    return ref2;
  }
  function fieldRef$1(field3, name4) {
    return name4 ? {
      $field: field3,
      $name: name4
    } : {
      $field: field3
    };
  }
  var keyFieldRef = fieldRef$1("key");
  function compareRef(fields, orders) {
    return {
      $compare: fields,
      $order: orders
    };
  }
  function keyRef(fields, flat) {
    const ref2 = {
      $key: fields
    };
    if (flat) ref2.$flat = true;
    return ref2;
  }
  var Ascending = "ascending";
  var Descending = "descending";
  function sortKey(sort3) {
    return !isObject(sort3) ? "" : (sort3.order === Descending ? "-" : "+") + aggrField(sort3.op, sort3.field);
  }
  function aggrField(op, field3) {
    return (op && op.signal ? "$" + op.signal : op || "") + (op && field3 ? "_" : "") + (field3 && field3.signal ? "$" + field3.signal : field3 || "");
  }
  var Scope$1 = "scope";
  var View2 = "view";
  function isSignal(_) {
    return _ && _.signal;
  }
  function isExpr$1(_) {
    return _ && _.expr;
  }
  function hasSignal(_) {
    if (isSignal(_)) return true;
    if (isObject(_)) for (const key2 in _) {
      if (hasSignal(_[key2])) return true;
    }
    return false;
  }
  function value2(specValue, defaultValue) {
    return specValue != null ? specValue : defaultValue;
  }
  function deref(v3) {
    return v3 && v3.signal || v3;
  }
  var Timer2 = "timer";
  function parseStream3(stream2, scope) {
    const method2 = stream2.merge ? mergeStream : stream2.stream ? nestedStream : stream2.type ? eventStream : error("Invalid stream specification: " + $(stream2));
    return method2(stream2, scope);
  }
  function eventSource(source4) {
    return source4 === Scope$1 ? View2 : source4 || View2;
  }
  function mergeStream(stream2, scope) {
    const list = stream2.merge.map((s2) => parseStream3(s2, scope)), entry2 = streamParameters({
      merge: list
    }, stream2, scope);
    return scope.addStream(entry2).id;
  }
  function nestedStream(stream2, scope) {
    const id2 = parseStream3(stream2.stream, scope), entry2 = streamParameters({
      stream: id2
    }, stream2, scope);
    return scope.addStream(entry2).id;
  }
  function eventStream(stream2, scope) {
    let id2;
    if (stream2.type === Timer2) {
      id2 = scope.event(Timer2, stream2.throttle);
      stream2 = {
        between: stream2.between,
        filter: stream2.filter
      };
    } else {
      id2 = scope.event(eventSource(stream2.source), stream2.type);
    }
    const entry2 = streamParameters({
      stream: id2
    }, stream2, scope);
    return Object.keys(entry2).length === 1 ? id2 : scope.addStream(entry2).id;
  }
  function streamParameters(entry2, stream2, scope) {
    let param2 = stream2.between;
    if (param2) {
      if (param2.length !== 2) {
        error('Stream "between" parameter must have 2 entries: ' + $(stream2));
      }
      entry2.between = [parseStream3(param2[0], scope), parseStream3(param2[1], scope)];
    }
    param2 = stream2.filter ? [].concat(stream2.filter) : [];
    if (stream2.marktype || stream2.markname || stream2.markrole) {
      param2.push(filterMark(stream2.marktype, stream2.markname, stream2.markrole));
    }
    if (stream2.source === Scope$1) {
      param2.push("inScope(event.item)");
    }
    if (param2.length) {
      entry2.filter = parser2("(" + param2.join(")&&(") + ")", scope).$expr;
    }
    if ((param2 = stream2.throttle) != null) {
      entry2.throttle = +param2;
    }
    if ((param2 = stream2.debounce) != null) {
      entry2.debounce = +param2;
    }
    if (stream2.consume) {
      entry2.consume = true;
    }
    return entry2;
  }
  function filterMark(type3, name4, role) {
    const item = "event.item";
    return item + (type3 && type3 !== "*" ? "&&" + item + ".mark.marktype==='" + type3 + "'" : "") + (role ? "&&" + item + ".mark.role==='" + role + "'" : "") + (name4 ? "&&" + item + ".mark.name==='" + name4 + "'" : "");
  }
  var OP_VALUE_EXPR = {
    code: "_.$value",
    ast: {
      type: "Identifier",
      value: "value"
    }
  };
  function parseUpdate2(spec, scope, target2) {
    const encode2 = spec.encode, entry2 = {
      target: target2
    };
    let events3 = spec.events, update3 = spec.update, sources = [];
    if (!events3) {
      error("Signal update missing events specification.");
    }
    if (isString(events3)) {
      events3 = eventSelector(events3, scope.isSubscope() ? Scope$1 : View2);
    }
    events3 = array(events3).filter((s2) => s2.signal || s2.scale ? (sources.push(s2), 0) : 1);
    if (sources.length > 1) {
      sources = [mergeSources(sources)];
    }
    if (events3.length) {
      sources.push(events3.length > 1 ? {
        merge: events3
      } : events3[0]);
    }
    if (encode2 != null) {
      if (update3) error("Signal encode and update are mutually exclusive.");
      update3 = "encode(item()," + $(encode2) + ")";
    }
    entry2.update = isString(update3) ? parser2(update3, scope) : update3.expr != null ? parser2(update3.expr, scope) : update3.value != null ? update3.value : update3.signal != null ? {
      $expr: OP_VALUE_EXPR,
      $params: {
        $value: scope.signalRef(update3.signal)
      }
    } : error("Invalid signal update specification.");
    if (spec.force) {
      entry2.options = {
        force: true
      };
    }
    sources.forEach((source4) => scope.addUpdate(extend(streamSource(source4, scope), entry2)));
  }
  function streamSource(stream2, scope) {
    return {
      source: stream2.signal ? scope.signalRef(stream2.signal) : stream2.scale ? scope.scaleRef(stream2.scale) : parseStream3(stream2, scope)
    };
  }
  function mergeSources(sources) {
    return {
      signal: "[" + sources.map((s2) => s2.scale ? 'scale("' + s2.scale + '")' : s2.signal) + "]"
    };
  }
  function parseSignalUpdates(signal, scope) {
    const op = scope.getSignal(signal.name);
    let expr2 = signal.update;
    if (signal.init) {
      if (expr2) {
        error("Signals can not include both init and update expressions.");
      } else {
        expr2 = signal.init;
        op.initonly = true;
      }
    }
    if (expr2) {
      expr2 = parser2(expr2, scope);
      op.update = expr2.$expr;
      op.params = expr2.$params;
    }
    if (signal.on) {
      signal.on.forEach((_) => parseUpdate2(_, scope, op.id));
    }
  }
  var transform3 = (name4) => (params2, value3, parent) => entry(name4, value3, params2 || void 0, parent);
  var Aggregate2 = transform3("aggregate");
  var AxisTicks2 = transform3("axisticks");
  var Bound2 = transform3("bound");
  var Collect2 = transform3("collect");
  var Compare2 = transform3("compare");
  var DataJoin2 = transform3("datajoin");
  var Encode2 = transform3("encode");
  var Expression2 = transform3("expression");
  var Facet2 = transform3("facet");
  var Field2 = transform3("field");
  var Key2 = transform3("key");
  var LegendEntries2 = transform3("legendentries");
  var Load2 = transform3("load");
  var Mark2 = transform3("mark");
  var MultiExtent2 = transform3("multiextent");
  var MultiValues2 = transform3("multivalues");
  var Overlap2 = transform3("overlap");
  var Params3 = transform3("params");
  var PreFacet2 = transform3("prefacet");
  var Projection2 = transform3("projection");
  var Proxy3 = transform3("proxy");
  var Relay2 = transform3("relay");
  var Render2 = transform3("render");
  var Scale2 = transform3("scale");
  var Sieve2 = transform3("sieve");
  var SortItems2 = transform3("sortitems");
  var ViewLayout2 = transform3("viewlayout");
  var Values2 = transform3("values");
  var FIELD_REF_ID = 0;
  var MULTIDOMAIN_SORT_OPS = {
    min: "min",
    max: "max",
    count: "sum"
  };
  function initScale(spec, scope) {
    const type3 = spec.type || "linear";
    if (!isValidScaleType(type3)) {
      error("Unrecognized scale type: " + $(type3));
    }
    scope.addScale(spec.name, {
      type: type3,
      domain: void 0
    });
  }
  function parseScale(spec, scope) {
    const params2 = scope.getScale(spec.name).params;
    let key2;
    params2.domain = parseScaleDomain(spec.domain, spec, scope);
    if (spec.range != null) {
      params2.range = parseScaleRange(spec, scope, params2);
    }
    if (spec.interpolate != null) {
      parseScaleInterpolate(spec.interpolate, params2);
    }
    if (spec.nice != null) {
      params2.nice = parseScaleNice(spec.nice, scope);
    }
    if (spec.bins != null) {
      params2.bins = parseScaleBins(spec.bins, scope);
    }
    for (key2 in spec) {
      if (has(params2, key2) || key2 === "name") continue;
      params2[key2] = parseLiteral(spec[key2], scope);
    }
  }
  function parseLiteral(v3, scope) {
    return !isObject(v3) ? v3 : v3.signal ? scope.signalRef(v3.signal) : error("Unsupported object: " + $(v3));
  }
  function parseArray(v3, scope) {
    return v3.signal ? scope.signalRef(v3.signal) : v3.map((v5) => parseLiteral(v5, scope));
  }
  function dataLookupError(name4) {
    error("Can not find data set: " + $(name4));
  }
  function parseScaleDomain(domain4, spec, scope) {
    if (!domain4) {
      if (spec.domainMin != null || spec.domainMax != null) {
        error("No scale domain defined for domainMin/domainMax to override.");
      }
      return;
    }
    return domain4.signal ? scope.signalRef(domain4.signal) : (isArray(domain4) ? explicitDomain : domain4.fields ? multipleDomain : singularDomain)(domain4, spec, scope);
  }
  function explicitDomain(domain4, spec, scope) {
    return domain4.map((v3) => parseLiteral(v3, scope));
  }
  function singularDomain(domain4, spec, scope) {
    const data3 = scope.getData(domain4.data);
    if (!data3) dataLookupError(domain4.data);
    return isDiscrete(spec.type) ? data3.valuesRef(scope, domain4.field, parseSort(domain4.sort, false)) : isQuantile(spec.type) ? data3.domainRef(scope, domain4.field) : data3.extentRef(scope, domain4.field);
  }
  function multipleDomain(domain4, spec, scope) {
    const data3 = domain4.data, fields = domain4.fields.reduce((dom, d2) => {
      d2 = isString(d2) ? {
        data: data3,
        field: d2
      } : isArray(d2) || d2.signal ? fieldRef(d2, scope) : d2;
      dom.push(d2);
      return dom;
    }, []);
    return (isDiscrete(spec.type) ? ordinalMultipleDomain : isQuantile(spec.type) ? quantileMultipleDomain : numericMultipleDomain)(domain4, scope, fields);
  }
  function fieldRef(data3, scope) {
    const name4 = "_:vega:_" + FIELD_REF_ID++, coll = Collect2({});
    if (isArray(data3)) {
      coll.value = {
        $ingest: data3
      };
    } else if (data3.signal) {
      const code = "setdata(" + $(name4) + "," + data3.signal + ")";
      coll.params.input = scope.signalRef(code);
    }
    scope.addDataPipeline(name4, [coll, Sieve2({})]);
    return {
      data: name4,
      field: "data"
    };
  }
  function ordinalMultipleDomain(domain4, scope, fields) {
    const sort3 = parseSort(domain4.sort, true);
    let a4, v3;
    const counts = fields.map((f2) => {
      const data3 = scope.getData(f2.data);
      if (!data3) dataLookupError(f2.data);
      return data3.countsRef(scope, f2.field, sort3);
    });
    const p2 = {
      groupby: keyFieldRef,
      pulse: counts
    };
    if (sort3) {
      a4 = sort3.op || "count";
      v3 = sort3.field ? aggrField(a4, sort3.field) : "count";
      p2.ops = [MULTIDOMAIN_SORT_OPS[a4]];
      p2.fields = [scope.fieldRef(v3)];
      p2.as = [v3];
    }
    a4 = scope.add(Aggregate2(p2));
    const c4 = scope.add(Collect2({
      pulse: ref(a4)
    }));
    v3 = scope.add(Values2({
      field: keyFieldRef,
      sort: scope.sortRef(sort3),
      pulse: ref(c4)
    }));
    return ref(v3);
  }
  function parseSort(sort3, multidomain) {
    if (sort3) {
      if (!sort3.field && !sort3.op) {
        if (isObject(sort3)) sort3.field = "key";
        else sort3 = {
          field: "key"
        };
      } else if (!sort3.field && sort3.op !== "count") {
        error("No field provided for sort aggregate op: " + sort3.op);
      } else if (multidomain && sort3.field) {
        if (sort3.op && !MULTIDOMAIN_SORT_OPS[sort3.op]) {
          error("Multiple domain scales can not be sorted using " + sort3.op);
        }
      }
    }
    return sort3;
  }
  function quantileMultipleDomain(domain4, scope, fields) {
    const values4 = fields.map((f2) => {
      const data3 = scope.getData(f2.data);
      if (!data3) dataLookupError(f2.data);
      return data3.domainRef(scope, f2.field);
    });
    return ref(scope.add(MultiValues2({
      values: values4
    })));
  }
  function numericMultipleDomain(domain4, scope, fields) {
    const extents = fields.map((f2) => {
      const data3 = scope.getData(f2.data);
      if (!data3) dataLookupError(f2.data);
      return data3.extentRef(scope, f2.field);
    });
    return ref(scope.add(MultiExtent2({
      extents
    })));
  }
  function parseScaleBins(v3, scope) {
    return v3.signal || isArray(v3) ? parseArray(v3, scope) : scope.objectProperty(v3);
  }
  function parseScaleNice(nice3, scope) {
    return nice3.signal ? scope.signalRef(nice3.signal) : isObject(nice3) ? {
      interval: parseLiteral(nice3.interval),
      step: parseLiteral(nice3.step)
    } : parseLiteral(nice3);
  }
  function parseScaleInterpolate(interpolate3, params2) {
    params2.interpolate = parseLiteral(interpolate3.type || interpolate3);
    if (interpolate3.gamma != null) {
      params2.interpolateGamma = parseLiteral(interpolate3.gamma);
    }
  }
  function parseScaleRange(spec, scope, params2) {
    const config = scope.config.range;
    let range7 = spec.range;
    if (range7.signal) {
      return scope.signalRef(range7.signal);
    } else if (isString(range7)) {
      if (config && has(config, range7)) {
        spec = extend({}, spec, {
          range: config[range7]
        });
        return parseScaleRange(spec, scope, params2);
      } else if (range7 === "width") {
        range7 = [0, {
          signal: "width"
        }];
      } else if (range7 === "height") {
        range7 = isDiscrete(spec.type) ? [0, {
          signal: "height"
        }] : [{
          signal: "height"
        }, 0];
      } else {
        error("Unrecognized scale range value: " + $(range7));
      }
    } else if (range7.scheme) {
      params2.scheme = isArray(range7.scheme) ? parseArray(range7.scheme, scope) : parseLiteral(range7.scheme, scope);
      if (range7.extent) params2.schemeExtent = parseArray(range7.extent, scope);
      if (range7.count) params2.schemeCount = parseLiteral(range7.count, scope);
      return;
    } else if (range7.step) {
      params2.rangeStep = parseLiteral(range7.step, scope);
      return;
    } else if (isDiscrete(spec.type) && !isArray(range7)) {
      return parseScaleDomain(range7, spec, scope);
    } else if (!isArray(range7)) {
      error("Unsupported range type: " + $(range7));
    }
    return range7.map((v3) => (isArray(v3) ? parseArray : parseLiteral)(v3, scope));
  }
  function parseProjection(proj, scope) {
    const config = scope.config.projection || {}, params2 = {};
    for (const name4 in proj) {
      if (name4 === "name") continue;
      params2[name4] = parseParameter$1(proj[name4], name4, scope);
    }
    for (const name4 in config) {
      if (params2[name4] == null) {
        params2[name4] = parseParameter$1(config[name4], name4, scope);
      }
    }
    scope.addProjection(proj.name, params2);
  }
  function parseParameter$1(_, name4, scope) {
    return isArray(_) ? _.map((_2) => parseParameter$1(_2, name4, scope)) : !isObject(_) ? _ : _.signal ? scope.signalRef(_.signal) : name4 === "fit" ? _ : error("Unsupported parameter object: " + $(_));
  }
  var Top2 = "top";
  var Left2 = "left";
  var Right2 = "right";
  var Bottom2 = "bottom";
  var Center2 = "center";
  var Vertical = "vertical";
  var Start2 = "start";
  var Middle2 = "middle";
  var End2 = "end";
  var Index = "index";
  var Label2 = "label";
  var Offset = "offset";
  var Perc = "perc";
  var Perc2 = "perc2";
  var Value = "value";
  var GuideLabelStyle = "guide-label";
  var GuideTitleStyle = "guide-title";
  var GroupTitleStyle = "group-title";
  var GroupSubtitleStyle = "group-subtitle";
  var Symbols2 = "symbol";
  var Gradient2 = "gradient";
  var Discrete2 = "discrete";
  var Size = "size";
  var Shape = "shape";
  var Fill = "fill";
  var Stroke = "stroke";
  var StrokeWidth = "strokeWidth";
  var StrokeDash = "strokeDash";
  var Opacity = "opacity";
  var LegendScales = [Size, Shape, Fill, Stroke, StrokeWidth, StrokeDash, Opacity];
  var Skip3 = {
    name: 1,
    style: 1,
    interactive: 1
  };
  var zero4 = {
    value: 0
  };
  var one3 = {
    value: 1
  };
  var GroupMark = "group";
  var RectMark = "rect";
  var RuleMark = "rule";
  var SymbolMark = "symbol";
  var TextMark = "text";
  function guideGroup(mark) {
    mark.type = GroupMark;
    mark.interactive = mark.interactive || false;
    return mark;
  }
  function lookup5(spec, config) {
    const _ = (name4, dflt) => value2(spec[name4], value2(config[name4], dflt));
    _.isVertical = (s2) => Vertical === value2(spec.direction, config.direction || (s2 ? config.symbolDirection : config.gradientDirection));
    _.gradientLength = () => value2(spec.gradientLength, config.gradientLength || config.gradientWidth);
    _.gradientThickness = () => value2(spec.gradientThickness, config.gradientThickness || config.gradientHeight);
    _.entryColumns = () => value2(spec.columns, value2(config.columns, +_.isVertical(true)));
    return _;
  }
  function getEncoding(name4, encode2) {
    const v3 = encode2 && (encode2.update && encode2.update[name4] || encode2.enter && encode2.enter[name4]);
    return v3 && v3.signal ? v3 : v3 ? v3.value : null;
  }
  function getStyle(name4, scope, style2) {
    const s2 = scope.config.style[style2];
    return s2 && s2[name4];
  }
  function anchorExpr(s2, e4, m4) {
    return `item.anchor === '${Start2}' ? ${s2} : item.anchor === '${End2}' ? ${e4} : ${m4}`;
  }
  var alignExpr$1 = anchorExpr($(Left2), $(Right2), $(Center2));
  function tickBand(_) {
    const v3 = _("tickBand");
    let offset4 = _("tickOffset"), band2, extra;
    if (!v3) {
      band2 = _("bandPosition");
      extra = _("tickExtra");
    } else if (v3.signal) {
      band2 = {
        signal: `(${v3.signal}) === 'extent' ? 1 : 0.5`
      };
      extra = {
        signal: `(${v3.signal}) === 'extent'`
      };
      if (!isObject(offset4)) {
        offset4 = {
          signal: `(${v3.signal}) === 'extent' ? 0 : ${offset4}`
        };
      }
    } else if (v3 === "extent") {
      band2 = 1;
      extra = true;
      offset4 = 0;
    } else {
      band2 = 0.5;
      extra = false;
    }
    return {
      extra,
      band: band2,
      offset: offset4
    };
  }
  function extendOffset(value3, offset4) {
    return !offset4 ? value3 : !value3 ? offset4 : !isObject(value3) ? {
      value: value3,
      offset: offset4
    } : Object.assign({}, value3, {
      offset: extendOffset(value3.offset, offset4)
    });
  }
  function guideMark(mark, extras) {
    if (extras) {
      mark.name = extras.name;
      mark.style = extras.style || mark.style;
      mark.interactive = !!extras.interactive;
      mark.encode = extendEncode(mark.encode, extras, Skip3);
    } else {
      mark.interactive = false;
    }
    return mark;
  }
  function legendGradient(spec, scale7, config, userEncode) {
    const _ = lookup5(spec, config), vertical = _.isVertical(), thickness = _.gradientThickness(), length3 = _.gradientLength();
    let enter, start, stop2, width2, height2;
    if (vertical) {
      start = [0, 1];
      stop2 = [0, 0];
      width2 = thickness;
      height2 = length3;
    } else {
      start = [0, 0];
      stop2 = [1, 0];
      width2 = length3;
      height2 = thickness;
    }
    const encode2 = {
      enter: enter = {
        opacity: zero4,
        x: zero4,
        y: zero4,
        width: encoder(width2),
        height: encoder(height2)
      },
      update: extend({}, enter, {
        opacity: one3,
        fill: {
          gradient: scale7,
          start,
          stop: stop2
        }
      }),
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      stroke: _("gradientStrokeColor"),
      strokeWidth: _("gradientStrokeWidth")
    }, {
      // update
      opacity: _("gradientOpacity")
    });
    return guideMark({
      type: RectMark,
      role: LegendGradientRole,
      encode: encode2
    }, userEncode);
  }
  function legendGradientDiscrete(spec, scale7, config, userEncode, dataRef) {
    const _ = lookup5(spec, config), vertical = _.isVertical(), thickness = _.gradientThickness(), length3 = _.gradientLength();
    let u5, v3, uu, vv, adjust = "";
    vertical ? (u5 = "y", uu = "y2", v3 = "x", vv = "width", adjust = "1-") : (u5 = "x", uu = "x2", v3 = "y", vv = "height");
    const enter = {
      opacity: zero4,
      fill: {
        scale: scale7,
        field: Value
      }
    };
    enter[u5] = {
      signal: adjust + "datum." + Perc,
      mult: length3
    };
    enter[v3] = zero4;
    enter[uu] = {
      signal: adjust + "datum." + Perc2,
      mult: length3
    };
    enter[vv] = encoder(thickness);
    const encode2 = {
      enter,
      update: extend({}, enter, {
        opacity: one3
      }),
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      stroke: _("gradientStrokeColor"),
      strokeWidth: _("gradientStrokeWidth")
    }, {
      // update
      opacity: _("gradientOpacity")
    });
    return guideMark({
      type: RectMark,
      role: LegendBandRole,
      key: Value,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  var alignExpr = `datum.${Perc}<=0?"${Left2}":datum.${Perc}>=1?"${Right2}":"${Center2}"`;
  var baselineExpr = `datum.${Perc}<=0?"${Bottom2}":datum.${Perc}>=1?"${Top2}":"${Middle2}"`;
  function legendGradientLabels(spec, config, userEncode, dataRef) {
    const _ = lookup5(spec, config), vertical = _.isVertical(), thickness = encoder(_.gradientThickness()), length3 = _.gradientLength();
    let overlap = _("labelOverlap"), enter, update3, u5, v3, adjust = "";
    const encode2 = {
      enter: enter = {
        opacity: zero4
      },
      update: update3 = {
        opacity: one3,
        text: {
          field: Label2
        }
      },
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      fill: _("labelColor"),
      fillOpacity: _("labelOpacity"),
      font: _("labelFont"),
      fontSize: _("labelFontSize"),
      fontStyle: _("labelFontStyle"),
      fontWeight: _("labelFontWeight"),
      limit: value2(spec.labelLimit, config.gradientLabelLimit)
    });
    if (vertical) {
      enter.align = {
        value: "left"
      };
      enter.baseline = update3.baseline = {
        signal: baselineExpr
      };
      u5 = "y";
      v3 = "x";
      adjust = "1-";
    } else {
      enter.align = update3.align = {
        signal: alignExpr
      };
      enter.baseline = {
        value: "top"
      };
      u5 = "x";
      v3 = "y";
    }
    enter[u5] = update3[u5] = {
      signal: adjust + "datum." + Perc,
      mult: length3
    };
    enter[v3] = update3[v3] = thickness;
    thickness.offset = value2(spec.labelOffset, config.gradientLabelOffset) || 0;
    overlap = overlap ? {
      separation: _("labelSeparation"),
      method: overlap,
      order: "datum." + Index
    } : void 0;
    return guideMark({
      type: TextMark,
      role: LegendLabelRole,
      style: GuideLabelStyle,
      key: Value,
      from: dataRef,
      encode: encode2,
      overlap
    }, userEncode);
  }
  function legendSymbolGroups(spec, config, userEncode, dataRef, columns2) {
    const _ = lookup5(spec, config), entries3 = userEncode.entries, interactive2 = !!(entries3 && entries3.interactive), name4 = entries3 ? entries3.name : void 0, height2 = _("clipHeight"), symbolOffset = _("symbolOffset"), valueRef = {
      data: "value"
    }, xSignal = `(${columns2}) ? datum.${Offset} : datum.${Size}`, yEncode = height2 ? encoder(height2) : {
      field: Size
    }, index4 = `datum.${Index}`, ncols = `max(1, ${columns2})`;
    let encode2, enter, update3, nrows, sort3;
    yEncode.mult = 0.5;
    encode2 = {
      enter: enter = {
        opacity: zero4,
        x: {
          signal: xSignal,
          mult: 0.5,
          offset: symbolOffset
        },
        y: yEncode
      },
      update: update3 = {
        opacity: one3,
        x: enter.x,
        y: enter.y
      },
      exit: {
        opacity: zero4
      }
    };
    let baseFill = null, baseStroke = null;
    if (!spec.fill) {
      baseFill = config.symbolBaseFillColor;
      baseStroke = config.symbolBaseStrokeColor;
    }
    addEncoders(encode2, {
      fill: _("symbolFillColor", baseFill),
      shape: _("symbolType"),
      size: _("symbolSize"),
      stroke: _("symbolStrokeColor", baseStroke),
      strokeDash: _("symbolDash"),
      strokeDashOffset: _("symbolDashOffset"),
      strokeWidth: _("symbolStrokeWidth")
    }, {
      // update
      opacity: _("symbolOpacity")
    });
    LegendScales.forEach((scale7) => {
      if (spec[scale7]) {
        update3[scale7] = enter[scale7] = {
          scale: spec[scale7],
          field: Value
        };
      }
    });
    const symbols4 = guideMark({
      type: SymbolMark,
      role: LegendSymbolRole,
      key: Value,
      from: valueRef,
      clip: height2 ? true : void 0,
      encode: encode2
    }, userEncode.symbols);
    const labelOffset = encoder(symbolOffset);
    labelOffset.offset = _("labelOffset");
    encode2 = {
      enter: enter = {
        opacity: zero4,
        x: {
          signal: xSignal,
          offset: labelOffset
        },
        y: yEncode
      },
      update: update3 = {
        opacity: one3,
        text: {
          field: Label2
        },
        x: enter.x,
        y: enter.y
      },
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      align: _("labelAlign"),
      baseline: _("labelBaseline"),
      fill: _("labelColor"),
      fillOpacity: _("labelOpacity"),
      font: _("labelFont"),
      fontSize: _("labelFontSize"),
      fontStyle: _("labelFontStyle"),
      fontWeight: _("labelFontWeight"),
      limit: _("labelLimit")
    });
    const labels3 = guideMark({
      type: TextMark,
      role: LegendLabelRole,
      style: GuideLabelStyle,
      key: Value,
      from: valueRef,
      encode: encode2
    }, userEncode.labels);
    encode2 = {
      enter: {
        noBound: {
          value: !height2
        },
        // ignore width/height in bounds calc
        width: zero4,
        height: height2 ? encoder(height2) : zero4,
        opacity: zero4
      },
      exit: {
        opacity: zero4
      },
      update: update3 = {
        opacity: one3,
        row: {
          signal: null
        },
        column: {
          signal: null
        }
      }
    };
    if (_.isVertical(true)) {
      nrows = `ceil(item.mark.items.length / ${ncols})`;
      update3.row.signal = `${index4}%${nrows}`;
      update3.column.signal = `floor(${index4} / ${nrows})`;
      sort3 = {
        field: ["row", index4]
      };
    } else {
      update3.row.signal = `floor(${index4} / ${ncols})`;
      update3.column.signal = `${index4} % ${ncols}`;
      sort3 = {
        field: index4
      };
    }
    update3.column.signal = `(${columns2})?${update3.column.signal}:${index4}`;
    dataRef = {
      facet: {
        data: dataRef,
        name: "value",
        groupby: Index
      }
    };
    return guideGroup({
      role: ScopeRole2,
      from: dataRef,
      encode: extendEncode(encode2, entries3, Skip3),
      marks: [symbols4, labels3],
      name: name4,
      interactive: interactive2,
      sort: sort3
    });
  }
  function legendSymbolLayout(spec, config) {
    const _ = lookup5(spec, config);
    return {
      align: _("gridAlign"),
      columns: _.entryColumns(),
      center: {
        row: true,
        column: false
      },
      padding: {
        row: _("rowPadding"),
        column: _("columnPadding")
      }
    };
  }
  var isL = 'item.orient === "left"';
  var isR = 'item.orient === "right"';
  var isLR = `(${isL} || ${isR})`;
  var isVG = `datum.vgrad && ${isLR}`;
  var baseline = anchorExpr('"top"', '"bottom"', '"middle"');
  var alignFlip = anchorExpr('"right"', '"left"', '"center"');
  var exprAlign = `datum.vgrad && ${isR} ? (${alignFlip}) : (${isLR} && !(datum.vgrad && ${isL})) ? "left" : ${alignExpr$1}`;
  var exprAnchor = `item._anchor || (${isLR} ? "middle" : "start")`;
  var exprAngle = `${isVG} ? (${isL} ? -90 : 90) : 0`;
  var exprBaseline = `${isLR} ? (datum.vgrad ? (${isR} ? "bottom" : "top") : ${baseline}) : "top"`;
  function legendTitle(spec, config, userEncode, dataRef) {
    const _ = lookup5(spec, config);
    const encode2 = {
      enter: {
        opacity: zero4
      },
      update: {
        opacity: one3,
        x: {
          field: {
            group: "padding"
          }
        },
        y: {
          field: {
            group: "padding"
          }
        }
      },
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      orient: _("titleOrient"),
      _anchor: _("titleAnchor"),
      anchor: {
        signal: exprAnchor
      },
      angle: {
        signal: exprAngle
      },
      align: {
        signal: exprAlign
      },
      baseline: {
        signal: exprBaseline
      },
      text: spec.title,
      fill: _("titleColor"),
      fillOpacity: _("titleOpacity"),
      font: _("titleFont"),
      fontSize: _("titleFontSize"),
      fontStyle: _("titleFontStyle"),
      fontWeight: _("titleFontWeight"),
      limit: _("titleLimit"),
      lineHeight: _("titleLineHeight")
    }, {
      // require update
      align: _("titleAlign"),
      baseline: _("titleBaseline")
    });
    return guideMark({
      type: TextMark,
      role: LegendTitleRole,
      style: GuideTitleStyle,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function clip2(clip3, scope) {
    let expr2;
    if (isObject(clip3)) {
      if (clip3.signal) {
        expr2 = clip3.signal;
      } else if (clip3.path) {
        expr2 = "pathShape(" + param(clip3.path) + ")";
      } else if (clip3.sphere) {
        expr2 = "geoShape(" + param(clip3.sphere) + ', {type: "Sphere"})';
      }
    }
    return expr2 ? scope.signalRef(expr2) : !!clip3;
  }
  function param(value3) {
    return isObject(value3) && value3.signal ? value3.signal : $(value3);
  }
  function getRole(spec) {
    const role = spec.role || "";
    return role.startsWith("axis") || role.startsWith("legend") || role.startsWith("title") ? role : spec.type === GroupMark ? ScopeRole2 : role || MarkRole;
  }
  function definition2(spec) {
    return {
      marktype: spec.type,
      name: spec.name || void 0,
      role: spec.role || getRole(spec),
      zindex: +spec.zindex || void 0,
      aria: spec.aria,
      description: spec.description
    };
  }
  function interactive(spec, scope) {
    return spec && spec.signal ? scope.signalRef(spec.signal) : spec === false ? false : true;
  }
  function parseTransform(spec, scope) {
    const def2 = definition(spec.type);
    if (!def2) error("Unrecognized transform type: " + $(spec.type));
    const t4 = entry(def2.type.toLowerCase(), null, parseParameters2(def2, spec, scope));
    if (spec.signal) scope.addSignal(spec.signal, scope.proxy(t4));
    t4.metadata = def2.metadata || {};
    return t4;
  }
  function parseParameters2(def2, spec, scope) {
    const params2 = {}, n2 = def2.params.length;
    for (let i2 = 0; i2 < n2; ++i2) {
      const pdef = def2.params[i2];
      params2[pdef.name] = parseParameter2(pdef, spec, scope);
    }
    return params2;
  }
  function parseParameter2(def2, spec, scope) {
    const type3 = def2.type, value3 = spec[def2.name];
    if (type3 === "index") {
      return parseIndexParameter(def2, spec, scope);
    } else if (value3 === void 0) {
      if (def2.required) {
        error("Missing required " + $(spec.type) + " parameter: " + $(def2.name));
      }
      return;
    } else if (type3 === "param") {
      return parseSubParameters(def2, spec, scope);
    } else if (type3 === "projection") {
      return scope.projectionRef(spec[def2.name]);
    }
    return def2.array && !isSignal(value3) ? value3.map((v3) => parameterValue(def2, v3, scope)) : parameterValue(def2, value3, scope);
  }
  function parameterValue(def2, value3, scope) {
    const type3 = def2.type;
    if (isSignal(value3)) {
      return isExpr(type3) ? error("Expression references can not be signals.") : isField(type3) ? scope.fieldRef(value3) : isCompare(type3) ? scope.compareRef(value3) : scope.signalRef(value3.signal);
    } else {
      const expr2 = def2.expr || isField(type3);
      return expr2 && outerExpr(value3) ? scope.exprRef(value3.expr, value3.as) : expr2 && outerField(value3) ? fieldRef$1(value3.field, value3.as) : isExpr(type3) ? parser2(value3, scope) : isData(type3) ? ref(scope.getData(value3).values) : isField(type3) ? fieldRef$1(value3) : isCompare(type3) ? scope.compareRef(value3) : value3;
    }
  }
  function parseIndexParameter(def2, spec, scope) {
    if (!isString(spec.from)) {
      error('Lookup "from" parameter must be a string literal.');
    }
    return scope.getData(spec.from).lookupRef(scope, spec.key);
  }
  function parseSubParameters(def2, spec, scope) {
    const value3 = spec[def2.name];
    if (def2.array) {
      if (!isArray(value3)) {
        error("Expected an array of sub-parameters. Instead: " + $(value3));
      }
      return value3.map((v3) => parseSubParameter(def2, v3, scope));
    } else {
      return parseSubParameter(def2, value3, scope);
    }
  }
  function parseSubParameter(def2, value3, scope) {
    const n2 = def2.params.length;
    let pdef;
    for (let i2 = 0; i2 < n2; ++i2) {
      pdef = def2.params[i2];
      for (const k2 in pdef.key) {
        if (pdef.key[k2] !== value3[k2]) {
          pdef = null;
          break;
        }
      }
      if (pdef) break;
    }
    if (!pdef) error("Unsupported parameter: " + $(value3));
    const params2 = extend(parseParameters2(pdef, value3, scope), pdef.key);
    return ref(scope.add(Params3(params2)));
  }
  var outerExpr = (_) => _ && _.expr;
  var outerField = (_) => _ && _.field;
  var isData = (_) => _ === "data";
  var isExpr = (_) => _ === "expr";
  var isField = (_) => _ === "field";
  var isCompare = (_) => _ === "compare";
  function parseData$1(from, group2, scope) {
    let facet, key2, op, dataRef, parent;
    if (!from) {
      dataRef = ref(scope.add(Collect2(null, [{}])));
    } else if (facet = from.facet) {
      if (!group2) error("Only group marks can be faceted.");
      if (facet.field != null) {
        dataRef = parent = getDataRef(facet, scope);
      } else {
        if (!from.data) {
          op = parseTransform(extend({
            type: "aggregate",
            groupby: array(facet.groupby)
          }, facet.aggregate), scope);
          op.params.key = scope.keyRef(facet.groupby);
          op.params.pulse = getDataRef(facet, scope);
          dataRef = parent = ref(scope.add(op));
        } else {
          parent = ref(scope.getData(from.data).aggregate);
        }
        key2 = scope.keyRef(facet.groupby, true);
      }
    }
    if (!dataRef) {
      dataRef = getDataRef(from, scope);
    }
    return {
      key: key2,
      pulse: dataRef,
      parent
    };
  }
  function getDataRef(from, scope) {
    return from.$ref ? from : from.data && from.data.$ref ? from.data : ref(scope.getData(from.data).output);
  }
  function DataScope(scope, input, output3, values4, aggr) {
    this.scope = scope;
    this.input = input;
    this.output = output3;
    this.values = values4;
    this.aggregate = aggr;
    this.index = {};
  }
  DataScope.fromEntries = function(scope, entries3) {
    const n2 = entries3.length, values4 = entries3[n2 - 1], output3 = entries3[n2 - 2];
    let input = entries3[0], aggr = null, i2 = 1;
    if (input && input.type === "load") {
      input = entries3[1];
    }
    scope.add(entries3[0]);
    for (; i2 < n2; ++i2) {
      entries3[i2].params.pulse = ref(entries3[i2 - 1]);
      scope.add(entries3[i2]);
      if (entries3[i2].type === "aggregate") aggr = entries3[i2];
    }
    return new DataScope(scope, input, output3, values4, aggr);
  };
  function fieldKey(field3) {
    return isString(field3) ? field3 : null;
  }
  function addSortField(scope, p2, sort3) {
    const as = aggrField(sort3.op, sort3.field);
    let s2;
    if (p2.ops) {
      for (let i2 = 0, n2 = p2.as.length; i2 < n2; ++i2) {
        if (p2.as[i2] === as) return;
      }
    } else {
      p2.ops = ["count"];
      p2.fields = [null];
      p2.as = ["count"];
    }
    if (sort3.op) {
      p2.ops.push((s2 = sort3.op.signal) ? scope.signalRef(s2) : sort3.op);
      p2.fields.push(scope.fieldRef(sort3.field));
      p2.as.push(as);
    }
  }
  function cache(scope, ds, name4, optype, field3, counts, index4) {
    const cache3 = ds[name4] || (ds[name4] = {}), sort3 = sortKey(counts);
    let k2 = fieldKey(field3), v3, op;
    if (k2 != null) {
      scope = ds.scope;
      k2 = k2 + (sort3 ? "|" + sort3 : "");
      v3 = cache3[k2];
    }
    if (!v3) {
      const params2 = counts ? {
        field: keyFieldRef,
        pulse: ds.countsRef(scope, field3, counts)
      } : {
        field: scope.fieldRef(field3),
        pulse: ref(ds.output)
      };
      if (sort3) params2.sort = scope.sortRef(counts);
      op = scope.add(entry(optype, void 0, params2));
      if (index4) ds.index[field3] = op;
      v3 = ref(op);
      if (k2 != null) cache3[k2] = v3;
    }
    return v3;
  }
  DataScope.prototype = {
    countsRef(scope, field3, sort3) {
      const ds = this, cache3 = ds.counts || (ds.counts = {}), k2 = fieldKey(field3);
      let v3, a4, p2;
      if (k2 != null) {
        scope = ds.scope;
        v3 = cache3[k2];
      }
      if (!v3) {
        p2 = {
          groupby: scope.fieldRef(field3, "key"),
          pulse: ref(ds.output)
        };
        if (sort3 && sort3.field) addSortField(scope, p2, sort3);
        a4 = scope.add(Aggregate2(p2));
        v3 = scope.add(Collect2({
          pulse: ref(a4)
        }));
        v3 = {
          agg: a4,
          ref: ref(v3)
        };
        if (k2 != null) cache3[k2] = v3;
      } else if (sort3 && sort3.field) {
        addSortField(scope, v3.agg.params, sort3);
      }
      return v3.ref;
    },
    tuplesRef() {
      return ref(this.values);
    },
    extentRef(scope, field3) {
      return cache(scope, this, "extent", "extent", field3, false);
    },
    domainRef(scope, field3) {
      return cache(scope, this, "domain", "values", field3, false);
    },
    valuesRef(scope, field3, sort3) {
      return cache(scope, this, "vals", "values", field3, sort3 || true);
    },
    lookupRef(scope, field3) {
      return cache(scope, this, "lookup", "tupleindex", field3, false);
    },
    indataRef(scope, field3) {
      return cache(scope, this, "indata", "tupleindex", field3, true, true);
    }
  };
  function parseFacet(spec, scope, group2) {
    const facet = spec.from.facet, name4 = facet.name, data3 = getDataRef(facet, scope);
    let op;
    if (!facet.name) {
      error("Facet must have a name: " + $(facet));
    }
    if (!facet.data) {
      error("Facet must reference a data set: " + $(facet));
    }
    if (facet.field) {
      op = scope.add(PreFacet2({
        field: scope.fieldRef(facet.field),
        pulse: data3
      }));
    } else if (facet.groupby) {
      op = scope.add(Facet2({
        key: scope.keyRef(facet.groupby),
        group: ref(scope.proxy(group2.parent)),
        pulse: data3
      }));
    } else {
      error("Facet must specify groupby or field: " + $(facet));
    }
    const subscope = scope.fork(), source4 = subscope.add(Collect2()), values4 = subscope.add(Sieve2({
      pulse: ref(source4)
    }));
    subscope.addData(name4, new DataScope(subscope, source4, source4, values4));
    subscope.addSignal("parent", null);
    op.params.subflow = {
      $subflow: subscope.parse(spec).toRuntime()
    };
  }
  function parseSubflow(spec, scope, input) {
    const op = scope.add(PreFacet2({
      pulse: input.pulse
    })), subscope = scope.fork();
    subscope.add(Sieve2());
    subscope.addSignal("parent", null);
    op.params.subflow = {
      $subflow: subscope.parse(spec).toRuntime()
    };
  }
  function parseTrigger(spec, scope, name4) {
    const remove2 = spec.remove, insert2 = spec.insert, toggle2 = spec.toggle, modify2 = spec.modify, values4 = spec.values, op = scope.add(operator());
    const update3 = "if(" + spec.trigger + ',modify("' + name4 + '",' + [insert2, remove2, toggle2, modify2, values4].map((_) => _ == null ? "null" : _).join(",") + "),0)";
    const expr2 = parser2(update3, scope);
    op.update = expr2.$expr;
    op.params = expr2.$params;
  }
  function parseMark(spec, scope) {
    const role = getRole(spec), group2 = spec.type === GroupMark, facet = spec.from && spec.from.facet, overlap = spec.overlap;
    let layout = spec.layout || role === ScopeRole2 || role === FrameRole2, ops2, op, store, enc, name4, layoutRef, boundRef;
    const nested = role === MarkRole || layout || facet;
    const input = parseData$1(spec.from, group2, scope);
    op = scope.add(DataJoin2({
      key: input.key || (spec.key ? fieldRef$1(spec.key) : void 0),
      pulse: input.pulse,
      clean: !group2
    }));
    const joinRef = ref(op);
    op = store = scope.add(Collect2({
      pulse: joinRef
    }));
    op = scope.add(Mark2({
      markdef: definition2(spec),
      interactive: interactive(spec.interactive, scope),
      clip: clip2(spec.clip, scope),
      context: {
        $context: true
      },
      groups: scope.lookup(),
      parent: scope.signals.parent ? scope.signalRef("parent") : null,
      index: scope.markpath(),
      pulse: ref(op)
    }));
    const markRef = ref(op);
    op = enc = scope.add(Encode2(parseEncode(spec.encode, spec.type, role, spec.style, scope, {
      mod: false,
      pulse: markRef
    })));
    op.params.parent = scope.encode();
    if (spec.transform) {
      spec.transform.forEach((_) => {
        const tx = parseTransform(_, scope), md2 = tx.metadata;
        if (md2.generates || md2.changes) {
          error("Mark transforms should not generate new data.");
        }
        if (!md2.nomod) enc.params.mod = true;
        tx.params.pulse = ref(op);
        scope.add(op = tx);
      });
    }
    if (spec.sort) {
      op = scope.add(SortItems2({
        sort: scope.compareRef(spec.sort),
        pulse: ref(op)
      }));
    }
    const encodeRef = ref(op);
    if (facet || layout) {
      layout = scope.add(ViewLayout2({
        layout: scope.objectProperty(spec.layout),
        legends: scope.legends,
        mark: markRef,
        pulse: encodeRef
      }));
      layoutRef = ref(layout);
    }
    const bound2 = scope.add(Bound2({
      mark: markRef,
      pulse: layoutRef || encodeRef
    }));
    boundRef = ref(bound2);
    if (group2) {
      if (nested) {
        ops2 = scope.operators;
        ops2.pop();
        if (layout) ops2.pop();
      }
      scope.pushState(encodeRef, layoutRef || boundRef, joinRef);
      facet ? parseFacet(spec, scope, input) : nested ? parseSubflow(spec, scope, input) : scope.parse(spec);
      scope.popState();
      if (nested) {
        if (layout) ops2.push(layout);
        ops2.push(bound2);
      }
    }
    if (overlap) {
      boundRef = parseOverlap(overlap, boundRef, scope);
    }
    const render = scope.add(Render2({
      pulse: boundRef
    })), sieve = scope.add(Sieve2({
      pulse: ref(render)
    }, void 0, scope.parent()));
    if (spec.name != null) {
      name4 = spec.name;
      scope.addData(name4, new DataScope(scope, store, render, sieve));
      if (spec.on) spec.on.forEach((on2) => {
        if (on2.insert || on2.remove || on2.toggle) {
          error("Marks only support modify triggers.");
        }
        parseTrigger(on2, scope, name4);
      });
    }
  }
  function parseOverlap(overlap, source4, scope) {
    const method2 = overlap.method, bound2 = overlap.bound, sep = overlap.separation;
    const params2 = {
      separation: isSignal(sep) ? scope.signalRef(sep.signal) : sep,
      method: isSignal(method2) ? scope.signalRef(method2.signal) : method2,
      pulse: source4
    };
    if (overlap.order) {
      params2.sort = scope.compareRef({
        field: overlap.order
      });
    }
    if (bound2) {
      const tol = bound2.tolerance;
      params2.boundTolerance = isSignal(tol) ? scope.signalRef(tol.signal) : +tol;
      params2.boundScale = scope.scaleRef(bound2.scale);
      params2.boundOrient = bound2.orient;
    }
    return ref(scope.add(Overlap2(params2)));
  }
  function parseLegend(spec, scope) {
    const config = scope.config.legend, encode2 = spec.encode || {}, _ = lookup5(spec, config), legendEncode = encode2.legend || {}, name4 = legendEncode.name || void 0, interactive2 = legendEncode.interactive, style2 = legendEncode.style, scales2 = {};
    let scale7 = 0, entryLayout, params2, children4;
    LegendScales.forEach((s2) => spec[s2] ? (scales2[s2] = spec[s2], scale7 = scale7 || spec[s2]) : 0);
    if (!scale7) error("Missing valid scale for legend.");
    const type3 = legendType(spec, scope.scaleType(scale7));
    const datum2 = {
      title: spec.title != null,
      scales: scales2,
      type: type3,
      vgrad: type3 !== "symbol" && _.isVertical()
    };
    const dataRef = ref(scope.add(Collect2(null, [datum2])));
    const entryEncode = {
      enter: {
        x: {
          value: 0
        },
        y: {
          value: 0
        }
      }
    };
    const entryRef = ref(scope.add(LegendEntries2(params2 = {
      type: type3,
      scale: scope.scaleRef(scale7),
      count: scope.objectProperty(_("tickCount")),
      limit: scope.property(_("symbolLimit")),
      values: scope.objectProperty(spec.values),
      minstep: scope.property(spec.tickMinStep),
      formatType: scope.property(spec.formatType),
      formatSpecifier: scope.property(spec.format)
    })));
    if (type3 === Gradient2) {
      children4 = [legendGradient(spec, scale7, config, encode2.gradient), legendGradientLabels(spec, config, encode2.labels, entryRef)];
      params2.count = params2.count || scope.signalRef(`max(2,2*floor((${deref(_.gradientLength())})/100))`);
    } else if (type3 === Discrete2) {
      children4 = [legendGradientDiscrete(spec, scale7, config, encode2.gradient, entryRef), legendGradientLabels(spec, config, encode2.labels, entryRef)];
    } else {
      entryLayout = legendSymbolLayout(spec, config);
      children4 = [legendSymbolGroups(spec, config, encode2, entryRef, deref(entryLayout.columns))];
      params2.size = sizeExpression(spec, scope, children4[0].marks);
    }
    children4 = [guideGroup({
      role: LegendEntryRole,
      from: dataRef,
      encode: entryEncode,
      marks: children4,
      layout: entryLayout,
      interactive: interactive2
    })];
    if (datum2.title) {
      children4.push(legendTitle(spec, config, encode2.title, dataRef));
    }
    return parseMark(guideGroup({
      role: LegendRole2,
      from: dataRef,
      encode: extendEncode(buildLegendEncode(_, spec, config), legendEncode, Skip3),
      marks: children4,
      aria: _("aria"),
      description: _("description"),
      zindex: _("zindex"),
      name: name4,
      interactive: interactive2,
      style: style2
    }), scope);
  }
  function legendType(spec, scaleType2) {
    let type3 = spec.type || Symbols2;
    if (!spec.type && scaleCount(spec) === 1 && (spec.fill || spec.stroke)) {
      type3 = isContinuous(scaleType2) ? Gradient2 : isDiscretizing(scaleType2) ? Discrete2 : Symbols2;
    }
    return type3 !== Gradient2 ? type3 : isDiscretizing(scaleType2) ? Discrete2 : Gradient2;
  }
  function scaleCount(spec) {
    return LegendScales.reduce((count2, type3) => count2 + (spec[type3] ? 1 : 0), 0);
  }
  function buildLegendEncode(_, spec, config) {
    const encode2 = {
      enter: {},
      update: {}
    };
    addEncoders(encode2, {
      orient: _("orient"),
      offset: _("offset"),
      padding: _("padding"),
      titlePadding: _("titlePadding"),
      cornerRadius: _("cornerRadius"),
      fill: _("fillColor"),
      stroke: _("strokeColor"),
      strokeWidth: config.strokeWidth,
      strokeDash: config.strokeDash,
      x: _("legendX"),
      y: _("legendY"),
      // accessibility support
      format: spec.format,
      formatType: spec.formatType
    });
    return encode2;
  }
  function sizeExpression(spec, scope, marks) {
    const size = deref(getChannel("size", spec, marks)), strokeWidth = deref(getChannel("strokeWidth", spec, marks)), fontSize2 = deref(getFontSize(marks[1].encode, scope, GuideLabelStyle));
    return parser2(`max(ceil(sqrt(${size})+${strokeWidth}),${fontSize2})`, scope);
  }
  function getChannel(name4, spec, marks) {
    return spec[name4] ? `scale("${spec[name4]}",datum)` : getEncoding(name4, marks[0].encode);
  }
  function getFontSize(encode2, scope, style2) {
    return getEncoding("fontSize", encode2) || getStyle("fontSize", scope, style2);
  }
  var angleExpr = `item.orient==="${Left2}"?-90:item.orient==="${Right2}"?90:0`;
  function parseTitle(spec, scope) {
    spec = isString(spec) ? {
      text: spec
    } : spec;
    const _ = lookup5(spec, scope.config.title), encode2 = spec.encode || {}, userEncode = encode2.group || {}, name4 = userEncode.name || void 0, interactive2 = userEncode.interactive, style2 = userEncode.style, children4 = [];
    const datum2 = {}, dataRef = ref(scope.add(Collect2(null, [datum2])));
    children4.push(buildTitle(spec, _, titleEncode(spec), dataRef));
    if (spec.subtitle) {
      children4.push(buildSubTitle(spec, _, encode2.subtitle, dataRef));
    }
    return parseMark(guideGroup({
      role: TitleRole2,
      from: dataRef,
      encode: groupEncode(_, userEncode),
      marks: children4,
      aria: _("aria"),
      description: _("description"),
      zindex: _("zindex"),
      name: name4,
      interactive: interactive2,
      style: style2
    }), scope);
  }
  function titleEncode(spec) {
    const encode2 = spec.encode;
    return encode2 && encode2.title || extend({
      name: spec.name,
      interactive: spec.interactive,
      style: spec.style
    }, encode2);
  }
  function groupEncode(_, userEncode) {
    const encode2 = {
      enter: {},
      update: {}
    };
    addEncoders(encode2, {
      orient: _("orient"),
      anchor: _("anchor"),
      align: {
        signal: alignExpr$1
      },
      angle: {
        signal: angleExpr
      },
      limit: _("limit"),
      frame: _("frame"),
      offset: _("offset") || 0,
      padding: _("subtitlePadding")
    });
    return extendEncode(encode2, userEncode, Skip3);
  }
  function buildTitle(spec, _, userEncode, dataRef) {
    const zero6 = {
      value: 0
    }, text4 = spec.text, encode2 = {
      enter: {
        opacity: zero6
      },
      update: {
        opacity: {
          value: 1
        }
      },
      exit: {
        opacity: zero6
      }
    };
    addEncoders(encode2, {
      text: text4,
      align: {
        signal: "item.mark.group.align"
      },
      angle: {
        signal: "item.mark.group.angle"
      },
      limit: {
        signal: "item.mark.group.limit"
      },
      baseline: "top",
      dx: _("dx"),
      dy: _("dy"),
      fill: _("color"),
      font: _("font"),
      fontSize: _("fontSize"),
      fontStyle: _("fontStyle"),
      fontWeight: _("fontWeight"),
      lineHeight: _("lineHeight")
    }, {
      // update
      align: _("align"),
      angle: _("angle"),
      baseline: _("baseline")
    });
    return guideMark({
      type: TextMark,
      role: TitleTextRole,
      style: GroupTitleStyle,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function buildSubTitle(spec, _, userEncode, dataRef) {
    const zero6 = {
      value: 0
    }, text4 = spec.subtitle, encode2 = {
      enter: {
        opacity: zero6
      },
      update: {
        opacity: {
          value: 1
        }
      },
      exit: {
        opacity: zero6
      }
    };
    addEncoders(encode2, {
      text: text4,
      align: {
        signal: "item.mark.group.align"
      },
      angle: {
        signal: "item.mark.group.angle"
      },
      limit: {
        signal: "item.mark.group.limit"
      },
      baseline: "top",
      dx: _("dx"),
      dy: _("dy"),
      fill: _("subtitleColor"),
      font: _("subtitleFont"),
      fontSize: _("subtitleFontSize"),
      fontStyle: _("subtitleFontStyle"),
      fontWeight: _("subtitleFontWeight"),
      lineHeight: _("subtitleLineHeight")
    }, {
      // update
      align: _("align"),
      angle: _("angle"),
      baseline: _("baseline")
    });
    return guideMark({
      type: TextMark,
      role: TitleSubtitleRole,
      style: GroupSubtitleStyle,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function parseData(data3, scope) {
    const transforms2 = [];
    if (data3.transform) {
      data3.transform.forEach((tx) => {
        transforms2.push(parseTransform(tx, scope));
      });
    }
    if (data3.on) {
      data3.on.forEach((on2) => {
        parseTrigger(on2, scope, data3.name);
      });
    }
    scope.addDataPipeline(data3.name, analyze(data3, scope, transforms2));
  }
  function analyze(data3, scope, ops2) {
    const output3 = [];
    let source4 = null, modify2 = false, generate3 = false, upstream, i2, n2, t4, m4;
    if (data3.values) {
      if (isSignal(data3.values) || hasSignal(data3.format)) {
        output3.push(load2(scope, data3));
        output3.push(source4 = collect());
      } else {
        output3.push(source4 = collect({
          $ingest: data3.values,
          $format: data3.format
        }));
      }
    } else if (data3.url) {
      if (hasSignal(data3.url) || hasSignal(data3.format)) {
        output3.push(load2(scope, data3));
        output3.push(source4 = collect());
      } else {
        output3.push(source4 = collect({
          $request: data3.url,
          $format: data3.format
        }));
      }
    } else if (data3.source) {
      source4 = upstream = array(data3.source).map((d2) => ref(scope.getData(d2).output));
      output3.push(null);
    }
    for (i2 = 0, n2 = ops2.length; i2 < n2; ++i2) {
      t4 = ops2[i2];
      m4 = t4.metadata;
      if (!source4 && !m4.source) {
        output3.push(source4 = collect());
      }
      output3.push(t4);
      if (m4.generates) generate3 = true;
      if (m4.modifies && !generate3) modify2 = true;
      if (m4.source) source4 = t4;
      else if (m4.changes) source4 = null;
    }
    if (upstream) {
      n2 = upstream.length - 1;
      output3[0] = Relay2({
        derive: modify2,
        pulse: n2 ? upstream : upstream[0]
      });
      if (modify2 || n2) {
        output3.splice(1, 0, collect());
      }
    }
    if (!source4) output3.push(collect());
    output3.push(Sieve2({}));
    return output3;
  }
  function collect(values4) {
    const s2 = Collect2({}, values4);
    s2.metadata = {
      source: true
    };
    return s2;
  }
  function load2(scope, data3) {
    return Load2({
      url: data3.url ? scope.property(data3.url) : void 0,
      async: data3.async ? scope.property(data3.async) : void 0,
      values: data3.values ? scope.property(data3.values) : void 0,
      format: scope.objectProperty(data3.format)
    });
  }
  var isX = (orient2) => orient2 === Bottom2 || orient2 === Top2;
  var getSign = (orient2, a4, b3) => isSignal(orient2) ? ifLeftTopExpr(orient2.signal, a4, b3) : orient2 === Left2 || orient2 === Top2 ? a4 : b3;
  var ifX = (orient2, a4, b3) => isSignal(orient2) ? ifXEnc(orient2.signal, a4, b3) : isX(orient2) ? a4 : b3;
  var ifY = (orient2, a4, b3) => isSignal(orient2) ? ifYEnc(orient2.signal, a4, b3) : isX(orient2) ? b3 : a4;
  var ifTop = (orient2, a4, b3) => isSignal(orient2) ? ifTopExpr(orient2.signal, a4, b3) : orient2 === Top2 ? {
    value: a4
  } : {
    value: b3
  };
  var ifRight = (orient2, a4, b3) => isSignal(orient2) ? ifRightExpr(orient2.signal, a4, b3) : orient2 === Right2 ? {
    value: a4
  } : {
    value: b3
  };
  var ifXEnc = ($orient, a4, b3) => ifEnc(`${$orient} === '${Top2}' || ${$orient} === '${Bottom2}'`, a4, b3);
  var ifYEnc = ($orient, a4, b3) => ifEnc(`${$orient} !== '${Top2}' && ${$orient} !== '${Bottom2}'`, a4, b3);
  var ifLeftTopExpr = ($orient, a4, b3) => ifExpr(`${$orient} === '${Left2}' || ${$orient} === '${Top2}'`, a4, b3);
  var ifTopExpr = ($orient, a4, b3) => ifExpr(`${$orient} === '${Top2}'`, a4, b3);
  var ifRightExpr = ($orient, a4, b3) => ifExpr(`${$orient} === '${Right2}'`, a4, b3);
  var ifEnc = (test2, a4, b3) => {
    a4 = a4 != null ? encoder(a4) : a4;
    b3 = b3 != null ? encoder(b3) : b3;
    if (isSimple(a4) && isSimple(b3)) {
      a4 = a4 ? a4.signal || $(a4.value) : null;
      b3 = b3 ? b3.signal || $(b3.value) : null;
      return {
        signal: `${test2} ? (${a4}) : (${b3})`
      };
    } else {
      return [extend({
        test: test2
      }, a4)].concat(b3 || []);
    }
  };
  var isSimple = (enc) => enc == null || Object.keys(enc).length === 1;
  var ifExpr = (test2, a4, b3) => ({
    signal: `${test2} ? (${toExpr(a4)}) : (${toExpr(b3)})`
  });
  var ifOrient = ($orient, t4, b3, l2, r2) => ({
    signal: (l2 != null ? `${$orient} === '${Left2}' ? (${toExpr(l2)}) : ` : "") + (b3 != null ? `${$orient} === '${Bottom2}' ? (${toExpr(b3)}) : ` : "") + (r2 != null ? `${$orient} === '${Right2}' ? (${toExpr(r2)}) : ` : "") + (t4 != null ? `${$orient} === '${Top2}' ? (${toExpr(t4)}) : ` : "") + "(null)"
  });
  var toExpr = (v3) => isSignal(v3) ? v3.signal : v3 == null ? null : $(v3);
  var mult = (sign3, value3) => value3 === 0 ? 0 : isSignal(sign3) ? {
    signal: `(${sign3.signal}) * ${value3}`
  } : {
    value: sign3 * value3
  };
  var patch = (value3, base) => {
    const s2 = value3.signal;
    return s2 && s2.endsWith("(null)") ? {
      signal: s2.slice(0, -6) + base.signal
    } : value3;
  };
  function fallback(prop, config, axisConfig2, style2) {
    let styleProp;
    if (config && has(config, prop)) {
      return config[prop];
    } else if (has(axisConfig2, prop)) {
      return axisConfig2[prop];
    } else if (prop.startsWith("title")) {
      switch (prop) {
        case "titleColor":
          styleProp = "fill";
          break;
        case "titleFont":
        case "titleFontSize":
        case "titleFontWeight":
          styleProp = prop[5].toLowerCase() + prop.slice(6);
      }
      return style2[GuideTitleStyle][styleProp];
    } else if (prop.startsWith("label")) {
      switch (prop) {
        case "labelColor":
          styleProp = "fill";
          break;
        case "labelFont":
        case "labelFontSize":
          styleProp = prop[5].toLowerCase() + prop.slice(6);
      }
      return style2[GuideLabelStyle][styleProp];
    }
    return null;
  }
  function keys2(objects) {
    const map4 = {};
    for (const obj of objects) {
      if (!obj) continue;
      for (const key2 in obj) map4[key2] = 1;
    }
    return Object.keys(map4);
  }
  function axisConfig(spec, scope) {
    var config = scope.config, style2 = config.style, axis = config.axis, band2 = scope.scaleType(spec.scale) === "band" && config.axisBand, orient2 = spec.orient, xy, or2, key2;
    if (isSignal(orient2)) {
      const xyKeys = keys2([config.axisX, config.axisY]), orientKeys = keys2([config.axisTop, config.axisBottom, config.axisLeft, config.axisRight]);
      xy = {};
      for (key2 of xyKeys) {
        xy[key2] = ifX(orient2, fallback(key2, config.axisX, axis, style2), fallback(key2, config.axisY, axis, style2));
      }
      or2 = {};
      for (key2 of orientKeys) {
        or2[key2] = ifOrient(orient2.signal, fallback(key2, config.axisTop, axis, style2), fallback(key2, config.axisBottom, axis, style2), fallback(key2, config.axisLeft, axis, style2), fallback(key2, config.axisRight, axis, style2));
      }
    } else {
      xy = orient2 === Top2 || orient2 === Bottom2 ? config.axisX : config.axisY;
      or2 = config["axis" + orient2[0].toUpperCase() + orient2.slice(1)];
    }
    const result = xy || or2 || band2 ? extend({}, axis, xy, or2, band2) : axis;
    return result;
  }
  function axisDomain(spec, config, userEncode, dataRef) {
    const _ = lookup5(spec, config), orient2 = spec.orient;
    let enter, update3;
    const encode2 = {
      enter: enter = {
        opacity: zero4
      },
      update: update3 = {
        opacity: one3
      },
      exit: {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      stroke: _("domainColor"),
      strokeCap: _("domainCap"),
      strokeDash: _("domainDash"),
      strokeDashOffset: _("domainDashOffset"),
      strokeWidth: _("domainWidth"),
      strokeOpacity: _("domainOpacity")
    });
    const pos0 = position(spec, 0);
    const pos1 = position(spec, 1);
    enter.x = update3.x = ifX(orient2, pos0, zero4);
    enter.x2 = update3.x2 = ifX(orient2, pos1);
    enter.y = update3.y = ifY(orient2, pos0, zero4);
    enter.y2 = update3.y2 = ifY(orient2, pos1);
    return guideMark({
      type: RuleMark,
      role: AxisDomainRole,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function position(spec, pos) {
    return {
      scale: spec.scale,
      range: pos
    };
  }
  function axisGrid(spec, config, userEncode, dataRef, band2) {
    const _ = lookup5(spec, config), orient2 = spec.orient, vscale = spec.gridScale, sign3 = getSign(orient2, 1, -1), offset4 = offsetValue2(spec.offset, sign3);
    let enter, exit, update3;
    const encode2 = {
      enter: enter = {
        opacity: zero4
      },
      update: update3 = {
        opacity: one3
      },
      exit: exit = {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      stroke: _("gridColor"),
      strokeCap: _("gridCap"),
      strokeDash: _("gridDash"),
      strokeDashOffset: _("gridDashOffset"),
      strokeOpacity: _("gridOpacity"),
      strokeWidth: _("gridWidth")
    });
    const tickPos = {
      scale: spec.scale,
      field: Value,
      band: band2.band,
      extra: band2.extra,
      offset: band2.offset,
      round: _("tickRound")
    };
    const sz2 = ifX(orient2, {
      signal: "height"
    }, {
      signal: "width"
    });
    const gridStart = vscale ? {
      scale: vscale,
      range: 0,
      mult: sign3,
      offset: offset4
    } : {
      value: 0,
      offset: offset4
    };
    const gridEnd = vscale ? {
      scale: vscale,
      range: 1,
      mult: sign3,
      offset: offset4
    } : extend(sz2, {
      mult: sign3,
      offset: offset4
    });
    enter.x = update3.x = ifX(orient2, tickPos, gridStart);
    enter.y = update3.y = ifY(orient2, tickPos, gridStart);
    enter.x2 = update3.x2 = ifY(orient2, gridEnd);
    enter.y2 = update3.y2 = ifX(orient2, gridEnd);
    exit.x = ifX(orient2, tickPos);
    exit.y = ifY(orient2, tickPos);
    return guideMark({
      type: RuleMark,
      role: AxisGridRole,
      key: Value,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function offsetValue2(offset4, sign3) {
    if (sign3 === 1) ;
    else if (!isObject(offset4)) {
      offset4 = isSignal(sign3) ? {
        signal: `(${sign3.signal}) * (${offset4 || 0})`
      } : sign3 * (offset4 || 0);
    } else {
      let entry2 = offset4 = extend({}, offset4);
      while (entry2.mult != null) {
        if (!isObject(entry2.mult)) {
          entry2.mult = isSignal(sign3) ? {
            signal: `(${entry2.mult}) * (${sign3.signal})`
          } : entry2.mult * sign3;
          return offset4;
        } else {
          entry2 = entry2.mult = extend({}, entry2.mult);
        }
      }
      entry2.mult = sign3;
    }
    return offset4;
  }
  function axisTicks(spec, config, userEncode, dataRef, size, band2) {
    const _ = lookup5(spec, config), orient2 = spec.orient, sign3 = getSign(orient2, -1, 1);
    let enter, exit, update3;
    const encode2 = {
      enter: enter = {
        opacity: zero4
      },
      update: update3 = {
        opacity: one3
      },
      exit: exit = {
        opacity: zero4
      }
    };
    addEncoders(encode2, {
      stroke: _("tickColor"),
      strokeCap: _("tickCap"),
      strokeDash: _("tickDash"),
      strokeDashOffset: _("tickDashOffset"),
      strokeOpacity: _("tickOpacity"),
      strokeWidth: _("tickWidth")
    });
    const tickSize = encoder(size);
    tickSize.mult = sign3;
    const tickPos = {
      scale: spec.scale,
      field: Value,
      band: band2.band,
      extra: band2.extra,
      offset: band2.offset,
      round: _("tickRound")
    };
    update3.y = enter.y = ifX(orient2, zero4, tickPos);
    update3.y2 = enter.y2 = ifX(orient2, tickSize);
    exit.x = ifX(orient2, tickPos);
    update3.x = enter.x = ifY(orient2, zero4, tickPos);
    update3.x2 = enter.x2 = ifY(orient2, tickSize);
    exit.y = ifY(orient2, tickPos);
    return guideMark({
      type: RuleMark,
      role: AxisTickRole,
      key: Value,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function flushExpr(scale7, threshold2, a4, b3, c4) {
    return {
      signal: 'flush(range("' + scale7 + '"), scale("' + scale7 + '", datum.value), ' + threshold2 + "," + a4 + "," + b3 + "," + c4 + ")"
    };
  }
  function axisLabels(spec, config, userEncode, dataRef, size, band2) {
    const _ = lookup5(spec, config), orient2 = spec.orient, scale7 = spec.scale, sign3 = getSign(orient2, -1, 1), flush2 = deref(_("labelFlush")), flushOffset = deref(_("labelFlushOffset")), labelAlign = _("labelAlign"), labelBaseline = _("labelBaseline");
    let flushOn = flush2 === 0 || !!flush2, update3;
    const tickSize = encoder(size);
    tickSize.mult = sign3;
    tickSize.offset = encoder(_("labelPadding") || 0);
    tickSize.offset.mult = sign3;
    const tickPos = {
      scale: scale7,
      field: Value,
      band: 0.5,
      offset: extendOffset(band2.offset, _("labelOffset"))
    };
    const align2 = ifX(orient2, flushOn ? flushExpr(scale7, flush2, '"left"', '"right"', '"center"') : {
      value: "center"
    }, ifRight(orient2, "left", "right"));
    const baseline3 = ifX(orient2, ifTop(orient2, "bottom", "top"), flushOn ? flushExpr(scale7, flush2, '"top"', '"bottom"', '"middle"') : {
      value: "middle"
    });
    const offsetExpr2 = flushExpr(scale7, flush2, `-(${flushOffset})`, flushOffset, 0);
    flushOn = flushOn && flushOffset;
    const enter = {
      opacity: zero4,
      x: ifX(orient2, tickPos, tickSize),
      y: ifY(orient2, tickPos, tickSize)
    };
    const encode2 = {
      enter,
      update: update3 = {
        opacity: one3,
        text: {
          field: Label2
        },
        x: enter.x,
        y: enter.y,
        align: align2,
        baseline: baseline3
      },
      exit: {
        opacity: zero4,
        x: enter.x,
        y: enter.y
      }
    };
    addEncoders(encode2, {
      dx: !labelAlign && flushOn ? ifX(orient2, offsetExpr2) : null,
      dy: !labelBaseline && flushOn ? ifY(orient2, offsetExpr2) : null
    });
    addEncoders(encode2, {
      angle: _("labelAngle"),
      fill: _("labelColor"),
      fillOpacity: _("labelOpacity"),
      font: _("labelFont"),
      fontSize: _("labelFontSize"),
      fontWeight: _("labelFontWeight"),
      fontStyle: _("labelFontStyle"),
      limit: _("labelLimit"),
      lineHeight: _("labelLineHeight")
    }, {
      align: labelAlign,
      baseline: labelBaseline
    });
    const bound2 = _("labelBound");
    let overlap = _("labelOverlap");
    overlap = overlap || bound2 ? {
      separation: _("labelSeparation"),
      method: overlap,
      order: "datum.index",
      bound: bound2 ? {
        scale: scale7,
        orient: orient2,
        tolerance: bound2
      } : null
    } : void 0;
    if (update3.align !== align2) {
      update3.align = patch(update3.align, align2);
    }
    if (update3.baseline !== baseline3) {
      update3.baseline = patch(update3.baseline, baseline3);
    }
    return guideMark({
      type: TextMark,
      role: AxisLabelRole,
      style: GuideLabelStyle,
      key: Value,
      from: dataRef,
      encode: encode2,
      overlap
    }, userEncode);
  }
  function axisTitle(spec, config, userEncode, dataRef) {
    const _ = lookup5(spec, config), orient2 = spec.orient, sign3 = getSign(orient2, -1, 1);
    let enter, update3;
    const encode2 = {
      enter: enter = {
        opacity: zero4,
        anchor: encoder(_("titleAnchor", null)),
        align: {
          signal: alignExpr$1
        }
      },
      update: update3 = extend({}, enter, {
        opacity: one3,
        text: encoder(spec.title)
      }),
      exit: {
        opacity: zero4
      }
    };
    const titlePos = {
      signal: `lerp(range("${spec.scale}"), ${anchorExpr(0, 1, 0.5)})`
    };
    update3.x = ifX(orient2, titlePos);
    update3.y = ifY(orient2, titlePos);
    enter.angle = ifX(orient2, zero4, mult(sign3, 90));
    enter.baseline = ifX(orient2, ifTop(orient2, Bottom2, Top2), {
      value: Bottom2
    });
    update3.angle = enter.angle;
    update3.baseline = enter.baseline;
    addEncoders(encode2, {
      fill: _("titleColor"),
      fillOpacity: _("titleOpacity"),
      font: _("titleFont"),
      fontSize: _("titleFontSize"),
      fontStyle: _("titleFontStyle"),
      fontWeight: _("titleFontWeight"),
      limit: _("titleLimit"),
      lineHeight: _("titleLineHeight")
    }, {
      // require update
      align: _("titleAlign"),
      angle: _("titleAngle"),
      baseline: _("titleBaseline")
    });
    autoLayout(_, orient2, encode2, userEncode);
    encode2.update.align = patch(encode2.update.align, enter.align);
    encode2.update.angle = patch(encode2.update.angle, enter.angle);
    encode2.update.baseline = patch(encode2.update.baseline, enter.baseline);
    return guideMark({
      type: TextMark,
      role: AxisTitleRole,
      style: GuideTitleStyle,
      from: dataRef,
      encode: encode2
    }, userEncode);
  }
  function autoLayout(_, orient2, encode2, userEncode) {
    const auto = (value3, dim) => value3 != null ? (encode2.update[dim] = patch(encoder(value3), encode2.update[dim]), false) : !has2(dim, userEncode) ? true : false;
    const autoY = auto(_("titleX"), "x"), autoX = auto(_("titleY"), "y");
    encode2.enter.auto = autoX === autoY ? encoder(autoX) : ifX(orient2, encoder(autoX), encoder(autoY));
  }
  function parseAxis(spec, scope) {
    const config = axisConfig(spec, scope), encode2 = spec.encode || {}, axisEncode = encode2.axis || {}, name4 = axisEncode.name || void 0, interactive2 = axisEncode.interactive, style2 = axisEncode.style, _ = lookup5(spec, config), band2 = tickBand(_);
    const datum2 = {
      scale: spec.scale,
      ticks: !!_("ticks"),
      labels: !!_("labels"),
      grid: !!_("grid"),
      domain: !!_("domain"),
      title: spec.title != null
    };
    const dataRef = ref(scope.add(Collect2({}, [datum2])));
    const ticksRef = ref(scope.add(AxisTicks2({
      scale: scope.scaleRef(spec.scale),
      extra: scope.property(band2.extra),
      count: scope.objectProperty(spec.tickCount),
      values: scope.objectProperty(spec.values),
      minstep: scope.property(spec.tickMinStep),
      formatType: scope.property(spec.formatType),
      formatSpecifier: scope.property(spec.format)
    })));
    const children4 = [];
    let size;
    if (datum2.grid) {
      children4.push(axisGrid(spec, config, encode2.grid, ticksRef, band2));
    }
    if (datum2.ticks) {
      size = _("tickSize");
      children4.push(axisTicks(spec, config, encode2.ticks, ticksRef, size, band2));
    }
    if (datum2.labels) {
      size = datum2.ticks ? size : 0;
      children4.push(axisLabels(spec, config, encode2.labels, ticksRef, size, band2));
    }
    if (datum2.domain) {
      children4.push(axisDomain(spec, config, encode2.domain, dataRef));
    }
    if (datum2.title) {
      children4.push(axisTitle(spec, config, encode2.title, dataRef));
    }
    return parseMark(guideGroup({
      role: AxisRole2,
      from: dataRef,
      encode: extendEncode(buildAxisEncode(_, spec), axisEncode, Skip3),
      marks: children4,
      aria: _("aria"),
      description: _("description"),
      zindex: _("zindex"),
      name: name4,
      interactive: interactive2,
      style: style2
    }), scope);
  }
  function buildAxisEncode(_, spec) {
    const encode2 = {
      enter: {},
      update: {}
    };
    addEncoders(encode2, {
      orient: _("orient"),
      offset: _("offset") || 0,
      position: value2(spec.position, 0),
      titlePadding: _("titlePadding"),
      minExtent: _("minExtent"),
      maxExtent: _("maxExtent"),
      range: {
        signal: `abs(span(range("${spec.scale}")))`
      },
      translate: _("translate"),
      // accessibility support
      format: spec.format,
      formatType: spec.formatType
    });
    return encode2;
  }
  function parseScope(spec, scope, preprocessed) {
    const signals = array(spec.signals), scales2 = array(spec.scales);
    if (!preprocessed) signals.forEach((_) => parseSignal(_, scope));
    array(spec.projections).forEach((_) => parseProjection(_, scope));
    scales2.forEach((_) => initScale(_, scope));
    array(spec.data).forEach((_) => parseData(_, scope));
    scales2.forEach((_) => parseScale(_, scope));
    (preprocessed || signals).forEach((_) => parseSignalUpdates(_, scope));
    array(spec.axes).forEach((_) => parseAxis(_, scope));
    array(spec.marks).forEach((_) => parseMark(_, scope));
    array(spec.legends).forEach((_) => parseLegend(_, scope));
    if (spec.title) parseTitle(spec.title, scope);
    scope.parseLambdas();
    return scope;
  }
  var rootEncode = (spec) => extendEncode({
    enter: {
      x: {
        value: 0
      },
      y: {
        value: 0
      }
    },
    update: {
      width: {
        signal: "width"
      },
      height: {
        signal: "height"
      }
    }
  }, spec);
  function parseView(spec, scope) {
    const config = scope.config;
    const root = ref(scope.root = scope.add(operator()));
    const signals = collectSignals(spec, config);
    signals.forEach((_) => parseSignal(_, scope));
    scope.description = spec.description || config.description;
    scope.eventConfig = config.events;
    scope.legends = scope.objectProperty(config.legend && config.legend.layout);
    scope.locale = config.locale;
    const input = scope.add(Collect2());
    const encode2 = scope.add(Encode2(parseEncode(rootEncode(spec.encode), GroupMark, FrameRole2, spec.style, scope, {
      pulse: ref(input)
    })));
    const parent = scope.add(ViewLayout2({
      layout: scope.objectProperty(spec.layout),
      legends: scope.legends,
      autosize: scope.signalRef("autosize"),
      mark: root,
      pulse: ref(encode2)
    }));
    scope.operators.pop();
    scope.pushState(ref(encode2), ref(parent), null);
    parseScope(spec, scope, signals);
    scope.operators.push(parent);
    let op = scope.add(Bound2({
      mark: root,
      pulse: ref(parent)
    }));
    op = scope.add(Render2({
      pulse: ref(op)
    }));
    op = scope.add(Sieve2({
      pulse: ref(op)
    }));
    scope.addData("root", new DataScope(scope, input, input, op));
    return scope;
  }
  function signalObject(name4, value3) {
    return value3 && value3.signal ? {
      name: name4,
      update: value3.signal
    } : {
      name: name4,
      value: value3
    };
  }
  function collectSignals(spec, config) {
    const _ = (name4) => value2(spec[name4], config[name4]), signals = [signalObject("background", _("background")), signalObject("autosize", parseAutosize(_("autosize"))), signalObject("padding", parsePadding(_("padding"))), signalObject("width", _("width") || 0), signalObject("height", _("height") || 0)], pre = signals.reduce((p2, s2) => (p2[s2.name] = s2, p2), {}), map4 = {};
    array(spec.signals).forEach((s2) => {
      if (has(pre, s2.name)) {
        s2 = extend(pre[s2.name], s2);
      } else {
        signals.push(s2);
      }
      map4[s2.name] = s2;
    });
    array(config.signals).forEach((s2) => {
      if (!has(map4, s2.name) && !has(pre, s2.name)) {
        signals.push(s2);
      }
    });
    return signals;
  }
  function Scope(config, options) {
    this.config = config || {};
    this.options = options || {};
    this.bindings = [];
    this.field = {};
    this.signals = {};
    this.lambdas = {};
    this.scales = {};
    this.events = {};
    this.data = {};
    this.streams = [];
    this.updates = [];
    this.operators = [];
    this.eventConfig = null;
    this.locale = null;
    this._id = 0;
    this._subid = 0;
    this._nextsub = [0];
    this._parent = [];
    this._encode = [];
    this._lookup = [];
    this._markpath = [];
  }
  function Subscope(scope) {
    this.config = scope.config;
    this.options = scope.options;
    this.legends = scope.legends;
    this.field = Object.create(scope.field);
    this.signals = Object.create(scope.signals);
    this.lambdas = Object.create(scope.lambdas);
    this.scales = Object.create(scope.scales);
    this.events = Object.create(scope.events);
    this.data = Object.create(scope.data);
    this.streams = [];
    this.updates = [];
    this.operators = [];
    this._id = 0;
    this._subid = ++scope._nextsub[0];
    this._nextsub = scope._nextsub;
    this._parent = scope._parent.slice();
    this._encode = scope._encode.slice();
    this._lookup = scope._lookup.slice();
    this._markpath = scope._markpath;
  }
  Scope.prototype = Subscope.prototype = {
    parse(spec) {
      return parseScope(spec, this);
    },
    fork() {
      return new Subscope(this);
    },
    isSubscope() {
      return this._subid > 0;
    },
    toRuntime() {
      this.finish();
      return {
        description: this.description,
        operators: this.operators,
        streams: this.streams,
        updates: this.updates,
        bindings: this.bindings,
        eventConfig: this.eventConfig,
        locale: this.locale
      };
    },
    id() {
      return (this._subid ? this._subid + ":" : 0) + this._id++;
    },
    add(op) {
      this.operators.push(op);
      op.id = this.id();
      if (op.refs) {
        op.refs.forEach((ref2) => {
          ref2.$ref = op.id;
        });
        op.refs = null;
      }
      return op;
    },
    proxy(op) {
      const vref = op instanceof Entry ? ref(op) : op;
      return this.add(Proxy3({
        value: vref
      }));
    },
    addStream(stream2) {
      this.streams.push(stream2);
      stream2.id = this.id();
      return stream2;
    },
    addUpdate(update3) {
      this.updates.push(update3);
      return update3;
    },
    // Apply metadata
    finish() {
      let name4, ds;
      if (this.root) this.root.root = true;
      for (name4 in this.signals) {
        this.signals[name4].signal = name4;
      }
      for (name4 in this.scales) {
        this.scales[name4].scale = name4;
      }
      function annotate(op, name5, type3) {
        let data3, list;
        if (op) {
          data3 = op.data || (op.data = {});
          list = data3[name5] || (data3[name5] = []);
          list.push(type3);
        }
      }
      for (name4 in this.data) {
        ds = this.data[name4];
        annotate(ds.input, name4, "input");
        annotate(ds.output, name4, "output");
        annotate(ds.values, name4, "values");
        for (const field3 in ds.index) {
          annotate(ds.index[field3], name4, "index:" + field3);
        }
      }
      return this;
    },
    // ----
    pushState(encode2, parent, lookup6) {
      this._encode.push(ref(this.add(Sieve2({
        pulse: encode2
      }))));
      this._parent.push(parent);
      this._lookup.push(lookup6 ? ref(this.proxy(lookup6)) : null);
      this._markpath.push(-1);
    },
    popState() {
      this._encode.pop();
      this._parent.pop();
      this._lookup.pop();
      this._markpath.pop();
    },
    parent() {
      return peek(this._parent);
    },
    encode() {
      return peek(this._encode);
    },
    lookup() {
      return peek(this._lookup);
    },
    markpath() {
      const p2 = this._markpath;
      return ++p2[p2.length - 1];
    },
    // ----
    fieldRef(field3, name4) {
      if (isString(field3)) return fieldRef$1(field3, name4);
      if (!field3.signal) {
        error("Unsupported field reference: " + $(field3));
      }
      const s2 = field3.signal;
      let f2 = this.field[s2];
      if (!f2) {
        const params2 = {
          name: this.signalRef(s2)
        };
        if (name4) params2.as = name4;
        this.field[s2] = f2 = ref(this.add(Field2(params2)));
      }
      return f2;
    },
    compareRef(cmp) {
      let signal = false;
      const check = (_) => isSignal(_) ? (signal = true, this.signalRef(_.signal)) : isExpr$1(_) ? (signal = true, this.exprRef(_.expr)) : _;
      const fields = array(cmp.field).map(check), orders = array(cmp.order).map(check);
      return signal ? ref(this.add(Compare2({
        fields,
        orders
      }))) : compareRef(fields, orders);
    },
    keyRef(fields, flat) {
      let signal = false;
      const check = (_) => isSignal(_) ? (signal = true, ref(sig[_.signal])) : _;
      const sig = this.signals;
      fields = array(fields).map(check);
      return signal ? ref(this.add(Key2({
        fields,
        flat
      }))) : keyRef(fields, flat);
    },
    sortRef(sort3) {
      if (!sort3) return sort3;
      const a4 = aggrField(sort3.op, sort3.field), o2 = sort3.order || Ascending;
      return o2.signal ? ref(this.add(Compare2({
        fields: a4,
        orders: this.signalRef(o2.signal)
      }))) : compareRef(a4, o2);
    },
    // ----
    event(source4, type3) {
      const key2 = source4 + ":" + type3;
      if (!this.events[key2]) {
        const id2 = this.id();
        this.streams.push({
          id: id2,
          source: source4,
          type: type3
        });
        this.events[key2] = id2;
      }
      return this.events[key2];
    },
    // ----
    hasOwnSignal(name4) {
      return has(this.signals, name4);
    },
    addSignal(name4, value3) {
      if (this.hasOwnSignal(name4)) {
        error("Duplicate signal name: " + $(name4));
      }
      const op = value3 instanceof Entry ? value3 : this.add(operator(value3));
      return this.signals[name4] = op;
    },
    getSignal(name4) {
      if (!this.signals[name4]) {
        error("Unrecognized signal name: " + $(name4));
      }
      return this.signals[name4];
    },
    signalRef(s2) {
      if (this.signals[s2]) {
        return ref(this.signals[s2]);
      } else if (!has(this.lambdas, s2)) {
        this.lambdas[s2] = this.add(operator(null));
      }
      return ref(this.lambdas[s2]);
    },
    parseLambdas() {
      const code = Object.keys(this.lambdas);
      for (let i2 = 0, n2 = code.length; i2 < n2; ++i2) {
        const s2 = code[i2], e4 = parser2(s2, this), op = this.lambdas[s2];
        op.params = e4.$params;
        op.update = e4.$expr;
      }
    },
    property(spec) {
      return spec && spec.signal ? this.signalRef(spec.signal) : spec;
    },
    objectProperty(spec) {
      return !spec || !isObject(spec) ? spec : this.signalRef(spec.signal || propertyLambda(spec));
    },
    exprRef(code, name4) {
      const params2 = {
        expr: parser2(code, this)
      };
      if (name4) params2.expr.$name = name4;
      return ref(this.add(Expression2(params2)));
    },
    addBinding(name4, bind3) {
      if (!this.bindings) {
        error("Nested signals do not support binding: " + $(name4));
      }
      this.bindings.push(extend({
        signal: name4
      }, bind3));
    },
    // ----
    addScaleProj(name4, transform4) {
      if (has(this.scales, name4)) {
        error("Duplicate scale or projection name: " + $(name4));
      }
      this.scales[name4] = this.add(transform4);
    },
    addScale(name4, params2) {
      this.addScaleProj(name4, Scale2(params2));
    },
    addProjection(name4, params2) {
      this.addScaleProj(name4, Projection2(params2));
    },
    getScale(name4) {
      if (!this.scales[name4]) {
        error("Unrecognized scale name: " + $(name4));
      }
      return this.scales[name4];
    },
    scaleRef(name4) {
      return ref(this.getScale(name4));
    },
    scaleType(name4) {
      return this.getScale(name4).params.type;
    },
    projectionRef(name4) {
      return this.scaleRef(name4);
    },
    projectionType(name4) {
      return this.scaleType(name4);
    },
    // ----
    addData(name4, dataScope) {
      if (has(this.data, name4)) {
        error("Duplicate data set name: " + $(name4));
      }
      return this.data[name4] = dataScope;
    },
    getData(name4) {
      if (!this.data[name4]) {
        error("Undefined data set name: " + $(name4));
      }
      return this.data[name4];
    },
    addDataPipeline(name4, entries3) {
      if (has(this.data, name4)) {
        error("Duplicate data set name: " + $(name4));
      }
      return this.addData(name4, DataScope.fromEntries(this, entries3));
    }
  };
  function propertyLambda(spec) {
    return (isArray(spec) ? arrayLambda : objectLambda)(spec);
  }
  function arrayLambda(array4) {
    const n2 = array4.length;
    let code = "[";
    for (let i2 = 0; i2 < n2; ++i2) {
      const value3 = array4[i2];
      code += (i2 > 0 ? "," : "") + (isObject(value3) ? value3.signal || propertyLambda(value3) : $(value3));
    }
    return code + "]";
  }
  function objectLambda(obj) {
    let code = "{", i2 = 0, key2, value3;
    for (key2 in obj) {
      value3 = obj[key2];
      code += (++i2 > 1 ? "," : "") + $(key2) + ":" + (isObject(value3) ? value3.signal || propertyLambda(value3) : $(value3));
    }
    return code + "}";
  }
  function defaults() {
    const defaultFont2 = "sans-serif", defaultSymbolSize = 30, defaultStrokeWidth = 2, defaultColor = "#4c78a8", black = "#000", gray2 = "#888", lightGray = "#ddd";
    return {
      // default visualization description
      description: "Vega visualization",
      // default padding around visualization
      padding: 0,
      // default for automatic sizing; options: 'none', 'pad', 'fit'
      // or provide an object (e.g., {'type': 'pad', 'resize': true})
      autosize: "pad",
      // default view background color
      // covers the entire view component
      background: null,
      // default event handling configuration
      // preventDefault for view-sourced event types except 'wheel'
      events: {
        defaults: {
          allow: ["wheel"]
        }
      },
      // defaults for top-level group marks
      // accepts mark properties (fill, stroke, etc)
      // covers the data rectangle within group width/height
      group: null,
      // defaults for basic mark types
      // each subset accepts mark properties (fill, stroke, etc)
      mark: null,
      arc: {
        fill: defaultColor
      },
      area: {
        fill: defaultColor
      },
      image: null,
      line: {
        stroke: defaultColor,
        strokeWidth: defaultStrokeWidth
      },
      path: {
        stroke: defaultColor
      },
      rect: {
        fill: defaultColor
      },
      rule: {
        stroke: black
      },
      shape: {
        stroke: defaultColor
      },
      symbol: {
        fill: defaultColor,
        size: 64
      },
      text: {
        fill: black,
        font: defaultFont2,
        fontSize: 11
      },
      trail: {
        fill: defaultColor,
        size: defaultStrokeWidth
      },
      // style definitions
      style: {
        // axis & legend labels
        "guide-label": {
          fill: black,
          font: defaultFont2,
          fontSize: 10
        },
        // axis & legend titles
        "guide-title": {
          fill: black,
          font: defaultFont2,
          fontSize: 11,
          fontWeight: "bold"
        },
        // headers, including chart title
        "group-title": {
          fill: black,
          font: defaultFont2,
          fontSize: 13,
          fontWeight: "bold"
        },
        // chart subtitle
        "group-subtitle": {
          fill: black,
          font: defaultFont2,
          fontSize: 12
        },
        // defaults for styled point marks in Vega-Lite
        point: {
          size: defaultSymbolSize,
          strokeWidth: defaultStrokeWidth,
          shape: "circle"
        },
        circle: {
          size: defaultSymbolSize,
          strokeWidth: defaultStrokeWidth
        },
        square: {
          size: defaultSymbolSize,
          strokeWidth: defaultStrokeWidth,
          shape: "square"
        },
        // defaults for styled group marks in Vega-Lite
        cell: {
          fill: "transparent",
          stroke: lightGray
        },
        view: {
          fill: "transparent"
        }
      },
      // defaults for title
      title: {
        orient: "top",
        anchor: "middle",
        offset: 4,
        subtitlePadding: 3
      },
      // defaults for axes
      axis: {
        minExtent: 0,
        maxExtent: 200,
        bandPosition: 0.5,
        domain: true,
        domainWidth: 1,
        domainColor: gray2,
        grid: false,
        gridWidth: 1,
        gridColor: lightGray,
        labels: true,
        labelAngle: 0,
        labelLimit: 180,
        labelOffset: 0,
        labelPadding: 2,
        ticks: true,
        tickColor: gray2,
        tickOffset: 0,
        tickRound: true,
        tickSize: 5,
        tickWidth: 1,
        titlePadding: 4
      },
      // correction for centering bias
      axisBand: {
        tickOffset: -0.5
      },
      // defaults for cartographic projection
      projection: {
        type: "mercator"
      },
      // defaults for legends
      legend: {
        orient: "right",
        padding: 0,
        gridAlign: "each",
        columnPadding: 10,
        rowPadding: 2,
        symbolDirection: "vertical",
        gradientDirection: "vertical",
        gradientLength: 200,
        gradientThickness: 16,
        gradientStrokeColor: lightGray,
        gradientStrokeWidth: 0,
        gradientLabelOffset: 2,
        labelAlign: "left",
        labelBaseline: "middle",
        labelLimit: 160,
        labelOffset: 4,
        labelOverlap: true,
        symbolLimit: 30,
        symbolType: "circle",
        symbolSize: 100,
        symbolOffset: 0,
        symbolStrokeWidth: 1.5,
        symbolBaseFillColor: "transparent",
        symbolBaseStrokeColor: gray2,
        titleLimit: 180,
        titleOrient: "top",
        titlePadding: 5,
        layout: {
          offset: 18,
          direction: "horizontal",
          left: {
            direction: "vertical"
          },
          right: {
            direction: "vertical"
          }
        }
      },
      // defaults for scale ranges
      range: {
        category: {
          scheme: "tableau10"
        },
        ordinal: {
          scheme: "blues"
        },
        heatmap: {
          scheme: "yellowgreenblue"
        },
        ramp: {
          scheme: "blues"
        },
        diverging: {
          scheme: "blueorange",
          extent: [1, 0]
        },
        symbol: ["circle", "square", "triangle-up", "cross", "diamond", "triangle-right", "triangle-down", "triangle-left"]
      }
    };
  }
  function parse6(spec, config, options) {
    if (!isObject(spec)) {
      error("Input Vega specification must be an object.");
    }
    config = mergeConfig(defaults(), config, spec.config);
    return parseView(spec, new Scope(config, options)).toRuntime();
  }

  // node_modules/vega/build/vega.module.js
  var version = "5.33.0";
  extend(transforms, vega_transforms_module_exports, vega_view_transforms_module_exports, vega_encode_module_exports, vega_geo_module_exports, vega_force_module_exports, vega_label_module_exports, vega_hierarchy_module_exports, vega_regression_module_exports, vega_voronoi_module_exports, vega_wordcloud_module_exports, vega_crossfilter_module_exports);

  // node_modules/vega-interpreter/build/vega-interpreter.module.js
  function adjustSpatial2(item, encode2, swap3) {
    let t4;
    if (encode2.x2) {
      if (encode2.x) {
        if (swap3 && item.x > item.x2) {
          t4 = item.x;
          item.x = item.x2;
          item.x2 = t4;
        }
        item.width = item.x2 - item.x;
      } else {
        item.x = item.x2 - (item.width || 0);
      }
    }
    if (encode2.xc) {
      item.x = item.xc - (item.width || 0) / 2;
    }
    if (encode2.y2) {
      if (encode2.y) {
        if (swap3 && item.y > item.y2) {
          t4 = item.y;
          item.y = item.y2;
          item.y2 = t4;
        }
        item.height = item.y2 - item.y;
      } else {
        item.y = item.y2 - (item.height || 0);
      }
    }
    if (encode2.yc) {
      item.y = item.yc - (item.height || 0) / 2;
    }
  }
  var Constants2 = {
    NaN: NaN,
    E: Math.E,
    LN2: Math.LN2,
    LN10: Math.LN10,
    LOG2E: Math.LOG2E,
    LOG10E: Math.LOG10E,
    PI: Math.PI,
    SQRT1_2: Math.SQRT1_2,
    SQRT2: Math.SQRT2,
    MIN_VALUE: Number.MIN_VALUE,
    MAX_VALUE: Number.MAX_VALUE
  };
  var Ops = {
    "*": (a4, b3) => a4 * b3,
    "+": (a4, b3) => a4 + b3,
    "-": (a4, b3) => a4 - b3,
    "/": (a4, b3) => a4 / b3,
    "%": (a4, b3) => a4 % b3,
    ">": (a4, b3) => a4 > b3,
    "<": (a4, b3) => a4 < b3,
    "<=": (a4, b3) => a4 <= b3,
    ">=": (a4, b3) => a4 >= b3,
    "==": (a4, b3) => a4 == b3,
    "!=": (a4, b3) => a4 != b3,
    "===": (a4, b3) => a4 === b3,
    "!==": (a4, b3) => a4 !== b3,
    "&": (a4, b3) => a4 & b3,
    "|": (a4, b3) => a4 | b3,
    "^": (a4, b3) => a4 ^ b3,
    "<<": (a4, b3) => a4 << b3,
    ">>": (a4, b3) => a4 >> b3,
    ">>>": (a4, b3) => a4 >>> b3
  };
  var Unary = {
    "+": (a4) => +a4,
    "-": (a4) => -a4,
    "~": (a4) => ~a4,
    "!": (a4) => !a4
  };
  var slice4 = Array.prototype.slice;
  var apply2 = (m4, args, cast) => {
    const obj = cast ? cast(args[0]) : args[0];
    return obj[m4].apply(obj, slice4.call(args, 1));
  };
  var datetime = (y5, m4, d2, H, M2, S, ms) => new Date(y5, m4 || 0, d2 != null ? d2 : 1, H || 0, M2 || 0, S || 0, ms || 0);
  var Functions2 = {
    // math functions
    isNaN: Number.isNaN,
    isFinite: Number.isFinite,
    abs: Math.abs,
    acos: Math.acos,
    asin: Math.asin,
    atan: Math.atan,
    atan2: Math.atan2,
    ceil: Math.ceil,
    cos: Math.cos,
    exp: Math.exp,
    floor: Math.floor,
    log: Math.log,
    max: Math.max,
    min: Math.min,
    pow: Math.pow,
    random: Math.random,
    round: Math.round,
    sin: Math.sin,
    sqrt: Math.sqrt,
    tan: Math.tan,
    clamp: (a4, b3, c4) => Math.max(b3, Math.min(c4, a4)),
    // date functions
    now: Date.now,
    utc: Date.UTC,
    datetime,
    date: (d2) => new Date(d2).getDate(),
    day: (d2) => new Date(d2).getDay(),
    year: (d2) => new Date(d2).getFullYear(),
    month: (d2) => new Date(d2).getMonth(),
    hours: (d2) => new Date(d2).getHours(),
    minutes: (d2) => new Date(d2).getMinutes(),
    seconds: (d2) => new Date(d2).getSeconds(),
    milliseconds: (d2) => new Date(d2).getMilliseconds(),
    time: (d2) => new Date(d2).getTime(),
    timezoneoffset: (d2) => new Date(d2).getTimezoneOffset(),
    utcdate: (d2) => new Date(d2).getUTCDate(),
    utcday: (d2) => new Date(d2).getUTCDay(),
    utcyear: (d2) => new Date(d2).getUTCFullYear(),
    utcmonth: (d2) => new Date(d2).getUTCMonth(),
    utchours: (d2) => new Date(d2).getUTCHours(),
    utcminutes: (d2) => new Date(d2).getUTCMinutes(),
    utcseconds: (d2) => new Date(d2).getUTCSeconds(),
    utcmilliseconds: (d2) => new Date(d2).getUTCMilliseconds(),
    // sequence functions
    length: (x5) => x5.length,
    join: function() {
      return apply2("join", arguments);
    },
    indexof: function() {
      return apply2("indexOf", arguments);
    },
    lastindexof: function() {
      return apply2("lastIndexOf", arguments);
    },
    slice: function() {
      return apply2("slice", arguments);
    },
    reverse: (x5) => x5.slice().reverse(),
    sort: (x5) => x5.slice().sort(ascending),
    // string functions
    parseFloat,
    parseInt,
    upper: (x5) => String(x5).toUpperCase(),
    lower: (x5) => String(x5).toLowerCase(),
    substring: function() {
      return apply2("substring", arguments, String);
    },
    split: function() {
      return apply2("split", arguments, String);
    },
    replace: function() {
      return apply2("replace", arguments, String);
    },
    trim: (x5) => String(x5).trim(),
    // Base64 encode/decode
    // Convert binary string to base64-encoded ascii
    btoa: (x5) => btoa(x5),
    // Convert base64-encoded ascii to binary string
    atob: (x5) => atob(x5),
    // regexp functions
    regexp: RegExp,
    test: (r2, t4) => RegExp(r2).test(t4)
  };
  var EventFunctions = ["view", "item", "group", "xy", "x", "y"];
  var DisallowedMethods = /* @__PURE__ */ new Set([Function, eval, setTimeout, setInterval]);
  if (typeof setImmediate === "function") DisallowedMethods.add(setImmediate);
  var Visitors = {
    Literal: ($2, n2) => n2.value,
    Identifier: ($2, n2) => {
      const id2 = n2.name;
      return $2.memberDepth > 0 ? id2 : id2 === "datum" ? $2.datum : id2 === "event" ? $2.event : id2 === "item" ? $2.item : Constants2[id2] || $2.params["$" + id2];
    },
    MemberExpression: ($2, n2) => {
      const d2 = !n2.computed, o2 = $2(n2.object);
      if (d2) $2.memberDepth += 1;
      const p2 = $2(n2.property);
      if (d2) $2.memberDepth -= 1;
      if (DisallowedMethods.has(o2[p2])) {
        console.error(`Prevented interpretation of member "${p2}" which could lead to insecure code execution`);
        return;
      }
      return o2[p2];
    },
    CallExpression: ($2, n2) => {
      const args = n2.arguments;
      let name4 = n2.callee.name;
      if (name4.startsWith("_")) {
        name4 = name4.slice(1);
      }
      return name4 === "if" ? $2(args[0]) ? $2(args[1]) : $2(args[2]) : ($2.fn[name4] || Functions2[name4]).apply($2.fn, args.map($2));
    },
    ArrayExpression: ($2, n2) => n2.elements.map($2),
    BinaryExpression: ($2, n2) => Ops[n2.operator]($2(n2.left), $2(n2.right)),
    UnaryExpression: ($2, n2) => Unary[n2.operator]($2(n2.argument)),
    ConditionalExpression: ($2, n2) => $2(n2.test) ? $2(n2.consequent) : $2(n2.alternate),
    LogicalExpression: ($2, n2) => n2.operator === "&&" ? $2(n2.left) && $2(n2.right) : $2(n2.left) || $2(n2.right),
    ObjectExpression: ($2, n2) => n2.properties.reduce((o2, p2) => {
      $2.memberDepth += 1;
      const k2 = $2(p2.key);
      $2.memberDepth -= 1;
      if (DisallowedMethods.has($2(p2.value))) {
        console.error(`Prevented interpretation of property "${k2}" which could lead to insecure code execution`);
      } else {
        o2[k2] = $2(p2.value);
      }
      return o2;
    }, {})
  };
  function interpret(ast, fn, params2, datum2, event2, item) {
    const $2 = (n2) => Visitors[n2.type]($2, n2);
    $2.memberDepth = 0;
    $2.fn = Object.create(fn);
    $2.params = params2;
    $2.datum = datum2;
    $2.event = event2;
    $2.item = item;
    EventFunctions.forEach((f2) => $2.fn[f2] = function() {
      return event2.vega[f2](...arguments);
    });
    return $2(ast);
  }
  var expression2 = {
    /**
     * Parse an expression used to update an operator value.
     */
    operator(ctx, expr2) {
      const ast = expr2.ast, fn = ctx.functions;
      return (_) => interpret(ast, fn, _);
    },
    /**
     * Parse an expression provided as an operator parameter value.
     */
    parameter(ctx, expr2) {
      const ast = expr2.ast, fn = ctx.functions;
      return (datum2, _) => interpret(ast, fn, _, datum2);
    },
    /**
     * Parse an expression applied to an event stream.
     */
    event(ctx, expr2) {
      const ast = expr2.ast, fn = ctx.functions;
      return (event2) => interpret(ast, fn, void 0, void 0, event2);
    },
    /**
     * Parse an expression used to handle an event-driven operator update.
     */
    handler(ctx, expr2) {
      const ast = expr2.ast, fn = ctx.functions;
      return (_, event2) => {
        const datum2 = event2.item && event2.item.datum;
        return interpret(ast, fn, _, datum2, event2);
      };
    },
    /**
     * Parse an expression that performs visual encoding.
     */
    encode(ctx, encode2) {
      const {
        marktype,
        channels
      } = encode2, fn = ctx.functions, swap3 = marktype === "group" || marktype === "image" || marktype === "rect";
      return (item, _) => {
        const datum2 = item.datum;
        let m4 = 0, v3;
        for (const name4 in channels) {
          v3 = interpret(channels[name4].ast, fn, _, datum2, void 0, item);
          if (item[name4] !== v3) {
            item[name4] = v3;
            m4 = 1;
          }
        }
        if (marktype !== "rule") {
          adjustSpatial2(item, channels, swap3);
        }
        return m4;
      };
    }
  };

  // node_modules/vega-lite/build/src/index.js
  var src_exports3 = {};
  __export(src_exports3, {
    accessPathDepth: () => accessPathDepth,
    accessPathWithDatum: () => accessPathWithDatum,
    accessWithDatumToUnescapedPath: () => accessWithDatumToUnescapedPath,
    compile: () => compile,
    contains: () => contains2,
    deepEqual: () => deepEqual,
    deleteNestedProperty: () => deleteNestedProperty,
    duplicate: () => duplicate,
    entries: () => entries,
    every: () => every,
    fieldIntersection: () => fieldIntersection,
    flatAccessWithDatum: () => flatAccessWithDatum,
    getFirstDefined: () => getFirstDefined,
    hasIntersection: () => hasIntersection,
    hasProperty: () => hasProperty,
    hash: () => hash,
    internalField: () => internalField,
    isBoolean: () => isBoolean3,
    isEmpty: () => isEmpty,
    isEqual: () => isEqual,
    isInternalField: () => isInternalField,
    isNullOrFalse: () => isNullOrFalse,
    isNumeric: () => isNumeric,
    keys: () => keys3,
    logicalExpr: () => logicalExpr,
    mergeDeep: () => mergeDeep,
    never: () => never,
    normalize: () => normalize3,
    normalizeAngle: () => normalizeAngle,
    omit: () => omit,
    pick: () => pick2,
    prefixGenerator: () => prefixGenerator,
    removePathFromField: () => removePathFromField,
    replaceAll: () => replaceAll,
    replacePathInField: () => replacePathInField,
    resetIdCounter: () => resetIdCounter,
    setEqual: () => setEqual,
    some: () => some,
    stringify: () => stringify2,
    titleCase: () => titleCase,
    unique: () => unique,
    uniqueId: () => uniqueId,
    vals: () => vals,
    varName: () => varName,
    version: () => version2
  });

  // node_modules/vega-lite/build/package.json
  var package_default = {
    name: "vega-lite",
    author: 'Dominik Moritz, Kanit "Ham" Wongsuphasawat, Arvind Satyanarayan, Jeffrey Heer',
    version: "5.23.0",
    collaborators: [
      "Kanit Wongsuphasawat (http://kanitw.yellowpigz.com)",
      "Dominik Moritz (https://www.domoritz.de)",
      "Arvind Satyanarayan (https://arvindsatya.com)",
      "Jeffrey Heer (https://jheer.org)"
    ],
    homepage: "https://vega.github.io/vega-lite/",
    description: "Vega-Lite is a concise high-level language for interactive visualization.",
    keywords: [
      "vega",
      "chart",
      "visualization"
    ],
    main: "build/vega-lite.js",
    unpkg: "build/vega-lite.min.js",
    jsdelivr: "build/vega-lite.min.js",
    module: "build/src/index",
    types: "build/src/index.d.ts",
    bin: {
      vl2pdf: "./bin/vl2pdf",
      vl2png: "./bin/vl2png",
      vl2svg: "./bin/vl2svg",
      vl2vg: "./bin/vl2vg"
    },
    files: [
      "bin",
      "build",
      "src",
      "vega-lite*",
      "tsconfig.json"
    ],
    scripts: {
      changelog: "conventional-changelog -p angular -r 2",
      prebuild: "yarn clean:build",
      build: "yarn build:only",
      "build:only": "tsc -p tsconfig.build.json && rollup -c",
      "prebuild:examples": "yarn build:only",
      "build:examples": "yarn data && TZ=America/Los_Angeles scripts/build-examples.sh",
      "prebuild:examples-full": "yarn build:only",
      "build:examples-full": "TZ=America/Los_Angeles scripts/build-examples.sh 1",
      "build:example": "TZ=America/Los_Angeles scripts/build-example.sh",
      "build:toc": "yarn build:jekyll && scripts/generate-toc",
      "build:site": "rollup -c site/rollup.config.mjs",
      "build:jekyll": "pushd site && bundle exec jekyll build -q && popd",
      "build:versions": "scripts/update-version.sh",
      clean: "yarn clean:build && del-cli 'site/data/*' 'examples/compiled/*.png' && find site/examples ! -name 'index.md' ! -name 'data' -type f -delete",
      "clean:build": "del-cli 'build/*' !build/vega-lite-schema.json",
      data: "rsync -r node_modules/vega-datasets/data/* site/data",
      "build-editor-preview": "scripts/build-editor-preview.sh",
      schema: "mkdir -p build && ts-json-schema-generator -f tsconfig.json -p src/index.ts -t TopLevelSpec --no-type-check --no-ref-encode > build/vega-lite-schema.json && yarn renameschema && cp build/vega-lite-schema.json site/_data/",
      renameschema: "scripts/rename-schema.sh",
      presite: "yarn data && yarn schema && yarn build:site && yarn build:versions && scripts/create-example-pages.sh",
      site: "yarn site:only",
      "site:only": "pushd site && bundle exec jekyll serve -I -l && popd",
      prettierbase: "prettier '**/*.{md,css,yml}'",
      format: "eslint . --fix && yarn prettierbase --write",
      lint: "eslint . && yarn prettierbase --check",
      test: "yarn jest test/ && yarn lint && yarn schema && yarn jest examples/ && yarn test:runtime",
      "test:cover": "yarn jest --collectCoverage test/",
      "test:inspect": "node --inspect-brk ./node_modules/.bin/jest --runInBand test",
      "test:runtime": "TZ=America/Los_Angeles npx jest test-runtime/ --config test-runtime/jest-config.json",
      "test:runtime:generate": "yarn build:only && del-cli test-runtime/resources && VL_GENERATE_TESTS=true yarn test:runtime",
      watch: "tsc -p tsconfig.build.json -w",
      "watch:site": "yarn build:site -w",
      "watch:test": "yarn jest --watch test/",
      "watch:test:runtime": "TZ=America/Los_Angeles npx jest --watch test-runtime/ --config test-runtime/jest-config.json",
      release: "release-it"
    },
    repository: {
      type: "git",
      url: "https://github.com/vega/vega-lite.git"
    },
    license: "BSD-3-Clause",
    bugs: {
      url: "https://github.com/vega/vega-lite/issues"
    },
    devDependencies: {
      "@babel/core": "^7.26.0",
      "@babel/preset-env": "^7.26.0",
      "@babel/preset-typescript": "^7.26.0",
      "@release-it/conventional-changelog": "^9.0.3",
      "@rollup/plugin-alias": "^5.1.1",
      "@rollup/plugin-babel": "^6.0.4",
      "@rollup/plugin-commonjs": "^28.0.1",
      "@rollup/plugin-json": "^6.1.0",
      "@rollup/plugin-node-resolve": "^15.3.0",
      "@rollup/plugin-terser": "^0.4.4",
      "@types/d3": "^7.4.3",
      "@types/jest": "^29.5.14",
      "@types/pako": "^2.0.3",
      "@typescript-eslint/eslint-plugin": "^7.17.0",
      "@typescript-eslint/parser": "^7.17.0",
      ajv: "^8.17.1",
      "ajv-formats": "^3.0.1",
      cheerio: "^1.0.0",
      "conventional-changelog-cli": "^5.0.0",
      d3: "^7.9.0",
      "del-cli": "^6.0.0",
      eslint: "^8.57.0",
      "eslint-config-prettier": "^9.1.0",
      "eslint-plugin-jest": "^27.9.0",
      "eslint-plugin-prettier": "^5.2.1",
      "fast-json-stable-stringify": "~2.1.0",
      "highlight.js": "^11.10.0",
      jest: "^29.7.0",
      "jest-dev-server": "^10.1.4",
      mkdirp: "^3.0.1",
      pako: "^2.1.0",
      prettier: "^3.3.3",
      puppeteer: "^15.0.0",
      "release-it": "17.10.0",
      rollup: "^4.27.3",
      "rollup-plugin-bundle-size": "^1.0.3",
      serve: "^14.2.4",
      terser: "^5.36.0",
      "ts-jest": "^29.2.5",
      "ts-json-schema-generator": "^2.3.0",
      typescript: "~5.7.2",
      "vega-cli": "^5.30.0",
      "vega-datasets": "^2.11.0",
      "vega-embed": "^6.28.0",
      "vega-tooltip": "^0.35.2",
      "yaml-front-matter": "^4.1.1"
    },
    dependencies: {
      "json-stringify-pretty-compact": "~4.0.0",
      tslib: "~2.8.1",
      "vega-event-selector": "~3.0.1",
      "vega-expression": "~5.1.1",
      "vega-util": "~1.17.2",
      yargs: "~17.7.2"
    },
    peerDependencies: {
      vega: "^5.24.0"
    },
    engines: {
      node: ">=18"
    },
    packageManager: "yarn@1.22.22"
  };

  // node_modules/vega-lite/build/src/logical.js
  function isLogicalOr(op) {
    return hasProperty(op, "or");
  }
  function isLogicalAnd(op) {
    return hasProperty(op, "and");
  }
  function isLogicalNot(op) {
    return hasProperty(op, "not");
  }
  function forEachLeaf(op, fn) {
    if (isLogicalNot(op)) {
      forEachLeaf(op.not, fn);
    } else if (isLogicalAnd(op)) {
      for (const subop of op.and) {
        forEachLeaf(subop, fn);
      }
    } else if (isLogicalOr(op)) {
      for (const subop of op.or) {
        forEachLeaf(subop, fn);
      }
    } else {
      fn(op);
    }
  }
  function normalizeLogicalComposition(op, normalizer) {
    if (isLogicalNot(op)) {
      return { not: normalizeLogicalComposition(op.not, normalizer) };
    } else if (isLogicalAnd(op)) {
      return { and: op.and.map((o2) => normalizeLogicalComposition(o2, normalizer)) };
    } else if (isLogicalOr(op)) {
      return { or: op.or.map((o2) => normalizeLogicalComposition(o2, normalizer)) };
    } else {
      return normalizer(op);
    }
  }

  // node_modules/vega-lite/build/src/util.js
  var duplicate = structuredClone;
  function never(message) {
    throw new Error(message);
  }
  function pick2(obj, props) {
    const copy4 = {};
    for (const prop of props) {
      if (has(obj, prop)) {
        copy4[prop] = obj[prop];
      }
    }
    return copy4;
  }
  function omit(obj, props) {
    const copy4 = { ...obj };
    for (const prop of props) {
      delete copy4[prop];
    }
    return copy4;
  }
  Set.prototype["toJSON"] = function() {
    return `Set(${[...this].map((x5) => stringify2(x5)).join(",")})`;
  };
  function hash(a4) {
    if (isNumber(a4)) {
      return a4;
    }
    const str = isString(a4) ? a4 : stringify2(a4);
    if (str.length < 250) {
      return str;
    }
    let h3 = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      const char = str.charCodeAt(i2);
      h3 = (h3 << 5) - h3 + char;
      h3 = h3 & h3;
    }
    return h3;
  }
  function isNullOrFalse(x5) {
    return x5 === false || x5 === null;
  }
  function contains2(array4, item) {
    return array4.includes(item);
  }
  function some(arr, f2) {
    let i2 = 0;
    for (const [k2, a4] of arr.entries()) {
      if (f2(a4, k2, i2++)) {
        return true;
      }
    }
    return false;
  }
  function every(arr, f2) {
    let i2 = 0;
    for (const [k2, a4] of arr.entries()) {
      if (!f2(a4, k2, i2++)) {
        return false;
      }
    }
    return true;
  }
  function mergeDeep(dest, ...src) {
    for (const s2 of src) {
      deepMerge_(dest, s2 ?? {});
    }
    return dest;
  }
  function deepMerge_(dest, src) {
    for (const property2 of keys3(src)) {
      writeConfig(dest, property2, src[property2], true);
    }
  }
  function unique(values4, f2) {
    const results = [];
    const u5 = {};
    let v3;
    for (const val of values4) {
      v3 = f2(val);
      if (v3 in u5) {
        continue;
      }
      u5[v3] = 1;
      results.push(val);
    }
    return results;
  }
  function isEqual(dict, other) {
    const dictKeys = keys3(dict);
    const otherKeys = keys3(other);
    if (dictKeys.length !== otherKeys.length) {
      return false;
    }
    for (const key2 of dictKeys) {
      if (dict[key2] !== other[key2]) {
        return false;
      }
    }
    return true;
  }
  function setEqual(a4, b3) {
    if (a4.size !== b3.size) {
      return false;
    }
    for (const e4 of a4) {
      if (!b3.has(e4)) {
        return false;
      }
    }
    return true;
  }
  function hasIntersection(a4, b3) {
    for (const key2 of a4) {
      if (b3.has(key2)) {
        return true;
      }
    }
    return false;
  }
  function prefixGenerator(a4) {
    const prefixes2 = /* @__PURE__ */ new Set();
    for (const x5 of a4) {
      const splitField = splitAccessPath(x5);
      const wrappedWithAccessors = splitField.map((y5, i2) => i2 === 0 ? y5 : `[${y5}]`);
      const computedPrefixes = wrappedWithAccessors.map((_, i2) => wrappedWithAccessors.slice(0, i2 + 1).join(""));
      for (const y5 of computedPrefixes) {
        prefixes2.add(y5);
      }
    }
    return prefixes2;
  }
  function fieldIntersection(a4, b3) {
    if (a4 === void 0 || b3 === void 0) {
      return true;
    }
    return hasIntersection(prefixGenerator(a4), prefixGenerator(b3));
  }
  function isEmpty(obj) {
    return keys3(obj).length === 0;
  }
  var keys3 = Object.keys;
  var vals = Object.values;
  var entries = Object.entries;
  function isBoolean3(b3) {
    return b3 === true || b3 === false;
  }
  function varName(s2) {
    const alphanumericS = s2.replace(/\W/g, "_");
    return (s2.match(/^\d+/) ? "_" : "") + alphanumericS;
  }
  function logicalExpr(op, cb) {
    if (isLogicalNot(op)) {
      return `!(${logicalExpr(op.not, cb)})`;
    } else if (isLogicalAnd(op)) {
      return `(${op.and.map((and) => logicalExpr(and, cb)).join(") && (")})`;
    } else if (isLogicalOr(op)) {
      return `(${op.or.map((or2) => logicalExpr(or2, cb)).join(") || (")})`;
    } else {
      return cb(op);
    }
  }
  function deleteNestedProperty(obj, orderedProps) {
    if (orderedProps.length === 0) {
      return true;
    }
    const prop = orderedProps.shift();
    if (prop in obj && deleteNestedProperty(obj[prop], orderedProps)) {
      delete obj[prop];
    }
    return isEmpty(obj);
  }
  function titleCase(s2) {
    return s2.charAt(0).toUpperCase() + s2.substr(1);
  }
  function accessPathWithDatum(path3, datum2 = "datum") {
    const pieces = splitAccessPath(path3);
    const prefixes2 = [];
    for (let i2 = 1; i2 <= pieces.length; i2++) {
      const prefix = `[${pieces.slice(0, i2).map($).join("][")}]`;
      prefixes2.push(`${datum2}${prefix}`);
    }
    return prefixes2.join(" && ");
  }
  function flatAccessWithDatum(path3, datum2 = "datum") {
    return `${datum2}[${$(splitAccessPath(path3).join("."))}]`;
  }
  function accessWithDatumToUnescapedPath(unescapedPath) {
    const singleQuoteEscapedPath = unescapedPath.replaceAll("'", "\\'");
    return `datum['${singleQuoteEscapedPath}']`;
  }
  function escapePathAccess(string) {
    return string.replace(/(\[|\]|\.|'|")/g, "\\$1");
  }
  function replacePathInField(path3) {
    return `${splitAccessPath(path3).map(escapePathAccess).join("\\.")}`;
  }
  function replaceAll(string, find4, replacement) {
    return string.replace(new RegExp(find4.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), "g"), replacement);
  }
  function removePathFromField(path3) {
    return `${splitAccessPath(path3).join(".")}`;
  }
  function accessPathDepth(path3) {
    if (!path3) {
      return 0;
    }
    return splitAccessPath(path3).length;
  }
  function getFirstDefined(...args) {
    return args.find((a4) => a4 !== void 0);
  }
  var idCounter = 42;
  function uniqueId(prefix) {
    const id2 = ++idCounter;
    return prefix ? String(prefix) + id2 : id2;
  }
  function resetIdCounter() {
    idCounter = 42;
  }
  function internalField(name4) {
    return isInternalField(name4) ? name4 : `__${name4}`;
  }
  function isInternalField(name4) {
    return name4.startsWith("__");
  }
  function normalizeAngle(angle2) {
    if (angle2 === void 0) {
      return void 0;
    }
    return (angle2 % 360 + 360) % 360;
  }
  function isNumeric(value3) {
    if (isNumber(value3)) {
      return true;
    }
    return !isNaN(value3) && !isNaN(parseFloat(value3));
  }
  var clonedProto = Object.getPrototypeOf(structuredClone({}));
  function deepEqual(a4, b3) {
    if (a4 === b3)
      return true;
    if (a4 && b3 && typeof a4 == "object" && typeof b3 == "object") {
      if (a4.constructor.name !== b3.constructor.name)
        return false;
      let length3;
      let i2;
      if (Array.isArray(a4)) {
        length3 = a4.length;
        if (length3 != b3.length)
          return false;
        for (i2 = length3; i2-- !== 0; )
          if (!deepEqual(a4[i2], b3[i2]))
            return false;
        return true;
      }
      if (a4 instanceof Map && b3 instanceof Map) {
        if (a4.size !== b3.size)
          return false;
        for (const e4 of a4.entries())
          if (!b3.has(e4[0]))
            return false;
        for (const e4 of a4.entries())
          if (!deepEqual(e4[1], b3.get(e4[0])))
            return false;
        return true;
      }
      if (a4 instanceof Set && b3 instanceof Set) {
        if (a4.size !== b3.size)
          return false;
        for (const e4 of a4.entries())
          if (!b3.has(e4[0]))
            return false;
        return true;
      }
      if (ArrayBuffer.isView(a4) && ArrayBuffer.isView(b3)) {
        length3 = a4.length;
        if (length3 != b3.length)
          return false;
        for (i2 = length3; i2-- !== 0; )
          if (a4[i2] !== b3[i2])
            return false;
        return true;
      }
      if (a4.constructor === RegExp)
        return a4.source === b3.source && a4.flags === b3.flags;
      if (a4.valueOf !== Object.prototype.valueOf && a4.valueOf !== clonedProto.valueOf)
        return a4.valueOf() === b3.valueOf();
      if (a4.toString !== Object.prototype.toString && a4.toString !== clonedProto.toString)
        return a4.toString() === b3.toString();
      const ks = Object.keys(a4);
      length3 = ks.length;
      if (length3 !== Object.keys(b3).length)
        return false;
      for (i2 = length3; i2-- !== 0; )
        if (!Object.prototype.hasOwnProperty.call(b3, ks[i2]))
          return false;
      for (i2 = length3; i2-- !== 0; ) {
        const key2 = ks[i2];
        if (!deepEqual(a4[key2], b3[key2]))
          return false;
      }
      return true;
    }
    return a4 !== a4 && b3 !== b3;
  }
  function stringify2(data3) {
    const seen = [];
    return function _stringify(node) {
      if (node && node.toJSON && typeof node.toJSON === "function") {
        node = node.toJSON();
      }
      if (node === void 0)
        return void 0;
      if (typeof node == "number")
        return isFinite(node) ? "" + node : "null";
      if (typeof node !== "object")
        return JSON.stringify(node);
      let i2, out;
      if (Array.isArray(node)) {
        out = "[";
        for (i2 = 0; i2 < node.length; i2++) {
          if (i2)
            out += ",";
          out += _stringify(node[i2]) || "null";
        }
        return out + "]";
      }
      if (node === null)
        return "null";
      if (seen.includes(node)) {
        throw new TypeError("Converting circular structure to JSON");
      }
      const seenIndex = seen.push(node) - 1;
      const ks = Object.keys(node).sort();
      out = "";
      for (i2 = 0; i2 < ks.length; i2++) {
        const key2 = ks[i2];
        const value3 = _stringify(node[key2]);
        if (!value3)
          continue;
        if (out)
          out += ",";
        out += JSON.stringify(key2) + ":" + value3;
      }
      seen.splice(seenIndex, 1);
      return `{${out}}`;
    }(data3);
  }
  function hasProperty(obj, key2) {
    return isObject(obj) && has(obj, key2) && obj[key2] !== void 0;
  }

  // node_modules/vega-lite/build/src/channel.js
  var ROW = "row";
  var COLUMN = "column";
  var FACET = "facet";
  var X3 = "x";
  var Y3 = "y";
  var X23 = "x2";
  var Y23 = "y2";
  var XOFFSET = "xOffset";
  var YOFFSET = "yOffset";
  var RADIUS = "radius";
  var RADIUS2 = "radius2";
  var THETA = "theta";
  var THETA2 = "theta2";
  var LATITUDE = "latitude";
  var LONGITUDE = "longitude";
  var LATITUDE2 = "latitude2";
  var LONGITUDE2 = "longitude2";
  var TIME = "time";
  var COLOR = "color";
  var FILL = "fill";
  var STROKE = "stroke";
  var SHAPE = "shape";
  var SIZE2 = "size";
  var ANGLE = "angle";
  var OPACITY = "opacity";
  var FILLOPACITY = "fillOpacity";
  var STROKEOPACITY = "strokeOpacity";
  var STROKEWIDTH = "strokeWidth";
  var STROKEDASH = "strokeDash";
  var TEXT = "text";
  var ORDER = "order";
  var DETAIL = "detail";
  var KEY = "key";
  var TOOLTIP = "tooltip";
  var HREF = "href";
  var URL2 = "url";
  var DESCRIPTION = "description";
  var POSITION_CHANNEL_INDEX = {
    x: 1,
    y: 1,
    x2: 1,
    y2: 1
  };
  var POLAR_POSITION_CHANNEL_INDEX = {
    theta: 1,
    theta2: 1,
    radius: 1,
    radius2: 1
  };
  function isPolarPositionChannel(c4) {
    return has(POLAR_POSITION_CHANNEL_INDEX, c4);
  }
  var GEO_POSIITON_CHANNEL_INDEX = {
    longitude: 1,
    longitude2: 1,
    latitude: 1,
    latitude2: 1
  };
  function getPositionChannelFromLatLong(channel) {
    switch (channel) {
      case LATITUDE:
        return "y";
      case LATITUDE2:
        return "y2";
      case LONGITUDE:
        return "x";
      case LONGITUDE2:
        return "x2";
    }
  }
  function isGeoPositionChannel(c4) {
    return has(GEO_POSIITON_CHANNEL_INDEX, c4);
  }
  var GEOPOSITION_CHANNELS = keys3(GEO_POSIITON_CHANNEL_INDEX);
  var UNIT_CHANNEL_INDEX = {
    ...POSITION_CHANNEL_INDEX,
    ...POLAR_POSITION_CHANNEL_INDEX,
    ...GEO_POSIITON_CHANNEL_INDEX,
    xOffset: 1,
    yOffset: 1,
    // color
    color: 1,
    fill: 1,
    stroke: 1,
    // time
    time: 1,
    // other non-position with scale
    opacity: 1,
    fillOpacity: 1,
    strokeOpacity: 1,
    strokeWidth: 1,
    strokeDash: 1,
    size: 1,
    angle: 1,
    shape: 1,
    // channels without scales
    order: 1,
    text: 1,
    detail: 1,
    key: 1,
    tooltip: 1,
    href: 1,
    url: 1,
    description: 1
  };
  function isColorChannel(channel) {
    return channel === COLOR || channel === FILL || channel === STROKE;
  }
  var FACET_CHANNEL_INDEX = {
    row: 1,
    column: 1,
    facet: 1
  };
  var FACET_CHANNELS = keys3(FACET_CHANNEL_INDEX);
  var CHANNEL_INDEX = {
    ...UNIT_CHANNEL_INDEX,
    ...FACET_CHANNEL_INDEX
  };
  var CHANNELS = keys3(CHANNEL_INDEX);
  var { order: _o, detail: _d, tooltip: _tt1, ...SINGLE_DEF_CHANNEL_INDEX } = CHANNEL_INDEX;
  var { row: _r, column: _c, facet: _f, ...SINGLE_DEF_UNIT_CHANNEL_INDEX } = SINGLE_DEF_CHANNEL_INDEX;
  var SINGLE_DEF_CHANNELS = keys3(SINGLE_DEF_CHANNEL_INDEX);
  var SINGLE_DEF_UNIT_CHANNELS = keys3(SINGLE_DEF_UNIT_CHANNEL_INDEX);
  function isSingleDefUnitChannel(str) {
    return has(SINGLE_DEF_UNIT_CHANNEL_INDEX, str);
  }
  function isChannel(str) {
    return has(CHANNEL_INDEX, str);
  }
  var SECONDARY_RANGE_CHANNEL = [X23, Y23, LATITUDE2, LONGITUDE2, THETA2, RADIUS2];
  function isSecondaryRangeChannel(c4) {
    const main5 = getMainRangeChannel(c4);
    return main5 !== c4;
  }
  function getMainRangeChannel(channel) {
    switch (channel) {
      case X23:
        return X3;
      case Y23:
        return Y3;
      case LATITUDE2:
        return LATITUDE;
      case LONGITUDE2:
        return LONGITUDE;
      case THETA2:
        return THETA;
      case RADIUS2:
        return RADIUS;
    }
    return channel;
  }
  function getVgPositionChannel(channel) {
    if (isPolarPositionChannel(channel)) {
      switch (channel) {
        case THETA:
          return "startAngle";
        case THETA2:
          return "endAngle";
        case RADIUS:
          return "outerRadius";
        case RADIUS2:
          return "innerRadius";
      }
    }
    return channel;
  }
  function getSecondaryRangeChannel(channel) {
    switch (channel) {
      case X3:
        return X23;
      case Y3:
        return Y23;
      case LATITUDE:
        return LATITUDE2;
      case LONGITUDE:
        return LONGITUDE2;
      case THETA:
        return THETA2;
      case RADIUS:
        return RADIUS2;
    }
    return void 0;
  }
  function getSizeChannel(channel) {
    switch (channel) {
      case X3:
      case X23:
        return "width";
      case Y3:
      case Y23:
        return "height";
    }
    return void 0;
  }
  function getOffsetChannel(channel) {
    switch (channel) {
      case X3:
        return "xOffset";
      case Y3:
        return "yOffset";
      case X23:
        return "x2Offset";
      case Y23:
        return "y2Offset";
      case THETA:
        return "thetaOffset";
      case RADIUS:
        return "radiusOffset";
      case THETA2:
        return "theta2Offset";
      case RADIUS2:
        return "radius2Offset";
    }
    return void 0;
  }
  function getOffsetScaleChannel(channel) {
    switch (channel) {
      case X3:
        return "xOffset";
      case Y3:
        return "yOffset";
    }
    return void 0;
  }
  function getMainChannelFromOffsetChannel(channel) {
    switch (channel) {
      case "xOffset":
        return "x";
      case "yOffset":
        return "y";
    }
  }
  var UNIT_CHANNELS = keys3(UNIT_CHANNEL_INDEX);
  var {
    x: _x,
    y: _y,
    // x2 and y2 share the same scale as x and y
    x2: _x2,
    y2: _y2,
    //
    xOffset: _xo,
    yOffset: _yo,
    latitude: _latitude,
    longitude: _longitude,
    latitude2: _latitude2,
    longitude2: _longitude2,
    theta: _theta,
    theta2: _theta2,
    radius: _radius,
    radius2: _radius2,
    // The rest of unit channels then have scale
    ...NONPOSITION_CHANNEL_INDEX
  } = UNIT_CHANNEL_INDEX;
  var NONPOSITION_CHANNELS = keys3(NONPOSITION_CHANNEL_INDEX);
  var POSITION_SCALE_CHANNEL_INDEX = {
    x: 1,
    y: 1
  };
  var POSITION_SCALE_CHANNELS = keys3(POSITION_SCALE_CHANNEL_INDEX);
  function isXorY(channel) {
    return has(POSITION_SCALE_CHANNEL_INDEX, channel);
  }
  var POLAR_POSITION_SCALE_CHANNEL_INDEX = {
    theta: 1,
    radius: 1
  };
  var POLAR_POSITION_SCALE_CHANNELS = keys3(POLAR_POSITION_SCALE_CHANNEL_INDEX);
  function getPositionScaleChannel(sizeType) {
    return sizeType === "width" ? X3 : Y3;
  }
  var OFFSET_SCALE_CHANNEL_INDEX = { xOffset: 1, yOffset: 1 };
  var OFFSET_SCALE_CHANNELS = keys3(OFFSET_SCALE_CHANNEL_INDEX);
  function isXorYOffset(channel) {
    return has(OFFSET_SCALE_CHANNEL_INDEX, channel);
  }
  var TIME_SCALE_CHANNEL_INDEX = {
    time: 1
  };
  var TIME_SCALE_CHANNELS = keys3(TIME_SCALE_CHANNEL_INDEX);
  function isTime(channel) {
    return channel in TIME_SCALE_CHANNEL_INDEX;
  }
  var {
    // x2 and y2 share the same scale as x and y
    // text and tooltip have format instead of scale,
    // href has neither format, nor scale
    text: _t,
    tooltip: _tt,
    href: _hr,
    url: _u,
    description: _al,
    // detail and order have no scale
    detail: _dd,
    key: _k,
    order: _oo,
    ...NONPOSITION_SCALE_CHANNEL_INDEX
  } = NONPOSITION_CHANNEL_INDEX;
  var NONPOSITION_SCALE_CHANNELS = keys3(NONPOSITION_SCALE_CHANNEL_INDEX);
  function isNonPositionScaleChannel(channel) {
    return has(NONPOSITION_CHANNEL_INDEX, channel);
  }
  function supportLegend(channel) {
    switch (channel) {
      case COLOR:
      case FILL:
      case STROKE:
      case SIZE2:
      case SHAPE:
      case OPACITY:
      case STROKEWIDTH:
      case STROKEDASH:
        return true;
      case FILLOPACITY:
      case STROKEOPACITY:
      case ANGLE:
      case TIME:
        return false;
    }
  }
  var SCALE_CHANNEL_INDEX = {
    ...POSITION_SCALE_CHANNEL_INDEX,
    ...POLAR_POSITION_SCALE_CHANNEL_INDEX,
    ...OFFSET_SCALE_CHANNEL_INDEX,
    ...NONPOSITION_SCALE_CHANNEL_INDEX
  };
  var SCALE_CHANNELS = keys3(SCALE_CHANNEL_INDEX);
  function isScaleChannel(channel) {
    return has(SCALE_CHANNEL_INDEX, channel);
  }
  function supportMark(channel, mark) {
    return getSupportedMark(channel)[mark];
  }
  var ALL_MARKS = {
    // all marks
    arc: "always",
    area: "always",
    bar: "always",
    circle: "always",
    geoshape: "always",
    image: "always",
    line: "always",
    rule: "always",
    point: "always",
    rect: "always",
    square: "always",
    trail: "always",
    text: "always",
    tick: "always"
  };
  var { geoshape: _g, ...ALL_MARKS_EXCEPT_GEOSHAPE } = ALL_MARKS;
  function getSupportedMark(channel) {
    switch (channel) {
      case COLOR:
      case FILL:
      case STROKE:
      // falls through
      case DESCRIPTION:
      case DETAIL:
      case KEY:
      case TOOLTIP:
      case HREF:
      case ORDER:
      // TODO: revise (order might not support rect, which is not stackable?)
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
      case STROKEWIDTH:
      // falls through
      case FACET:
      case ROW:
      // falls through
      case COLUMN:
        return ALL_MARKS;
      case X3:
      case Y3:
      case XOFFSET:
      case YOFFSET:
      case LATITUDE:
      case LONGITUDE:
      case TIME:
        return ALL_MARKS_EXCEPT_GEOSHAPE;
      case X23:
      case Y23:
      case LATITUDE2:
      case LONGITUDE2:
        return {
          area: "always",
          bar: "always",
          image: "always",
          rect: "always",
          rule: "always",
          circle: "binned",
          point: "binned",
          square: "binned",
          tick: "binned",
          line: "binned",
          trail: "binned"
        };
      case SIZE2:
        return {
          point: "always",
          tick: "always",
          rule: "always",
          circle: "always",
          square: "always",
          bar: "always",
          text: "always",
          line: "always",
          trail: "always"
        };
      case STROKEDASH:
        return {
          line: "always",
          point: "always",
          tick: "always",
          rule: "always",
          circle: "always",
          square: "always",
          bar: "always",
          geoshape: "always"
        };
      case SHAPE:
        return { point: "always", geoshape: "always" };
      case TEXT:
        return { text: "always" };
      case ANGLE:
        return { point: "always", square: "always", text: "always" };
      case URL2:
        return { image: "always" };
      case THETA:
        return { text: "always", arc: "always" };
      case RADIUS:
        return { text: "always", arc: "always" };
      case THETA2:
      case RADIUS2:
        return { arc: "always" };
    }
  }
  function rangeType(channel) {
    switch (channel) {
      case X3:
      case Y3:
      case THETA:
      case RADIUS:
      case XOFFSET:
      case YOFFSET:
      case SIZE2:
      case ANGLE:
      case STROKEWIDTH:
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
      case TIME:
      // X2 and Y2 use X and Y scales, so they similarly have continuous range. [falls through]
      case X23:
      case Y23:
      case THETA2:
      case RADIUS2:
        return void 0;
      case FACET:
      case ROW:
      case COLUMN:
      case SHAPE:
      case STROKEDASH:
      // TEXT, TOOLTIP, URL, and HREF have no scale but have discrete output [falls through]
      case TEXT:
      case TOOLTIP:
      case HREF:
      case URL2:
      case DESCRIPTION:
        return "discrete";
      // Color can be either continuous or discrete, depending on scale type.
      case COLOR:
      case FILL:
      case STROKE:
        return "flexible";
      // No scale, no range type.
      case LATITUDE:
      case LONGITUDE:
      case LATITUDE2:
      case LONGITUDE2:
      case DETAIL:
      case KEY:
      case ORDER:
        return void 0;
    }
  }

  // node_modules/vega-lite/build/src/aggregate.js
  var AGGREGATE_OP_INDEX = {
    argmax: 1,
    argmin: 1,
    average: 1,
    count: 1,
    distinct: 1,
    exponential: 1,
    exponentialb: 1,
    product: 1,
    max: 1,
    mean: 1,
    median: 1,
    min: 1,
    missing: 1,
    q1: 1,
    q3: 1,
    ci0: 1,
    ci1: 1,
    stderr: 1,
    stdev: 1,
    stdevp: 1,
    sum: 1,
    valid: 1,
    values: 1,
    variance: 1,
    variancep: 1
  };
  var MULTIDOMAIN_SORT_OP_INDEX = {
    count: 1,
    min: 1,
    max: 1
  };
  function isArgminDef(a4) {
    return hasProperty(a4, "argmin");
  }
  function isArgmaxDef(a4) {
    return hasProperty(a4, "argmax");
  }
  function isAggregateOp(a4) {
    return isString(a4) && has(AGGREGATE_OP_INDEX, a4);
  }
  var COUNTING_OPS = /* @__PURE__ */ new Set([
    "count",
    "valid",
    "missing",
    "distinct"
  ]);
  function isCountingAggregateOp(aggregate) {
    return isString(aggregate) && COUNTING_OPS.has(aggregate);
  }
  function isMinMaxOp(aggregate) {
    return isString(aggregate) && contains2(["min", "max"], aggregate);
  }
  var SUM_OPS = /* @__PURE__ */ new Set([
    "count",
    "sum",
    "distinct",
    "valid",
    "missing"
  ]);
  var SHARED_DOMAIN_OPS = /* @__PURE__ */ new Set([
    "mean",
    "average",
    "median",
    "q1",
    "q3",
    "min",
    "max"
  ]);

  // node_modules/vega-lite/build/src/bin.js
  function binToString(bin3) {
    if (isBoolean(bin3)) {
      bin3 = normalizeBin(bin3, void 0);
    }
    return "bin" + keys3(bin3).map((p2) => isParameterExtent(bin3[p2]) ? varName(`_${p2}_${entries(bin3[p2])}`) : varName(`_${p2}_${bin3[p2]}`)).join("");
  }
  function isBinning(bin3) {
    return bin3 === true || isBinParams(bin3) && !bin3.binned;
  }
  function isBinned(bin3) {
    return bin3 === "binned" || isBinParams(bin3) && bin3.binned === true;
  }
  function isBinParams(bin3) {
    return isObject(bin3);
  }
  function isParameterExtent(extent2) {
    return hasProperty(extent2, "param");
  }
  function autoMaxBins(channel) {
    switch (channel) {
      case ROW:
      case COLUMN:
      case SIZE2:
      case COLOR:
      case FILL:
      case STROKE:
      case STROKEWIDTH:
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
      // Facets and Size shouldn't have too many bins
      // We choose 6 like shape to simplify the rule [falls through]
      case SHAPE:
        return 6;
      // Vega's "shape" has 6 distinct values
      case STROKEDASH:
        return 4;
      // We only provide 5 different stroke dash values (but 4 is more effective)
      default:
        return 10;
    }
  }

  // node_modules/vega-lite/build/src/expr.js
  function isExprRef(o2) {
    return hasProperty(o2, "expr");
  }
  function replaceExprRef(index4, { level } = { level: 0 }) {
    const props = keys3(index4 || {});
    const newIndex = {};
    for (const prop of props) {
      newIndex[prop] = level === 0 ? signalRefOrValue(index4[prop]) : replaceExprRef(index4[prop], { level: level - 1 });
    }
    return newIndex;
  }

  // node_modules/vega-lite/build/src/title.js
  function extractTitleConfig(titleConfig) {
    const {
      // These are non-mark title config that need to be hardcoded
      anchor,
      frame: frame2,
      offset: offset4,
      orient: orient2,
      angle: angle2,
      limit,
      // color needs to be redirect to fill
      color: color5,
      // subtitle properties
      subtitleColor,
      subtitleFont,
      subtitleFontSize,
      subtitleFontStyle,
      subtitleFontWeight,
      subtitleLineHeight,
      subtitlePadding,
      // The rest are mark config.
      ...rest
    } = titleConfig;
    const titleMarkConfig = {
      ...rest,
      ...color5 ? { fill: color5 } : {}
    };
    const nonMarkTitleProperties = {
      ...anchor ? { anchor } : {},
      ...frame2 ? { frame: frame2 } : {},
      ...offset4 ? { offset: offset4 } : {},
      ...orient2 ? { orient: orient2 } : {},
      ...angle2 !== void 0 ? { angle: angle2 } : {},
      ...limit !== void 0 ? { limit } : {}
    };
    const subtitle = {
      ...subtitleColor ? { subtitleColor } : {},
      ...subtitleFont ? { subtitleFont } : {},
      ...subtitleFontSize ? { subtitleFontSize } : {},
      ...subtitleFontStyle ? { subtitleFontStyle } : {},
      ...subtitleFontWeight ? { subtitleFontWeight } : {},
      ...subtitleLineHeight ? { subtitleLineHeight } : {},
      ...subtitlePadding ? { subtitlePadding } : {}
    };
    const subtitleMarkConfig = pick2(titleConfig, ["align", "baseline", "dx", "dy", "limit"]);
    return { titleMarkConfig, subtitleMarkConfig, nonMarkTitleProperties, subtitle };
  }
  function isText(v3) {
    return isString(v3) || isArray(v3) && isString(v3[0]);
  }

  // node_modules/vega-lite/build/src/vega.schema.js
  function isSignalRef(o2) {
    return hasProperty(o2, "signal");
  }
  function isVgRangeStep(range7) {
    return hasProperty(range7, "step");
  }
  function isDataRefUnionedDomain(domain4) {
    if (!isArray(domain4)) {
      return hasProperty(domain4, "fields") && !hasProperty(domain4, "data");
    }
    return false;
  }
  function isFieldRefUnionDomain(domain4) {
    if (!isArray(domain4)) {
      return hasProperty(domain4, "fields") && hasProperty(domain4, "data");
    }
    return false;
  }
  function isDataRefDomain(domain4) {
    if (!isArray(domain4)) {
      return hasProperty(domain4, "field") && hasProperty(domain4, "data");
    }
    return false;
  }
  var VG_MARK_CONFIG_INDEX = {
    aria: 1,
    description: 1,
    ariaRole: 1,
    ariaRoleDescription: 1,
    blend: 1,
    opacity: 1,
    fill: 1,
    fillOpacity: 1,
    stroke: 1,
    strokeCap: 1,
    strokeWidth: 1,
    strokeOpacity: 1,
    strokeDash: 1,
    strokeDashOffset: 1,
    strokeJoin: 1,
    strokeOffset: 1,
    strokeMiterLimit: 1,
    startAngle: 1,
    endAngle: 1,
    padAngle: 1,
    innerRadius: 1,
    outerRadius: 1,
    size: 1,
    shape: 1,
    interpolate: 1,
    tension: 1,
    orient: 1,
    align: 1,
    baseline: 1,
    text: 1,
    dir: 1,
    dx: 1,
    dy: 1,
    ellipsis: 1,
    limit: 1,
    radius: 1,
    theta: 1,
    angle: 1,
    font: 1,
    fontSize: 1,
    fontWeight: 1,
    fontStyle: 1,
    lineBreak: 1,
    lineHeight: 1,
    cursor: 1,
    href: 1,
    tooltip: 1,
    cornerRadius: 1,
    cornerRadiusTopLeft: 1,
    cornerRadiusTopRight: 1,
    cornerRadiusBottomLeft: 1,
    cornerRadiusBottomRight: 1,
    aspect: 1,
    width: 1,
    height: 1,
    url: 1,
    smooth: 1
    // commented below are vg channel that do not have mark config.
    // x: 1,
    // y: 1,
    // x2: 1,
    // y2: 1,
    // xc'|'yc'
    // clip: 1,
    // path: 1,
    // url: 1,
  };
  var VG_MARK_CONFIGS = keys3(VG_MARK_CONFIG_INDEX);
  var VG_MARK_INDEX = {
    arc: 1,
    area: 1,
    group: 1,
    image: 1,
    line: 1,
    path: 1,
    rect: 1,
    rule: 1,
    shape: 1,
    symbol: 1,
    text: 1,
    trail: 1
  };
  var VG_CORNERRADIUS_CHANNELS = [
    "cornerRadius",
    "cornerRadiusTopLeft",
    "cornerRadiusTopRight",
    "cornerRadiusBottomLeft",
    "cornerRadiusBottomRight"
  ];

  // node_modules/vega-lite/build/src/compile/common.js
  function signalOrValueRefWithCondition(val) {
    const condition = isArray(val.condition) ? val.condition.map(conditionalSignalRefOrValue) : conditionalSignalRefOrValue(val.condition);
    return {
      ...signalRefOrValue(val),
      condition
    };
  }
  function signalRefOrValue(value3) {
    if (isExprRef(value3)) {
      const { expr: expr2, ...rest } = value3;
      return { signal: expr2, ...rest };
    }
    return value3;
  }
  function conditionalSignalRefOrValue(value3) {
    if (isExprRef(value3)) {
      const { expr: expr2, ...rest } = value3;
      return { signal: expr2, ...rest };
    }
    return value3;
  }
  function signalOrValueRef(value3) {
    if (isExprRef(value3)) {
      const { expr: expr2, ...rest } = value3;
      return { signal: expr2, ...rest };
    }
    if (isSignalRef(value3)) {
      return value3;
    }
    return value3 !== void 0 ? { value: value3 } : void 0;
  }
  function exprFromSignalRefOrValue(ref2) {
    if (isSignalRef(ref2)) {
      return ref2.signal;
    }
    return $(ref2);
  }
  function exprFromValueRefOrSignalRef(ref2) {
    if (isSignalRef(ref2)) {
      return ref2.signal;
    }
    return $(ref2.value);
  }
  function signalOrStringValue(v3) {
    if (isSignalRef(v3)) {
      return v3.signal;
    }
    return v3 == null ? null : $(v3);
  }
  function applyMarkConfig(e4, model, propsList) {
    for (const property2 of propsList) {
      const value3 = getMarkConfig(property2, model.markDef, model.config);
      if (value3 !== void 0) {
        e4[property2] = signalOrValueRef(value3);
      }
    }
    return e4;
  }
  function getStyles(mark) {
    return [].concat(mark.type, mark.style ?? []);
  }
  function getMarkPropOrConfig(channel, mark, config, opt = {}) {
    const { vgChannel, ignoreVgConfig } = opt;
    if (vgChannel && hasProperty(mark, vgChannel)) {
      return mark[vgChannel];
    } else if (mark[channel] !== void 0) {
      return mark[channel];
    } else if (ignoreVgConfig && (!vgChannel || vgChannel === channel)) {
      return void 0;
    }
    return getMarkConfig(channel, mark, config, opt);
  }
  function getMarkConfig(channel, mark, config, { vgChannel } = {}) {
    const cfg = getMarkStyleConfig(channel, mark, config.style);
    return getFirstDefined(
      // style config has highest precedence
      vgChannel ? cfg : void 0,
      cfg,
      // then mark-specific config
      vgChannel ? config[mark.type][vgChannel] : void 0,
      config[mark.type][channel],
      // Need to cast because MarkDef doesn't perfectly match with AnyMarkConfig, but if the type isn't available, we'll get nothing here, which is fine
      // If there is vgChannel, skip vl channel.
      // For example, vl size for text is vg fontSize, but config.mark.size is only for point size.
      vgChannel ? config.mark[vgChannel] : config.mark[channel]
      // Need to cast for the same reason as above
    );
  }
  function getMarkStyleConfig(prop, mark, styleConfigIndex) {
    return getStyleConfig(prop, getStyles(mark), styleConfigIndex);
  }
  function getStyleConfig(p2, styles, styleConfigIndex) {
    styles = array(styles);
    let value3;
    for (const style2 of styles) {
      const styleConfig = styleConfigIndex[style2];
      if (hasProperty(styleConfig, p2)) {
        value3 = styleConfig[p2];
      }
    }
    return value3;
  }
  function sortParams(orderDef, fieldRefOption) {
    return array(orderDef).reduce((s2, orderChannelDef) => {
      s2.field.push(vgField(orderChannelDef, fieldRefOption));
      s2.order.push(orderChannelDef.sort ?? "ascending");
      return s2;
    }, { field: [], order: [] });
  }
  function mergeTitleFieldDefs(f1, f2) {
    const merged = [...f1];
    f2.forEach((fdToMerge) => {
      for (const fieldDef1 of merged) {
        if (deepEqual(fieldDef1, fdToMerge)) {
          return;
        }
      }
      merged.push(fdToMerge);
    });
    return merged;
  }
  function mergeTitle(title1, title2) {
    if (deepEqual(title1, title2) || !title2) {
      return title1;
    } else if (!title1) {
      return title2;
    } else {
      return [...array(title1), ...array(title2)].join(", ");
    }
  }
  function mergeTitleComponent(v1, v22) {
    const v1Val = v1.value;
    const v2Val = v22.value;
    if (v1Val == null || v2Val === null) {
      return {
        explicit: v1.explicit,
        value: null
      };
    } else if ((isText(v1Val) || isSignalRef(v1Val)) && (isText(v2Val) || isSignalRef(v2Val))) {
      return {
        explicit: v1.explicit,
        value: mergeTitle(v1Val, v2Val)
      };
    } else if (isText(v1Val) || isSignalRef(v1Val)) {
      return {
        explicit: v1.explicit,
        value: v1Val
      };
    } else if (isText(v2Val) || isSignalRef(v2Val)) {
      return {
        explicit: v1.explicit,
        value: v2Val
      };
    } else if (!isText(v1Val) && !isSignalRef(v1Val) && !isText(v2Val) && !isSignalRef(v2Val)) {
      return {
        explicit: v1.explicit,
        value: mergeTitleFieldDefs(v1Val, v2Val)
      };
    }
    throw new Error("It should never reach here");
  }

  // node_modules/vega-lite/build/src/log/message.js
  var message_exports = {};
  __export(message_exports, {
    ADD_SAME_CHILD_TWICE: () => ADD_SAME_CHILD_TWICE,
    CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN: () => CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN,
    CONCAT_CANNOT_SHARE_AXIS: () => CONCAT_CANNOT_SHARE_AXIS,
    FACETED_INDEPENDENT_DIFFERENT_SOURCES: () => FACETED_INDEPENDENT_DIFFERENT_SOURCES,
    FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES: () => FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES,
    FACETED_INDEPENDENT_SAME_SOURCE: () => FACETED_INDEPENDENT_SAME_SOURCE,
    FIT_NON_SINGLE: () => FIT_NON_SINGLE,
    INTERVAL_INITIALIZED_WITH_POS: () => INTERVAL_INITIALIZED_WITH_POS,
    INVALID_CHANNEL_FOR_AXIS: () => INVALID_CHANNEL_FOR_AXIS,
    LEGEND_BINDINGS_MUST_HAVE_PROJECTION: () => LEGEND_BINDINGS_MUST_HAVE_PROJECTION,
    LINE_WITH_VARYING_SIZE: () => LINE_WITH_VARYING_SIZE,
    MORE_THAN_ONE_SORT: () => MORE_THAN_ONE_SORT,
    MULTIPLE_TIMER_ANIMATION_SELECTION: () => MULTIPLE_TIMER_ANIMATION_SELECTION,
    MULTI_VIEW_ANIMATION_UNSUPPORTED: () => MULTI_VIEW_ANIMATION_UNSUPPORTED,
    NEEDS_SAME_SELECTION: () => NEEDS_SAME_SELECTION,
    NO_FIELDS_NEEDS_AS: () => NO_FIELDS_NEEDS_AS,
    REPLACE_ANGLE_WITH_THETA: () => REPLACE_ANGLE_WITH_THETA,
    SCALE_BINDINGS_CONTINUOUS: () => SCALE_BINDINGS_CONTINUOUS,
    SEQUENTIAL_SCALE_DEPRECATED: () => SEQUENTIAL_SCALE_DEPRECATED,
    cannotApplySizeToNonOrientedMark: () => cannotApplySizeToNonOrientedMark,
    cannotLookupVariableParameter: () => cannotLookupVariableParameter,
    cannotProjectAggregate: () => cannotProjectAggregate,
    cannotProjectOnChannelWithoutField: () => cannotProjectOnChannelWithoutField,
    cannotStackRangedMark: () => cannotStackRangedMark,
    cannotUseRelativeBandSizeWithNonBandScale: () => cannotUseRelativeBandSizeWithNonBandScale,
    cannotUseScalePropertyWithNonColor: () => cannotUseScalePropertyWithNonColor,
    channelRequiredForBinned: () => channelRequiredForBinned,
    channelShouldBeDiscrete: () => channelShouldBeDiscrete,
    channelShouldBeDiscreteOrDiscretizing: () => channelShouldBeDiscreteOrDiscretizing,
    channelShouldNotBeUsedForBinned: () => channelShouldNotBeUsedForBinned,
    columnsNotSupportByRowCol: () => columnsNotSupportByRowCol,
    containerSizeNonSingle: () => containerSizeNonSingle,
    containerSizeNotCompatibleWithAutosize: () => containerSizeNotCompatibleWithAutosize,
    customFormatTypeNotAllowed: () => customFormatTypeNotAllowed,
    differentParse: () => differentParse,
    discreteChannelCannotEncode: () => discreteChannelCannotEncode,
    domainRequiredForThresholdScale: () => domainRequiredForThresholdScale,
    domainSortDropped: () => domainSortDropped,
    droppedDay: () => droppedDay,
    droppingColor: () => droppingColor,
    droppingFit: () => droppingFit,
    emptyFieldDef: () => emptyFieldDef,
    errorBand1DNotSupport: () => errorBand1DNotSupport,
    errorBarCenterAndExtentAreNotNeeded: () => errorBarCenterAndExtentAreNotNeeded,
    errorBarCenterIsUsedWithWrongExtent: () => errorBarCenterIsUsedWithWrongExtent,
    errorBarContinuousAxisHasCustomizedAggregate: () => errorBarContinuousAxisHasCustomizedAggregate,
    facetChannelDropped: () => facetChannelDropped,
    incompatibleChannel: () => incompatibleChannel,
    independentScaleMeansIndependentGuide: () => independentScaleMeansIndependentGuide,
    invalidAggregate: () => invalidAggregate,
    invalidEncodingChannel: () => invalidEncodingChannel,
    invalidFieldType: () => invalidFieldType,
    invalidFieldTypeForCountAggregate: () => invalidFieldTypeForCountAggregate,
    invalidSpec: () => invalidSpec,
    invalidTimeUnit: () => invalidTimeUnit,
    invalidTransformIgnored: () => invalidTransformIgnored,
    lineWithRange: () => lineWithRange,
    mergeConflictingDomainProperty: () => mergeConflictingDomainProperty,
    mergeConflictingProperty: () => mergeConflictingProperty,
    missingFieldType: () => missingFieldType,
    nearestNotSupportForContinuous: () => nearestNotSupportForContinuous,
    noSameUnitLookup: () => noSameUnitLookup,
    noSuchRepeatedValue: () => noSuchRepeatedValue,
    offsetEncodingScaleIgnored: () => offsetEncodingScaleIgnored,
    offsetNestedInsideContinuousPositionScaleDropped: () => offsetNestedInsideContinuousPositionScaleDropped,
    orientOverridden: () => orientOverridden,
    primitiveChannelDef: () => primitiveChannelDef,
    projectionOverridden: () => projectionOverridden,
    rangeMarkAlignmentCannotBeExpression: () => rangeMarkAlignmentCannotBeExpression,
    relativeBandSizeNotSupported: () => relativeBandSizeNotSupported,
    scalePropertyNotWorkWithScaleType: () => scalePropertyNotWorkWithScaleType,
    scaleTypeNotWorkWithChannel: () => scaleTypeNotWorkWithChannel,
    scaleTypeNotWorkWithFieldDef: () => scaleTypeNotWorkWithFieldDef,
    scaleTypeNotWorkWithMark: () => scaleTypeNotWorkWithMark,
    selectionAsScaleDomainWithoutField: () => selectionAsScaleDomainWithoutField,
    selectionAsScaleDomainWrongEncodings: () => selectionAsScaleDomainWrongEncodings,
    selectionNotFound: () => selectionNotFound,
    selectionNotSupported: () => selectionNotSupported,
    stackNonLinearScale: () => stackNonLinearScale,
    stackNonSummativeAggregate: () => stackNonSummativeAggregate,
    stepDropped: () => stepDropped,
    unaggregateDomainHasNoEffectForRawField: () => unaggregateDomainHasNoEffectForRawField,
    unaggregateDomainWithNonSharedDomainOp: () => unaggregateDomainWithNonSharedDomainOp,
    unaggregatedDomainWithLogScale: () => unaggregatedDomainWithLogScale,
    unknownField: () => unknownField,
    unrecognizedParse: () => unrecognizedParse
  });
  function invalidSpec(spec) {
    return `Invalid specification ${stringify2(spec)}. Make sure the specification includes at least one of the following properties: "mark", "layer", "facet", "hconcat", "vconcat", "concat", or "repeat".`;
  }
  var FIT_NON_SINGLE = 'Autosize "fit" only works for single views and layered views.';
  function containerSizeNonSingle(name4) {
    const uName = name4 == "width" ? "Width" : "Height";
    return `${uName} "container" only works for single views and layered views.`;
  }
  function containerSizeNotCompatibleWithAutosize(name4) {
    const uName = name4 == "width" ? "Width" : "Height";
    const fitDirection = name4 == "width" ? "x" : "y";
    return `${uName} "container" only works well with autosize "fit" or "fit-${fitDirection}".`;
  }
  function droppingFit(channel) {
    return channel ? `Dropping "fit-${channel}" because spec has discrete ${getSizeChannel(channel)}.` : `Dropping "fit" because spec has discrete size.`;
  }
  function unknownField(channel) {
    return `Unknown field for ${channel}. Cannot calculate view size.`;
  }
  function cannotProjectOnChannelWithoutField(channel) {
    return `Cannot project a selection on encoding channel "${channel}", which has no field.`;
  }
  function cannotProjectAggregate(channel, aggregate) {
    return `Cannot project a selection on encoding channel "${channel}" as it uses an aggregate function ("${aggregate}").`;
  }
  function nearestNotSupportForContinuous(mark) {
    return `The "nearest" transform is not supported for ${mark} marks.`;
  }
  function selectionNotSupported(mark) {
    return `Selection not supported for ${mark} yet.`;
  }
  function selectionNotFound(name4) {
    return `Cannot find a selection named "${name4}".`;
  }
  var SCALE_BINDINGS_CONTINUOUS = "Scale bindings are currently only supported for scales with unbinned, continuous domains.";
  var SEQUENTIAL_SCALE_DEPRECATED = "Sequntial scales are deprecated. The available quantitative scale type values are linear, log, pow, sqrt, symlog, time and utc";
  var LEGEND_BINDINGS_MUST_HAVE_PROJECTION = "Legend bindings are only supported for selections over an individual field or encoding channel.";
  function cannotLookupVariableParameter(name4) {
    return `Lookups can only be performed on selection parameters. "${name4}" is a variable parameter.`;
  }
  function noSameUnitLookup(name4) {
    return `Cannot define and lookup the "${name4}" selection in the same view. Try moving the lookup into a second, layered view?`;
  }
  var NEEDS_SAME_SELECTION = "The same selection must be used to override scale domains in a layered view.";
  var INTERVAL_INITIALIZED_WITH_POS = 'Interval selections should be initialized using "x", "y", "longitude", or "latitude" keys.';
  function noSuchRepeatedValue(field3) {
    return `Unknown repeated value "${field3}".`;
  }
  function columnsNotSupportByRowCol(type3) {
    return `The "columns" property cannot be used when "${type3}" has nested row/column.`;
  }
  var MULTIPLE_TIMER_ANIMATION_SELECTION = "Multiple timer selections in one unit spec are not supported. Ignoring all but the first.";
  var MULTI_VIEW_ANIMATION_UNSUPPORTED = "Animation involving facet, layer, or concat is currently unsupported.";
  function selectionAsScaleDomainWithoutField(field3) {
    return `A "field" or "encoding" must be specified when using a selection as a scale domain. Using "field": ${$(field3)}.`;
  }
  function selectionAsScaleDomainWrongEncodings(encodings, encoding, extent2, field3) {
    return (!encodings.length ? "No " : "Multiple ") + `matching ${$(encoding)} encoding found for selection ${$(extent2.param)}. Using "field": ${$(field3)}.`;
  }
  var CONCAT_CANNOT_SHARE_AXIS = "Axes cannot be shared in concatenated or repeated views yet (https://github.com/vega/vega-lite/issues/2415).";
  function unrecognizedParse(p2) {
    return `Unrecognized parse "${p2}".`;
  }
  function differentParse(field3, local, ancestor) {
    return `An ancestor parsed field "${field3}" as ${ancestor} but a child wants to parse the field as ${local}.`;
  }
  var ADD_SAME_CHILD_TWICE = "Attempt to add the same child twice.";
  function invalidTransformIgnored(transform4) {
    return `Ignoring an invalid transform: ${stringify2(transform4)}.`;
  }
  var NO_FIELDS_NEEDS_AS = 'If "from.fields" is not specified, "as" has to be a string that specifies the key to be used for the data from the secondary source.';
  function customFormatTypeNotAllowed(channel) {
    return `Config.customFormatTypes is not true, thus custom format type and format for channel ${channel} are dropped.`;
  }
  function projectionOverridden(opt) {
    const { parentProjection, projection: projection3 } = opt;
    return `Layer's shared projection ${stringify2(parentProjection)} is overridden by a child projection ${stringify2(projection3)}.`;
  }
  var REPLACE_ANGLE_WITH_THETA = "Arc marks uses theta channel rather than angle, replacing angle with theta.";
  function offsetNestedInsideContinuousPositionScaleDropped(mainChannel) {
    return `${mainChannel}Offset dropped because ${mainChannel} is continuous`;
  }
  function primitiveChannelDef(channel, type3, value3) {
    return `Channel ${channel} is a ${type3}. Converted to {value: ${stringify2(value3)}}.`;
  }
  function invalidFieldType(type3) {
    return `Invalid field type "${type3}".`;
  }
  function invalidFieldTypeForCountAggregate(type3, aggregate) {
    return `Invalid field type "${type3}" for aggregate: "${aggregate}", using "quantitative" instead.`;
  }
  function invalidAggregate(aggregate) {
    return `Invalid aggregation operator "${aggregate}".`;
  }
  function missingFieldType(channel, newType) {
    return `Missing type for channel "${channel}", using "${newType}" instead.`;
  }
  function droppingColor(type3, opt) {
    const { fill: fill2, stroke: stroke2 } = opt;
    return `Dropping color ${type3} as the plot also has ${fill2 && stroke2 ? "fill and stroke" : fill2 ? "fill" : "stroke"}.`;
  }
  function relativeBandSizeNotSupported(sizeChannel) {
    return `Position range does not support relative band size for ${sizeChannel}.`;
  }
  function emptyFieldDef(fieldDef, channel) {
    return `Dropping ${stringify2(fieldDef)} from channel "${channel}" since it does not contain any data field, datum, value, or signal.`;
  }
  var LINE_WITH_VARYING_SIZE = "Line marks cannot encode size with a non-groupby field. You may want to use trail marks instead.";
  function incompatibleChannel(channel, markOrFacet, when) {
    return `${channel} dropped as it is incompatible with "${markOrFacet}"${when ? ` when ${when}` : ""}.`;
  }
  function offsetEncodingScaleIgnored(channel) {
    return `${channel} encoding has no scale, so specified scale is ignored.`;
  }
  function invalidEncodingChannel(channel) {
    return `${channel}-encoding is dropped as ${channel} is not a valid encoding channel.`;
  }
  function channelShouldBeDiscrete(channel) {
    return `${channel} encoding should be discrete (ordinal / nominal / binned).`;
  }
  function channelShouldBeDiscreteOrDiscretizing(channel) {
    return `${channel} encoding should be discrete (ordinal / nominal / binned) or use a discretizing scale (e.g. threshold).`;
  }
  function facetChannelDropped(channels) {
    return `Facet encoding dropped as ${channels.join(" and ")} ${channels.length > 1 ? "are" : "is"} also specified.`;
  }
  function discreteChannelCannotEncode(channel, type3) {
    return `Using discrete channel "${channel}" to encode "${type3}" field can be misleading as it does not encode ${type3 === "ordinal" ? "order" : "magnitude"}.`;
  }
  function rangeMarkAlignmentCannotBeExpression(align2) {
    return `The ${align2} for range marks cannot be an expression`;
  }
  function lineWithRange(hasX2, hasY2) {
    const channels = hasX2 && hasY2 ? "x2 and y2" : hasX2 ? "x2" : "y2";
    return `Line mark is for continuous lines and thus cannot be used with ${channels}. We will use the rule mark (line segments) instead.`;
  }
  function orientOverridden(original, actual) {
    return `Specified orient "${original}" overridden with "${actual}".`;
  }
  var CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN = "Custom domain scale cannot be unioned with default field-based domain.";
  function cannotUseScalePropertyWithNonColor(prop) {
    return `Cannot use the scale property "${prop}" with non-color channel.`;
  }
  function cannotUseRelativeBandSizeWithNonBandScale(scaleType2) {
    return `Cannot use the relative band size with ${scaleType2} scale.`;
  }
  function unaggregateDomainHasNoEffectForRawField(fieldDef) {
    return `Using unaggregated domain with raw field has no effect (${stringify2(fieldDef)}).`;
  }
  function unaggregateDomainWithNonSharedDomainOp(aggregate) {
    return `Unaggregated domain not applicable for "${aggregate}" since it produces values outside the origin domain of the source data.`;
  }
  function unaggregatedDomainWithLogScale(fieldDef) {
    return `Unaggregated domain is currently unsupported for log scale (${stringify2(fieldDef)}).`;
  }
  function cannotApplySizeToNonOrientedMark(mark) {
    return `Cannot apply size to non-oriented mark "${mark}".`;
  }
  function scaleTypeNotWorkWithChannel(channel, scaleType2, defaultScaleType) {
    return `Channel "${channel}" does not work with "${scaleType2}" scale. We are using "${defaultScaleType}" scale instead.`;
  }
  function scaleTypeNotWorkWithFieldDef(scaleType2, defaultScaleType) {
    return `FieldDef does not work with "${scaleType2}" scale. We are using "${defaultScaleType}" scale instead.`;
  }
  function scalePropertyNotWorkWithScaleType(scaleType2, propName, channel) {
    return `${channel}-scale's "${propName}" is dropped as it does not work with ${scaleType2} scale.`;
  }
  function scaleTypeNotWorkWithMark(mark, scaleType2) {
    return `Scale type "${scaleType2}" does not work with mark "${mark}".`;
  }
  function stepDropped(channel) {
    return `The step for "${channel}" is dropped because the ${channel === "width" ? "x" : "y"} is continuous.`;
  }
  function mergeConflictingProperty(property2, propertyOf, v1, v22) {
    return `Conflicting ${propertyOf.toString()} property "${property2.toString()}" (${stringify2(v1)} and ${stringify2(v22)}). Using ${stringify2(v1)}.`;
  }
  function mergeConflictingDomainProperty(property2, propertyOf, v1, v22) {
    return `Conflicting ${propertyOf.toString()} property "${property2.toString()}" (${stringify2(v1)} and ${stringify2(v22)}). Using the union of the two domains.`;
  }
  function independentScaleMeansIndependentGuide(channel) {
    return `Setting the scale to be independent for "${channel}" means we also have to set the guide (axis or legend) to be independent.`;
  }
  function domainSortDropped(sort3) {
    return `Dropping sort property ${stringify2(sort3)} as unioned domains only support boolean or op "count", "min", and "max".`;
  }
  var MORE_THAN_ONE_SORT = "Domains that should be unioned has conflicting sort properties. Sort will be set to true.";
  var FACETED_INDEPENDENT_DIFFERENT_SOURCES = "Detected faceted independent scales that union domain of multiple fields from different data sources. We will use the first field. The result view size may be incorrect.";
  var FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES = "Detected faceted independent scales that union domain of the same fields from different source. We will assume that this is the same field from a different fork of the same data source. However, if this is not the case, the result view size may be incorrect.";
  var FACETED_INDEPENDENT_SAME_SOURCE = "Detected faceted independent scales that union domain of multiple fields from the same data source. We will use the first field. The result view size may be incorrect.";
  var INVALID_CHANNEL_FOR_AXIS = "Invalid channel for axis.";
  function cannotStackRangedMark(channel) {
    return `Cannot stack "${channel}" if there is already "${channel}2".`;
  }
  function stackNonLinearScale(scaleType2) {
    return `Stack is applied to a non-linear scale (${scaleType2}).`;
  }
  function stackNonSummativeAggregate(aggregate) {
    return `Stacking is applied even though the aggregate function is non-summative ("${aggregate}").`;
  }
  function invalidTimeUnit(unitName2, value3) {
    return `Invalid ${unitName2}: ${stringify2(value3)}.`;
  }
  function droppedDay(d2) {
    return `Dropping day from datetime ${stringify2(d2)} as day cannot be combined with other units.`;
  }
  function errorBarCenterAndExtentAreNotNeeded(center, extent2) {
    return `${extent2 ? "extent " : ""}${extent2 && center ? "and " : ""}${center ? "center " : ""}${extent2 && center ? "are " : "is "}not needed when data are aggregated.`;
  }
  function errorBarCenterIsUsedWithWrongExtent(center, extent2, mark) {
    return `${center} is not usually used with ${extent2} for ${mark}.`;
  }
  function errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark) {
    return `Continuous axis should not have customized aggregation function ${aggregate}; ${compositeMark} already agregates the axis.`;
  }
  function errorBand1DNotSupport(property2) {
    return `1D error band does not support ${property2}.`;
  }
  function channelRequiredForBinned(channel) {
    return `Channel ${channel} is required for "binned" bin.`;
  }
  function channelShouldNotBeUsedForBinned(channel) {
    return `Channel ${channel} should not be used with "binned" bin.`;
  }
  function domainRequiredForThresholdScale(channel) {
    return `Domain for ${channel} is required for threshold scale.`;
  }

  // node_modules/vega-lite/build/src/log/index.js
  var _LocalLogger_level;
  var main = logger(Warn);
  var current = main;
  _LocalLogger_level = /* @__PURE__ */ new WeakMap();
  function set6(newLogger) {
    current = newLogger;
    return current;
  }
  function reset2() {
    current = main;
    return current;
  }
  function error2(...args) {
    current.error(...args);
  }
  function warn2(...args) {
    current.warn(...args);
  }
  function debug2(...args) {
    current.debug(...args);
  }

  // node_modules/vega-lite/build/src/datetime.js
  function isDateTime(o2) {
    if (o2 && isObject(o2)) {
      for (const part of TIMEUNIT_PARTS) {
        if (hasProperty(o2, part)) {
          return true;
        }
      }
    }
    return false;
  }
  var MONTHS = [
    "january",
    "february",
    "march",
    "april",
    "may",
    "june",
    "july",
    "august",
    "september",
    "october",
    "november",
    "december"
  ];
  var SHORT_MONTHS = MONTHS.map((m4) => m4.substr(0, 3));
  var DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
  var SHORT_DAYS = DAYS.map((d2) => d2.substr(0, 3));
  function normalizeQuarter(q2) {
    if (isNumeric(q2)) {
      q2 = +q2;
    }
    if (isNumber(q2)) {
      if (q2 > 4) {
        warn2(message_exports.invalidTimeUnit("quarter", q2));
      }
      return q2 - 1;
    } else {
      throw new Error(message_exports.invalidTimeUnit("quarter", q2));
    }
  }
  function normalizeMonth(m4) {
    if (isNumeric(m4)) {
      m4 = +m4;
    }
    if (isNumber(m4)) {
      return m4 - 1;
    } else {
      const lowerM = m4.toLowerCase();
      const monthIndex = MONTHS.indexOf(lowerM);
      if (monthIndex !== -1) {
        return monthIndex;
      }
      const shortM = lowerM.substr(0, 3);
      const shortMonthIndex = SHORT_MONTHS.indexOf(shortM);
      if (shortMonthIndex !== -1) {
        return shortMonthIndex;
      }
      throw new Error(message_exports.invalidTimeUnit("month", m4));
    }
  }
  function normalizeDay(d2) {
    if (isNumeric(d2)) {
      d2 = +d2;
    }
    if (isNumber(d2)) {
      return d2 % 7;
    } else {
      const lowerD = d2.toLowerCase();
      const dayIndex = DAYS.indexOf(lowerD);
      if (dayIndex !== -1) {
        return dayIndex;
      }
      const shortD = lowerD.substr(0, 3);
      const shortDayIndex = SHORT_DAYS.indexOf(shortD);
      if (shortDayIndex !== -1) {
        return shortDayIndex;
      }
      throw new Error(message_exports.invalidTimeUnit("day", d2));
    }
  }
  function dateTimeParts(d2, normalize4) {
    const parts = [];
    if (normalize4 && d2.day !== void 0) {
      if (keys3(d2).length > 1) {
        warn2(message_exports.droppedDay(d2));
        d2 = duplicate(d2);
        delete d2.day;
      }
    }
    if (d2.year !== void 0) {
      parts.push(d2.year);
    } else {
      parts.push(2012);
    }
    if (d2.month !== void 0) {
      const month = normalize4 ? normalizeMonth(d2.month) : d2.month;
      parts.push(month);
    } else if (d2.quarter !== void 0) {
      const quarter2 = normalize4 ? normalizeQuarter(d2.quarter) : d2.quarter;
      parts.push(isNumber(quarter2) ? quarter2 * 3 : `${quarter2}*3`);
    } else {
      parts.push(0);
    }
    if (d2.date !== void 0) {
      parts.push(d2.date);
    } else if (d2.day !== void 0) {
      const day = normalize4 ? normalizeDay(d2.day) : d2.day;
      parts.push(isNumber(day) ? day + 1 : `${day}+1`);
    } else {
      parts.push(1);
    }
    for (const timeUnit of ["hours", "minutes", "seconds", "milliseconds"]) {
      const unit2 = d2[timeUnit];
      parts.push(typeof unit2 === "undefined" ? 0 : unit2);
    }
    return parts;
  }
  function dateTimeToExpr(d2) {
    const parts = dateTimeParts(d2, true);
    const string = parts.join(", ");
    if (d2.utc) {
      return `utc(${string})`;
    } else {
      return `datetime(${string})`;
    }
  }
  function dateTimeExprToExpr(d2) {
    const parts = dateTimeParts(d2, false);
    const string = parts.join(", ");
    if (d2.utc) {
      return `utc(${string})`;
    } else {
      return `datetime(${string})`;
    }
  }
  function dateTimeToTimestamp(d2) {
    const parts = dateTimeParts(d2, true);
    if (d2.utc) {
      return +new Date(Date.UTC(...parts));
    } else {
      return +new Date(...parts);
    }
  }

  // node_modules/vega-lite/build/src/timeunit.js
  var LOCAL_SINGLE_TIMEUNIT_INDEX = {
    year: 1,
    quarter: 1,
    month: 1,
    week: 1,
    day: 1,
    dayofyear: 1,
    date: 1,
    hours: 1,
    minutes: 1,
    seconds: 1,
    milliseconds: 1
  };
  var TIMEUNIT_PARTS = keys3(LOCAL_SINGLE_TIMEUNIT_INDEX);
  function isLocalSingleTimeUnit(timeUnit) {
    return has(LOCAL_SINGLE_TIMEUNIT_INDEX, timeUnit);
  }
  var BINNED_LOCAL_TIMEUNIT_INDEX = {
    binnedyear: 1,
    binnedyearquarter: 1,
    binnedyearquartermonth: 1,
    binnedyearmonth: 1,
    binnedyearmonthdate: 1,
    binnedyearmonthdatehours: 1,
    binnedyearmonthdatehoursminutes: 1,
    binnedyearmonthdatehoursminutesseconds: 1,
    binnedyearweek: 1,
    binnedyearweekday: 1,
    binnedyearweekdayhours: 1,
    binnedyearweekdayhoursminutes: 1,
    binnedyearweekdayhoursminutesseconds: 1,
    binnedyeardayofyear: 1
  };
  var BINNED_UTC_TIMEUNIT_INDEX = {
    binnedutcyear: 1,
    binnedutcyearquarter: 1,
    binnedutcyearquartermonth: 1,
    binnedutcyearmonth: 1,
    binnedutcyearmonthdate: 1,
    binnedutcyearmonthdatehours: 1,
    binnedutcyearmonthdatehoursminutes: 1,
    binnedutcyearmonthdatehoursminutesseconds: 1,
    binnedutcyearweek: 1,
    binnedutcyearweekday: 1,
    binnedutcyearweekdayhours: 1,
    binnedutcyearweekdayhoursminutes: 1,
    binnedutcyearweekdayhoursminutesseconds: 1,
    binnedutcyeardayofyear: 1
  };
  var BINNED_TIMEUNIT_INDEX = {
    ...BINNED_LOCAL_TIMEUNIT_INDEX,
    ...BINNED_UTC_TIMEUNIT_INDEX
  };
  function isBinnedTimeUnit(timeUnit) {
    if (isObject(timeUnit)) {
      return timeUnit.binned;
    }
    return isBinnedTimeUnitString(timeUnit);
  }
  function isBinnedTimeUnitString(timeUnit) {
    return timeUnit && timeUnit.startsWith("binned");
  }
  function isUTCTimeUnit(t4) {
    return t4.startsWith("utc");
  }
  function getLocalTimeUnitFromUTCTimeUnit(t4) {
    return t4.substring(3);
  }
  var VEGALITE_TIMEFORMAT = {
    "year-month": "%b %Y ",
    "year-month-date": "%b %d, %Y "
  };
  function getTimeUnitParts(timeUnit) {
    return TIMEUNIT_PARTS.filter((part) => containsTimeUnit(timeUnit, part));
  }
  function getSmallestTimeUnitPart(timeUnit) {
    const parts = getTimeUnitParts(timeUnit);
    return parts[parts.length - 1];
  }
  function containsTimeUnit(fullTimeUnit, timeUnit) {
    const index4 = fullTimeUnit.indexOf(timeUnit);
    if (index4 < 0) {
      return false;
    }
    if (index4 > 0 && timeUnit === "seconds" && fullTimeUnit.charAt(index4 - 1) === "i") {
      return false;
    }
    if (fullTimeUnit.length > index4 + 3 && timeUnit === "day" && fullTimeUnit.charAt(index4 + 3) === "o") {
      return false;
    }
    if (index4 > 0 && timeUnit === "year" && fullTimeUnit.charAt(index4 - 1) === "f") {
      return false;
    }
    return true;
  }
  function fieldExpr(fullTimeUnit, field3, { end } = { end: false }) {
    const fieldRef2 = accessPathWithDatum(field3);
    const utc = isUTCTimeUnit(fullTimeUnit) ? "utc" : "";
    function func(timeUnit) {
      if (timeUnit === "quarter") {
        return `(${utc}quarter(${fieldRef2})-1)`;
      } else {
        return `${utc}${timeUnit}(${fieldRef2})`;
      }
    }
    let lastTimeUnit;
    const dateExpr = {};
    for (const part of TIMEUNIT_PARTS) {
      if (containsTimeUnit(fullTimeUnit, part)) {
        dateExpr[part] = func(part);
        lastTimeUnit = part;
      }
    }
    if (end) {
      dateExpr[lastTimeUnit] += "+1";
    }
    return dateTimeExprToExpr(dateExpr);
  }
  function timeUnitSpecifierExpression(timeUnit) {
    if (!timeUnit) {
      return void 0;
    }
    const timeUnitParts = getTimeUnitParts(timeUnit);
    return `timeUnitSpecifier(${stringify2(timeUnitParts)}, ${stringify2(VEGALITE_TIMEFORMAT)})`;
  }
  function formatExpression(timeUnit, field3, isUTCScale) {
    if (!timeUnit) {
      return void 0;
    }
    const expr2 = timeUnitSpecifierExpression(timeUnit);
    const utc = isUTCScale || isUTCTimeUnit(timeUnit);
    return `${utc ? "utc" : "time"}Format(${field3}, ${expr2})`;
  }
  function normalizeTimeUnit(timeUnit) {
    if (!timeUnit) {
      return void 0;
    }
    let params2;
    if (isString(timeUnit)) {
      if (isBinnedTimeUnitString(timeUnit)) {
        params2 = {
          unit: timeUnit.substring(6),
          binned: true
        };
      } else {
        params2 = {
          unit: timeUnit
        };
      }
    } else if (isObject(timeUnit)) {
      params2 = {
        ...timeUnit,
        ...timeUnit.unit ? { unit: timeUnit.unit } : {}
      };
    }
    if (isUTCTimeUnit(params2.unit)) {
      params2.utc = true;
      params2.unit = getLocalTimeUnitFromUTCTimeUnit(params2.unit);
    }
    return params2;
  }
  function timeUnitToString(tu) {
    const { utc, ...rest } = normalizeTimeUnit(tu);
    if (rest.unit) {
      return (utc ? "utc" : "") + keys3(rest).map((p2) => varName(`${p2 === "unit" ? "" : `_${p2}_`}${rest[p2]}`)).join("");
    } else {
      return (utc ? "utc" : "") + "timeunit" + keys3(rest).map((p2) => varName(`_${p2}_${rest[p2]}`)).join("");
    }
  }
  function durationExpr(timeUnit, wrap2 = (x5) => x5) {
    const normalizedTimeUnit = normalizeTimeUnit(timeUnit);
    const smallestUnitPart = getSmallestTimeUnitPart(normalizedTimeUnit.unit);
    if (smallestUnitPart && smallestUnitPart !== "day") {
      const startDate = {
        year: 2001,
        // pick a non-leap year
        month: 1,
        date: 1,
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0
      };
      const { step, part } = getDateTimePartAndStep(smallestUnitPart, normalizedTimeUnit.step);
      const endDate = {
        ...startDate,
        [part]: +startDate[part] + step
      };
      return `${wrap2(dateTimeToExpr(endDate))} - ${wrap2(dateTimeToExpr(startDate))}`;
    }
    return void 0;
  }
  var DATE_PARTS = {
    year: 1,
    month: 1,
    date: 1,
    hours: 1,
    minutes: 1,
    seconds: 1,
    milliseconds: 1
  };
  function isDatePart(timeUnit) {
    return has(DATE_PARTS, timeUnit);
  }
  function getDateTimePartAndStep(timeUnit, step = 1) {
    if (isDatePart(timeUnit)) {
      return { part: timeUnit, step };
    }
    switch (timeUnit) {
      case "day":
      case "dayofyear":
        return { part: "date", step };
      case "quarter":
        return { part: "month", step: step * 3 };
      case "week":
        return { part: "date", step: step * 7 };
    }
  }

  // node_modules/vega-lite/build/src/predicate.js
  function isSelectionPredicate(predicate) {
    return hasProperty(predicate, "param");
  }
  function isFieldEqualPredicate(predicate) {
    return !!predicate?.field && predicate.equal !== void 0;
  }
  function isFieldLTPredicate(predicate) {
    return !!predicate?.field && predicate.lt !== void 0;
  }
  function isFieldLTEPredicate(predicate) {
    return !!predicate?.field && predicate.lte !== void 0;
  }
  function isFieldGTPredicate(predicate) {
    return !!predicate?.field && predicate.gt !== void 0;
  }
  function isFieldGTEPredicate(predicate) {
    return !!predicate?.field && predicate.gte !== void 0;
  }
  function isFieldRangePredicate(predicate) {
    if (predicate?.field) {
      if (isArray(predicate.range) && predicate.range.length === 2) {
        return true;
      } else if (isSignalRef(predicate.range)) {
        return true;
      }
    }
    return false;
  }
  function isFieldOneOfPredicate(predicate) {
    return !!predicate?.field && (isArray(predicate.oneOf) || isArray(predicate.in));
  }
  function isFieldValidPredicate(predicate) {
    return !!predicate?.field && predicate.valid !== void 0;
  }
  function isFieldPredicate(predicate) {
    return isFieldOneOfPredicate(predicate) || isFieldEqualPredicate(predicate) || isFieldRangePredicate(predicate) || isFieldLTPredicate(predicate) || isFieldGTPredicate(predicate) || isFieldLTEPredicate(predicate) || isFieldGTEPredicate(predicate);
  }
  function predicateValueExpr(v3, timeUnit) {
    return valueExpr(v3, { timeUnit, wrapTime: true });
  }
  function predicateValuesExpr(vals2, timeUnit) {
    return vals2.map((v3) => predicateValueExpr(v3, timeUnit));
  }
  function fieldFilterExpression(predicate, useInRange = true) {
    const { field: field3 } = predicate;
    const normalizedTimeUnit = normalizeTimeUnit(predicate.timeUnit);
    const { unit: unit2, binned } = normalizedTimeUnit || {};
    const rawFieldExpr = vgField(predicate, { expr: "datum" });
    const fieldExpr2 = unit2 ? (
      // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.
      // TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline
      // TODO: support utc
      `time(${!binned ? fieldExpr(unit2, field3) : rawFieldExpr})`
    ) : rawFieldExpr;
    if (isFieldEqualPredicate(predicate)) {
      return `${fieldExpr2}===${predicateValueExpr(predicate.equal, unit2)}`;
    } else if (isFieldLTPredicate(predicate)) {
      const upper = predicate.lt;
      return `${fieldExpr2}<${predicateValueExpr(upper, unit2)}`;
    } else if (isFieldGTPredicate(predicate)) {
      const lower = predicate.gt;
      return `${fieldExpr2}>${predicateValueExpr(lower, unit2)}`;
    } else if (isFieldLTEPredicate(predicate)) {
      const upper = predicate.lte;
      return `${fieldExpr2}<=${predicateValueExpr(upper, unit2)}`;
    } else if (isFieldGTEPredicate(predicate)) {
      const lower = predicate.gte;
      return `${fieldExpr2}>=${predicateValueExpr(lower, unit2)}`;
    } else if (isFieldOneOfPredicate(predicate)) {
      return `indexof([${predicateValuesExpr(predicate.oneOf, unit2).join(",")}], ${fieldExpr2}) !== -1`;
    } else if (isFieldValidPredicate(predicate)) {
      return fieldValidPredicate(fieldExpr2, predicate.valid);
    } else if (isFieldRangePredicate(predicate)) {
      const { range: range7 } = replaceExprRef(predicate);
      const lower = isSignalRef(range7) ? { signal: `${range7.signal}[0]` } : range7[0];
      const upper = isSignalRef(range7) ? { signal: `${range7.signal}[1]` } : range7[1];
      if (lower !== null && upper !== null && useInRange) {
        return "inrange(" + fieldExpr2 + ", [" + predicateValueExpr(lower, unit2) + ", " + predicateValueExpr(upper, unit2) + "])";
      }
      const exprs = [];
      if (lower !== null) {
        exprs.push(`${fieldExpr2} >= ${predicateValueExpr(lower, unit2)}`);
      }
      if (upper !== null) {
        exprs.push(`${fieldExpr2} <= ${predicateValueExpr(upper, unit2)}`);
      }
      return exprs.length > 0 ? exprs.join(" && ") : "true";
    }
    throw new Error(`Invalid field predicate: ${stringify2(predicate)}`);
  }
  function fieldValidPredicate(fieldExpr2, valid = true) {
    if (valid) {
      return `isValid(${fieldExpr2}) && isFinite(+${fieldExpr2})`;
    } else {
      return `!isValid(${fieldExpr2}) || !isFinite(+${fieldExpr2})`;
    }
  }
  function normalizePredicate(f2) {
    if (isFieldPredicate(f2) && f2.timeUnit) {
      return {
        ...f2,
        timeUnit: normalizeTimeUnit(f2.timeUnit)
      };
    }
    return f2;
  }

  // node_modules/vega-lite/build/src/type.js
  var Type = {
    quantitative: "quantitative",
    ordinal: "ordinal",
    temporal: "temporal",
    nominal: "nominal",
    geojson: "geojson"
  };
  function isContinuous2(type3) {
    return type3 === "quantitative" || type3 === "temporal";
  }
  function isDiscrete2(type3) {
    return type3 === "ordinal" || type3 === "nominal";
  }
  var QUANTITATIVE = Type.quantitative;
  var ORDINAL = Type.ordinal;
  var TEMPORAL = Type.temporal;
  var NOMINAL = Type.nominal;
  var GEOJSON = Type.geojson;
  var TYPES = keys3(Type);
  function getFullName(type3) {
    if (type3) {
      type3 = type3.toLowerCase();
      switch (type3) {
        case "q":
        case QUANTITATIVE:
          return "quantitative";
        case "t":
        case TEMPORAL:
          return "temporal";
        case "o":
        case ORDINAL:
          return "ordinal";
        case "n":
        case NOMINAL:
          return "nominal";
        case GEOJSON:
          return "geojson";
      }
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/scale.js
  var ScaleType = {
    // Continuous - Quantitative
    LINEAR: "linear",
    LOG: "log",
    POW: "pow",
    SQRT: "sqrt",
    SYMLOG: "symlog",
    IDENTITY: "identity",
    SEQUENTIAL: "sequential",
    // Continuous - Time
    TIME: "time",
    UTC: "utc",
    // Discretizing scales
    QUANTILE: "quantile",
    QUANTIZE: "quantize",
    THRESHOLD: "threshold",
    BIN_ORDINAL: "bin-ordinal",
    // Discrete scales
    ORDINAL: "ordinal",
    POINT: "point",
    BAND: "band"
  };
  var SCALE_CATEGORY_INDEX = {
    linear: "numeric",
    log: "numeric",
    pow: "numeric",
    sqrt: "numeric",
    symlog: "numeric",
    identity: "numeric",
    sequential: "numeric",
    time: "time",
    utc: "time",
    ordinal: "ordinal",
    "bin-ordinal": "bin-ordinal",
    // TODO: should bin-ordinal support merging with other
    point: "ordinal-position",
    band: "ordinal-position",
    quantile: "discretizing",
    quantize: "discretizing",
    threshold: "discretizing"
  };
  var SCALE_TYPES = keys3(SCALE_CATEGORY_INDEX);
  function scaleCompatible(scaleType1, scaleType2) {
    const scaleCategory1 = SCALE_CATEGORY_INDEX[scaleType1];
    const scaleCategory2 = SCALE_CATEGORY_INDEX[scaleType2];
    return scaleCategory1 === scaleCategory2 || scaleCategory1 === "ordinal-position" && scaleCategory2 === "time" || scaleCategory2 === "ordinal-position" && scaleCategory1 === "time";
  }
  var SCALE_PRECEDENCE_INDEX = {
    // numeric
    linear: 0,
    log: 1,
    pow: 1,
    sqrt: 1,
    symlog: 1,
    identity: 1,
    sequential: 1,
    // time
    time: 0,
    utc: 0,
    // ordinal-position -- these have higher precedence than continuous scales as they support more types of data
    point: 10,
    band: 11,
    // band has higher precedence as it is better for interaction
    // non grouped types
    ordinal: 0,
    "bin-ordinal": 0,
    quantile: 0,
    quantize: 0,
    threshold: 0
  };
  function scaleTypePrecedence(scaleType2) {
    return SCALE_PRECEDENCE_INDEX[scaleType2];
  }
  var QUANTITATIVE_SCALES = /* @__PURE__ */ new Set([
    "linear",
    "log",
    "pow",
    "sqrt",
    "symlog"
  ]);
  var CONTINUOUS_TO_CONTINUOUS_SCALES = /* @__PURE__ */ new Set([
    ...QUANTITATIVE_SCALES,
    "time",
    "utc"
  ]);
  function isQuantitative(type3) {
    return QUANTITATIVE_SCALES.has(type3);
  }
  var CONTINUOUS_TO_DISCRETE_SCALES = /* @__PURE__ */ new Set([
    "quantile",
    "quantize",
    "threshold"
  ]);
  var CONTINUOUS_DOMAIN_SCALES = /* @__PURE__ */ new Set([
    ...CONTINUOUS_TO_CONTINUOUS_SCALES,
    ...CONTINUOUS_TO_DISCRETE_SCALES,
    "sequential",
    "identity"
  ]);
  var DISCRETE_DOMAIN_SCALES = /* @__PURE__ */ new Set([
    "ordinal",
    "bin-ordinal",
    "point",
    "band"
  ]);
  function hasDiscreteDomain(type3) {
    return DISCRETE_DOMAIN_SCALES.has(type3);
  }
  function hasContinuousDomain(type3) {
    return CONTINUOUS_DOMAIN_SCALES.has(type3);
  }
  function isContinuousToContinuous(type3) {
    return CONTINUOUS_TO_CONTINUOUS_SCALES.has(type3);
  }
  function isContinuousToDiscrete(type3) {
    return CONTINUOUS_TO_DISCRETE_SCALES.has(type3);
  }
  var defaultScaleConfig = {
    pointPadding: 0.5,
    barBandPaddingInner: 0.1,
    rectBandPaddingInner: 0,
    tickBandPaddingInner: 0.25,
    bandWithNestedOffsetPaddingInner: 0.2,
    bandWithNestedOffsetPaddingOuter: 0.2,
    minBandSize: 2,
    minFontSize: 8,
    maxFontSize: 40,
    minOpacity: 0.3,
    maxOpacity: 0.8,
    // FIXME: revise if these *can* become ratios of width/height step
    minSize: 4,
    // Point size is area. For square point, 9 = 3 pixel ^ 2, not too small!
    minStrokeWidth: 1,
    maxStrokeWidth: 4,
    quantileCount: 4,
    quantizeCount: 4,
    zero: true,
    framesPerSecond: 2,
    animationDuration: 5
  };
  function isExtendedScheme(scheme3) {
    return !isString(scheme3) && hasProperty(scheme3, "name");
  }
  function isParameterDomain(domain4) {
    return hasProperty(domain4, "param");
  }
  function isDomainUnionWith(domain4) {
    return hasProperty(domain4, "unionWith");
  }
  function isFieldRange(range7) {
    return isObject(range7) && "field" in range7;
  }
  var SCALE_PROPERTY_INDEX = {
    type: 1,
    domain: 1,
    domainMax: 1,
    domainMin: 1,
    domainMid: 1,
    domainRaw: 1,
    align: 1,
    range: 1,
    rangeMax: 1,
    rangeMin: 1,
    scheme: 1,
    bins: 1,
    // Other properties
    reverse: 1,
    round: 1,
    // quantitative / time
    clamp: 1,
    nice: 1,
    // quantitative
    base: 1,
    exponent: 1,
    constant: 1,
    interpolate: 1,
    zero: 1,
    // zero depends on domain
    // band/point
    padding: 1,
    paddingInner: 1,
    paddingOuter: 1
  };
  var SCALE_PROPERTIES = keys3(SCALE_PROPERTY_INDEX);
  var { type: type2, domain: domain2, range: range5, rangeMax, rangeMin, scheme: scheme2, ...NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX } = SCALE_PROPERTY_INDEX;
  var NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = keys3(NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTY_INDEX);
  function scaleTypeSupportProperty(scaleType2, propName) {
    switch (propName) {
      case "type":
      case "domain":
      case "reverse":
      case "range":
        return true;
      case "scheme":
      case "interpolate":
        return !["point", "band", "identity"].includes(scaleType2);
      case "bins":
        return !["point", "band", "identity", "ordinal"].includes(scaleType2);
      case "round":
        return isContinuousToContinuous(scaleType2) || scaleType2 === "band" || scaleType2 === "point";
      case "padding":
      case "rangeMin":
      case "rangeMax":
        return isContinuousToContinuous(scaleType2) || ["point", "band"].includes(scaleType2);
      case "paddingOuter":
      case "align":
        return ["point", "band"].includes(scaleType2);
      case "paddingInner":
        return scaleType2 === "band";
      case "domainMax":
      case "domainMid":
      case "domainMin":
      case "domainRaw":
      case "clamp":
        return isContinuousToContinuous(scaleType2);
      case "nice":
        return isContinuousToContinuous(scaleType2) || scaleType2 === "quantize" || scaleType2 === "threshold";
      case "exponent":
        return scaleType2 === "pow";
      case "base":
        return scaleType2 === "log";
      case "constant":
        return scaleType2 === "symlog";
      case "zero":
        return hasContinuousDomain(scaleType2) && !contains2([
          "log",
          // log scale cannot have zero value
          "time",
          "utc",
          // zero is not meaningful for time
          "threshold",
          // threshold requires custom domain so zero does not matter
          "quantile"
          // quantile depends on distribution so zero does not matter
        ], scaleType2);
    }
  }
  function channelScalePropertyIncompatability(channel, propName) {
    switch (propName) {
      case "interpolate":
      case "scheme":
      case "domainMid":
        if (!isColorChannel(channel)) {
          return message_exports.cannotUseScalePropertyWithNonColor(propName);
        }
        return void 0;
      case "align":
      case "type":
      case "bins":
      case "domain":
      case "domainMax":
      case "domainMin":
      case "domainRaw":
      case "range":
      case "base":
      case "exponent":
      case "constant":
      case "nice":
      case "padding":
      case "paddingInner":
      case "paddingOuter":
      case "rangeMax":
      case "rangeMin":
      case "reverse":
      case "round":
      case "clamp":
      case "zero":
        return void 0;
    }
  }
  function scaleTypeSupportDataType(specifiedType, fieldDefType) {
    if (contains2([ORDINAL, NOMINAL], fieldDefType)) {
      return specifiedType === void 0 || hasDiscreteDomain(specifiedType);
    } else if (fieldDefType === TEMPORAL) {
      return contains2([ScaleType.TIME, ScaleType.UTC, void 0], specifiedType);
    } else if (fieldDefType === QUANTITATIVE) {
      return isQuantitative(specifiedType) || isContinuousToDiscrete(specifiedType) || specifiedType === void 0;
    }
    return true;
  }
  function channelSupportScaleType(channel, scaleType2, hasNestedOffsetScale = false) {
    if (!isScaleChannel(channel)) {
      return false;
    }
    switch (channel) {
      case X3:
      case Y3:
      case XOFFSET:
      case YOFFSET:
      case THETA:
      case RADIUS:
        if (isContinuousToContinuous(scaleType2)) {
          return true;
        } else if (scaleType2 === "band") {
          return true;
        } else if (scaleType2 === "point") {
          return !hasNestedOffsetScale;
        }
        return false;
      case TIME:
        return contains2(["linear", "band"], scaleType2);
      case SIZE2:
      // TODO: size and opacity can support ordinal with more modification
      case STROKEWIDTH:
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
      case ANGLE:
        return isContinuousToContinuous(scaleType2) || isContinuousToDiscrete(scaleType2) || contains2(["band", "point", "ordinal"], scaleType2);
      case COLOR:
      case FILL:
      case STROKE:
        return scaleType2 !== "band";
      // band does not make sense with color
      case STROKEDASH:
      case SHAPE:
        return scaleType2 === "ordinal" || isContinuousToDiscrete(scaleType2);
    }
  }

  // node_modules/vega-lite/build/src/invalid.js
  function isScaleInvalidDataIncludeAsValue(invalidDataMode) {
    return isObject(invalidDataMode) && "value" in invalidDataMode;
  }

  // node_modules/vega-lite/build/src/mark.js
  var Mark3 = {
    arc: "arc",
    area: "area",
    bar: "bar",
    image: "image",
    line: "line",
    point: "point",
    rect: "rect",
    rule: "rule",
    text: "text",
    tick: "tick",
    trail: "trail",
    circle: "circle",
    square: "square",
    geoshape: "geoshape"
  };
  var ARC = Mark3.arc;
  var AREA = Mark3.area;
  var BAR = Mark3.bar;
  var IMAGE = Mark3.image;
  var LINE = Mark3.line;
  var POINT = Mark3.point;
  var RECT = Mark3.rect;
  var RULE = Mark3.rule;
  var TEXT2 = Mark3.text;
  var TICK = Mark3.tick;
  var TRAIL = Mark3.trail;
  var CIRCLE = Mark3.circle;
  var SQUARE = Mark3.square;
  var GEOSHAPE = Mark3.geoshape;
  function isPathMark(m4) {
    return ["line", "area", "trail"].includes(m4);
  }
  function isRectBasedMark(m4) {
    return [
      "rect",
      "bar",
      "image",
      "arc",
      "tick"
      /* arc is rect/interval in polar coordinate */
    ].includes(m4);
  }
  var PRIMITIVE_MARKS = new Set(keys3(Mark3));
  function isMarkDef(mark) {
    return hasProperty(mark, "type");
  }
  var STROKE_CONFIG = [
    "stroke",
    "strokeWidth",
    "strokeDash",
    "strokeDashOffset",
    "strokeOpacity",
    "strokeJoin",
    "strokeMiterLimit"
  ];
  var FILL_CONFIG = ["fill", "fillOpacity"];
  var FILL_STROKE_CONFIG = [...STROKE_CONFIG, ...FILL_CONFIG];
  var VL_ONLY_MARK_CONFIG_INDEX = {
    color: 1,
    filled: 1,
    invalid: 1,
    order: 1,
    radius2: 1,
    theta2: 1,
    timeUnitBandSize: 1,
    timeUnitBandPosition: 1
  };
  var VL_ONLY_MARK_CONFIG_PROPERTIES = keys3(VL_ONLY_MARK_CONFIG_INDEX);
  var VL_ONLY_RECT_CONFIG = [
    "binSpacing",
    "continuousBandSize",
    "discreteBandSize",
    "minBandSize"
  ];
  var VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
    area: ["line", "point"],
    bar: VL_ONLY_RECT_CONFIG,
    rect: VL_ONLY_RECT_CONFIG,
    line: ["point"],
    tick: ["bandSize", "thickness", ...VL_ONLY_RECT_CONFIG]
  };
  var defaultMarkConfig = {
    color: "#4c78a8",
    invalid: "break-paths-show-path-domains",
    timeUnitBandSize: 1
  };
  var MARK_CONFIG_INDEX = {
    mark: 1,
    arc: 1,
    area: 1,
    bar: 1,
    circle: 1,
    image: 1,
    line: 1,
    point: 1,
    rect: 1,
    rule: 1,
    square: 1,
    text: 1,
    tick: 1,
    trail: 1,
    geoshape: 1
  };
  var MARK_CONFIGS = keys3(MARK_CONFIG_INDEX);
  function isRelativeBandSize(o2) {
    return hasProperty(o2, "band");
  }
  var BAR_CORNER_RADIUS_INDEX = {
    horizontal: ["cornerRadiusTopRight", "cornerRadiusBottomRight"],
    vertical: ["cornerRadiusTopLeft", "cornerRadiusTopRight"]
  };
  var DEFAULT_RECT_BAND_SIZE = 5;
  var defaultRectConfig = {
    binSpacing: 0,
    continuousBandSize: DEFAULT_RECT_BAND_SIZE,
    minBandSize: 0.25,
    timeUnitBandPosition: 0.5
  };
  var defaultBarConfig = {
    ...defaultRectConfig,
    binSpacing: 1
  };
  var defaultTickConfig = {
    ...defaultRectConfig,
    thickness: 1
  };
  function getMarkType(m4) {
    return isMarkDef(m4) ? m4.type : m4;
  }

  // node_modules/vega-lite/build/src/compile/invalid/normalizeInvalidDataMode.js
  function normalizeInvalidDataMode(mode, { isPath }) {
    if (mode === void 0 || mode === "break-paths-show-path-domains") {
      return isPath ? "break-paths-show-domains" : "filter";
    } else if (mode === null) {
      return "show";
    }
    return mode;
  }

  // node_modules/vega-lite/build/src/compile/invalid/ScaleInvalidDataMode.js
  function getScaleInvalidDataMode({ markDef, config, scaleChannel, scaleType: scaleType2, isCountAggregate }) {
    if (!scaleType2 || !hasContinuousDomain(scaleType2) || isCountAggregate) {
      return "always-valid";
    }
    const invalidMode = normalizeInvalidDataMode(getMarkPropOrConfig("invalid", markDef, config), {
      isPath: isPathMark(markDef.type)
    });
    const scaleOutputForInvalid = config.scale?.invalid?.[scaleChannel];
    if (scaleOutputForInvalid !== void 0) {
      return "show";
    }
    return invalidMode;
  }
  function shouldBreakPath(mode) {
    return mode === "break-paths-filter-domains" || mode === "break-paths-show-domains";
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/scaledZeroOrMinOrMax.js
  function scaledZeroOrMinOrMax({ scaleName, scale: scale7, mode }) {
    const domain4 = `domain('${scaleName}')`;
    if (!scale7 || !scaleName) {
      return void 0;
    }
    const min4 = `${domain4}[0]`;
    const max4 = `peek(${domain4})`;
    const domainHasZero = scale7.domainHasZero();
    if (domainHasZero === "definitely") {
      return {
        scale: scaleName,
        value: 0
      };
    } else if (domainHasZero === "maybe") {
      const nonZeroValue = mode === "zeroOrMin" ? min4 : max4;
      return { signal: `scale('${scaleName}', inrange(0, ${domain4}) ? 0 : ${nonZeroValue})` };
    } else {
      return { signal: `scale('${scaleName}', ${mode === "zeroOrMin" ? min4 : max4})` };
    }
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/invalid.js
  function getConditionalValueRefForIncludingInvalidValue({ scaleChannel, channelDef, scale: scale7, scaleName, markDef, config }) {
    const scaleType2 = scale7?.get("type");
    const fieldDef = getFieldDef(channelDef);
    const isCountAggregate = isCountingAggregateOp(fieldDef?.aggregate);
    const invalidDataMode = getScaleInvalidDataMode({
      scaleChannel,
      markDef,
      config,
      scaleType: scaleType2,
      isCountAggregate
    });
    if (fieldDef && invalidDataMode === "show") {
      const includeAs = config.scale.invalid?.[scaleChannel] ?? "zero-or-min";
      return {
        test: fieldValidPredicate(vgField(fieldDef, { expr: "datum" }), false),
        ...refForInvalidValues(includeAs, scale7, scaleName)
      };
    }
    return void 0;
  }
  function refForInvalidValues(includeAs, scale7, scaleName) {
    if (isScaleInvalidDataIncludeAsValue(includeAs)) {
      const { value: value3 } = includeAs;
      return isSignalRef(value3) ? { signal: value3.signal } : { value: value3 };
    }
    return scaledZeroOrMinOrMax({
      scale: scale7,
      scaleName,
      mode: "zeroOrMin"
    });
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/valueref.js
  function midPointRefWithPositionInvalidTest(params2) {
    const { channel, channelDef, markDef, scale: scale7, scaleName, config } = params2;
    const scaleChannel = getMainRangeChannel(channel);
    const mainRef = midPoint(params2);
    const valueRefForIncludingInvalid = getConditionalValueRefForIncludingInvalidValue({
      scaleChannel,
      channelDef,
      scale: scale7,
      scaleName,
      markDef,
      config
    });
    return valueRefForIncludingInvalid !== void 0 ? [valueRefForIncludingInvalid, mainRef] : mainRef;
  }
  function datumDefToExpr(datumDef) {
    const { datum: datum2 } = datumDef;
    if (isDateTime(datum2)) {
      return dateTimeToExpr(datum2);
    }
    return `${stringify2(datum2)}`;
  }
  function valueRefForFieldOrDatumDef(fieldDef, scaleName, opt, encode2) {
    const ref2 = {};
    if (scaleName) {
      ref2.scale = scaleName;
    }
    if (isDatumDef(fieldDef)) {
      const { datum: datum2 } = fieldDef;
      if (isDateTime(datum2)) {
        ref2.signal = dateTimeToExpr(datum2);
      } else if (isSignalRef(datum2)) {
        ref2.signal = datum2.signal;
      } else if (isExprRef(datum2)) {
        ref2.signal = datum2.expr;
      } else {
        ref2.value = datum2;
      }
    } else {
      ref2.field = vgField(fieldDef, opt);
    }
    if (encode2) {
      const { offset: offset4, band: band2 } = encode2;
      if (offset4) {
        ref2.offset = offset4;
      }
      if (band2) {
        ref2.band = band2;
      }
    }
    return ref2;
  }
  function interpolatedSignalRef({ scaleName, fieldOrDatumDef, fieldOrDatumDef2, offset: offset4, startSuffix, endSuffix = "end", bandPosition = 0.5 }) {
    const expr2 = !isSignalRef(bandPosition) && 0 < bandPosition && bandPosition < 1 ? "datum" : void 0;
    const start = vgField(fieldOrDatumDef, { expr: expr2, suffix: startSuffix });
    const end = fieldOrDatumDef2 !== void 0 ? vgField(fieldOrDatumDef2, { expr: expr2 }) : vgField(fieldOrDatumDef, { suffix: endSuffix, expr: expr2 });
    const ref2 = {};
    if (bandPosition === 0 || bandPosition === 1) {
      ref2.scale = scaleName;
      const field3 = bandPosition === 0 ? start : end;
      ref2.field = field3;
    } else {
      const datum2 = isSignalRef(bandPosition) ? `(1-${bandPosition.signal}) * ${start} + ${bandPosition.signal} * ${end}` : `${1 - bandPosition} * ${start} + ${bandPosition} * ${end}`;
      ref2.signal = `scale("${scaleName}", ${datum2})`;
    }
    if (offset4) {
      ref2.offset = offset4;
    }
    return ref2;
  }
  function binSizeExpr({ scaleName, fieldDef }) {
    const start = vgField(fieldDef, { expr: "datum" });
    const end = vgField(fieldDef, { expr: "datum", suffix: "end" });
    return `abs(scale("${scaleName}", ${end}) - scale("${scaleName}", ${start}))`;
  }
  function midPoint({ channel, channelDef, channel2Def, markDef, config, scaleName, scale: scale7, stack: stack2, offset: offset4, defaultRef, bandPosition }) {
    if (channelDef) {
      if (isFieldOrDatumDef(channelDef)) {
        const scaleType2 = scale7?.get("type");
        if (isTypedFieldDef(channelDef)) {
          bandPosition ?? (bandPosition = getBandPosition({
            fieldDef: channelDef,
            fieldDef2: channel2Def,
            markDef,
            config
          }));
          const { bin: bin3, timeUnit, type: type3 } = channelDef;
          if (isBinning(bin3) || bandPosition && timeUnit && type3 === TEMPORAL) {
            if (stack2?.impute) {
              return valueRefForFieldOrDatumDef(channelDef, scaleName, { binSuffix: "mid" }, { offset: offset4 });
            }
            if (bandPosition && !hasDiscreteDomain(scaleType2)) {
              return interpolatedSignalRef({ scaleName, fieldOrDatumDef: channelDef, bandPosition, offset: offset4 });
            }
            return valueRefForFieldOrDatumDef(channelDef, scaleName, binRequiresRange(channelDef, channel) ? { binSuffix: "range" } : {}, {
              offset: offset4
            });
          } else if (isBinned(bin3)) {
            if (isFieldDef(channel2Def)) {
              return interpolatedSignalRef({
                scaleName,
                fieldOrDatumDef: channelDef,
                fieldOrDatumDef2: channel2Def,
                bandPosition,
                offset: offset4
              });
            } else {
              const channel2 = channel === X3 ? X23 : Y23;
              warn2(message_exports.channelRequiredForBinned(channel2));
            }
          }
        }
        return valueRefForFieldOrDatumDef(
          channelDef,
          scaleName,
          hasDiscreteDomain(scaleType2) ? { binSuffix: "range" } : {},
          // no need for bin suffix if there is no scale
          {
            offset: offset4,
            // For band, to get mid point, need to offset by half of the band
            band: scaleType2 === "band" ? bandPosition ?? channelDef.bandPosition ?? 0.5 : void 0
          }
        );
      } else if (isValueDef(channelDef)) {
        const value3 = channelDef.value;
        const offsetMixins = offset4 ? { offset: offset4 } : {};
        return { ...widthHeightValueOrSignalRef(channel, value3), ...offsetMixins };
      }
    }
    if (isFunction(defaultRef)) {
      defaultRef = defaultRef();
    }
    if (defaultRef) {
      return {
        ...defaultRef,
        // only include offset when it is non-zero (zero = no offset)
        ...offset4 ? { offset: offset4 } : {}
      };
    }
    return defaultRef;
  }
  function widthHeightValueOrSignalRef(channel, value3) {
    if (contains2(["x", "x2"], channel) && value3 === "width") {
      return { field: { group: "width" } };
    } else if (contains2(["y", "y2"], channel) && value3 === "height") {
      return { field: { group: "height" } };
    }
    return signalOrValueRef(value3);
  }

  // node_modules/vega-lite/build/src/compile/format.js
  function isCustomFormatType(formatType) {
    return formatType && formatType !== "number" && formatType !== "time";
  }
  function customFormatExpr(formatType, field3, format5) {
    return `${formatType}(${field3}${format5 ? `, ${stringify2(format5)}` : ""})`;
  }
  var BIN_RANGE_DELIMITER = " \u2013 ";
  function formatSignalRef({ fieldOrDatumDef, format: format5, formatType, expr: expr2, normalizeStack, config }) {
    if (isCustomFormatType(formatType)) {
      return formatCustomType({
        fieldOrDatumDef,
        format: format5,
        formatType,
        expr: expr2,
        config
      });
    }
    const field3 = fieldToFormat(fieldOrDatumDef, expr2, normalizeStack);
    const type3 = channelDefType(fieldOrDatumDef);
    if (format5 === void 0 && formatType === void 0 && config.customFormatTypes) {
      if (type3 === "quantitative") {
        if (normalizeStack && config.normalizedNumberFormatType)
          return formatCustomType({
            fieldOrDatumDef,
            format: config.normalizedNumberFormat,
            formatType: config.normalizedNumberFormatType,
            expr: expr2,
            config
          });
        if (config.numberFormatType) {
          return formatCustomType({
            fieldOrDatumDef,
            format: config.numberFormat,
            formatType: config.numberFormatType,
            expr: expr2,
            config
          });
        }
      }
      if (type3 === "temporal" && config.timeFormatType && isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit === void 0) {
        return formatCustomType({
          fieldOrDatumDef,
          format: config.timeFormat,
          formatType: config.timeFormatType,
          expr: expr2,
          config
        });
      }
    }
    if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {
      const signal = timeFormatExpression({
        field: field3,
        timeUnit: isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : void 0,
        format: format5,
        formatType: config.timeFormatType,
        rawTimeFormat: config.timeFormat,
        isUTCScale: isScaleFieldDef(fieldOrDatumDef) && fieldOrDatumDef.scale?.type === ScaleType.UTC
      });
      return signal ? { signal } : void 0;
    }
    format5 = numberFormat({ type: type3, specifiedFormat: format5, config, normalizeStack });
    if (isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {
      const endField = vgField(fieldOrDatumDef, { expr: expr2, binSuffix: "end" });
      return {
        signal: binFormatExpression(field3, endField, format5, formatType, config)
      };
    } else if (format5 || channelDefType(fieldOrDatumDef) === "quantitative") {
      return {
        signal: `${formatExpr(field3, format5)}`
      };
    } else {
      return { signal: `isValid(${field3}) ? ${field3} : ""+${field3}` };
    }
  }
  function fieldToFormat(fieldOrDatumDef, expr2, normalizeStack) {
    if (isFieldDef(fieldOrDatumDef)) {
      if (normalizeStack) {
        return `${vgField(fieldOrDatumDef, { expr: expr2, suffix: "end" })}-${vgField(fieldOrDatumDef, {
          expr: expr2,
          suffix: "start"
        })}`;
      } else {
        return vgField(fieldOrDatumDef, { expr: expr2 });
      }
    } else {
      return datumDefToExpr(fieldOrDatumDef);
    }
  }
  function formatCustomType({ fieldOrDatumDef, format: format5, formatType, expr: expr2, normalizeStack, config, field: field3 }) {
    field3 ?? (field3 = fieldToFormat(fieldOrDatumDef, expr2, normalizeStack));
    if (field3 !== "datum.value" && // For axis/legend, we can't correctly know the end of the bin from `datum`
    isFieldDef(fieldOrDatumDef) && isBinning(fieldOrDatumDef.bin)) {
      const endField = vgField(fieldOrDatumDef, { expr: expr2, binSuffix: "end" });
      return {
        signal: binFormatExpression(field3, endField, format5, formatType, config)
      };
    }
    return { signal: customFormatExpr(formatType, field3, format5) };
  }
  function guideFormat(fieldOrDatumDef, type3, format5, formatType, config, omitTimeFormatConfig) {
    if (isString(formatType) && isCustomFormatType(formatType)) {
      return void 0;
    } else if (format5 === void 0 && formatType === void 0 && config.customFormatTypes) {
      if (channelDefType(fieldOrDatumDef) === "quantitative") {
        if (config.normalizedNumberFormatType && isPositionFieldOrDatumDef(fieldOrDatumDef) && fieldOrDatumDef.stack === "normalize") {
          return void 0;
        }
        if (config.numberFormatType) {
          return void 0;
        }
      }
    }
    if (isPositionFieldOrDatumDef(fieldOrDatumDef) && fieldOrDatumDef.stack === "normalize" && config.normalizedNumberFormat) {
      return numberFormat({
        type: "quantitative",
        config,
        normalizeStack: true
      });
    }
    if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef)) {
      const timeUnit = isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : void 0;
      if (timeUnit === void 0 && config.customFormatTypes && config.timeFormatType) {
        return void 0;
      }
      return timeFormat3({ specifiedFormat: format5, timeUnit, config, omitTimeFormatConfig });
    }
    return numberFormat({ type: type3, specifiedFormat: format5, config });
  }
  function guideFormatType(formatType, fieldOrDatumDef, scaleType2) {
    if (formatType && (isSignalRef(formatType) || formatType === "number" || formatType === "time")) {
      return formatType;
    }
    if (isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) && scaleType2 !== "time" && scaleType2 !== "utc") {
      return isFieldDef(fieldOrDatumDef) && normalizeTimeUnit(fieldOrDatumDef?.timeUnit)?.utc ? "utc" : "time";
    }
    return void 0;
  }
  function numberFormat({ type: type3, specifiedFormat, config, normalizeStack }) {
    if (isString(specifiedFormat)) {
      return specifiedFormat;
    }
    if (type3 === QUANTITATIVE) {
      return normalizeStack ? config.normalizedNumberFormat : config.numberFormat;
    }
    return void 0;
  }
  function timeFormat3({ specifiedFormat, timeUnit, config, omitTimeFormatConfig }) {
    if (specifiedFormat) {
      return specifiedFormat;
    }
    if (timeUnit) {
      return {
        signal: timeUnitSpecifierExpression(timeUnit)
      };
    }
    return omitTimeFormatConfig ? void 0 : config.timeFormat;
  }
  function formatExpr(field3, format5) {
    return `format(${field3}, "${format5 || ""}")`;
  }
  function binNumberFormatExpr(field3, format5, formatType, config) {
    if (isCustomFormatType(formatType)) {
      return customFormatExpr(formatType, field3, format5);
    }
    return formatExpr(field3, (isString(format5) ? format5 : void 0) ?? config.numberFormat);
  }
  function binFormatExpression(startField, endField, format5, formatType, config) {
    if (format5 === void 0 && formatType === void 0 && config.customFormatTypes && config.numberFormatType) {
      return binFormatExpression(startField, endField, config.numberFormat, config.numberFormatType, config);
    }
    const start = binNumberFormatExpr(startField, format5, formatType, config);
    const end = binNumberFormatExpr(endField, format5, formatType, config);
    return `${fieldValidPredicate(startField, false)} ? "null" : ${start} + "${BIN_RANGE_DELIMITER}" + ${end}`;
  }
  function timeFormatExpression({ field: field3, timeUnit, format: format5, formatType, rawTimeFormat, isUTCScale }) {
    if (!timeUnit || format5) {
      if (!timeUnit && formatType) {
        return `${formatType}(${field3}, '${format5}')`;
      }
      format5 = isString(format5) ? format5 : rawTimeFormat;
      return `${isUTCScale ? "utc" : "time"}Format(${field3}, '${format5}')`;
    } else {
      return formatExpression(timeUnit, field3, isUTCScale);
    }
  }

  // node_modules/vega-lite/build/src/sort.js
  var DEFAULT_SORT_OP = "min";
  var SORT_BY_CHANNEL_INDEX = {
    x: 1,
    y: 1,
    color: 1,
    fill: 1,
    stroke: 1,
    strokeWidth: 1,
    size: 1,
    shape: 1,
    fillOpacity: 1,
    strokeOpacity: 1,
    opacity: 1,
    text: 1
  };
  function isSortByChannel(c4) {
    return has(SORT_BY_CHANNEL_INDEX, c4);
  }
  function isSortByEncoding(sort3) {
    return hasProperty(sort3, "encoding");
  }
  function isSortField(sort3) {
    return sort3 && (sort3.op === "count" || hasProperty(sort3, "field"));
  }
  function isSortArray(sort3) {
    return sort3 && isArray(sort3);
  }

  // node_modules/vega-lite/build/src/spec/facet.js
  function isFacetMapping(f2) {
    return hasProperty(f2, "row") || hasProperty(f2, "column");
  }
  function isFacetFieldDef(channelDef) {
    return hasProperty(channelDef, "header");
  }
  function isFacetSpec(spec) {
    return hasProperty(spec, "facet");
  }

  // node_modules/vega-lite/build/src/channeldef.js
  function isConditionalParameter(c4) {
    return hasProperty(c4, "param");
  }
  function isRepeatRef(field3) {
    return !isString(field3) && hasProperty(field3, "repeat");
  }
  function toFieldDefBase(fieldDef) {
    const { field: field3, timeUnit, bin: bin3, aggregate } = fieldDef;
    return {
      ...timeUnit ? { timeUnit } : {},
      ...bin3 ? { bin: bin3 } : {},
      ...aggregate ? { aggregate } : {},
      field: field3
    };
  }
  function isSortableFieldDef(fieldDef) {
    return hasProperty(fieldDef, "sort");
  }
  function getBandPosition({ fieldDef, fieldDef2, markDef: mark, config }) {
    if (isFieldOrDatumDef(fieldDef) && fieldDef.bandPosition !== void 0) {
      return fieldDef.bandPosition;
    }
    if (isFieldDef(fieldDef)) {
      const { timeUnit, bin: bin3 } = fieldDef;
      if (timeUnit && !fieldDef2) {
        return getMarkConfig("timeUnitBandPosition", mark, config);
      } else if (isBinning(bin3)) {
        return 0.5;
      }
    }
    return void 0;
  }
  function getBandSize({ channel, fieldDef, fieldDef2, markDef: mark, config, scaleType: scaleType2, useVlSizeChannel }) {
    const sizeChannel = getSizeChannel(channel);
    const size = getMarkPropOrConfig(useVlSizeChannel ? "size" : sizeChannel, mark, config, {
      vgChannel: sizeChannel
    });
    if (size !== void 0) {
      return size;
    }
    if (isFieldDef(fieldDef)) {
      const { timeUnit, bin: bin3 } = fieldDef;
      if (timeUnit && !fieldDef2) {
        return { band: getMarkConfig("timeUnitBandSize", mark, config) };
      } else if (isBinning(bin3) && !hasDiscreteDomain(scaleType2)) {
        return { band: 1 };
      }
    }
    if (isRectBasedMark(mark.type)) {
      if (scaleType2) {
        if (hasDiscreteDomain(scaleType2)) {
          return config[mark.type]?.discreteBandSize || { band: 1 };
        } else {
          return config[mark.type]?.continuousBandSize;
        }
      }
      return config[mark.type]?.discreteBandSize;
    }
    return void 0;
  }
  function hasBandEnd(fieldDef, fieldDef2, markDef, config) {
    if (isBinning(fieldDef.bin) || fieldDef.timeUnit && isTypedFieldDef(fieldDef) && fieldDef.type === "temporal") {
      return getBandPosition({ fieldDef, fieldDef2, markDef, config }) !== void 0;
    }
    return false;
  }
  function isOrderOnlyDef(orderDef) {
    return hasProperty(orderDef, "sort") && !hasProperty(orderDef, "field");
  }
  function isConditionalDef(channelDef) {
    return hasProperty(channelDef, "condition");
  }
  function hasConditionalFieldDef(channelDef) {
    const condition = channelDef?.["condition"];
    return !!condition && !isArray(condition) && isFieldDef(condition);
  }
  function hasConditionalFieldOrDatumDef(channelDef) {
    const condition = channelDef?.["condition"];
    return !!condition && !isArray(condition) && isFieldOrDatumDef(condition);
  }
  function hasConditionalValueDef(channelDef) {
    const condition = channelDef?.["condition"];
    return !!condition && (isArray(condition) || isValueDef(condition));
  }
  function isFieldDef(channelDef) {
    return hasProperty(channelDef, "field") || channelDef?.aggregate === "count";
  }
  function channelDefType(channelDef) {
    return channelDef?.["type"];
  }
  function isDatumDef(channelDef) {
    return hasProperty(channelDef, "datum");
  }
  function isContinuousFieldOrDatumDef(cd2) {
    return isTypedFieldDef(cd2) && !isDiscrete3(cd2) || isNumericDataDef(cd2);
  }
  function isUnbinnedQuantitativeFieldOrDatumDef(cd2) {
    return isTypedFieldDef(cd2) && cd2.type === "quantitative" && !cd2.bin || isNumericDataDef(cd2);
  }
  function isNumericDataDef(cd2) {
    return isDatumDef(cd2) && isNumber(cd2.datum);
  }
  function isFieldOrDatumDef(channelDef) {
    return isFieldDef(channelDef) || isDatumDef(channelDef);
  }
  function isTypedFieldDef(channelDef) {
    return channelDef && (hasProperty(channelDef, "field") || channelDef["aggregate"] === "count") && hasProperty(channelDef, "type");
  }
  function isValueDef(channelDef) {
    return hasProperty(channelDef, "value");
  }
  function isScaleFieldDef(channelDef) {
    return hasProperty(channelDef, "scale") || hasProperty(channelDef, "sort");
  }
  function isPositionFieldOrDatumDef(channelDef) {
    return hasProperty(channelDef, "axis") || hasProperty(channelDef, "stack") || hasProperty(channelDef, "impute");
  }
  function isMarkPropFieldOrDatumDef(channelDef) {
    return hasProperty(channelDef, "legend");
  }
  function isStringFieldOrDatumDef(channelDef) {
    return hasProperty(channelDef, "format") || hasProperty(channelDef, "formatType");
  }
  function toStringFieldDef(fieldDef) {
    return omit(fieldDef, ["legend", "axis", "header", "scale"]);
  }
  function isOpFieldDef(fieldDef) {
    return hasProperty(fieldDef, "op");
  }
  function vgField(fieldDef, opt = {}) {
    let field3 = fieldDef.field;
    const prefix = opt.prefix;
    let suffix = opt.suffix;
    let argAccessor = "";
    if (isCount(fieldDef)) {
      field3 = internalField("count");
    } else {
      let fn;
      if (!opt.nofn) {
        if (isOpFieldDef(fieldDef)) {
          fn = fieldDef.op;
        } else {
          const { bin: bin3, aggregate, timeUnit } = fieldDef;
          if (isBinning(bin3)) {
            fn = binToString(bin3);
            suffix = (opt.binSuffix ?? "") + (opt.suffix ?? "");
          } else if (aggregate) {
            if (isArgmaxDef(aggregate)) {
              argAccessor = `["${field3}"]`;
              field3 = `argmax_${aggregate.argmax}`;
            } else if (isArgminDef(aggregate)) {
              argAccessor = `["${field3}"]`;
              field3 = `argmin_${aggregate.argmin}`;
            } else {
              fn = String(aggregate);
            }
          } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {
            fn = timeUnitToString(timeUnit);
            suffix = (!["range", "mid"].includes(opt.binSuffix) && opt.binSuffix || "") + (opt.suffix ?? "");
          }
        }
      }
      if (fn) {
        field3 = field3 ? `${fn}_${field3}` : fn;
      }
    }
    if (suffix) {
      field3 = `${field3}_${suffix}`;
    }
    if (prefix) {
      field3 = `${prefix}_${field3}`;
    }
    if (opt.forAs) {
      return removePathFromField(field3);
    } else if (opt.expr) {
      return flatAccessWithDatum(field3, opt.expr) + argAccessor;
    } else {
      return replacePathInField(field3) + argAccessor;
    }
  }
  function isDiscrete3(def2) {
    switch (def2.type) {
      case "nominal":
      case "ordinal":
      case "geojson":
        return true;
      case "quantitative":
        return isFieldDef(def2) && !!def2.bin;
      case "temporal":
        return false;
    }
    throw new Error(message_exports.invalidFieldType(def2.type));
  }
  function isDiscretizing2(def2) {
    return isScaleFieldDef(def2) && isContinuousToDiscrete(def2.scale?.type);
  }
  function isCount(fieldDef) {
    return fieldDef.aggregate === "count";
  }
  function verbalTitleFormatter(fieldDef, config) {
    const { field: field3, bin: bin3, timeUnit, aggregate } = fieldDef;
    if (aggregate === "count") {
      return config.countTitle;
    } else if (isBinning(bin3)) {
      return `${field3} (binned)`;
    } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {
      const unit2 = normalizeTimeUnit(timeUnit)?.unit;
      if (unit2) {
        return `${field3} (${getTimeUnitParts(unit2).join("-")})`;
      }
    } else if (aggregate) {
      if (isArgmaxDef(aggregate)) {
        return `${field3} for max ${aggregate.argmax}`;
      } else if (isArgminDef(aggregate)) {
        return `${field3} for min ${aggregate.argmin}`;
      } else {
        return `${titleCase(aggregate)} of ${field3}`;
      }
    }
    return field3;
  }
  function functionalTitleFormatter(fieldDef) {
    const { aggregate, bin: bin3, timeUnit, field: field3 } = fieldDef;
    if (isArgmaxDef(aggregate)) {
      return `${field3} for argmax(${aggregate.argmax})`;
    } else if (isArgminDef(aggregate)) {
      return `${field3} for argmin(${aggregate.argmin})`;
    }
    const timeUnitParams = timeUnit && !isBinnedTimeUnit(timeUnit) ? normalizeTimeUnit(timeUnit) : void 0;
    const fn = aggregate || timeUnitParams?.unit || timeUnitParams?.maxbins && "timeunit" || isBinning(bin3) && "bin";
    return fn ? `${fn.toUpperCase()}(${field3})` : field3;
  }
  var defaultTitleFormatter = (fieldDef, config) => {
    switch (config.fieldTitle) {
      case "plain":
        return fieldDef.field;
      case "functional":
        return functionalTitleFormatter(fieldDef);
      default:
        return verbalTitleFormatter(fieldDef, config);
    }
  };
  var titleFormatter = defaultTitleFormatter;
  function setTitleFormatter(formatter) {
    titleFormatter = formatter;
  }
  function resetTitleFormatter() {
    setTitleFormatter(defaultTitleFormatter);
  }
  function title(fieldOrDatumDef, config, { allowDisabling, includeDefault = true }) {
    const guideTitle = getGuide(fieldOrDatumDef)?.title;
    if (!isFieldDef(fieldOrDatumDef)) {
      return guideTitle ?? fieldOrDatumDef.title;
    }
    const fieldDef = fieldOrDatumDef;
    const def2 = includeDefault ? defaultTitle(fieldDef, config) : void 0;
    if (allowDisabling) {
      return getFirstDefined(guideTitle, fieldDef.title, def2);
    } else {
      return guideTitle ?? fieldDef.title ?? def2;
    }
  }
  function getGuide(fieldDef) {
    if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis) {
      return fieldDef.axis;
    } else if (isMarkPropFieldOrDatumDef(fieldDef) && fieldDef.legend) {
      return fieldDef.legend;
    } else if (isFacetFieldDef(fieldDef) && fieldDef.header) {
      return fieldDef.header;
    }
    return void 0;
  }
  function defaultTitle(fieldDef, config) {
    return titleFormatter(fieldDef, config);
  }
  function getFormatMixins(fieldDef) {
    if (isStringFieldOrDatumDef(fieldDef)) {
      const { format: format5, formatType } = fieldDef;
      return { format: format5, formatType };
    } else {
      const guide = getGuide(fieldDef) ?? {};
      const { format: format5, formatType } = guide;
      return { format: format5, formatType };
    }
  }
  function defaultType(fieldDef, channel) {
    switch (channel) {
      case "latitude":
      case "longitude":
        return "quantitative";
      case "row":
      case "column":
      case "facet":
      case "shape":
      case "strokeDash":
        return "nominal";
      case "order":
        return "ordinal";
    }
    if (isSortableFieldDef(fieldDef) && isArray(fieldDef.sort)) {
      return "ordinal";
    }
    const { aggregate, bin: bin3, timeUnit } = fieldDef;
    if (timeUnit) {
      return "temporal";
    }
    if (bin3 || aggregate && !isArgmaxDef(aggregate) && !isArgminDef(aggregate)) {
      return "quantitative";
    }
    if (isScaleFieldDef(fieldDef) && fieldDef.scale?.type) {
      switch (SCALE_CATEGORY_INDEX[fieldDef.scale.type]) {
        case "numeric":
        case "discretizing":
          return "quantitative";
        case "time":
          return "temporal";
      }
    }
    return "nominal";
  }
  function getFieldDef(channelDef) {
    if (isFieldDef(channelDef)) {
      return channelDef;
    } else if (hasConditionalFieldDef(channelDef)) {
      return channelDef.condition;
    }
    return void 0;
  }
  function getFieldOrDatumDef(channelDef) {
    if (isFieldOrDatumDef(channelDef)) {
      return channelDef;
    } else if (hasConditionalFieldOrDatumDef(channelDef)) {
      return channelDef.condition;
    }
    return void 0;
  }
  function initChannelDef(channelDef, channel, config, opt = {}) {
    if (isString(channelDef) || isNumber(channelDef) || isBoolean(channelDef)) {
      const primitiveType = isString(channelDef) ? "string" : isNumber(channelDef) ? "number" : "boolean";
      warn2(message_exports.primitiveChannelDef(channel, primitiveType, channelDef));
      return { value: channelDef };
    }
    if (isFieldOrDatumDef(channelDef)) {
      return initFieldOrDatumDef(channelDef, channel, config, opt);
    } else if (hasConditionalFieldOrDatumDef(channelDef)) {
      return {
        ...channelDef,
        // Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition<FieldDef>
        condition: initFieldOrDatumDef(channelDef.condition, channel, config, opt)
      };
    }
    return channelDef;
  }
  function initFieldOrDatumDef(fd, channel, config, opt) {
    if (isStringFieldOrDatumDef(fd)) {
      const { format: format5, formatType, ...rest } = fd;
      if (isCustomFormatType(formatType) && !config.customFormatTypes) {
        warn2(message_exports.customFormatTypeNotAllowed(channel));
        return initFieldOrDatumDef(rest, channel, config, opt);
      }
    } else {
      const guideType = isPositionFieldOrDatumDef(fd) ? "axis" : isMarkPropFieldOrDatumDef(fd) ? "legend" : isFacetFieldDef(fd) ? "header" : null;
      if (guideType && fd[guideType]) {
        const { format: format5, formatType, ...newGuide } = fd[guideType];
        if (isCustomFormatType(formatType) && !config.customFormatTypes) {
          warn2(message_exports.customFormatTypeNotAllowed(channel));
          return initFieldOrDatumDef({ ...fd, [guideType]: newGuide }, channel, config, opt);
        }
      }
    }
    if (isFieldDef(fd)) {
      return initFieldDef(fd, channel, opt);
    }
    return initDatumDef(fd);
  }
  function initDatumDef(datumDef) {
    let type3 = datumDef["type"];
    if (type3) {
      return datumDef;
    }
    const { datum: datum2 } = datumDef;
    type3 = isNumber(datum2) ? "quantitative" : isString(datum2) ? "nominal" : isDateTime(datum2) ? "temporal" : void 0;
    return { ...datumDef, type: type3 };
  }
  function initFieldDef(fd, channel, { compositeMark = false } = {}) {
    const { aggregate, timeUnit, bin: bin3, field: field3 } = fd;
    const fieldDef = { ...fd };
    if (!compositeMark && aggregate && !isAggregateOp(aggregate) && !isArgmaxDef(aggregate) && !isArgminDef(aggregate)) {
      warn2(message_exports.invalidAggregate(aggregate));
      delete fieldDef.aggregate;
    }
    if (timeUnit) {
      fieldDef.timeUnit = normalizeTimeUnit(timeUnit);
    }
    if (field3) {
      fieldDef.field = `${field3}`;
    }
    if (isBinning(bin3)) {
      fieldDef.bin = normalizeBin(bin3, channel);
    }
    if (isBinned(bin3) && !isXorY(channel)) {
      warn2(message_exports.channelShouldNotBeUsedForBinned(channel));
    }
    if (isTypedFieldDef(fieldDef)) {
      const { type: type3 } = fieldDef;
      const fullType = getFullName(type3);
      if (type3 !== fullType) {
        fieldDef.type = fullType;
      }
      if (type3 !== "quantitative") {
        if (isCountingAggregateOp(aggregate)) {
          warn2(message_exports.invalidFieldTypeForCountAggregate(type3, aggregate));
          fieldDef.type = "quantitative";
        }
      }
    } else if (!isSecondaryRangeChannel(channel)) {
      const newType = defaultType(fieldDef, channel);
      fieldDef["type"] = newType;
    }
    if (isTypedFieldDef(fieldDef)) {
      const { compatible, warning } = channelCompatibility(fieldDef, channel) || {};
      if (compatible === false) {
        warn2(warning);
      }
    }
    if (isSortableFieldDef(fieldDef) && isString(fieldDef.sort)) {
      const { sort: sort3 } = fieldDef;
      if (isSortByChannel(sort3)) {
        return {
          ...fieldDef,
          sort: { encoding: sort3 }
        };
      }
      const sub = sort3.substring(1);
      if (sort3.charAt(0) === "-" && isSortByChannel(sub)) {
        return {
          ...fieldDef,
          sort: { encoding: sub, order: "descending" }
        };
      }
    }
    if (isFacetFieldDef(fieldDef)) {
      const { header } = fieldDef;
      if (header) {
        const { orient: orient2, ...rest } = header;
        if (orient2) {
          return {
            ...fieldDef,
            header: {
              ...rest,
              labelOrient: header.labelOrient || orient2,
              titleOrient: header.titleOrient || orient2
            }
          };
        }
      }
    }
    return fieldDef;
  }
  function normalizeBin(bin3, channel) {
    if (isBoolean(bin3)) {
      return { maxbins: autoMaxBins(channel) };
    } else if (bin3 === "binned") {
      return {
        binned: true
      };
    } else if (!bin3.maxbins && !bin3.step) {
      return { ...bin3, maxbins: autoMaxBins(channel) };
    } else {
      return bin3;
    }
  }
  var COMPATIBLE = { compatible: true };
  function channelCompatibility(fieldDef, channel) {
    const type3 = fieldDef.type;
    if (type3 === "geojson" && channel !== "shape") {
      return {
        compatible: false,
        warning: `Channel ${channel} should not be used with a geojson data.`
      };
    }
    switch (channel) {
      case ROW:
      case COLUMN:
      case FACET:
        if (!isDiscrete3(fieldDef)) {
          return {
            compatible: false,
            warning: message_exports.channelShouldBeDiscrete(channel)
          };
        }
        return COMPATIBLE;
      case X3:
      case Y3:
      case XOFFSET:
      case YOFFSET:
      case COLOR:
      case FILL:
      case STROKE:
      case TEXT:
      case DETAIL:
      case KEY:
      case TOOLTIP:
      case HREF:
      case URL2:
      case ANGLE:
      case THETA:
      case RADIUS:
      case DESCRIPTION:
        return COMPATIBLE;
      case LONGITUDE:
      case LONGITUDE2:
      case LATITUDE:
      case LATITUDE2:
        if (type3 !== QUANTITATIVE) {
          return {
            compatible: false,
            warning: `Channel ${channel} should be used with a quantitative field only, not ${fieldDef.type} field.`
          };
        }
        return COMPATIBLE;
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
      case STROKEWIDTH:
      case SIZE2:
      case THETA2:
      case RADIUS2:
      case X23:
      case Y23:
      case TIME:
        if (type3 === "nominal" && !fieldDef["sort"]) {
          return {
            compatible: false,
            warning: `Channel ${channel} should not be used with an unsorted discrete field.`
          };
        }
        return COMPATIBLE;
      case SHAPE:
      case STROKEDASH:
        if (!isDiscrete3(fieldDef) && !isDiscretizing2(fieldDef)) {
          return {
            compatible: false,
            warning: message_exports.channelShouldBeDiscreteOrDiscretizing(channel)
          };
        }
        return COMPATIBLE;
      case ORDER:
        if (fieldDef.type === "nominal" && !("sort" in fieldDef)) {
          return {
            compatible: false,
            warning: `Channel order is inappropriate for nominal field, which has no inherent order.`
          };
        }
        return COMPATIBLE;
    }
  }
  function isFieldOrDatumDefForTimeFormat(fieldOrDatumDef) {
    const { formatType } = getFormatMixins(fieldOrDatumDef);
    return formatType === "time" || !formatType && isTemporalFieldDef(fieldOrDatumDef);
  }
  function isTemporalFieldDef(def2) {
    return def2 && (def2["type"] === "temporal" || isFieldDef(def2) && !!def2.timeUnit);
  }
  function valueExpr(v3, { timeUnit, type: type3, wrapTime, undefinedIfExprNotRequired }) {
    const unit2 = timeUnit && normalizeTimeUnit(timeUnit)?.unit;
    let isTime2 = unit2 || type3 === "temporal";
    let expr2;
    if (isExprRef(v3)) {
      expr2 = v3.expr;
    } else if (isSignalRef(v3)) {
      expr2 = v3.signal;
    } else if (isDateTime(v3)) {
      isTime2 = true;
      expr2 = dateTimeToExpr(v3);
    } else if (isString(v3) || isNumber(v3)) {
      if (isTime2) {
        expr2 = `datetime(${stringify2(v3)})`;
        if (isLocalSingleTimeUnit(unit2)) {
          if (isNumber(v3) && v3 < 1e4 || isString(v3) && isNaN(Date.parse(v3))) {
            expr2 = dateTimeToExpr({ [unit2]: v3 });
          }
        }
      }
    }
    if (expr2) {
      return wrapTime && isTime2 ? `time(${expr2})` : expr2;
    }
    return undefinedIfExprNotRequired ? void 0 : stringify2(v3);
  }
  function valueArray(fieldOrDatumDef, values4) {
    const { type: type3 } = fieldOrDatumDef;
    return values4.map((v3) => {
      const timeUnit = isFieldDef(fieldOrDatumDef) && !isBinnedTimeUnit(fieldOrDatumDef.timeUnit) ? fieldOrDatumDef.timeUnit : void 0;
      const expr2 = valueExpr(v3, {
        timeUnit,
        type: type3,
        undefinedIfExprNotRequired: true
      });
      if (expr2 !== void 0) {
        return { signal: expr2 };
      }
      return v3;
    });
  }
  function binRequiresRange(fieldDef, channel) {
    if (!isBinning(fieldDef.bin)) {
      console.warn("Only call this method for binned field defs.");
      return false;
    }
    return isScaleChannel(channel) && ["ordinal", "nominal"].includes(fieldDef.type);
  }

  // node_modules/vega-lite/build/src/axis.js
  var CONDITIONAL_AXIS_PROP_INDEX = {
    labelAlign: {
      part: "labels",
      vgProp: "align"
    },
    labelBaseline: {
      part: "labels",
      vgProp: "baseline"
    },
    labelColor: {
      part: "labels",
      vgProp: "fill"
    },
    labelFont: {
      part: "labels",
      vgProp: "font"
    },
    labelFontSize: {
      part: "labels",
      vgProp: "fontSize"
    },
    labelFontStyle: {
      part: "labels",
      vgProp: "fontStyle"
    },
    labelFontWeight: {
      part: "labels",
      vgProp: "fontWeight"
    },
    labelOpacity: {
      part: "labels",
      vgProp: "opacity"
    },
    labelOffset: null,
    labelPadding: null,
    // There is no fixed vgProp for tickSize, need to use signal.
    gridColor: {
      part: "grid",
      vgProp: "stroke"
    },
    gridDash: {
      part: "grid",
      vgProp: "strokeDash"
    },
    gridDashOffset: {
      part: "grid",
      vgProp: "strokeDashOffset"
    },
    gridOpacity: {
      part: "grid",
      vgProp: "opacity"
    },
    gridWidth: {
      part: "grid",
      vgProp: "strokeWidth"
    },
    tickColor: {
      part: "ticks",
      vgProp: "stroke"
    },
    tickDash: {
      part: "ticks",
      vgProp: "strokeDash"
    },
    tickDashOffset: {
      part: "ticks",
      vgProp: "strokeDashOffset"
    },
    tickOpacity: {
      part: "ticks",
      vgProp: "opacity"
    },
    tickSize: null,
    // There is no fixed vgProp for tickSize, need to use signal.
    tickWidth: {
      part: "ticks",
      vgProp: "strokeWidth"
    }
  };
  function isConditionalAxisValue(v3) {
    return v3?.condition;
  }
  var AXIS_PARTS = ["domain", "grid", "labels", "ticks", "title"];
  var AXIS_PROPERTY_TYPE = {
    grid: "grid",
    gridCap: "grid",
    gridColor: "grid",
    gridDash: "grid",
    gridDashOffset: "grid",
    gridOpacity: "grid",
    gridScale: "grid",
    gridWidth: "grid",
    orient: "main",
    bandPosition: "both",
    // Need to be applied to grid axis too, so the grid will align with ticks.
    aria: "main",
    description: "main",
    domain: "main",
    domainCap: "main",
    domainColor: "main",
    domainDash: "main",
    domainDashOffset: "main",
    domainOpacity: "main",
    domainWidth: "main",
    format: "main",
    formatType: "main",
    labelAlign: "main",
    labelAngle: "main",
    labelBaseline: "main",
    labelBound: "main",
    labelColor: "main",
    labelFlush: "main",
    labelFlushOffset: "main",
    labelFont: "main",
    labelFontSize: "main",
    labelFontStyle: "main",
    labelFontWeight: "main",
    labelLimit: "main",
    labelLineHeight: "main",
    labelOffset: "main",
    labelOpacity: "main",
    labelOverlap: "main",
    labelPadding: "main",
    labels: "main",
    labelSeparation: "main",
    maxExtent: "main",
    minExtent: "main",
    offset: "both",
    position: "main",
    tickCap: "main",
    tickColor: "main",
    tickDash: "main",
    tickDashOffset: "main",
    tickMinStep: "both",
    tickOffset: "both",
    // Need to be applied to grid axis too, so the grid will align with ticks.
    tickOpacity: "main",
    tickRound: "both",
    // Apply rounding to grid and ticks so they are aligned.
    ticks: "main",
    tickSize: "main",
    tickWidth: "both",
    title: "main",
    titleAlign: "main",
    titleAnchor: "main",
    titleAngle: "main",
    titleBaseline: "main",
    titleColor: "main",
    titleFont: "main",
    titleFontSize: "main",
    titleFontStyle: "main",
    titleFontWeight: "main",
    titleLimit: "main",
    titleLineHeight: "main",
    titleOpacity: "main",
    titlePadding: "main",
    titleX: "main",
    titleY: "main",
    encode: "both",
    // we hide this in Vega-Lite
    scale: "both",
    tickBand: "both",
    tickCount: "both",
    tickExtra: "both",
    translate: "both",
    values: "both",
    zindex: "both"
    // this is actually set afterward, so it doesn't matter
  };
  var COMMON_AXIS_PROPERTIES_INDEX = {
    orient: 1,
    // other things can depend on orient
    aria: 1,
    bandPosition: 1,
    description: 1,
    domain: 1,
    domainCap: 1,
    domainColor: 1,
    domainDash: 1,
    domainDashOffset: 1,
    domainOpacity: 1,
    domainWidth: 1,
    format: 1,
    formatType: 1,
    grid: 1,
    gridCap: 1,
    gridColor: 1,
    gridDash: 1,
    gridDashOffset: 1,
    gridOpacity: 1,
    gridWidth: 1,
    labelAlign: 1,
    labelAngle: 1,
    labelBaseline: 1,
    labelBound: 1,
    labelColor: 1,
    labelFlush: 1,
    labelFlushOffset: 1,
    labelFont: 1,
    labelFontSize: 1,
    labelFontStyle: 1,
    labelFontWeight: 1,
    labelLimit: 1,
    labelLineHeight: 1,
    labelOffset: 1,
    labelOpacity: 1,
    labelOverlap: 1,
    labelPadding: 1,
    labels: 1,
    labelSeparation: 1,
    maxExtent: 1,
    minExtent: 1,
    offset: 1,
    position: 1,
    tickBand: 1,
    tickCap: 1,
    tickColor: 1,
    tickCount: 1,
    tickDash: 1,
    tickDashOffset: 1,
    tickExtra: 1,
    tickMinStep: 1,
    tickOffset: 1,
    tickOpacity: 1,
    tickRound: 1,
    ticks: 1,
    tickSize: 1,
    tickWidth: 1,
    title: 1,
    titleAlign: 1,
    titleAnchor: 1,
    titleAngle: 1,
    titleBaseline: 1,
    titleColor: 1,
    titleFont: 1,
    titleFontSize: 1,
    titleFontStyle: 1,
    titleFontWeight: 1,
    titleLimit: 1,
    titleLineHeight: 1,
    titleOpacity: 1,
    titlePadding: 1,
    titleX: 1,
    titleY: 1,
    translate: 1,
    values: 1,
    zindex: 1
  };
  var AXIS_PROPERTIES_INDEX = {
    ...COMMON_AXIS_PROPERTIES_INDEX,
    style: 1,
    labelExpr: 1,
    encoding: 1
  };
  function isAxisProperty(prop) {
    return has(AXIS_PROPERTIES_INDEX, prop);
  }
  var AXIS_PROPERTIES = keys3(AXIS_PROPERTIES_INDEX);
  var AXIS_CONFIGS_INDEX = {
    axis: 1,
    axisBand: 1,
    axisBottom: 1,
    axisDiscrete: 1,
    axisLeft: 1,
    axisPoint: 1,
    axisQuantitative: 1,
    axisRight: 1,
    axisTemporal: 1,
    axisTop: 1,
    axisX: 1,
    axisXBand: 1,
    axisXDiscrete: 1,
    axisXPoint: 1,
    axisXQuantitative: 1,
    axisXTemporal: 1,
    axisY: 1,
    axisYBand: 1,
    axisYDiscrete: 1,
    axisYPoint: 1,
    axisYQuantitative: 1,
    axisYTemporal: 1
  };
  var AXIS_CONFIGS = keys3(AXIS_CONFIGS_INDEX);

  // node_modules/vega-lite/build/src/spec/unit.js
  function isUnitSpec(spec) {
    return hasProperty(spec, "mark");
  }

  // node_modules/vega-lite/build/src/compositemark/base.js
  var CompositeMarkNormalizer = class {
    constructor(name4, run2) {
      this.name = name4;
      this.run = run2;
    }
    hasMatchingType(spec) {
      if (isUnitSpec(spec)) {
        return getMarkType(spec.mark) === this.name;
      }
      return false;
    }
  };

  // node_modules/vega-lite/build/src/encoding.js
  function channelHasField(encoding, channel) {
    const channelDef = encoding && encoding[channel];
    if (channelDef) {
      if (isArray(channelDef)) {
        return some(channelDef, (fieldDef) => !!fieldDef.field);
      } else {
        return isFieldDef(channelDef) || hasConditionalFieldDef(channelDef);
      }
    }
    return false;
  }
  function channelHasFieldOrDatum(encoding, channel) {
    const channelDef = encoding && encoding[channel];
    if (channelDef) {
      if (isArray(channelDef)) {
        return some(channelDef, (fieldDef) => !!fieldDef.field);
      } else {
        return isFieldDef(channelDef) || isDatumDef(channelDef) || hasConditionalFieldOrDatumDef(channelDef);
      }
    }
    return false;
  }
  function channelHasNestedOffsetScale(encoding, channel) {
    if (isXorY(channel)) {
      const fieldDef = encoding[channel];
      if ((isFieldDef(fieldDef) || isDatumDef(fieldDef)) && (isDiscrete2(fieldDef.type) || isFieldDef(fieldDef) && fieldDef.timeUnit)) {
        const offsetChannel = getOffsetScaleChannel(channel);
        return channelHasFieldOrDatum(encoding, offsetChannel);
      }
    }
    return false;
  }
  function isAggregate(encoding) {
    return some(CHANNELS, (channel) => {
      if (channelHasField(encoding, channel)) {
        const channelDef = encoding[channel];
        if (isArray(channelDef)) {
          return some(channelDef, (fieldDef) => !!fieldDef.aggregate);
        } else {
          const fieldDef = getFieldDef(channelDef);
          return fieldDef && !!fieldDef.aggregate;
        }
      }
      return false;
    });
  }
  function extractTransformsFromEncoding(oldEncoding, config) {
    const groupby = [];
    const bins2 = [];
    const timeUnits2 = [];
    const aggregate = [];
    const encoding = {};
    forEach(oldEncoding, (channelDef, channel) => {
      if (isFieldDef(channelDef)) {
        const { field: field3, aggregate: aggOp, bin: bin3, timeUnit, ...remaining } = channelDef;
        if (aggOp || timeUnit || bin3) {
          const guide = getGuide(channelDef);
          const isTitleDefined = guide?.title;
          let newField = vgField(channelDef, { forAs: true });
          const newFieldDef = {
            // Only add title if it doesn't exist
            ...isTitleDefined ? [] : { title: title(channelDef, config, { allowDisabling: true }) },
            ...remaining,
            // Always overwrite field
            field: newField
          };
          if (aggOp) {
            let op;
            if (isArgmaxDef(aggOp)) {
              op = "argmax";
              newField = vgField({ op: "argmax", field: aggOp.argmax }, { forAs: true });
              newFieldDef.field = `${newField}.${field3}`;
            } else if (isArgminDef(aggOp)) {
              op = "argmin";
              newField = vgField({ op: "argmin", field: aggOp.argmin }, { forAs: true });
              newFieldDef.field = `${newField}.${field3}`;
            } else if (aggOp !== "boxplot" && aggOp !== "errorbar" && aggOp !== "errorband") {
              op = aggOp;
            }
            if (op) {
              const aggregateEntry = {
                op,
                as: newField
              };
              if (field3) {
                aggregateEntry.field = field3;
              }
              aggregate.push(aggregateEntry);
            }
          } else {
            groupby.push(newField);
            if (isTypedFieldDef(channelDef) && isBinning(bin3)) {
              bins2.push({ bin: bin3, field: field3, as: newField });
              groupby.push(vgField(channelDef, { binSuffix: "end" }));
              if (binRequiresRange(channelDef, channel)) {
                groupby.push(vgField(channelDef, { binSuffix: "range" }));
              }
              if (isXorY(channel)) {
                const secondaryChannel = {
                  field: `${newField}_end`
                };
                encoding[`${channel}2`] = secondaryChannel;
              }
              newFieldDef.bin = "binned";
              if (!isSecondaryRangeChannel(channel)) {
                newFieldDef["type"] = QUANTITATIVE;
              }
            } else if (timeUnit && !isBinnedTimeUnit(timeUnit)) {
              timeUnits2.push({
                timeUnit,
                field: field3,
                as: newField
              });
              const formatType = isTypedFieldDef(channelDef) && channelDef.type !== TEMPORAL && "time";
              if (formatType) {
                if (channel === TEXT || channel === TOOLTIP) {
                  newFieldDef["formatType"] = formatType;
                } else if (isNonPositionScaleChannel(channel)) {
                  newFieldDef["legend"] = {
                    formatType,
                    ...newFieldDef["legend"]
                  };
                } else if (isXorY(channel)) {
                  newFieldDef["axis"] = {
                    formatType,
                    ...newFieldDef["axis"]
                  };
                }
              }
            }
          }
          encoding[channel] = newFieldDef;
        } else {
          groupby.push(field3);
          encoding[channel] = oldEncoding[channel];
        }
      } else {
        encoding[channel] = oldEncoding[channel];
      }
    });
    return {
      bins: bins2,
      timeUnits: timeUnits2,
      aggregate,
      groupby,
      encoding
    };
  }
  function markChannelCompatible(encoding, channel, mark) {
    const markSupported = supportMark(channel, mark);
    if (!markSupported) {
      return false;
    } else if (markSupported === "binned") {
      const primaryFieldDef = encoding[channel === X23 ? X3 : Y3];
      if (isFieldDef(primaryFieldDef) && isFieldDef(encoding[channel]) && isBinned(primaryFieldDef.bin)) {
        return true;
      } else {
        return false;
      }
    }
    return true;
  }
  function initEncoding(encoding, mark, filled, config) {
    const normalizedEncoding = {};
    for (const key2 of keys3(encoding)) {
      if (!isChannel(key2)) {
        warn2(message_exports.invalidEncodingChannel(key2));
      }
    }
    for (let channel of UNIT_CHANNELS) {
      if (!encoding[channel]) {
        continue;
      }
      const channelDef = encoding[channel];
      if (isXorYOffset(channel)) {
        const mainChannel = getMainChannelFromOffsetChannel(channel);
        const positionDef = normalizedEncoding[mainChannel];
        if (isFieldDef(positionDef)) {
          if (isContinuous2(positionDef.type)) {
            if (isFieldDef(channelDef) && !positionDef.timeUnit) {
              warn2(message_exports.offsetNestedInsideContinuousPositionScaleDropped(mainChannel));
              continue;
            }
          }
        }
      }
      if (channel === "angle" && mark === "arc" && !encoding.theta) {
        warn2(message_exports.REPLACE_ANGLE_WITH_THETA);
        channel = THETA;
      }
      if (!markChannelCompatible(encoding, channel, mark)) {
        warn2(message_exports.incompatibleChannel(channel, mark));
        continue;
      }
      if (channel === SIZE2 && mark === "line") {
        const fieldDef = getFieldDef(encoding[channel]);
        if (fieldDef?.aggregate) {
          warn2(message_exports.LINE_WITH_VARYING_SIZE);
          continue;
        }
      }
      if (channel === COLOR && (filled ? "fill" in encoding : "stroke" in encoding)) {
        warn2(message_exports.droppingColor("encoding", { fill: "fill" in encoding, stroke: "stroke" in encoding }));
        continue;
      }
      if (channel === DETAIL || channel === ORDER && !isArray(channelDef) && !isValueDef(channelDef) || channel === TOOLTIP && isArray(channelDef)) {
        if (channelDef) {
          if (channel === ORDER) {
            const def2 = encoding[channel];
            if (isOrderOnlyDef(def2)) {
              normalizedEncoding[channel] = def2;
              continue;
            }
          }
          normalizedEncoding[channel] = array(channelDef).reduce((defs, fieldDef) => {
            if (!isFieldDef(fieldDef)) {
              warn2(message_exports.emptyFieldDef(fieldDef, channel));
            } else {
              defs.push(initFieldDef(fieldDef, channel));
            }
            return defs;
          }, []);
        }
      } else {
        if (channel === TOOLTIP && channelDef === null) {
          normalizedEncoding[channel] = null;
        } else if (!isFieldDef(channelDef) && !isDatumDef(channelDef) && !isValueDef(channelDef) && !isConditionalDef(channelDef) && !isSignalRef(channelDef)) {
          warn2(message_exports.emptyFieldDef(channelDef, channel));
          continue;
        }
        normalizedEncoding[channel] = initChannelDef(channelDef, channel, config);
      }
    }
    return normalizedEncoding;
  }
  function normalizeEncoding(encoding, config) {
    const normalizedEncoding = {};
    for (const channel of keys3(encoding)) {
      const newChannelDef = initChannelDef(encoding[channel], channel, config, { compositeMark: true });
      normalizedEncoding[channel] = newChannelDef;
    }
    return normalizedEncoding;
  }
  function fieldDefs(encoding) {
    const arr = [];
    for (const channel of keys3(encoding)) {
      if (channelHasField(encoding, channel)) {
        const channelDef = encoding[channel];
        const channelDefArray = array(channelDef);
        for (const def2 of channelDefArray) {
          if (isFieldDef(def2)) {
            arr.push(def2);
          } else if (hasConditionalFieldDef(def2)) {
            arr.push(def2.condition);
          }
        }
      }
    }
    return arr;
  }
  function forEach(mapping, f2, thisArg) {
    if (!mapping) {
      return;
    }
    for (const channel of keys3(mapping)) {
      const el = mapping[channel];
      if (isArray(el)) {
        for (const channelDef of el) {
          f2.call(thisArg, channelDef, channel);
        }
      } else {
        f2.call(thisArg, el, channel);
      }
    }
  }
  function reduce(mapping, f2, init2, thisArg) {
    if (!mapping) {
      return init2;
    }
    return keys3(mapping).reduce((r2, channel) => {
      const map4 = mapping[channel];
      if (isArray(map4)) {
        return map4.reduce((r1, channelDef) => {
          return f2.call(thisArg, r1, channelDef, channel);
        }, r2);
      } else {
        return f2.call(thisArg, r2, map4, channel);
      }
    }, init2);
  }
  function pathGroupingFields(mark, encoding) {
    return keys3(encoding).reduce((details, channel) => {
      switch (channel) {
        // x, y, x2, y2, lat, long, lat1, long2, order, tooltip, href, aria label, cursor should not cause lines to group
        case X3:
        case Y3:
        case HREF:
        case DESCRIPTION:
        case URL2:
        case X23:
        case Y23:
        case XOFFSET:
        case YOFFSET:
        case THETA:
        case THETA2:
        case RADIUS:
        case RADIUS2:
        case TIME:
        // falls through
        case LATITUDE:
        case LONGITUDE:
        case LATITUDE2:
        case LONGITUDE2:
        // TODO: case 'cursor':
        // text, shape, shouldn't be a part of line/trail/area [falls through]
        case TEXT:
        case SHAPE:
        case ANGLE:
        // falls through
        // tooltip fields should not be added to group by [falls through]
        case TOOLTIP:
          return details;
        case ORDER:
          if (mark === "line" || mark === "trail") {
            return details;
          }
        // but order should group area for stacking (falls through)
        case DETAIL:
        case KEY: {
          const channelDef = encoding[channel];
          if (isArray(channelDef) || isFieldDef(channelDef)) {
            for (const fieldDef of array(channelDef)) {
              if (!fieldDef.aggregate) {
                details.push(vgField(fieldDef, {}));
              }
            }
          }
          return details;
        }
        case SIZE2:
          if (mark === "trail") {
            return details;
          }
        // For line, size should group lines.
        // falls through
        case COLOR:
        case FILL:
        case STROKE:
        case OPACITY:
        case FILLOPACITY:
        case STROKEOPACITY:
        case STROKEDASH:
        case STROKEWIDTH: {
          const fieldDef = getFieldDef(encoding[channel]);
          if (fieldDef && !fieldDef.aggregate) {
            details.push(vgField(fieldDef, {}));
          }
          return details;
        }
      }
    }, []);
  }

  // node_modules/vega-lite/build/src/compositemark/common.js
  function filterTooltipWithAggregatedField(oldEncoding) {
    const { tooltip: tooltip2, ...filteredEncoding } = oldEncoding;
    if (!tooltip2) {
      return { filteredEncoding };
    }
    let customTooltipWithAggregatedField;
    let customTooltipWithoutAggregatedField;
    if (isArray(tooltip2)) {
      for (const t4 of tooltip2) {
        if (t4.aggregate) {
          if (!customTooltipWithAggregatedField) {
            customTooltipWithAggregatedField = [];
          }
          customTooltipWithAggregatedField.push(t4);
        } else {
          if (!customTooltipWithoutAggregatedField) {
            customTooltipWithoutAggregatedField = [];
          }
          customTooltipWithoutAggregatedField.push(t4);
        }
      }
      if (customTooltipWithAggregatedField) {
        filteredEncoding.tooltip = customTooltipWithAggregatedField;
      }
    } else {
      if (tooltip2.aggregate) {
        filteredEncoding.tooltip = tooltip2;
      } else {
        customTooltipWithoutAggregatedField = tooltip2;
      }
    }
    if (isArray(customTooltipWithoutAggregatedField) && customTooltipWithoutAggregatedField.length === 1) {
      customTooltipWithoutAggregatedField = customTooltipWithoutAggregatedField[0];
    }
    return { customTooltipWithoutAggregatedField, filteredEncoding };
  }
  function getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, withFieldName = true) {
    if ("tooltip" in encodingWithoutContinuousAxis) {
      return { tooltip: encodingWithoutContinuousAxis.tooltip };
    }
    const fiveSummaryTooltip = tooltipSummary.map(({ fieldPrefix, titlePrefix }) => {
      const mainTitle = withFieldName ? ` of ${getTitle(continuousAxisChannelDef)}` : "";
      return {
        field: fieldPrefix + continuousAxisChannelDef.field,
        type: continuousAxisChannelDef.type,
        title: isSignalRef(titlePrefix) ? { signal: `${titlePrefix}"${escape(mainTitle)}"` } : titlePrefix + mainTitle
      };
    });
    const tooltipFieldDefs = fieldDefs(encodingWithoutContinuousAxis).map(toStringFieldDef);
    return {
      tooltip: [
        ...fiveSummaryTooltip,
        // need to cast because TextFieldDef supports fewer types of bin
        ...unique(tooltipFieldDefs, hash)
      ]
    };
  }
  function getTitle(continuousAxisChannelDef) {
    const { title: title2, field: field3 } = continuousAxisChannelDef;
    return getFirstDefined(title2, field3);
  }
  function makeCompositeAggregatePartFactory(compositeMarkDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, compositeMarkConfig) {
    const { scale: scale7, axis } = continuousAxisChannelDef;
    return ({ partName, mark, positionPrefix, endPositionPrefix = void 0, extraEncoding = {} }) => {
      const title2 = getTitle(continuousAxisChannelDef);
      return partLayerMixins(compositeMarkDef, partName, compositeMarkConfig, {
        mark,
        // TODO better remove this method and just have mark as a parameter of the method
        encoding: {
          [continuousAxis]: {
            field: `${positionPrefix}_${continuousAxisChannelDef.field}`,
            type: continuousAxisChannelDef.type,
            ...title2 !== void 0 ? { title: title2 } : {},
            ...scale7 !== void 0 ? { scale: scale7 } : {},
            ...axis !== void 0 ? { axis } : {}
          },
          ...isString(endPositionPrefix) ? {
            [`${continuousAxis}2`]: {
              field: `${endPositionPrefix}_${continuousAxisChannelDef.field}`
            }
          } : {},
          ...sharedEncoding,
          ...extraEncoding
        }
      });
    };
  }
  function partLayerMixins(markDef, part, compositeMarkConfig, partBaseSpec) {
    const { clip: clip3, color: color5, opacity: opacity2 } = markDef;
    const mark = markDef.type;
    if (markDef[part] || markDef[part] === void 0 && compositeMarkConfig[part]) {
      return [
        {
          ...partBaseSpec,
          mark: {
            ...compositeMarkConfig[part],
            ...clip3 ? { clip: clip3 } : {},
            ...color5 ? { color: color5 } : {},
            ...opacity2 ? { opacity: opacity2 } : {},
            ...isMarkDef(partBaseSpec.mark) ? partBaseSpec.mark : { type: partBaseSpec.mark },
            style: `${mark}-${String(part)}`,
            ...isBoolean(markDef[part]) ? {} : markDef[part]
          }
        }
      ];
    }
    return [];
  }
  function compositeMarkContinuousAxis(spec, orient2, compositeMark) {
    const { encoding } = spec;
    const continuousAxis = orient2 === "vertical" ? "y" : "x";
    const continuousAxisChannelDef = encoding[continuousAxis];
    const continuousAxisChannelDef2 = encoding[`${continuousAxis}2`];
    const continuousAxisChannelDefError = encoding[`${continuousAxis}Error`];
    const continuousAxisChannelDefError2 = encoding[`${continuousAxis}Error2`];
    return {
      continuousAxisChannelDef: filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark),
      continuousAxisChannelDef2: filterAggregateFromChannelDef(continuousAxisChannelDef2, compositeMark),
      continuousAxisChannelDefError: filterAggregateFromChannelDef(continuousAxisChannelDefError, compositeMark),
      continuousAxisChannelDefError2: filterAggregateFromChannelDef(continuousAxisChannelDefError2, compositeMark),
      continuousAxis
    };
  }
  function filterAggregateFromChannelDef(continuousAxisChannelDef, compositeMark) {
    if (continuousAxisChannelDef?.aggregate) {
      const { aggregate, ...continuousAxisWithoutAggregate } = continuousAxisChannelDef;
      if (aggregate !== compositeMark) {
        warn2(message_exports.errorBarContinuousAxisHasCustomizedAggregate(aggregate, compositeMark));
      }
      return continuousAxisWithoutAggregate;
    } else {
      return continuousAxisChannelDef;
    }
  }
  function compositeMarkOrient(spec, compositeMark) {
    const { mark, encoding } = spec;
    const { x: x5, y: y5 } = encoding;
    if (isMarkDef(mark) && mark.orient) {
      return mark.orient;
    }
    if (isContinuousFieldOrDatumDef(x5)) {
      if (isContinuousFieldOrDatumDef(y5)) {
        const xAggregate = isFieldDef(x5) && x5.aggregate;
        const yAggregate = isFieldDef(y5) && y5.aggregate;
        if (!xAggregate && yAggregate === compositeMark) {
          return "vertical";
        } else if (!yAggregate && xAggregate === compositeMark) {
          return "horizontal";
        } else if (xAggregate === compositeMark && yAggregate === compositeMark) {
          throw new Error("Both x and y cannot have aggregate");
        } else {
          if (isFieldOrDatumDefForTimeFormat(y5) && !isFieldOrDatumDefForTimeFormat(x5)) {
            return "horizontal";
          }
          return "vertical";
        }
      }
      return "horizontal";
    } else if (isContinuousFieldOrDatumDef(y5)) {
      return "vertical";
    } else {
      throw new Error(`Need a valid continuous axis for ${compositeMark}s`);
    }
  }

  // node_modules/vega-lite/build/src/compositemark/boxplot.js
  var BOXPLOT = "boxplot";
  var BOXPLOT_PARTS = ["box", "median", "outliers", "rule", "ticks"];
  var boxPlotNormalizer = new CompositeMarkNormalizer(BOXPLOT, normalizeBoxPlot);
  function getBoxPlotType(extent2) {
    if (isNumber(extent2)) {
      return "tukey";
    }
    return extent2;
  }
  function normalizeBoxPlot(spec, { config }) {
    spec = {
      ...spec,
      encoding: normalizeEncoding(spec.encoding, config)
    };
    const { mark, encoding: _encoding, params: params2, projection: _p, ...outerSpec } = spec;
    const markDef = isMarkDef(mark) ? mark : { type: mark };
    if (params2) {
      warn2(message_exports.selectionNotSupported("boxplot"));
    }
    const extent2 = markDef.extent ?? config.boxplot.extent;
    const sizeValue = getMarkPropOrConfig(
      "size",
      markDef,
      // TODO: https://github.com/vega/vega-lite/issues/6245
      config
    );
    const invalid = markDef.invalid;
    const boxPlotType = getBoxPlotType(extent2);
    const { bins: bins2, timeUnits: timeUnits2, transform: transform4, continuousAxisChannelDef, continuousAxis, groupby, aggregate, encodingWithoutContinuousAxis, ticksOrient, boxOrient, customTooltipWithoutAggregatedField } = boxParams(spec, extent2, config);
    const aliasedFieldName = removePathFromField(continuousAxisChannelDef.field);
    const { color: color5, size, ...encodingWithoutSizeColorAndContinuousAxis } = encodingWithoutContinuousAxis;
    const makeBoxPlotPart = (sharedEncoding) => {
      return makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, sharedEncoding, config.boxplot);
    };
    const makeBoxPlotExtent = makeBoxPlotPart(encodingWithoutSizeColorAndContinuousAxis);
    const makeBoxPlotBox = makeBoxPlotPart(encodingWithoutContinuousAxis);
    const defaultBoxColor = (isObject(config.boxplot.box) ? config.boxplot.box.color : config.mark.color) || "#4c78a8";
    const makeBoxPlotMidTick = makeBoxPlotPart({
      ...encodingWithoutSizeColorAndContinuousAxis,
      ...size ? { size } : {},
      color: {
        condition: {
          test: `${accessWithDatumToUnescapedPath(`lower_box_${continuousAxisChannelDef.field}`)} >= ${accessWithDatumToUnescapedPath(`upper_box_${continuousAxisChannelDef.field}`)}`,
          ...color5 || { value: defaultBoxColor }
        }
      }
    });
    const fiveSummaryTooltipEncoding = getCompositeMarkTooltip([
      { fieldPrefix: boxPlotType === "min-max" ? "upper_whisker_" : "max_", titlePrefix: "Max" },
      { fieldPrefix: "upper_box_", titlePrefix: "Q3" },
      { fieldPrefix: "mid_box_", titlePrefix: "Median" },
      { fieldPrefix: "lower_box_", titlePrefix: "Q1" },
      { fieldPrefix: boxPlotType === "min-max" ? "lower_whisker_" : "min_", titlePrefix: "Min" }
    ], continuousAxisChannelDef, encodingWithoutContinuousAxis);
    const endTick = { type: "tick", color: "black", opacity: 1, orient: ticksOrient, invalid, aria: false };
    const whiskerTooltipEncoding = boxPlotType === "min-max" ? fiveSummaryTooltipEncoding : (
      // for tukey / k-IQR, just show upper/lower-whisker
      getCompositeMarkTooltip([
        { fieldPrefix: "upper_whisker_", titlePrefix: "Upper Whisker" },
        { fieldPrefix: "lower_whisker_", titlePrefix: "Lower Whisker" }
      ], continuousAxisChannelDef, encodingWithoutContinuousAxis)
    );
    const whiskerLayers = [
      ...makeBoxPlotExtent({
        partName: "rule",
        mark: { type: "rule", invalid, aria: false },
        positionPrefix: "lower_whisker",
        endPositionPrefix: "lower_box",
        extraEncoding: whiskerTooltipEncoding
      }),
      ...makeBoxPlotExtent({
        partName: "rule",
        mark: { type: "rule", invalid, aria: false },
        positionPrefix: "upper_box",
        endPositionPrefix: "upper_whisker",
        extraEncoding: whiskerTooltipEncoding
      }),
      ...makeBoxPlotExtent({
        partName: "ticks",
        mark: endTick,
        positionPrefix: "lower_whisker",
        extraEncoding: whiskerTooltipEncoding
      }),
      ...makeBoxPlotExtent({
        partName: "ticks",
        mark: endTick,
        positionPrefix: "upper_whisker",
        extraEncoding: whiskerTooltipEncoding
      })
    ];
    const boxLayers = [
      ...boxPlotType !== "tukey" ? whiskerLayers : [],
      ...makeBoxPlotBox({
        partName: "box",
        mark: {
          type: "bar",
          ...sizeValue ? { size: sizeValue } : {},
          orient: boxOrient,
          invalid,
          ariaRoleDescription: "box"
        },
        positionPrefix: "lower_box",
        endPositionPrefix: "upper_box",
        extraEncoding: fiveSummaryTooltipEncoding
      }),
      ...makeBoxPlotMidTick({
        partName: "median",
        mark: {
          type: "tick",
          invalid,
          ...isObject(config.boxplot.median) && config.boxplot.median.color ? { color: config.boxplot.median.color } : {},
          ...sizeValue ? { size: sizeValue } : {},
          orient: ticksOrient,
          aria: false
        },
        positionPrefix: "mid_box",
        extraEncoding: fiveSummaryTooltipEncoding
      })
    ];
    if (boxPlotType === "min-max") {
      return {
        ...outerSpec,
        transform: (outerSpec.transform ?? []).concat(transform4),
        layer: boxLayers
      };
    }
    const lowerBoxExpr = accessWithDatumToUnescapedPath(`lower_box_${continuousAxisChannelDef.field}`);
    const upperBoxExpr = accessWithDatumToUnescapedPath(`upper_box_${continuousAxisChannelDef.field}`);
    const iqrExpr = `(${upperBoxExpr} - ${lowerBoxExpr})`;
    const lowerWhiskerExpr = `${lowerBoxExpr} - ${extent2} * ${iqrExpr}`;
    const upperWhiskerExpr = `${upperBoxExpr} + ${extent2} * ${iqrExpr}`;
    const fieldExpr2 = accessWithDatumToUnescapedPath(continuousAxisChannelDef.field);
    const joinaggregateTransform = {
      joinaggregate: boxParamsQuartiles(continuousAxisChannelDef.field),
      groupby
    };
    const filteredWhiskerSpec = {
      transform: [
        {
          filter: `(${lowerWhiskerExpr} <= ${fieldExpr2}) && (${fieldExpr2} <= ${upperWhiskerExpr})`
        },
        {
          aggregate: [
            {
              op: "min",
              field: continuousAxisChannelDef.field,
              as: `lower_whisker_${aliasedFieldName}`
            },
            {
              op: "max",
              field: continuousAxisChannelDef.field,
              as: `upper_whisker_${aliasedFieldName}`
            },
            // preserve lower_box / upper_box
            {
              op: "min",
              field: `lower_box_${continuousAxisChannelDef.field}`,
              as: `lower_box_${aliasedFieldName}`
            },
            {
              op: "max",
              field: `upper_box_${continuousAxisChannelDef.field}`,
              as: `upper_box_${aliasedFieldName}`
            },
            ...aggregate
          ],
          groupby
        }
      ],
      layer: whiskerLayers
    };
    const { tooltip: tooltip2, ...encodingWithoutSizeColorContinuousAxisAndTooltip } = encodingWithoutSizeColorAndContinuousAxis;
    const { scale: scale7, axis } = continuousAxisChannelDef;
    const title2 = getTitle(continuousAxisChannelDef);
    const axisWithoutTitle = omit(axis, ["title"]);
    const outlierLayersMixins = partLayerMixins(markDef, "outliers", config.boxplot, {
      transform: [{ filter: `(${fieldExpr2} < ${lowerWhiskerExpr}) || (${fieldExpr2} > ${upperWhiskerExpr})` }],
      mark: "point",
      encoding: {
        [continuousAxis]: {
          field: continuousAxisChannelDef.field,
          type: continuousAxisChannelDef.type,
          ...title2 !== void 0 ? { title: title2 } : {},
          ...scale7 !== void 0 ? { scale: scale7 } : {},
          // add axis without title since we already added the title above
          ...isEmpty(axisWithoutTitle) ? {} : { axis: axisWithoutTitle }
        },
        ...encodingWithoutSizeColorContinuousAxisAndTooltip,
        ...color5 ? { color: color5 } : {},
        ...customTooltipWithoutAggregatedField ? { tooltip: customTooltipWithoutAggregatedField } : {}
      }
    })[0];
    let filteredLayersMixins;
    const filteredLayersMixinsTransforms = [...bins2, ...timeUnits2, joinaggregateTransform];
    if (outlierLayersMixins) {
      filteredLayersMixins = {
        transform: filteredLayersMixinsTransforms,
        layer: [outlierLayersMixins, filteredWhiskerSpec]
      };
    } else {
      filteredLayersMixins = filteredWhiskerSpec;
      filteredLayersMixins.transform.unshift(...filteredLayersMixinsTransforms);
    }
    return {
      ...outerSpec,
      layer: [
        filteredLayersMixins,
        {
          // boxplot
          transform: transform4,
          layer: boxLayers
        }
      ]
    };
  }
  function boxParamsQuartiles(continousAxisField) {
    const aliasedFieldName = removePathFromField(continousAxisField);
    return [
      {
        op: "q1",
        field: continousAxisField,
        as: `lower_box_${aliasedFieldName}`
      },
      {
        op: "q3",
        field: continousAxisField,
        as: `upper_box_${aliasedFieldName}`
      }
    ];
  }
  function boxParams(spec, extent2, config) {
    const orient2 = compositeMarkOrient(spec, BOXPLOT);
    const { continuousAxisChannelDef, continuousAxis } = compositeMarkContinuousAxis(spec, orient2, BOXPLOT);
    const continuousFieldName = continuousAxisChannelDef.field;
    const aliasedFieldName = removePathFromField(continuousFieldName);
    const boxPlotType = getBoxPlotType(extent2);
    const boxplotSpecificAggregate = [
      ...boxParamsQuartiles(continuousFieldName),
      {
        op: "median",
        field: continuousFieldName,
        as: `mid_box_${aliasedFieldName}`
      },
      {
        op: "min",
        field: continuousFieldName,
        as: (boxPlotType === "min-max" ? "lower_whisker_" : "min_") + aliasedFieldName
      },
      {
        op: "max",
        field: continuousFieldName,
        as: (boxPlotType === "min-max" ? "upper_whisker_" : "max_") + aliasedFieldName
      }
    ];
    const postAggregateCalculates = boxPlotType === "min-max" || boxPlotType === "tukey" ? [] : [
      // This is for the  original k-IQR, which we do not expose
      {
        calculate: `${accessWithDatumToUnescapedPath(`upper_box_${aliasedFieldName}`)} - ${accessWithDatumToUnescapedPath(`lower_box_${aliasedFieldName}`)}`,
        as: `iqr_${aliasedFieldName}`
      },
      {
        calculate: `min(${accessWithDatumToUnescapedPath(`upper_box_${aliasedFieldName}`)} + ${accessWithDatumToUnescapedPath(`iqr_${aliasedFieldName}`)} * ${extent2}, ${accessWithDatumToUnescapedPath(`max_${aliasedFieldName}`)})`,
        as: `upper_whisker_${aliasedFieldName}`
      },
      {
        calculate: `max(${accessWithDatumToUnescapedPath(`lower_box_${aliasedFieldName}`)} - ${accessWithDatumToUnescapedPath(`iqr_${aliasedFieldName}`)} * ${extent2}, ${accessWithDatumToUnescapedPath(`min_${aliasedFieldName}`)})`,
        as: `lower_whisker_${aliasedFieldName}`
      }
    ];
    const { [continuousAxis]: oldContinuousAxisChannelDef, ...oldEncodingWithoutContinuousAxis } = spec.encoding;
    const { customTooltipWithoutAggregatedField, filteredEncoding } = filterTooltipWithAggregatedField(oldEncodingWithoutContinuousAxis);
    const { bins: bins2, timeUnits: timeUnits2, aggregate, groupby, encoding: encodingWithoutContinuousAxis } = extractTransformsFromEncoding(filteredEncoding, config);
    const ticksOrient = orient2 === "vertical" ? "horizontal" : "vertical";
    const boxOrient = orient2;
    const transform4 = [
      ...bins2,
      ...timeUnits2,
      {
        aggregate: [...aggregate, ...boxplotSpecificAggregate],
        groupby
      },
      ...postAggregateCalculates
    ];
    return {
      bins: bins2,
      timeUnits: timeUnits2,
      transform: transform4,
      groupby,
      aggregate,
      continuousAxisChannelDef,
      continuousAxis,
      encodingWithoutContinuousAxis,
      ticksOrient,
      boxOrient,
      customTooltipWithoutAggregatedField
    };
  }

  // node_modules/vega-lite/build/src/compositemark/errorbar.js
  var ERRORBAR = "errorbar";
  var ERRORBAR_PARTS = ["ticks", "rule"];
  var errorBarNormalizer = new CompositeMarkNormalizer(ERRORBAR, normalizeErrorBar);
  function normalizeErrorBar(spec, { config }) {
    spec = {
      ...spec,
      encoding: normalizeEncoding(spec.encoding, config)
    };
    const { transform: transform4, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, ticksOrient, markDef, outerSpec, tooltipEncoding } = errorBarParams(spec, ERRORBAR, config);
    delete encodingWithoutContinuousAxis.size;
    const makeErrorBarPart = makeCompositeAggregatePartFactory(markDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorbar);
    const thickness = markDef.thickness;
    const size = markDef.size;
    const tick2 = {
      type: "tick",
      orient: ticksOrient,
      aria: false,
      ...thickness !== void 0 ? { thickness } : {},
      ...size !== void 0 ? { size } : {}
    };
    const layer = [
      ...makeErrorBarPart({
        partName: "ticks",
        mark: tick2,
        positionPrefix: "lower",
        extraEncoding: tooltipEncoding
      }),
      ...makeErrorBarPart({
        partName: "ticks",
        mark: tick2,
        positionPrefix: "upper",
        extraEncoding: tooltipEncoding
      }),
      ...makeErrorBarPart({
        partName: "rule",
        mark: {
          type: "rule",
          ariaRoleDescription: "errorbar",
          ...thickness !== void 0 ? { size: thickness } : {}
        },
        positionPrefix: "lower",
        endPositionPrefix: "upper",
        extraEncoding: tooltipEncoding
      })
    ];
    return {
      ...outerSpec,
      transform: transform4,
      ...layer.length > 1 ? { layer } : { ...layer[0] }
    };
  }
  function errorBarOrientAndInputType(spec, compositeMark) {
    const { encoding } = spec;
    if (errorBarIsInputTypeRaw(encoding)) {
      return {
        orient: compositeMarkOrient(spec, compositeMark),
        inputType: "raw"
      };
    }
    const isTypeAggregatedUpperLower = errorBarIsInputTypeAggregatedUpperLower(encoding);
    const isTypeAggregatedError = errorBarIsInputTypeAggregatedError(encoding);
    const x5 = encoding.x;
    const y5 = encoding.y;
    if (isTypeAggregatedUpperLower) {
      if (isTypeAggregatedError) {
        throw new Error(`${compositeMark} cannot be both type aggregated-upper-lower and aggregated-error`);
      }
      const x22 = encoding.x2;
      const y22 = encoding.y2;
      if (isFieldOrDatumDef(x22) && isFieldOrDatumDef(y22)) {
        throw new Error(`${compositeMark} cannot have both x2 and y2`);
      } else if (isFieldOrDatumDef(x22)) {
        if (isContinuousFieldOrDatumDef(x5)) {
          return { orient: "horizontal", inputType: "aggregated-upper-lower" };
        } else {
          throw new Error(`Both x and x2 have to be quantitative in ${compositeMark}`);
        }
      } else if (isFieldOrDatumDef(y22)) {
        if (isContinuousFieldOrDatumDef(y5)) {
          return { orient: "vertical", inputType: "aggregated-upper-lower" };
        } else {
          throw new Error(`Both y and y2 have to be quantitative in ${compositeMark}`);
        }
      }
      throw new Error("No ranged axis");
    } else {
      const xError = encoding.xError;
      const xError2 = encoding.xError2;
      const yError = encoding.yError;
      const yError2 = encoding.yError2;
      if (isFieldOrDatumDef(xError2) && !isFieldOrDatumDef(xError)) {
        throw new Error(`${compositeMark} cannot have xError2 without xError`);
      }
      if (isFieldOrDatumDef(yError2) && !isFieldOrDatumDef(yError)) {
        throw new Error(`${compositeMark} cannot have yError2 without yError`);
      }
      if (isFieldOrDatumDef(xError) && isFieldOrDatumDef(yError)) {
        throw new Error(`${compositeMark} cannot have both xError and yError with both are quantiative`);
      } else if (isFieldOrDatumDef(xError)) {
        if (isContinuousFieldOrDatumDef(x5)) {
          return { orient: "horizontal", inputType: "aggregated-error" };
        } else {
          throw new Error("All x, xError, and xError2 (if exist) have to be quantitative");
        }
      } else if (isFieldOrDatumDef(yError)) {
        if (isContinuousFieldOrDatumDef(y5)) {
          return { orient: "vertical", inputType: "aggregated-error" };
        } else {
          throw new Error("All y, yError, and yError2 (if exist) have to be quantitative");
        }
      }
      throw new Error("No ranged axis");
    }
  }
  function errorBarIsInputTypeRaw(encoding) {
    return (isFieldOrDatumDef(encoding.x) || isFieldOrDatumDef(encoding.y)) && !isFieldOrDatumDef(encoding.x2) && !isFieldOrDatumDef(encoding.y2) && !isFieldOrDatumDef(encoding.xError) && !isFieldOrDatumDef(encoding.xError2) && !isFieldOrDatumDef(encoding.yError) && !isFieldOrDatumDef(encoding.yError2);
  }
  function errorBarIsInputTypeAggregatedUpperLower(encoding) {
    return isFieldOrDatumDef(encoding.x2) || isFieldOrDatumDef(encoding.y2);
  }
  function errorBarIsInputTypeAggregatedError(encoding) {
    return isFieldOrDatumDef(encoding.xError) || isFieldOrDatumDef(encoding.xError2) || isFieldOrDatumDef(encoding.yError) || isFieldOrDatumDef(encoding.yError2);
  }
  function errorBarParams(spec, compositeMark, config) {
    const { mark, encoding, params: params2, projection: _p, ...outerSpec } = spec;
    const markDef = isMarkDef(mark) ? mark : { type: mark };
    if (params2) {
      warn2(message_exports.selectionNotSupported(compositeMark));
    }
    const { orient: orient2, inputType } = errorBarOrientAndInputType(spec, compositeMark);
    const { continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, continuousAxis } = compositeMarkContinuousAxis(spec, orient2, compositeMark);
    const { errorBarSpecificAggregate, postAggregateCalculates, tooltipSummary, tooltipTitleWithFieldName } = errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config);
    const { [continuousAxis]: oldContinuousAxisChannelDef, [continuousAxis === "x" ? "x2" : "y2"]: oldContinuousAxisChannelDef2, [continuousAxis === "x" ? "xError" : "yError"]: oldContinuousAxisChannelDefError, [continuousAxis === "x" ? "xError2" : "yError2"]: oldContinuousAxisChannelDefError2, ...oldEncodingWithoutContinuousAxis } = encoding;
    const { bins: bins2, timeUnits: timeUnits2, aggregate: oldAggregate, groupby: oldGroupBy, encoding: encodingWithoutContinuousAxis } = extractTransformsFromEncoding(oldEncodingWithoutContinuousAxis, config);
    const aggregate = [...oldAggregate, ...errorBarSpecificAggregate];
    const groupby = inputType !== "raw" ? [] : oldGroupBy;
    const tooltipEncoding = getCompositeMarkTooltip(tooltipSummary, continuousAxisChannelDef, encodingWithoutContinuousAxis, tooltipTitleWithFieldName);
    return {
      transform: [
        ...outerSpec.transform ?? [],
        ...bins2,
        ...timeUnits2,
        ...aggregate.length === 0 ? [] : [{ aggregate, groupby }],
        ...postAggregateCalculates
      ],
      groupby,
      continuousAxisChannelDef,
      continuousAxis,
      encodingWithoutContinuousAxis,
      ticksOrient: orient2 === "vertical" ? "horizontal" : "vertical",
      markDef,
      outerSpec,
      tooltipEncoding
    };
  }
  function errorBarAggregationAndCalculation(markDef, continuousAxisChannelDef, continuousAxisChannelDef2, continuousAxisChannelDefError, continuousAxisChannelDefError2, inputType, compositeMark, config) {
    let errorBarSpecificAggregate = [];
    let postAggregateCalculates = [];
    const continuousFieldName = continuousAxisChannelDef.field;
    let tooltipSummary;
    let tooltipTitleWithFieldName = false;
    if (inputType === "raw") {
      const center = markDef.center ? markDef.center : markDef.extent ? markDef.extent === "iqr" ? "median" : "mean" : config.errorbar.center;
      const extent2 = markDef.extent ? markDef.extent : center === "mean" ? "stderr" : "iqr";
      if (center === "median" !== (extent2 === "iqr")) {
        warn2(message_exports.errorBarCenterIsUsedWithWrongExtent(center, extent2, compositeMark));
      }
      if (extent2 === "stderr" || extent2 === "stdev") {
        errorBarSpecificAggregate = [
          { op: extent2, field: continuousFieldName, as: `extent_${continuousFieldName}` },
          { op: center, field: continuousFieldName, as: `center_${continuousFieldName}` }
        ];
        postAggregateCalculates = [
          {
            calculate: `${accessWithDatumToUnescapedPath(`center_${continuousFieldName}`)} + ${accessWithDatumToUnescapedPath(`extent_${continuousFieldName}`)}`,
            as: `upper_${continuousFieldName}`
          },
          {
            calculate: `${accessWithDatumToUnescapedPath(`center_${continuousFieldName}`)} - ${accessWithDatumToUnescapedPath(`extent_${continuousFieldName}`)}`,
            as: `lower_${continuousFieldName}`
          }
        ];
        tooltipSummary = [
          { fieldPrefix: "center_", titlePrefix: titleCase(center) },
          { fieldPrefix: "upper_", titlePrefix: getTitlePrefix(center, extent2, "+") },
          { fieldPrefix: "lower_", titlePrefix: getTitlePrefix(center, extent2, "-") }
        ];
        tooltipTitleWithFieldName = true;
      } else {
        let centerOp;
        let lowerExtentOp;
        let upperExtentOp;
        if (extent2 === "ci") {
          centerOp = "mean";
          lowerExtentOp = "ci0";
          upperExtentOp = "ci1";
        } else {
          centerOp = "median";
          lowerExtentOp = "q1";
          upperExtentOp = "q3";
        }
        errorBarSpecificAggregate = [
          { op: lowerExtentOp, field: continuousFieldName, as: `lower_${continuousFieldName}` },
          { op: upperExtentOp, field: continuousFieldName, as: `upper_${continuousFieldName}` },
          { op: centerOp, field: continuousFieldName, as: `center_${continuousFieldName}` }
        ];
        tooltipSummary = [
          {
            fieldPrefix: "upper_",
            titlePrefix: title({ field: continuousFieldName, aggregate: upperExtentOp, type: "quantitative" }, config, {
              allowDisabling: false
            })
          },
          {
            fieldPrefix: "lower_",
            titlePrefix: title({ field: continuousFieldName, aggregate: lowerExtentOp, type: "quantitative" }, config, {
              allowDisabling: false
            })
          },
          {
            fieldPrefix: "center_",
            titlePrefix: title({ field: continuousFieldName, aggregate: centerOp, type: "quantitative" }, config, {
              allowDisabling: false
            })
          }
        ];
      }
    } else {
      if (markDef.center || markDef.extent) {
        warn2(message_exports.errorBarCenterAndExtentAreNotNeeded(markDef.center, markDef.extent));
      }
      if (inputType === "aggregated-upper-lower") {
        tooltipSummary = [];
        postAggregateCalculates = [
          {
            calculate: accessWithDatumToUnescapedPath(continuousAxisChannelDef2.field),
            as: `upper_${continuousFieldName}`
          },
          { calculate: accessWithDatumToUnescapedPath(continuousFieldName), as: `lower_${continuousFieldName}` }
        ];
      } else if (inputType === "aggregated-error") {
        tooltipSummary = [{ fieldPrefix: "", titlePrefix: continuousFieldName }];
        postAggregateCalculates = [
          {
            calculate: `${accessWithDatumToUnescapedPath(continuousFieldName)} + ${accessWithDatumToUnescapedPath(continuousAxisChannelDefError.field)}`,
            as: `upper_${continuousFieldName}`
          }
        ];
        if (continuousAxisChannelDefError2) {
          postAggregateCalculates.push({
            calculate: `${accessWithDatumToUnescapedPath(continuousFieldName)} + ${accessWithDatumToUnescapedPath(continuousAxisChannelDefError2.field)}`,
            as: `lower_${continuousFieldName}`
          });
        } else {
          postAggregateCalculates.push({
            calculate: `${accessWithDatumToUnescapedPath(continuousFieldName)} - ${accessWithDatumToUnescapedPath(continuousAxisChannelDefError.field)}`,
            as: `lower_${continuousFieldName}`
          });
        }
      }
      for (const postAggregateCalculate of postAggregateCalculates) {
        tooltipSummary.push({
          fieldPrefix: postAggregateCalculate.as.substring(0, 6),
          titlePrefix: replaceAll(replaceAll(postAggregateCalculate.calculate, "datum['", ""), "']", "")
        });
      }
    }
    return { postAggregateCalculates, errorBarSpecificAggregate, tooltipSummary, tooltipTitleWithFieldName };
  }
  function getTitlePrefix(center, extent2, operation) {
    return `${titleCase(center)} ${operation} ${extent2}`;
  }

  // node_modules/vega-lite/build/src/compositemark/errorband.js
  var ERRORBAND = "errorband";
  var ERRORBAND_PARTS = ["band", "borders"];
  var errorBandNormalizer = new CompositeMarkNormalizer(ERRORBAND, normalizeErrorBand);
  function normalizeErrorBand(spec, { config }) {
    spec = {
      ...spec,
      encoding: normalizeEncoding(spec.encoding, config)
    };
    const { transform: transform4, continuousAxisChannelDef, continuousAxis, encodingWithoutContinuousAxis, markDef, outerSpec, tooltipEncoding } = errorBarParams(spec, ERRORBAND, config);
    const errorBandDef = markDef;
    const makeErrorBandPart = makeCompositeAggregatePartFactory(errorBandDef, continuousAxis, continuousAxisChannelDef, encodingWithoutContinuousAxis, config.errorband);
    const is2D = spec.encoding.x !== void 0 && spec.encoding.y !== void 0;
    let bandMark = { type: is2D ? "area" : "rect" };
    let bordersMark = { type: is2D ? "line" : "rule" };
    const interpolate3 = {
      ...errorBandDef.interpolate ? { interpolate: errorBandDef.interpolate } : {},
      ...errorBandDef.tension && errorBandDef.interpolate ? { tension: errorBandDef.tension } : {}
    };
    if (is2D) {
      bandMark = {
        ...bandMark,
        ...interpolate3,
        ariaRoleDescription: "errorband"
      };
      bordersMark = {
        ...bordersMark,
        ...interpolate3,
        aria: false
      };
    } else if (errorBandDef.interpolate) {
      warn2(message_exports.errorBand1DNotSupport("interpolate"));
    } else if (errorBandDef.tension) {
      warn2(message_exports.errorBand1DNotSupport("tension"));
    }
    return {
      ...outerSpec,
      transform: transform4,
      layer: [
        ...makeErrorBandPart({
          partName: "band",
          mark: bandMark,
          positionPrefix: "lower",
          endPositionPrefix: "upper",
          extraEncoding: tooltipEncoding
        }),
        ...makeErrorBandPart({
          partName: "borders",
          mark: bordersMark,
          positionPrefix: "lower",
          extraEncoding: tooltipEncoding
        }),
        ...makeErrorBandPart({
          partName: "borders",
          mark: bordersMark,
          positionPrefix: "upper",
          extraEncoding: tooltipEncoding
        })
      ]
    };
  }

  // node_modules/vega-lite/build/src/compositemark/index.js
  var compositeMarkRegistry = {};
  function add5(mark, run2, parts) {
    const normalizer = new CompositeMarkNormalizer(mark, run2);
    compositeMarkRegistry[mark] = { normalizer, parts };
  }
  function getAllCompositeMarks() {
    return keys3(compositeMarkRegistry);
  }
  add5(BOXPLOT, normalizeBoxPlot, BOXPLOT_PARTS);
  add5(ERRORBAR, normalizeErrorBar, ERRORBAR_PARTS);
  add5(ERRORBAND, normalizeErrorBand, ERRORBAND_PARTS);

  // node_modules/vega-lite/build/src/guide.js
  var VL_ONLY_LEGEND_CONFIG = [
    "gradientHorizontalMaxLength",
    "gradientHorizontalMinLength",
    "gradientVerticalMaxLength",
    "gradientVerticalMinLength",
    "unselectedOpacity"
  ];

  // node_modules/vega-lite/build/src/header.js
  var HEADER_TITLE_PROPERTIES_MAP = {
    titleAlign: "align",
    titleAnchor: "anchor",
    titleAngle: "angle",
    titleBaseline: "baseline",
    titleColor: "color",
    titleFont: "font",
    titleFontSize: "fontSize",
    titleFontStyle: "fontStyle",
    titleFontWeight: "fontWeight",
    titleLimit: "limit",
    titleLineHeight: "lineHeight",
    titleOrient: "orient",
    titlePadding: "offset"
  };
  var HEADER_LABEL_PROPERTIES_MAP = {
    labelAlign: "align",
    labelAnchor: "anchor",
    labelAngle: "angle",
    labelBaseline: "baseline",
    labelColor: "color",
    labelFont: "font",
    labelFontSize: "fontSize",
    labelFontStyle: "fontStyle",
    labelFontWeight: "fontWeight",
    labelLimit: "limit",
    labelLineHeight: "lineHeight",
    labelOrient: "orient",
    labelPadding: "offset"
  };
  var HEADER_TITLE_PROPERTIES = keys3(HEADER_TITLE_PROPERTIES_MAP);
  var HEADER_LABEL_PROPERTIES = keys3(HEADER_LABEL_PROPERTIES_MAP);
  var HEADER_CONFIGS_INDEX = {
    header: 1,
    headerRow: 1,
    headerColumn: 1,
    headerFacet: 1
  };
  var HEADER_CONFIGS = keys3(HEADER_CONFIGS_INDEX);

  // node_modules/vega-lite/build/src/legend.js
  var LEGEND_SCALE_CHANNELS = [
    "size",
    "shape",
    "fill",
    "stroke",
    "strokeDash",
    "strokeWidth",
    "opacity"
  ];
  var defaultLegendConfig = {
    gradientHorizontalMaxLength: 200,
    gradientHorizontalMinLength: 100,
    gradientVerticalMaxLength: 200,
    gradientVerticalMinLength: 64,
    // This is Vega's minimum.
    unselectedOpacity: 0.35
  };
  var COMMON_LEGEND_PROPERTY_INDEX = {
    aria: 1,
    clipHeight: 1,
    columnPadding: 1,
    columns: 1,
    cornerRadius: 1,
    description: 1,
    direction: 1,
    fillColor: 1,
    format: 1,
    formatType: 1,
    gradientLength: 1,
    gradientOpacity: 1,
    gradientStrokeColor: 1,
    gradientStrokeWidth: 1,
    gradientThickness: 1,
    gridAlign: 1,
    labelAlign: 1,
    labelBaseline: 1,
    labelColor: 1,
    labelFont: 1,
    labelFontSize: 1,
    labelFontStyle: 1,
    labelFontWeight: 1,
    labelLimit: 1,
    labelOffset: 1,
    labelOpacity: 1,
    labelOverlap: 1,
    labelPadding: 1,
    labelSeparation: 1,
    legendX: 1,
    legendY: 1,
    offset: 1,
    orient: 1,
    padding: 1,
    rowPadding: 1,
    strokeColor: 1,
    symbolDash: 1,
    symbolDashOffset: 1,
    symbolFillColor: 1,
    symbolLimit: 1,
    symbolOffset: 1,
    symbolOpacity: 1,
    symbolSize: 1,
    symbolStrokeColor: 1,
    symbolStrokeWidth: 1,
    symbolType: 1,
    tickCount: 1,
    tickMinStep: 1,
    title: 1,
    titleAlign: 1,
    titleAnchor: 1,
    titleBaseline: 1,
    titleColor: 1,
    titleFont: 1,
    titleFontSize: 1,
    titleFontStyle: 1,
    titleFontWeight: 1,
    titleLimit: 1,
    titleLineHeight: 1,
    titleOpacity: 1,
    titleOrient: 1,
    titlePadding: 1,
    type: 1,
    values: 1,
    zindex: 1
  };
  var LEGEND_PROPERTIES = keys3(COMMON_LEGEND_PROPERTY_INDEX);

  // node_modules/vega-lite/build/src/selection.js
  var SELECTION_ID = "_vgsid_";
  var defaultConfig = {
    point: {
      on: "click",
      fields: [SELECTION_ID],
      toggle: "event.shiftKey",
      resolve: "global",
      clear: "dblclick"
    },
    interval: {
      on: "[pointerdown, window:pointerup] > window:pointermove!",
      encodings: ["x", "y"],
      translate: "[pointerdown, window:pointerup] > window:pointermove!",
      zoom: "wheel!",
      mark: { fill: "#333", fillOpacity: 0.125, stroke: "white" },
      resolve: "global",
      clear: "dblclick"
    }
  };
  function isLegendBinding(bind3) {
    return bind3 === "legend" || !!bind3?.legend;
  }
  function isLegendStreamBinding(bind3) {
    return isLegendBinding(bind3) && isObject(bind3);
  }
  function isSelectionParameter(param2) {
    return !!param2?.["select"];
  }

  // node_modules/vega-lite/build/src/parameter.js
  function assembleParameterSignals(params2) {
    const signals = [];
    for (const param2 of params2 || []) {
      if (isSelectionParameter(param2))
        continue;
      const { expr: expr2, bind: bind3, ...rest } = param2;
      if (bind3 && expr2) {
        const signal = {
          ...rest,
          bind: bind3,
          init: expr2
        };
        signals.push(signal);
      } else {
        const signal = {
          ...rest,
          ...expr2 ? { update: expr2 } : {},
          ...bind3 ? { bind: bind3 } : {}
        };
        signals.push(signal);
      }
    }
    return signals;
  }

  // node_modules/vega-lite/build/src/spec/concat.js
  function isAnyConcatSpec(spec) {
    return isVConcatSpec(spec) || isHConcatSpec(spec) || isConcatSpec(spec);
  }
  function isConcatSpec(spec) {
    return hasProperty(spec, "concat");
  }
  function isVConcatSpec(spec) {
    return hasProperty(spec, "vconcat");
  }
  function isHConcatSpec(spec) {
    return hasProperty(spec, "hconcat");
  }

  // node_modules/vega-lite/build/src/spec/base.js
  function getStepFor({ step, offsetIsDiscrete }) {
    if (offsetIsDiscrete) {
      return step.for ?? "offset";
    } else {
      return "position";
    }
  }
  function isStep(size) {
    return hasProperty(size, "step");
  }
  function isFrameMixins(o2) {
    return hasProperty(o2, "view") || hasProperty(o2, "width") || hasProperty(o2, "height");
  }
  var DEFAULT_SPACING = 20;
  var COMPOSITION_LAYOUT_INDEX = {
    align: 1,
    bounds: 1,
    center: 1,
    columns: 1,
    spacing: 1
  };
  var COMPOSITION_LAYOUT_PROPERTIES = keys3(COMPOSITION_LAYOUT_INDEX);
  function extractCompositionLayout(spec, specType, config) {
    const compositionConfig = config[specType];
    const layout = {};
    const { spacing: spacingConfig, columns: columns2 } = compositionConfig;
    if (spacingConfig !== void 0) {
      layout.spacing = spacingConfig;
    }
    if (columns2 !== void 0) {
      if (isFacetSpec(spec) && !isFacetMapping(spec.facet) || isConcatSpec(spec)) {
        layout.columns = columns2;
      }
    }
    if (isVConcatSpec(spec)) {
      layout.columns = 1;
    }
    for (const prop of COMPOSITION_LAYOUT_PROPERTIES) {
      if (spec[prop] !== void 0) {
        if (prop === "spacing") {
          const spacing = spec[prop];
          layout[prop] = isNumber(spacing) ? spacing : {
            row: spacing.row ?? spacingConfig,
            column: spacing.column ?? spacingConfig
          };
        } else {
          layout[prop] = spec[prop];
        }
      }
    }
    return layout;
  }

  // node_modules/vega-lite/build/src/config.js
  function getViewConfigContinuousSize(viewConfig, channel) {
    return viewConfig[channel] ?? viewConfig[channel === "width" ? "continuousWidth" : "continuousHeight"];
  }
  function getViewConfigDiscreteStep(viewConfig, channel) {
    const size = getViewConfigDiscreteSize(viewConfig, channel);
    return isStep(size) ? size.step : DEFAULT_STEP;
  }
  function getViewConfigDiscreteSize(viewConfig, channel) {
    const size = viewConfig[channel] ?? viewConfig[channel === "width" ? "discreteWidth" : "discreteHeight"];
    return getFirstDefined(size, { step: viewConfig.step });
  }
  var DEFAULT_STEP = 20;
  var defaultViewConfig = {
    continuousWidth: 200,
    continuousHeight: 200,
    step: DEFAULT_STEP
  };
  var defaultConfig2 = {
    background: "white",
    padding: 5,
    timeFormat: "%b %d, %Y",
    countTitle: "Count of Records",
    view: defaultViewConfig,
    mark: defaultMarkConfig,
    arc: {},
    area: {},
    bar: defaultBarConfig,
    circle: {},
    geoshape: {},
    image: {},
    line: {},
    point: {},
    rect: defaultRectConfig,
    rule: { color: "black" },
    // Need this to override default color in mark config
    square: {},
    text: { color: "black" },
    // Need this to override default color in mark config
    tick: defaultTickConfig,
    trail: {},
    boxplot: {
      size: 14,
      extent: 1.5,
      box: {},
      median: { color: "white" },
      outliers: {},
      rule: {},
      ticks: null
    },
    errorbar: {
      center: "mean",
      rule: true,
      ticks: false
    },
    errorband: {
      band: {
        opacity: 0.3
      },
      borders: false
    },
    scale: defaultScaleConfig,
    projection: {},
    legend: defaultLegendConfig,
    header: { titlePadding: 10, labelPadding: 10 },
    headerColumn: {},
    headerRow: {},
    headerFacet: {},
    selection: defaultConfig,
    style: {},
    title: {},
    facet: { spacing: DEFAULT_SPACING },
    concat: { spacing: DEFAULT_SPACING },
    normalizedNumberFormat: ".0%"
  };
  var tab10 = [
    "#4c78a8",
    "#f58518",
    "#e45756",
    "#72b7b2",
    "#54a24b",
    "#eeca3b",
    "#b279a2",
    "#ff9da6",
    "#9d755d",
    "#bab0ac"
  ];
  var DEFAULT_FONT_SIZE = {
    text: 11,
    guideLabel: 10,
    guideTitle: 11,
    groupTitle: 13,
    groupSubtitle: 12
  };
  var DEFAULT_COLOR = {
    blue: tab10[0],
    orange: tab10[1],
    red: tab10[2],
    teal: tab10[3],
    green: tab10[4],
    yellow: tab10[5],
    purple: tab10[6],
    pink: tab10[7],
    brown: tab10[8],
    gray0: "#000",
    gray1: "#111",
    gray2: "#222",
    gray3: "#333",
    gray4: "#444",
    gray5: "#555",
    gray6: "#666",
    gray7: "#777",
    gray8: "#888",
    gray9: "#999",
    gray10: "#aaa",
    gray11: "#bbb",
    gray12: "#ccc",
    gray13: "#ddd",
    gray14: "#eee",
    gray15: "#fff"
  };
  function colorSignalConfig(color5 = {}) {
    return {
      signals: [
        {
          name: "color",
          value: isObject(color5) ? { ...DEFAULT_COLOR, ...color5 } : DEFAULT_COLOR
        }
      ],
      mark: { color: { signal: "color.blue" } },
      rule: { color: { signal: "color.gray0" } },
      text: {
        color: { signal: "color.gray0" }
      },
      style: {
        "guide-label": {
          fill: { signal: "color.gray0" }
        },
        "guide-title": {
          fill: { signal: "color.gray0" }
        },
        "group-title": {
          fill: { signal: "color.gray0" }
        },
        "group-subtitle": {
          fill: { signal: "color.gray0" }
        },
        cell: {
          stroke: { signal: "color.gray8" }
        }
      },
      axis: {
        domainColor: { signal: "color.gray13" },
        gridColor: { signal: "color.gray8" },
        tickColor: { signal: "color.gray13" }
      },
      range: {
        category: [
          { signal: "color.blue" },
          { signal: "color.orange" },
          { signal: "color.red" },
          { signal: "color.teal" },
          { signal: "color.green" },
          { signal: "color.yellow" },
          { signal: "color.purple" },
          { signal: "color.pink" },
          { signal: "color.brown" },
          { signal: "color.grey8" }
        ]
      }
    };
  }
  function fontSizeSignalConfig(fontSize2) {
    return {
      signals: [
        {
          name: "fontSize",
          value: isObject(fontSize2) ? { ...DEFAULT_FONT_SIZE, ...fontSize2 } : DEFAULT_FONT_SIZE
        }
      ],
      text: {
        fontSize: { signal: "fontSize.text" }
      },
      style: {
        "guide-label": {
          fontSize: { signal: "fontSize.guideLabel" }
        },
        "guide-title": {
          fontSize: { signal: "fontSize.guideTitle" }
        },
        "group-title": {
          fontSize: { signal: "fontSize.groupTitle" }
        },
        "group-subtitle": {
          fontSize: { signal: "fontSize.groupSubtitle" }
        }
      }
    };
  }
  function fontConfig(font3) {
    return {
      text: { font: font3 },
      style: {
        "guide-label": { font: font3 },
        "guide-title": { font: font3 },
        "group-title": { font: font3 },
        "group-subtitle": { font: font3 }
      }
    };
  }
  function getAxisConfigInternal(axisConfig2) {
    const props = keys3(axisConfig2 || {});
    const axisConfigInternal = {};
    for (const prop of props) {
      const val = axisConfig2[prop];
      axisConfigInternal[prop] = isConditionalAxisValue(val) ? signalOrValueRefWithCondition(val) : signalRefOrValue(val);
    }
    return axisConfigInternal;
  }
  function getStyleConfigInternal(styleConfig) {
    const props = keys3(styleConfig);
    const styleConfigInternal = {};
    for (const prop of props) {
      styleConfigInternal[prop] = getAxisConfigInternal(styleConfig[prop]);
    }
    return styleConfigInternal;
  }
  var configPropsWithExpr = [
    ...MARK_CONFIGS,
    ...AXIS_CONFIGS,
    ...HEADER_CONFIGS,
    "background",
    "padding",
    "legend",
    "lineBreak",
    "scale",
    "style",
    "title",
    "view"
  ];
  function initConfig(specifiedConfig = {}) {
    const { color: color5, font: font3, fontSize: fontSize2, selection, ...restConfig } = specifiedConfig;
    const mergedConfig = mergeConfig({}, duplicate(defaultConfig2), font3 ? fontConfig(font3) : {}, color5 ? colorSignalConfig(color5) : {}, fontSize2 ? fontSizeSignalConfig(fontSize2) : {}, restConfig || {});
    if (selection) {
      writeConfig(mergedConfig, "selection", selection, true);
    }
    const outputConfig = omit(mergedConfig, configPropsWithExpr);
    for (const prop of ["background", "lineBreak", "padding"]) {
      if (mergedConfig[prop]) {
        outputConfig[prop] = signalRefOrValue(mergedConfig[prop]);
      }
    }
    for (const markConfigType of MARK_CONFIGS) {
      if (mergedConfig[markConfigType]) {
        outputConfig[markConfigType] = replaceExprRef(mergedConfig[markConfigType]);
      }
    }
    for (const axisConfigType of AXIS_CONFIGS) {
      if (mergedConfig[axisConfigType]) {
        outputConfig[axisConfigType] = getAxisConfigInternal(mergedConfig[axisConfigType]);
      }
    }
    for (const headerConfigType of HEADER_CONFIGS) {
      if (mergedConfig[headerConfigType]) {
        outputConfig[headerConfigType] = replaceExprRef(mergedConfig[headerConfigType]);
      }
    }
    if (mergedConfig.legend) {
      outputConfig.legend = replaceExprRef(mergedConfig.legend);
    }
    if (mergedConfig.scale) {
      const { invalid, ...otherScaleConfig } = mergedConfig.scale;
      const newScaleInvalid = replaceExprRef(invalid, { level: 1 });
      outputConfig.scale = {
        ...replaceExprRef(otherScaleConfig),
        ...keys3(newScaleInvalid).length > 0 ? { invalid: newScaleInvalid } : {}
      };
    }
    if (mergedConfig.style) {
      outputConfig.style = getStyleConfigInternal(mergedConfig.style);
    }
    if (mergedConfig.title) {
      outputConfig.title = replaceExprRef(mergedConfig.title);
    }
    if (mergedConfig.view) {
      outputConfig.view = replaceExprRef(mergedConfig.view);
    }
    return outputConfig;
  }
  var MARK_STYLES = /* @__PURE__ */ new Set(["view", ...PRIMITIVE_MARKS]);
  var VL_ONLY_CONFIG_PROPERTIES = [
    "color",
    "fontSize",
    "background",
    // We apply background to the spec directly.
    "padding",
    "facet",
    "concat",
    "numberFormat",
    "numberFormatType",
    "normalizedNumberFormat",
    "normalizedNumberFormatType",
    "timeFormat",
    "countTitle",
    "header",
    "axisQuantitative",
    "axisTemporal",
    "axisDiscrete",
    "axisPoint",
    "axisXBand",
    "axisXPoint",
    "axisXDiscrete",
    "axisXQuantitative",
    "axisXTemporal",
    "axisYBand",
    "axisYPoint",
    "axisYDiscrete",
    "axisYQuantitative",
    "axisYTemporal",
    "scale",
    "selection",
    "overlay"
    // FIXME: Redesign and unhide this
  ];
  var VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = {
    view: ["continuousWidth", "continuousHeight", "discreteWidth", "discreteHeight", "step"],
    ...VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX
  };
  function stripAndRedirectConfig(config) {
    config = duplicate(config);
    for (const prop of VL_ONLY_CONFIG_PROPERTIES) {
      delete config[prop];
    }
    if (config.axis) {
      for (const prop in config.axis) {
        if (isConditionalAxisValue(config.axis[prop])) {
          delete config.axis[prop];
        }
      }
    }
    if (config.legend) {
      for (const prop of VL_ONLY_LEGEND_CONFIG) {
        delete config.legend[prop];
      }
    }
    if (config.mark) {
      for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {
        delete config.mark[prop];
      }
      if (config.mark.tooltip && isObject(config.mark.tooltip)) {
        delete config.mark.tooltip;
      }
    }
    if (config.params) {
      config.signals = (config.signals || []).concat(assembleParameterSignals(config.params));
      delete config.params;
    }
    for (const markType2 of MARK_STYLES) {
      for (const prop of VL_ONLY_MARK_CONFIG_PROPERTIES) {
        delete config[markType2][prop];
      }
      const vlOnlyMarkSpecificConfigs = VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[markType2];
      if (vlOnlyMarkSpecificConfigs) {
        for (const prop of vlOnlyMarkSpecificConfigs) {
          delete config[markType2][prop];
        }
      }
      redirectConfigToStyleConfig(config, markType2);
    }
    for (const m4 of getAllCompositeMarks()) {
      delete config[m4];
    }
    redirectTitleConfig(config);
    for (const prop in config) {
      if (isObject(config[prop]) && isEmpty(config[prop])) {
        delete config[prop];
      }
    }
    return isEmpty(config) ? void 0 : config;
  }
  function redirectTitleConfig(config) {
    const { titleMarkConfig, subtitleMarkConfig, subtitle } = extractTitleConfig(config.title);
    if (!isEmpty(titleMarkConfig)) {
      config.style["group-title"] = {
        ...config.style["group-title"],
        ...titleMarkConfig
        // config.title has higher precedence than config.style.group-title in Vega
      };
    }
    if (!isEmpty(subtitleMarkConfig)) {
      config.style["group-subtitle"] = {
        ...config.style["group-subtitle"],
        ...subtitleMarkConfig
      };
    }
    if (!isEmpty(subtitle)) {
      config.title = subtitle;
    } else {
      delete config.title;
    }
  }
  function redirectConfigToStyleConfig(config, prop, toProp, compositeMarkPart) {
    const propConfig = compositeMarkPart ? config[prop][compositeMarkPart] : config[prop];
    if (prop === "view") {
      toProp = "cell";
    }
    const style2 = {
      ...propConfig,
      ...config.style[toProp ?? prop]
    };
    if (!isEmpty(style2)) {
      config.style[toProp ?? prop] = style2;
    }
    if (!compositeMarkPart) {
      delete config[prop];
    }
  }

  // node_modules/vega-lite/build/src/spec/layer.js
  function isLayerSpec(spec) {
    return hasProperty(spec, "layer");
  }

  // node_modules/vega-lite/build/src/spec/repeat.js
  function isRepeatSpec(spec) {
    return hasProperty(spec, "repeat");
  }
  function isLayerRepeatSpec(spec) {
    return !isArray(spec.repeat) && hasProperty(spec.repeat, "layer");
  }

  // node_modules/vega-lite/build/src/spec/map.js
  var SpecMapper = class {
    map(spec, params2) {
      if (isFacetSpec(spec)) {
        return this.mapFacet(spec, params2);
      } else if (isRepeatSpec(spec)) {
        return this.mapRepeat(spec, params2);
      } else if (isHConcatSpec(spec)) {
        return this.mapHConcat(spec, params2);
      } else if (isVConcatSpec(spec)) {
        return this.mapVConcat(spec, params2);
      } else if (isConcatSpec(spec)) {
        return this.mapConcat(spec, params2);
      } else {
        return this.mapLayerOrUnit(spec, params2);
      }
    }
    mapLayerOrUnit(spec, params2) {
      if (isLayerSpec(spec)) {
        return this.mapLayer(spec, params2);
      } else if (isUnitSpec(spec)) {
        return this.mapUnit(spec, params2);
      }
      throw new Error(message_exports.invalidSpec(spec));
    }
    mapLayer(spec, params2) {
      return {
        ...spec,
        layer: spec.layer.map((subspec) => this.mapLayerOrUnit(subspec, params2))
      };
    }
    mapHConcat(spec, params2) {
      return {
        ...spec,
        hconcat: spec.hconcat.map((subspec) => this.map(subspec, params2))
      };
    }
    mapVConcat(spec, params2) {
      return {
        ...spec,
        vconcat: spec.vconcat.map((subspec) => this.map(subspec, params2))
      };
    }
    mapConcat(spec, params2) {
      const { concat, ...rest } = spec;
      return {
        ...rest,
        concat: concat.map((subspec) => this.map(subspec, params2))
      };
    }
    mapFacet(spec, params2) {
      return {
        // as any is required here since TS cannot infer that FO may only be FieldName or Field, but not RepeatRef
        ...spec,
        // TODO: remove "any" once we support all facet listed in https://github.com/vega/vega-lite/issues/2760
        spec: this.map(spec.spec, params2)
      };
    }
    mapRepeat(spec, params2) {
      return {
        ...spec,
        // as any is required here since TS cannot infer that the output type satisfies the input type
        spec: this.map(spec.spec, params2)
      };
    }
  };

  // node_modules/vega-lite/build/src/stack.js
  var STACK_OFFSET_INDEX = {
    zero: 1,
    center: 1,
    normalize: 1
  };
  function isStackOffset(s2) {
    return has(STACK_OFFSET_INDEX, s2);
  }
  var STACKABLE_MARKS = /* @__PURE__ */ new Set([ARC, BAR, AREA, RULE, POINT, CIRCLE, SQUARE, LINE, TEXT2, TICK]);
  var STACK_BY_DEFAULT_MARKS = /* @__PURE__ */ new Set([BAR, AREA, ARC]);
  function isUnbinnedQuantitative(channelDef) {
    return isFieldDef(channelDef) && channelDefType(channelDef) === "quantitative" && !channelDef.bin;
  }
  function potentialStackedChannel(encoding, x5, { orient: orient2, type: mark }) {
    const y5 = x5 === "x" ? "y" : "radius";
    const isCartesianBarOrArea = x5 === "x" && ["bar", "area"].includes(mark);
    const xDef = encoding[x5];
    const yDef = encoding[y5];
    if (isFieldDef(xDef) && isFieldDef(yDef)) {
      if (isUnbinnedQuantitative(xDef) && isUnbinnedQuantitative(yDef)) {
        if (xDef.stack) {
          return x5;
        } else if (yDef.stack) {
          return y5;
        }
        const xAggregate = isFieldDef(xDef) && !!xDef.aggregate;
        const yAggregate = isFieldDef(yDef) && !!yDef.aggregate;
        if (xAggregate !== yAggregate) {
          return xAggregate ? x5 : y5;
        }
        if (isCartesianBarOrArea) {
          if (orient2 === "vertical") {
            return y5;
          } else if (orient2 === "horizontal") {
            return x5;
          }
        }
      } else if (isUnbinnedQuantitative(xDef)) {
        return x5;
      } else if (isUnbinnedQuantitative(yDef)) {
        return y5;
      }
    } else if (isUnbinnedQuantitative(xDef)) {
      if (isCartesianBarOrArea && orient2 === "vertical") {
        return void 0;
      }
      return x5;
    } else if (isUnbinnedQuantitative(yDef)) {
      if (isCartesianBarOrArea && orient2 === "horizontal") {
        return void 0;
      }
      return y5;
    }
    return void 0;
  }
  function getDimensionChannel(channel) {
    switch (channel) {
      case "x":
        return "y";
      case "y":
        return "x";
      case "theta":
        return "radius";
      case "radius":
        return "theta";
    }
  }
  function stack(m4, encoding) {
    const markDef = isMarkDef(m4) ? m4 : { type: m4 };
    const mark = markDef.type;
    if (!STACKABLE_MARKS.has(mark)) {
      return null;
    }
    const fieldChannel = potentialStackedChannel(encoding, "x", markDef) || potentialStackedChannel(encoding, "theta", markDef);
    if (!fieldChannel) {
      return null;
    }
    const stackedFieldDef = encoding[fieldChannel];
    const stackedField = isFieldDef(stackedFieldDef) ? vgField(stackedFieldDef, {}) : void 0;
    const dimensionChannel = getDimensionChannel(fieldChannel);
    const groupbyChannels = [];
    const groupbyFields = /* @__PURE__ */ new Set();
    if (encoding[dimensionChannel]) {
      const dimensionDef = encoding[dimensionChannel];
      const dimensionField = isFieldDef(dimensionDef) ? vgField(dimensionDef, {}) : void 0;
      if (dimensionField && dimensionField !== stackedField) {
        groupbyChannels.push(dimensionChannel);
        groupbyFields.add(dimensionField);
      }
    }
    const dimensionOffsetChannel = dimensionChannel === "x" ? "xOffset" : "yOffset";
    const dimensionOffsetDef = encoding[dimensionOffsetChannel];
    const dimensionOffsetField = isFieldDef(dimensionOffsetDef) ? vgField(dimensionOffsetDef, {}) : void 0;
    if (dimensionOffsetField && dimensionOffsetField !== stackedField) {
      groupbyChannels.push(dimensionOffsetChannel);
      groupbyFields.add(dimensionOffsetField);
    }
    const stackBy = NONPOSITION_CHANNELS.reduce((sc, channel) => {
      if (channel !== "tooltip" && channelHasField(encoding, channel)) {
        const channelDef = encoding[channel];
        for (const cDef of array(channelDef)) {
          const fieldDef = getFieldDef(cDef);
          if (fieldDef.aggregate) {
            continue;
          }
          const f2 = vgField(fieldDef, {});
          if (
            // if fielddef is a repeat, just include it in the stack by
            !f2 || // otherwise, the field must be different from the groupBy fields.
            !groupbyFields.has(f2)
          ) {
            sc.push({ channel, fieldDef });
          }
        }
      }
      return sc;
    }, []);
    let offset4;
    if (stackedFieldDef.stack !== void 0) {
      if (isBoolean(stackedFieldDef.stack)) {
        offset4 = stackedFieldDef.stack ? "zero" : null;
      } else {
        offset4 = stackedFieldDef.stack;
      }
    } else if (STACK_BY_DEFAULT_MARKS.has(mark)) {
      offset4 = "zero";
    }
    if (!offset4 || !isStackOffset(offset4)) {
      return null;
    }
    if (isAggregate(encoding) && stackBy.length === 0) {
      return null;
    }
    if (stackedFieldDef?.scale?.type && stackedFieldDef?.scale?.type !== ScaleType.LINEAR) {
      if (stackedFieldDef?.stack) {
        warn2(message_exports.stackNonLinearScale(stackedFieldDef.scale.type));
      }
    }
    if (isFieldOrDatumDef(encoding[getSecondaryRangeChannel(fieldChannel)])) {
      if (stackedFieldDef.stack !== void 0) {
        warn2(message_exports.cannotStackRangedMark(fieldChannel));
      }
      return null;
    }
    if (isFieldDef(stackedFieldDef) && stackedFieldDef.aggregate && !SUM_OPS.has(stackedFieldDef.aggregate)) {
      warn2(message_exports.stackNonSummativeAggregate(stackedFieldDef.aggregate));
    }
    return {
      groupbyChannels,
      groupbyFields,
      fieldChannel,
      impute: stackedFieldDef.impute === null ? false : isPathMark(mark),
      stackBy,
      offset: offset4
    };
  }

  // node_modules/vega-lite/build/src/compile/mark/init.js
  function initMarkdef(originalMarkDef, encoding, config) {
    const markDef = replaceExprRef(originalMarkDef);
    const specifiedOrient = getMarkPropOrConfig("orient", markDef, config);
    markDef.orient = orient(markDef.type, encoding, specifiedOrient);
    if (specifiedOrient !== void 0 && specifiedOrient !== markDef.orient) {
      warn2(message_exports.orientOverridden(markDef.orient, specifiedOrient));
    }
    if (markDef.type === "bar" && markDef.orient) {
      const cornerRadiusEnd = getMarkPropOrConfig("cornerRadiusEnd", markDef, config);
      if (cornerRadiusEnd !== void 0) {
        const newProps = markDef.orient === "horizontal" && encoding.x2 || markDef.orient === "vertical" && encoding.y2 ? ["cornerRadius"] : BAR_CORNER_RADIUS_INDEX[markDef.orient];
        for (const newProp of newProps) {
          markDef[newProp] = cornerRadiusEnd;
        }
        if (markDef.cornerRadiusEnd !== void 0) {
          delete markDef.cornerRadiusEnd;
        }
      }
    }
    const specifiedOpacity = getMarkPropOrConfig("opacity", markDef, config);
    const specifiedfillOpacity = getMarkPropOrConfig("fillOpacity", markDef, config);
    if (specifiedOpacity === void 0 && specifiedfillOpacity === void 0) {
      markDef.opacity = opacity(markDef.type, encoding);
    }
    const specifiedCursor = getMarkPropOrConfig("cursor", markDef, config);
    if (specifiedCursor === void 0) {
      markDef.cursor = cursor2(markDef, encoding, config);
    }
    return markDef;
  }
  function cursor2(markDef, encoding, config) {
    if (encoding.href || markDef.href || getMarkPropOrConfig("href", markDef, config)) {
      return "pointer";
    }
    return markDef.cursor;
  }
  function opacity(mark, encoding) {
    if (contains2([POINT, TICK, CIRCLE, SQUARE], mark)) {
      if (!isAggregate(encoding)) {
        return 0.7;
      }
    }
    return void 0;
  }
  function defaultFilled(markDef, config, { graticule: graticule2 }) {
    if (graticule2) {
      return false;
    }
    const filledConfig = getMarkConfig("filled", markDef, config);
    const mark = markDef.type;
    return getFirstDefined(filledConfig, mark !== POINT && mark !== LINE && mark !== RULE);
  }
  function orient(mark, encoding, specifiedOrient) {
    switch (mark) {
      case POINT:
      case CIRCLE:
      case SQUARE:
      case TEXT2:
      case RECT:
      case IMAGE:
        return void 0;
    }
    const { x: x5, y: y5, x2: x22, y2: y22 } = encoding;
    switch (mark) {
      case BAR:
        if (isFieldDef(x5) && (isBinned(x5.bin) || isFieldDef(y5) && y5.aggregate && !x5.aggregate)) {
          return "vertical";
        }
        if (isFieldDef(y5) && (isBinned(y5.bin) || isFieldDef(x5) && x5.aggregate && !y5.aggregate)) {
          return "horizontal";
        }
        if (y22 || x22) {
          if (specifiedOrient) {
            return specifiedOrient;
          }
          if (!x22) {
            if (isFieldDef(x5) && x5.type === QUANTITATIVE && !isBinning(x5.bin) || isNumericDataDef(x5)) {
              if (isFieldDef(y5) && isBinned(y5.bin)) {
                return "horizontal";
              }
            }
            return "vertical";
          }
          if (!y22) {
            if (isFieldDef(y5) && y5.type === QUANTITATIVE && !isBinning(y5.bin) || isNumericDataDef(y5)) {
              if (isFieldDef(x5) && isBinned(x5.bin)) {
                return "vertical";
              }
            }
            return "horizontal";
          }
        }
      // falls through
      case RULE:
        if (x22 && !(isFieldDef(x5) && isBinned(x5.bin)) && y22 && !(isFieldDef(y5) && isBinned(y5.bin))) {
          return void 0;
        }
      // falls through
      case AREA:
        if (y22) {
          if (isFieldDef(y5) && isBinned(y5.bin)) {
            return "horizontal";
          } else {
            return "vertical";
          }
        } else if (x22) {
          if (isFieldDef(x5) && isBinned(x5.bin)) {
            return "vertical";
          } else {
            return "horizontal";
          }
        } else if (mark === RULE) {
          if (x5 && !y5) {
            return "vertical";
          } else if (y5 && !x5) {
            return "horizontal";
          }
        }
      // falls through
      case LINE:
      case TICK: {
        const xIsMeasure = isUnbinnedQuantitativeFieldOrDatumDef(x5);
        const yIsMeasure = isUnbinnedQuantitativeFieldOrDatumDef(y5);
        if (specifiedOrient) {
          return specifiedOrient;
        } else if (xIsMeasure && !yIsMeasure) {
          return mark !== "tick" ? "horizontal" : "vertical";
        } else if (!xIsMeasure && yIsMeasure) {
          return mark !== "tick" ? "vertical" : "horizontal";
        } else if (xIsMeasure && yIsMeasure) {
          return "vertical";
        } else {
          const xIsTemporal = isTypedFieldDef(x5) && x5.type === TEMPORAL;
          const yIsTemporal = isTypedFieldDef(y5) && y5.type === TEMPORAL;
          if (xIsTemporal && !yIsTemporal) {
            return "vertical";
          } else if (!xIsTemporal && yIsTemporal) {
            return "horizontal";
          }
        }
        return void 0;
      }
    }
    return "vertical";
  }

  // node_modules/vega-lite/build/src/normalize/pathoverlay.js
  function dropLineAndPoint(markDef) {
    const { point: _point, line: _line, ...mark } = markDef;
    return keys3(mark).length > 1 ? mark : mark.type;
  }
  function dropLineAndPointFromConfig(config) {
    for (const mark of ["line", "area", "rule", "trail"]) {
      if (config[mark]) {
        config = {
          ...config,
          // TODO: remove as any
          [mark]: omit(config[mark], ["point", "line"])
        };
      }
    }
    return config;
  }
  function getPointOverlay(markDef, markConfig = {}, encoding) {
    if (markDef.point === "transparent") {
      return { opacity: 0 };
    } else if (markDef.point) {
      return isObject(markDef.point) ? markDef.point : {};
    } else if (markDef.point !== void 0) {
      return null;
    } else {
      if (markConfig.point || encoding.shape) {
        return isObject(markConfig.point) ? markConfig.point : {};
      }
      return void 0;
    }
  }
  function getLineOverlay(markDef, markConfig = {}) {
    if (markDef.line) {
      return markDef.line === true ? {} : markDef.line;
    } else if (markDef.line !== void 0) {
      return null;
    } else {
      if (markConfig.line) {
        return markConfig.line === true ? {} : markConfig.line;
      }
      return void 0;
    }
  }
  var PathOverlayNormalizer = class {
    constructor() {
      this.name = "path-overlay";
    }
    hasMatchingType(spec, config) {
      if (isUnitSpec(spec)) {
        const { mark, encoding } = spec;
        const markDef = isMarkDef(mark) ? mark : { type: mark };
        switch (markDef.type) {
          case "line":
          case "rule":
          case "trail":
            return !!getPointOverlay(markDef, config[markDef.type], encoding);
          case "area":
            return (
              // false / null are also included as we want to remove the properties
              !!getPointOverlay(markDef, config[markDef.type], encoding) || !!getLineOverlay(markDef, config[markDef.type])
            );
        }
      }
      return false;
    }
    run(spec, normParams, normalize4) {
      const { config } = normParams;
      const { params: params2, projection: projection3, mark, name: name4, encoding: e4, ...outerSpec } = spec;
      const encoding = normalizeEncoding(e4, config);
      const markDef = isMarkDef(mark) ? mark : { type: mark };
      const pointOverlay = getPointOverlay(markDef, config[markDef.type], encoding);
      const lineOverlay = markDef.type === "area" && getLineOverlay(markDef, config[markDef.type]);
      const layer = [
        {
          name: name4,
          ...params2 ? { params: params2 } : {},
          mark: dropLineAndPoint({
            // TODO: extract this 0.7 to be shared with default opacity for point/tick/...
            ...markDef.type === "area" && markDef.opacity === void 0 && markDef.fillOpacity === void 0 ? { opacity: 0.7 } : {},
            ...markDef
          }),
          // drop shape from encoding as this might be used to trigger point overlay
          encoding: omit(encoding, ["shape"])
        }
      ];
      const stackProps = stack(initMarkdef(markDef, encoding, config), encoding);
      let overlayEncoding = encoding;
      if (stackProps) {
        const { fieldChannel: stackFieldChannel, offset: offset4 } = stackProps;
        overlayEncoding = {
          ...encoding,
          [stackFieldChannel]: {
            ...encoding[stackFieldChannel],
            ...offset4 ? { stack: offset4 } : {}
          }
        };
      }
      overlayEncoding = omit(overlayEncoding, ["y2", "x2"]);
      if (lineOverlay) {
        layer.push({
          ...projection3 ? { projection: projection3 } : {},
          mark: {
            type: "line",
            ...pick2(markDef, ["clip", "interpolate", "tension", "tooltip"]),
            ...lineOverlay
          },
          encoding: overlayEncoding
        });
      }
      if (pointOverlay) {
        layer.push({
          ...projection3 ? { projection: projection3 } : {},
          mark: {
            type: "point",
            opacity: 1,
            filled: true,
            ...pick2(markDef, ["clip", "tooltip"]),
            ...pointOverlay
          },
          encoding: overlayEncoding
        });
      }
      return normalize4({
        ...outerSpec,
        layer
      }, {
        ...normParams,
        config: dropLineAndPointFromConfig(config)
      });
    }
  };

  // node_modules/vega-lite/build/src/normalize/repeater.js
  function replaceRepeaterInFacet(facet, repeater) {
    if (!repeater) {
      return facet;
    }
    if (isFacetMapping(facet)) {
      return replaceRepeaterInMapping(facet, repeater);
    }
    return replaceRepeaterInFieldDef(facet, repeater);
  }
  function replaceRepeaterInEncoding(encoding, repeater) {
    if (!repeater) {
      return encoding;
    }
    return replaceRepeaterInMapping(encoding, repeater);
  }
  function replaceRepeatInProp(prop, o2, repeater) {
    const val = o2[prop];
    if (isRepeatRef(val)) {
      if (val.repeat in repeater) {
        return { ...o2, [prop]: repeater[val.repeat] };
      } else {
        warn2(message_exports.noSuchRepeatedValue(val.repeat));
        return void 0;
      }
    }
    return o2;
  }
  function replaceRepeaterInFieldDef(fieldDef, repeater) {
    fieldDef = replaceRepeatInProp("field", fieldDef, repeater);
    if (fieldDef === void 0) {
      return void 0;
    } else if (fieldDef === null) {
      return null;
    }
    if (isSortableFieldDef(fieldDef) && isSortField(fieldDef.sort)) {
      const sort3 = replaceRepeatInProp("field", fieldDef.sort, repeater);
      fieldDef = {
        ...fieldDef,
        ...sort3 ? { sort: sort3 } : {}
      };
    }
    return fieldDef;
  }
  function replaceRepeaterInFieldOrDatumDef(def2, repeater) {
    if (isFieldDef(def2)) {
      return replaceRepeaterInFieldDef(def2, repeater);
    } else {
      const datumDef = replaceRepeatInProp("datum", def2, repeater);
      if (datumDef !== def2 && !datumDef.type) {
        datumDef.type = "nominal";
      }
      return datumDef;
    }
  }
  function replaceRepeaterInChannelDef(channelDef, repeater) {
    if (isFieldOrDatumDef(channelDef)) {
      const fd = replaceRepeaterInFieldOrDatumDef(channelDef, repeater);
      if (fd) {
        return fd;
      } else if (isConditionalDef(channelDef)) {
        return { condition: channelDef.condition };
      }
    } else {
      if (hasConditionalFieldOrDatumDef(channelDef)) {
        const fd = replaceRepeaterInFieldOrDatumDef(channelDef.condition, repeater);
        if (fd) {
          return {
            ...channelDef,
            condition: fd
          };
        } else {
          const { condition, ...channelDefWithoutCondition } = channelDef;
          return channelDefWithoutCondition;
        }
      }
      return channelDef;
    }
    return void 0;
  }
  function replaceRepeaterInMapping(mapping, repeater) {
    const out = {};
    for (const channel in mapping) {
      if (hasProperty(mapping, channel)) {
        const channelDef = mapping[channel];
        if (isArray(channelDef)) {
          out[channel] = channelDef.map((cd2) => replaceRepeaterInChannelDef(cd2, repeater)).filter((cd2) => cd2);
        } else {
          const cd2 = replaceRepeaterInChannelDef(channelDef, repeater);
          if (cd2 !== void 0) {
            out[channel] = cd2;
          }
        }
      }
    }
    return out;
  }

  // node_modules/vega-lite/build/src/normalize/ruleforrangedline.js
  var RuleForRangedLineNormalizer = class {
    constructor() {
      this.name = "RuleForRangedLine";
    }
    hasMatchingType(spec) {
      if (isUnitSpec(spec)) {
        const { encoding, mark } = spec;
        if (mark === "line" || isMarkDef(mark) && mark.type === "line") {
          for (const channel of SECONDARY_RANGE_CHANNEL) {
            const mainChannel = getMainRangeChannel(channel);
            const mainChannelDef = encoding[mainChannel];
            if (encoding[channel]) {
              if (isFieldDef(mainChannelDef) && !isBinned(mainChannelDef.bin) || isDatumDef(mainChannelDef)) {
                return true;
              }
            }
          }
        }
      }
      return false;
    }
    run(spec, params2, normalize4) {
      const { encoding, mark } = spec;
      warn2(message_exports.lineWithRange(!!encoding.x2, !!encoding.y2));
      return normalize4({
        ...spec,
        mark: isObject(mark) ? { ...mark, type: "rule" } : "rule"
      }, params2);
    }
  };

  // node_modules/vega-lite/build/src/normalize/core.js
  var CoreNormalizer = class extends SpecMapper {
    constructor() {
      super(...arguments);
      this.nonFacetUnitNormalizers = [
        boxPlotNormalizer,
        errorBarNormalizer,
        errorBandNormalizer,
        new PathOverlayNormalizer(),
        new RuleForRangedLineNormalizer()
      ];
    }
    map(spec, params2) {
      if (isUnitSpec(spec)) {
        const hasRow = channelHasField(spec.encoding, ROW);
        const hasColumn = channelHasField(spec.encoding, COLUMN);
        const hasFacet = channelHasField(spec.encoding, FACET);
        if (hasRow || hasColumn || hasFacet) {
          return this.mapFacetedUnit(spec, params2);
        }
      }
      return super.map(spec, params2);
    }
    // This is for normalizing non-facet unit
    mapUnit(spec, params2) {
      const { parentEncoding, parentProjection } = params2;
      const encoding = replaceRepeaterInEncoding(spec.encoding, params2.repeater);
      const specWithReplacedEncoding = {
        ...spec,
        ...spec.name ? { name: [params2.repeaterPrefix, spec.name].filter((n2) => n2).join("_") } : {},
        ...encoding ? { encoding } : {}
      };
      if (parentEncoding || parentProjection) {
        return this.mapUnitWithParentEncodingOrProjection(specWithReplacedEncoding, params2);
      }
      const normalizeLayerOrUnit = this.mapLayerOrUnit.bind(this);
      for (const unitNormalizer of this.nonFacetUnitNormalizers) {
        if (unitNormalizer.hasMatchingType(specWithReplacedEncoding, params2.config)) {
          return unitNormalizer.run(specWithReplacedEncoding, params2, normalizeLayerOrUnit);
        }
      }
      return specWithReplacedEncoding;
    }
    mapRepeat(spec, params2) {
      if (isLayerRepeatSpec(spec)) {
        return this.mapLayerRepeat(spec, params2);
      } else {
        return this.mapNonLayerRepeat(spec, params2);
      }
    }
    mapLayerRepeat(spec, params2) {
      const { repeat: repeat2, spec: childSpec, ...rest } = spec;
      const { row, column, layer } = repeat2;
      const { repeater = {}, repeaterPrefix = "" } = params2;
      if (row || column) {
        return this.mapRepeat({
          ...spec,
          repeat: {
            ...row ? { row } : {},
            ...column ? { column } : {}
          },
          spec: {
            repeat: { layer },
            spec: childSpec
          }
        }, params2);
      } else {
        return {
          ...rest,
          layer: layer.map((layerValue) => {
            const childRepeater = {
              ...repeater,
              layer: layerValue
            };
            const childName = `${(childSpec.name ? `${childSpec.name}_` : "") + repeaterPrefix}child__layer_${varName(layerValue)}`;
            const child = this.mapLayerOrUnit(childSpec, { ...params2, repeater: childRepeater, repeaterPrefix: childName });
            child.name = childName;
            return child;
          })
        };
      }
    }
    mapNonLayerRepeat(spec, params2) {
      const { repeat: repeat2, spec: childSpec, data: data3, ...remainingProperties } = spec;
      if (!isArray(repeat2) && spec.columns) {
        spec = omit(spec, ["columns"]);
        warn2(message_exports.columnsNotSupportByRowCol("repeat"));
      }
      const concat = [];
      const { repeater = {}, repeaterPrefix = "" } = params2;
      const row = !isArray(repeat2) && repeat2.row || [repeater ? repeater.row : null];
      const column = !isArray(repeat2) && repeat2.column || [repeater ? repeater.column : null];
      const repeatValues = isArray(repeat2) && repeat2 || [repeater ? repeater.repeat : null];
      for (const repeatValue of repeatValues) {
        for (const rowValue of row) {
          for (const columnValue of column) {
            const childRepeater = {
              repeat: repeatValue,
              row: rowValue,
              column: columnValue,
              layer: repeater.layer
            };
            const childName = (childSpec.name ? `${childSpec.name}_` : "") + repeaterPrefix + "child__" + (isArray(repeat2) ? `${varName(repeatValue)}` : (repeat2.row ? `row_${varName(rowValue)}` : "") + (repeat2.column ? `column_${varName(columnValue)}` : ""));
            const child = this.map(childSpec, { ...params2, repeater: childRepeater, repeaterPrefix: childName });
            child.name = childName;
            concat.push(omit(child, ["data"]));
          }
        }
      }
      const columns2 = isArray(repeat2) ? spec.columns : repeat2.column ? repeat2.column.length : 1;
      return {
        data: childSpec.data ?? data3,
        // data from child spec should have precedence
        align: "all",
        ...remainingProperties,
        columns: columns2,
        concat
      };
    }
    mapFacet(spec, params2) {
      const { facet } = spec;
      if (isFacetMapping(facet) && spec.columns) {
        spec = omit(spec, ["columns"]);
        warn2(message_exports.columnsNotSupportByRowCol("facet"));
      }
      return super.mapFacet(spec, params2);
    }
    mapUnitWithParentEncodingOrProjection(spec, params2) {
      const { encoding, projection: projection3 } = spec;
      const { parentEncoding, parentProjection, config } = params2;
      const mergedProjection = mergeProjection({ parentProjection, projection: projection3 });
      const mergedEncoding = mergeEncoding({
        parentEncoding,
        encoding: replaceRepeaterInEncoding(encoding, params2.repeater)
      });
      return this.mapUnit({
        ...spec,
        ...mergedProjection ? { projection: mergedProjection } : {},
        ...mergedEncoding ? { encoding: mergedEncoding } : {}
      }, { config });
    }
    mapFacetedUnit(spec, normParams) {
      const { row, column, facet, ...encoding } = spec.encoding;
      const { mark, width: width2, projection: projection3, height: height2, view, params: params2, encoding: _, ...outerSpec } = spec;
      const { facetMapping, layout } = this.getFacetMappingAndLayout({ row, column, facet }, normParams);
      const newEncoding = replaceRepeaterInEncoding(encoding, normParams.repeater);
      return this.mapFacet({
        ...outerSpec,
        ...layout,
        // row / column has higher precedence than facet
        facet: facetMapping,
        spec: {
          ...width2 ? { width: width2 } : {},
          ...height2 ? { height: height2 } : {},
          ...view ? { view } : {},
          ...projection3 ? { projection: projection3 } : {},
          mark,
          encoding: newEncoding,
          ...params2 ? { params: params2 } : {}
        }
      }, normParams);
    }
    getFacetMappingAndLayout(facets, params2) {
      const { row, column, facet } = facets;
      if (row || column) {
        if (facet) {
          warn2(message_exports.facetChannelDropped([...row ? [ROW] : [], ...column ? [COLUMN] : []]));
        }
        const facetMapping = {};
        const layout = {};
        for (const channel of [ROW, COLUMN]) {
          const def2 = facets[channel];
          if (def2) {
            const { align: align2, center, spacing, columns: columns2, ...defWithoutLayout } = def2;
            facetMapping[channel] = defWithoutLayout;
            for (const prop of ["align", "center", "spacing"]) {
              if (def2[prop] !== void 0) {
                layout[prop] ?? (layout[prop] = {});
                layout[prop][channel] = def2[prop];
              }
            }
          }
        }
        return { facetMapping, layout };
      } else {
        const { align: align2, center, spacing, columns: columns2, ...facetMapping } = facet;
        return {
          facetMapping: replaceRepeaterInFacet(facetMapping, params2.repeater),
          layout: {
            ...align2 ? { align: align2 } : {},
            ...center ? { center } : {},
            ...spacing ? { spacing } : {},
            ...columns2 ? { columns: columns2 } : {}
          }
        };
      }
    }
    mapLayer(spec, { parentEncoding, parentProjection, ...otherParams }) {
      const { encoding, projection: projection3, ...rest } = spec;
      const params2 = {
        ...otherParams,
        parentEncoding: mergeEncoding({ parentEncoding, encoding, layer: true }),
        parentProjection: mergeProjection({ parentProjection, projection: projection3 })
      };
      return super.mapLayer({
        ...rest,
        ...spec.name ? { name: [params2.repeaterPrefix, spec.name].filter((n2) => n2).join("_") } : {}
      }, params2);
    }
  };
  function mergeEncoding({ parentEncoding, encoding = {}, layer }) {
    let merged = {};
    if (parentEncoding) {
      const channels = /* @__PURE__ */ new Set([...keys3(parentEncoding), ...keys3(encoding)]);
      for (const channel of channels) {
        const channelDef = encoding[channel];
        const parentChannelDef = parentEncoding[channel];
        if (isFieldOrDatumDef(channelDef)) {
          const mergedChannelDef = {
            ...parentChannelDef,
            ...channelDef
          };
          merged[channel] = mergedChannelDef;
        } else if (hasConditionalFieldOrDatumDef(channelDef)) {
          merged[channel] = {
            ...channelDef,
            condition: {
              ...parentChannelDef,
              ...channelDef.condition
            }
          };
        } else if (channelDef || channelDef === null) {
          merged[channel] = channelDef;
        } else if (layer || isValueDef(parentChannelDef) || isSignalRef(parentChannelDef) || isFieldOrDatumDef(parentChannelDef) || isArray(parentChannelDef)) {
          merged[channel] = parentChannelDef;
        }
      }
    } else {
      merged = encoding;
    }
    return !merged || isEmpty(merged) ? void 0 : merged;
  }
  function mergeProjection(opt) {
    const { parentProjection, projection: projection3 } = opt;
    if (parentProjection && projection3) {
      warn2(message_exports.projectionOverridden({ parentProjection, projection: projection3 }));
    }
    return projection3 ?? parentProjection;
  }

  // node_modules/vega-lite/build/src/transform.js
  function isFilter(t4) {
    return hasProperty(t4, "filter");
  }
  function isImputeSequence(t4) {
    return hasProperty(t4, "stop");
  }
  function isLookup(t4) {
    return hasProperty(t4, "lookup");
  }
  function isLookupData(from) {
    return hasProperty(from, "data");
  }
  function isLookupSelection(from) {
    return hasProperty(from, "param");
  }
  function isPivot(t4) {
    return hasProperty(t4, "pivot");
  }
  function isDensity(t4) {
    return hasProperty(t4, "density");
  }
  function isQuantile2(t4) {
    return hasProperty(t4, "quantile");
  }
  function isRegression(t4) {
    return hasProperty(t4, "regression");
  }
  function isLoess(t4) {
    return hasProperty(t4, "loess");
  }
  function isSample(t4) {
    return hasProperty(t4, "sample");
  }
  function isWindow(t4) {
    return hasProperty(t4, "window");
  }
  function isJoinAggregate(t4) {
    return hasProperty(t4, "joinaggregate");
  }
  function isFlatten(t4) {
    return hasProperty(t4, "flatten");
  }
  function isCalculate(t4) {
    return hasProperty(t4, "calculate");
  }
  function isBin(t4) {
    return hasProperty(t4, "bin");
  }
  function isImpute(t4) {
    return hasProperty(t4, "impute");
  }
  function isTimeUnit(t4) {
    return hasProperty(t4, "timeUnit");
  }
  function isAggregate2(t4) {
    return hasProperty(t4, "aggregate");
  }
  function isStack(t4) {
    return hasProperty(t4, "stack");
  }
  function isFold(t4) {
    return hasProperty(t4, "fold");
  }
  function isExtent(t4) {
    return hasProperty(t4, "extent") && !hasProperty(t4, "density") && !hasProperty(t4, "regression");
  }
  function normalizeTransform(transform4) {
    return transform4.map((t4) => {
      if (isFilter(t4)) {
        return {
          filter: normalizeLogicalComposition(t4.filter, normalizePredicate)
        };
      }
      return t4;
    });
  }

  // node_modules/vega-lite/build/src/normalize/selectioncompat.js
  var SelectionCompatibilityNormalizer = class extends SpecMapper {
    map(spec, normParams) {
      normParams.emptySelections ?? (normParams.emptySelections = {});
      normParams.selectionPredicates ?? (normParams.selectionPredicates = {});
      spec = normalizeTransforms(spec, normParams);
      return super.map(spec, normParams);
    }
    mapLayerOrUnit(spec, normParams) {
      spec = normalizeTransforms(spec, normParams);
      if (spec.encoding) {
        const encoding = {};
        for (const [channel, enc] of entries(spec.encoding)) {
          encoding[channel] = normalizeChannelDef(enc, normParams);
        }
        spec = { ...spec, encoding };
      }
      return super.mapLayerOrUnit(spec, normParams);
    }
    mapUnit(spec, normParams) {
      const { selection, ...rest } = spec;
      if (selection) {
        return {
          ...rest,
          params: entries(selection).map(([name4, selDef]) => {
            const { init: value3, bind: bind3, empty, ...select2 } = selDef;
            if (select2.type === "single") {
              select2.type = "point";
              select2.toggle = false;
            } else if (select2.type === "multi") {
              select2.type = "point";
            }
            normParams.emptySelections[name4] = empty !== "none";
            for (const pred of vals(normParams.selectionPredicates[name4] ?? {})) {
              pred.empty = empty !== "none";
            }
            return { name: name4, value: value3, select: select2, bind: bind3 };
          })
        };
      }
      return spec;
    }
  };
  function normalizeTransforms(spec, normParams) {
    const { transform: tx, ...rest } = spec;
    if (tx) {
      const transform4 = tx.map((t4) => {
        if (isFilter(t4)) {
          return { filter: normalizePredicate2(t4, normParams) };
        } else if (isBin(t4) && isBinParams(t4.bin)) {
          return {
            ...t4,
            bin: normalizeBinExtent(t4.bin)
          };
        } else if (isLookup(t4)) {
          const { selection: param2, ...from } = t4.from;
          return param2 ? {
            ...t4,
            from: { param: param2, ...from }
          } : t4;
        }
        return t4;
      });
      return { ...rest, transform: transform4 };
    }
    return spec;
  }
  function normalizeChannelDef(obj, normParams) {
    const enc = duplicate(obj);
    if (isFieldDef(enc) && isBinParams(enc.bin)) {
      enc.bin = normalizeBinExtent(enc.bin);
    }
    if (isScaleFieldDef(enc) && enc.scale?.domain?.selection) {
      const { selection: param2, ...domain4 } = enc.scale.domain;
      enc.scale.domain = { ...domain4, ...param2 ? { param: param2 } : {} };
    }
    if (isConditionalDef(enc)) {
      if (isArray(enc.condition)) {
        enc.condition = enc.condition.map((c4) => {
          const { selection, param: param2, test: test2, ...cond } = c4;
          return param2 ? c4 : { ...cond, test: normalizePredicate2(c4, normParams) };
        });
      } else {
        const { selection, param: param2, test: test2, ...cond } = normalizeChannelDef(enc.condition, normParams);
        enc.condition = param2 ? enc.condition : {
          ...cond,
          test: normalizePredicate2(enc.condition, normParams)
        };
      }
    }
    return enc;
  }
  function normalizeBinExtent(bin3) {
    const ext = bin3.extent;
    if (ext?.selection) {
      const { selection: param2, ...rest } = ext;
      return { ...bin3, extent: { ...rest, param: param2 } };
    }
    return bin3;
  }
  function normalizePredicate2(op, normParams) {
    const normalizeSelectionComposition = (o2) => {
      return normalizeLogicalComposition(o2, (param2) => {
        var _a2;
        const empty = normParams.emptySelections[param2] ?? true;
        const pred = { param: param2, empty };
        (_a2 = normParams.selectionPredicates)[param2] ?? (_a2[param2] = []);
        normParams.selectionPredicates[param2].push(pred);
        return pred;
      });
    };
    return op.selection ? normalizeSelectionComposition(op.selection) : normalizeLogicalComposition(op.test || op.filter, (o2) => o2.selection ? normalizeSelectionComposition(o2.selection) : o2);
  }

  // node_modules/vega-lite/build/src/normalize/toplevelselection.js
  var TopLevelSelectionsNormalizer = class extends SpecMapper {
    map(spec, normParams) {
      const selections = normParams.selections ?? [];
      if (spec.params && !isUnitSpec(spec)) {
        const params2 = [];
        for (const param2 of spec.params) {
          if (isSelectionParameter(param2)) {
            selections.push(param2);
          } else {
            params2.push(param2);
          }
        }
        spec.params = params2;
      }
      normParams.selections = selections;
      return super.map(spec, normParams);
    }
    mapUnit(spec, normParams) {
      const selections = normParams.selections;
      if (!selections || !selections.length)
        return spec;
      const path3 = (normParams.path ?? []).concat(spec.name);
      const params2 = [];
      for (const selection of selections) {
        if (!selection.views || !selection.views.length) {
          params2.push(selection);
        } else {
          for (const view of selection.views) {
            if (isString(view) && (view === spec.name || path3.includes(view)) || isArray(view) && // logic for backwards compatibility with view paths before we had unique names
            // @ts-ignore
            view.map((v3) => path3.indexOf(v3)).every((v3, i2, arr) => v3 !== -1 && (i2 === 0 || v3 > arr[i2 - 1]))) {
              params2.push(selection);
            }
          }
        }
      }
      if (params2.length)
        spec.params = params2;
      return spec;
    }
  };
  for (const method2 of ["mapFacet", "mapRepeat", "mapHConcat", "mapVConcat", "mapLayer"]) {
    const proto = TopLevelSelectionsNormalizer.prototype[method2];
    TopLevelSelectionsNormalizer.prototype[method2] = function(spec, params2) {
      return proto.call(this, spec, addSpecNameToParams(spec, params2));
    };
  }
  function addSpecNameToParams(spec, params2) {
    return spec.name ? {
      ...params2,
      path: (params2.path ?? []).concat(spec.name)
    } : params2;
  }

  // node_modules/vega-lite/build/src/normalize/index.js
  function normalize3(spec, config) {
    if (config === void 0) {
      config = initConfig(spec.config);
    }
    const normalizedSpec = normalizeGenericSpec(spec, config);
    const { width: width2, height: height2 } = spec;
    const autosize = normalizeAutoSize(normalizedSpec, { width: width2, height: height2, autosize: spec.autosize }, config);
    return {
      ...normalizedSpec,
      ...autosize ? { autosize } : {}
    };
  }
  var coreNormalizer = new CoreNormalizer();
  var selectionCompatNormalizer = new SelectionCompatibilityNormalizer();
  var topLevelSelectionNormalizer = new TopLevelSelectionsNormalizer();
  function normalizeGenericSpec(spec, config = {}) {
    const normParams = { config };
    return topLevelSelectionNormalizer.map(coreNormalizer.map(selectionCompatNormalizer.map(spec, normParams), normParams), normParams);
  }
  function _normalizeAutoSize(autosize) {
    return isString(autosize) ? { type: autosize } : autosize ?? {};
  }
  function normalizeAutoSize(spec, sizeInfo, config) {
    let { width: width2, height: height2 } = sizeInfo;
    const isFitCompatible = isUnitSpec(spec) || isLayerSpec(spec);
    const autosizeDefault = {};
    if (!isFitCompatible) {
      if (width2 == "container") {
        warn2(message_exports.containerSizeNonSingle("width"));
        width2 = void 0;
      }
      if (height2 == "container") {
        warn2(message_exports.containerSizeNonSingle("height"));
        height2 = void 0;
      }
    } else {
      if (width2 == "container" && height2 == "container") {
        autosizeDefault.type = "fit";
        autosizeDefault.contains = "padding";
      } else if (width2 == "container") {
        autosizeDefault.type = "fit-x";
        autosizeDefault.contains = "padding";
      } else if (height2 == "container") {
        autosizeDefault.type = "fit-y";
        autosizeDefault.contains = "padding";
      }
    }
    const autosize = {
      type: "pad",
      ...autosizeDefault,
      ...config ? _normalizeAutoSize(config.autosize) : {},
      ..._normalizeAutoSize(spec.autosize)
    };
    if (autosize.type === "fit" && !isFitCompatible) {
      warn2(message_exports.FIT_NON_SINGLE);
      autosize.type = "pad";
    }
    if (width2 == "container" && !(autosize.type == "fit" || autosize.type == "fit-x")) {
      warn2(message_exports.containerSizeNotCompatibleWithAutosize("width"));
    }
    if (height2 == "container" && !(autosize.type == "fit" || autosize.type == "fit-y")) {
      warn2(message_exports.containerSizeNotCompatibleWithAutosize("height"));
    }
    if (deepEqual(autosize, { type: "pad" })) {
      return void 0;
    }
    return autosize;
  }

  // node_modules/vega-lite/build/src/spec/toplevel.js
  function isFitType(autoSizeType) {
    return ["fit", "fit-x", "fit-y"].includes(autoSizeType);
  }
  function getFitType(sizeType) {
    return sizeType ? `fit-${getPositionScaleChannel(sizeType)}` : "fit";
  }
  var TOP_LEVEL_PROPERTIES = [
    "background",
    "padding"
    // We do not include "autosize" here as it is supported by only unit and layer specs and thus need to be normalized
  ];
  function extractTopLevelProperties(t4, includeParams) {
    const o2 = {};
    for (const p2 of TOP_LEVEL_PROPERTIES) {
      if (t4 && t4[p2] !== void 0) {
        o2[p2] = signalRefOrValue(t4[p2]);
      }
    }
    if (includeParams) {
      o2.params = t4.params;
    }
    return o2;
  }

  // node_modules/vega-lite/build/src/compile/split.js
  var Split = class _Split {
    constructor(explicit = {}, implicit2 = {}) {
      this.explicit = explicit;
      this.implicit = implicit2;
    }
    clone() {
      return new _Split(duplicate(this.explicit), duplicate(this.implicit));
    }
    combine() {
      return {
        ...this.explicit,
        // Explicit properties comes first
        ...this.implicit
      };
    }
    get(key2) {
      return getFirstDefined(this.explicit[key2], this.implicit[key2]);
    }
    getWithExplicit(key2) {
      if (this.explicit[key2] !== void 0) {
        return { explicit: true, value: this.explicit[key2] };
      } else if (this.implicit[key2] !== void 0) {
        return { explicit: false, value: this.implicit[key2] };
      }
      return { explicit: false, value: void 0 };
    }
    setWithExplicit(key2, { value: value3, explicit }) {
      if (value3 !== void 0) {
        this.set(key2, value3, explicit);
      }
    }
    set(key2, value3, explicit) {
      delete this[explicit ? "implicit" : "explicit"][key2];
      this[explicit ? "explicit" : "implicit"][key2] = value3;
      return this;
    }
    copyKeyFromSplit(key2, { explicit, implicit: implicit2 }) {
      if (explicit[key2] !== void 0) {
        this.set(key2, explicit[key2], true);
      } else if (implicit2[key2] !== void 0) {
        this.set(key2, implicit2[key2], false);
      }
    }
    copyKeyFromObject(key2, s2) {
      if (s2[key2] !== void 0) {
        this.set(key2, s2[key2], true);
      }
    }
    /**
     * Merge split object into this split object. Properties from the other split
     * overwrite properties from this split.
     */
    copyAll(other) {
      for (const key2 of keys3(other.combine())) {
        const val = other.getWithExplicit(key2);
        this.setWithExplicit(key2, val);
      }
    }
  };
  function makeExplicit(value3) {
    return {
      explicit: true,
      value: value3
    };
  }
  function makeImplicit(value3) {
    return {
      explicit: false,
      value: value3
    };
  }
  function tieBreakByComparing(compare4) {
    return (v1, v22, property2, propertyOf) => {
      const diff = compare4(v1.value, v22.value);
      if (diff > 0) {
        return v1;
      } else if (diff < 0) {
        return v22;
      }
      return defaultTieBreaker(v1, v22, property2, propertyOf);
    };
  }
  function defaultTieBreaker(v1, v22, property2, propertyOf) {
    if (v1.explicit && v22.explicit) {
      warn2(message_exports.mergeConflictingProperty(property2, propertyOf, v1.value, v22.value));
    }
    return v1;
  }
  function mergeValuesWithExplicit(v1, v22, property2, propertyOf, tieBreaker = defaultTieBreaker) {
    if (v1 === void 0 || v1.value === void 0) {
      return v22;
    }
    if (v1.explicit && !v22.explicit) {
      return v1;
    } else if (v22.explicit && !v1.explicit) {
      return v22;
    } else if (deepEqual(v1.value, v22.value)) {
      return v1;
    } else {
      return tieBreaker(v1, v22, property2, propertyOf);
    }
  }

  // node_modules/vega-lite/build/src/compile/data/index.js
  var AncestorParse = class extends Split {
    constructor(explicit = {}, implicit2 = {}, parseNothing = false) {
      super(explicit, implicit2);
      this.explicit = explicit;
      this.implicit = implicit2;
      this.parseNothing = parseNothing;
    }
    clone() {
      const clone = super.clone();
      clone.parseNothing = this.parseNothing;
      return clone;
    }
  };

  // node_modules/vega-lite/build/src/data.js
  function isUrlData(data3) {
    return hasProperty(data3, "url");
  }
  function isInlineData(data3) {
    return hasProperty(data3, "values");
  }
  function isNamedData(data3) {
    return hasProperty(data3, "name") && !isUrlData(data3) && !isInlineData(data3) && !isGenerator(data3);
  }
  function isGenerator(data3) {
    return data3 && (isSequenceGenerator(data3) || isSphereGenerator(data3) || isGraticuleGenerator(data3));
  }
  function isSequenceGenerator(data3) {
    return hasProperty(data3, "sequence");
  }
  function isSphereGenerator(data3) {
    return hasProperty(data3, "sphere");
  }
  function isGraticuleGenerator(data3) {
    return hasProperty(data3, "graticule");
  }
  var DataSourceType;
  (function(DataSourceType2) {
    DataSourceType2[DataSourceType2["Raw"] = 0] = "Raw";
    DataSourceType2[DataSourceType2["Main"] = 1] = "Main";
    DataSourceType2[DataSourceType2["Row"] = 2] = "Row";
    DataSourceType2[DataSourceType2["Column"] = 3] = "Column";
    DataSourceType2[DataSourceType2["Lookup"] = 4] = "Lookup";
    DataSourceType2[DataSourceType2["PreFilterInvalid"] = 5] = "PreFilterInvalid";
    DataSourceType2[DataSourceType2["PostFilterInvalid"] = 6] = "PostFilterInvalid";
  })(DataSourceType || (DataSourceType = {}));

  // node_modules/vega-lite/build/src/compile/invalid/datasources.js
  function getDataSourcesForHandlingInvalidValues({ invalid, isPath }) {
    const normalizedInvalid = normalizeInvalidDataMode(invalid, { isPath });
    switch (normalizedInvalid) {
      case "filter":
        return {
          marks: "exclude-invalid-values",
          scales: "exclude-invalid-values"
        };
      case "break-paths-show-domains":
        return {
          // Path-based marks use pre-filter data so we know to skip these invalid points in the path.
          // For non-path based marks, we skip by not showing them at all.
          marks: isPath ? "include-invalid-values" : "exclude-invalid-values",
          scales: "include-invalid-values"
        };
      case "break-paths-filter-domains":
        return {
          marks: isPath ? "include-invalid-values" : "exclude-invalid-values",
          // Unlike 'break-paths-show-domains', 'break-paths-filter-domains' uses post-filter data to feed scale.
          scales: "exclude-invalid-values"
        };
      case "show":
        return {
          marks: "include-invalid-values",
          scales: "include-invalid-values"
        };
    }
  }
  function getScaleDataSourceForHandlingInvalidValues(props) {
    const { marks, scales: scales2 } = getDataSourcesForHandlingInvalidValues(props);
    if (marks === scales2) {
      return DataSourceType.Main;
    }
    return scales2 === "include-invalid-values" ? DataSourceType.PreFilterInvalid : DataSourceType.PostFilterInvalid;
  }

  // node_modules/vega-lite/build/src/compile/data/dataflow.js
  var DataFlowNode = class {
    constructor(parent, debugName) {
      this.debugName = debugName;
      this._children = [];
      this._parent = null;
      if (parent) {
        this.parent = parent;
      }
    }
    /**
     * Clone this node with a deep copy but don't clone links to children or parents.
     */
    clone() {
      throw new Error("Cannot clone node");
    }
    get parent() {
      return this._parent;
    }
    /**
     * Set the parent of the node and also add this node to the parent's children.
     */
    set parent(parent) {
      this._parent = parent;
      if (parent) {
        parent.addChild(this);
      }
    }
    get children() {
      return this._children;
    }
    numChildren() {
      return this._children.length;
    }
    addChild(child, loc) {
      if (this._children.includes(child)) {
        warn2(message_exports.ADD_SAME_CHILD_TWICE);
        return;
      }
      if (loc !== void 0) {
        this._children.splice(loc, 0, child);
      } else {
        this._children.push(child);
      }
    }
    removeChild(oldChild) {
      const loc = this._children.indexOf(oldChild);
      this._children.splice(loc, 1);
      return loc;
    }
    /**
     * Remove node from the dataflow.
     */
    remove() {
      let loc = this._parent.removeChild(this);
      for (const child of this._children) {
        child._parent = this._parent;
        this._parent.addChild(child, loc++);
      }
    }
    /**
     * Insert another node as a parent of this node.
     */
    insertAsParentOf(other) {
      const parent = other.parent;
      parent.removeChild(this);
      this.parent = parent;
      other.parent = this;
    }
    swapWithParent() {
      const parent = this._parent;
      const newParent = parent.parent;
      for (const child of this._children) {
        child.parent = parent;
      }
      this._children = [];
      parent.removeChild(this);
      const loc = parent.parent.removeChild(parent);
      this._parent = newParent;
      newParent.addChild(this, loc);
      parent.parent = this;
    }
  };
  var OutputNode = class extends DataFlowNode {
    clone() {
      const cloneObj = new this.constructor();
      cloneObj.debugName = `clone_${this.debugName}`;
      cloneObj._source = this._source;
      cloneObj._name = `clone_${this._name}`;
      cloneObj.type = this.type;
      cloneObj.refCounts = this.refCounts;
      cloneObj.refCounts[cloneObj._name] = 0;
      return cloneObj;
    }
    /**
     * @param source The name of the source. Will change in assemble.
     * @param type The type of the output node.
     * @param refCounts A global ref counter map.
     */
    constructor(parent, source4, type3, refCounts) {
      super(parent, source4);
      this.type = type3;
      this.refCounts = refCounts;
      this._source = this._name = source4;
      if (this.refCounts && !(this._name in this.refCounts)) {
        this.refCounts[this._name] = 0;
      }
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    hash() {
      if (this._hash === void 0) {
        this._hash = `Output ${uniqueId()}`;
      }
      return this._hash;
    }
    /**
     * Request the datasource name and increase the ref counter.
     *
     * During the parsing phase, this will return the simple name such as 'main' or 'raw'.
     * It is crucial to request the name from an output node to mark it as a required node.
     * If nobody ever requests the name, this datasource will not be instantiated in the assemble phase.
     *
     * In the assemble phase, this will return the correct name.
     */
    getSource() {
      this.refCounts[this._name]++;
      return this._source;
    }
    isRequired() {
      return !!this.refCounts[this._name];
    }
    setSource(source4) {
      this._source = source4;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/timeunit.js
  function isTimeUnitTransformComponent(timeUnitComponent) {
    return timeUnitComponent.as !== void 0;
  }
  function offsetAs(field3) {
    return `${field3}_end`;
  }
  var TimeUnitNode = class _TimeUnitNode extends DataFlowNode {
    clone() {
      return new _TimeUnitNode(null, duplicate(this.timeUnits));
    }
    constructor(parent, timeUnits2) {
      super(parent);
      this.timeUnits = timeUnits2;
    }
    static makeFromEncoding(parent, model) {
      const formula = model.reduceFieldDef((timeUnitComponent, fieldDef, channel) => {
        const { field: field3, timeUnit } = fieldDef;
        if (timeUnit) {
          let component;
          if (isBinnedTimeUnit(timeUnit)) {
            if (isUnitModel(model)) {
              const { mark, markDef, config } = model;
              const bandPosition = getBandPosition({ fieldDef, markDef, config });
              if (isRectBasedMark(mark) || !!bandPosition) {
                component = {
                  timeUnit: normalizeTimeUnit(timeUnit),
                  field: field3
                };
              }
            }
          } else {
            component = {
              as: vgField(fieldDef, { forAs: true }),
              field: field3,
              timeUnit
            };
          }
          if (isUnitModel(model)) {
            const { mark, markDef, config } = model;
            const bandPosition = getBandPosition({ fieldDef, markDef, config });
            if (isRectBasedMark(mark) && isXorY(channel) && bandPosition !== 0.5) {
              component.rectBandPosition = bandPosition;
            }
          }
          if (component) {
            timeUnitComponent[hash(component)] = component;
          }
        }
        return timeUnitComponent;
      }, {});
      if (isEmpty(formula)) {
        return null;
      }
      return new _TimeUnitNode(parent, formula);
    }
    static makeFromTransform(parent, t4) {
      const { timeUnit, ...other } = { ...t4 };
      const normalizedTimeUnit = normalizeTimeUnit(timeUnit);
      const component = {
        ...other,
        timeUnit: normalizedTimeUnit
      };
      return new _TimeUnitNode(parent, {
        [hash(component)]: component
      });
    }
    /**
     * Merge together TimeUnitNodes assigning the children of `other` to `this`
     * and removing `other`.
     */
    merge(other) {
      this.timeUnits = { ...this.timeUnits };
      for (const key2 in other.timeUnits) {
        if (!this.timeUnits[key2]) {
          this.timeUnits[key2] = other.timeUnits[key2];
        }
      }
      for (const child of other.children) {
        other.removeChild(child);
        child.parent = this;
      }
      other.remove();
    }
    /**
     * Remove time units coming from the other node.
     */
    removeFormulas(fields) {
      const newFormula = {};
      for (const [key2, timeUnitComponent] of entries(this.timeUnits)) {
        const fieldAs = isTimeUnitTransformComponent(timeUnitComponent) ? timeUnitComponent.as : `${timeUnitComponent.field}_end`;
        if (!fields.has(fieldAs)) {
          newFormula[key2] = timeUnitComponent;
        }
      }
      this.timeUnits = newFormula;
    }
    producedFields() {
      return new Set(vals(this.timeUnits).map((f2) => {
        return isTimeUnitTransformComponent(f2) ? f2.as : offsetAs(f2.field);
      }));
    }
    dependentFields() {
      return new Set(vals(this.timeUnits).map((f2) => f2.field));
    }
    hash() {
      return `TimeUnit ${hash(this.timeUnits)}`;
    }
    assemble() {
      const transforms2 = [];
      for (const f2 of vals(this.timeUnits)) {
        const { rectBandPosition } = f2;
        const normalizedTimeUnit = normalizeTimeUnit(f2.timeUnit);
        if (isTimeUnitTransformComponent(f2)) {
          const { field: field3, as } = f2;
          const { unit: unit2, utc, ...params2 } = normalizedTimeUnit;
          const startEnd = [as, `${as}_end`];
          transforms2.push({
            field: replacePathInField(field3),
            type: "timeunit",
            ...unit2 ? { units: getTimeUnitParts(unit2) } : {},
            ...utc ? { timezone: "utc" } : {},
            ...params2,
            as: startEnd
          });
          transforms2.push(...offsetedRectFormulas(startEnd, rectBandPosition, normalizedTimeUnit));
        } else if (f2) {
          const { field: escapedField } = f2;
          const field3 = escapedField.replaceAll("\\.", ".");
          const expr2 = offsetExpr({ timeUnit: normalizedTimeUnit, field: field3 });
          const endAs = offsetAs(field3);
          transforms2.push({
            type: "formula",
            expr: expr2,
            as: endAs
          });
          transforms2.push(...offsetedRectFormulas([field3, endAs], rectBandPosition, normalizedTimeUnit));
        }
      }
      return transforms2;
    }
  };
  var OFFSETTED_RECT_START_SUFFIX = "offsetted_rect_start";
  var OFFSETTED_RECT_END_SUFFIX = "offsetted_rect_end";
  function offsetExpr({ timeUnit, field: field3, reverse: reverse3 }) {
    const { unit: unit2, utc } = timeUnit;
    const smallestUnit = getSmallestTimeUnitPart(unit2);
    const { part, step } = getDateTimePartAndStep(smallestUnit, timeUnit.step);
    const offsetFn = utc ? "utcOffset" : "timeOffset";
    const expr2 = `${offsetFn}('${part}', ${accessWithDatumToUnescapedPath(field3)}, ${reverse3 ? -step : step})`;
    return expr2;
  }
  function offsetedRectFormulas([startField, endField], rectBandPosition, timeUnit) {
    if (rectBandPosition !== void 0 && rectBandPosition !== 0.5) {
      const startExpr = accessWithDatumToUnescapedPath(startField);
      const endExpr = accessWithDatumToUnescapedPath(endField);
      return [
        {
          type: "formula",
          expr: interpolateExpr([
            offsetExpr({
              timeUnit,
              field: startField,
              reverse: true
            }),
            startExpr
          ], rectBandPosition + 0.5),
          as: `${startField}_${OFFSETTED_RECT_START_SUFFIX}`
        },
        {
          type: "formula",
          expr: interpolateExpr([startExpr, endExpr], rectBandPosition + 0.5),
          as: `${startField}_${OFFSETTED_RECT_END_SUFFIX}`
        }
      ];
    }
    return [];
  }
  function interpolateExpr([start, end], fraction) {
    return `${1 - fraction} * ${start} + ${fraction} * ${end}`;
  }

  // node_modules/vega-lite/build/src/compile/selection/project.js
  var TUPLE_FIELDS = "_tuple_fields";
  var SelectionProjectionComponent = class {
    constructor(...items) {
      this.items = items;
      this.hasChannel = {};
      this.hasField = {};
      this.hasSelectionId = false;
    }
  };
  var project2 = {
    defined: () => {
      return true;
    },
    parse: (model, selCmpt, selDef) => {
      const name4 = selCmpt.name;
      const proj = selCmpt.project ?? (selCmpt.project = new SelectionProjectionComponent());
      const parsed = {};
      const timeUnits2 = {};
      const signals = /* @__PURE__ */ new Set();
      const signalName = (p2, range7) => {
        const suffix = range7 === "visual" ? p2.channel : p2.field;
        let sg = varName(`${name4}_${suffix}`);
        for (let counter = 1; signals.has(sg); counter++) {
          sg = varName(`${name4}_${suffix}_${counter}`);
        }
        signals.add(sg);
        return { [range7]: sg };
      };
      const type3 = selCmpt.type;
      const cfg = model.config.selection[type3];
      const init2 = selDef.value !== void 0 ? array(selDef.value) : null;
      let { fields, encodings } = isObject(selDef.select) ? selDef.select : {};
      if (!fields && !encodings && init2) {
        for (const initVal of init2) {
          if (!isObject(initVal)) {
            continue;
          }
          for (const key2 of keys3(initVal)) {
            if (isSingleDefUnitChannel(key2)) {
              (encodings || (encodings = [])).push(key2);
            } else {
              if (type3 === "interval") {
                warn2(message_exports.INTERVAL_INITIALIZED_WITH_POS);
                encodings = cfg.encodings;
              } else {
                (fields ?? (fields = [])).push(key2);
              }
            }
          }
        }
      }
      if (!fields && !encodings) {
        encodings = cfg.encodings;
        if ("fields" in cfg) {
          fields = cfg.fields;
        }
      }
      for (const channel of encodings ?? []) {
        const fieldDef = model.fieldDef(channel);
        if (fieldDef) {
          let field3 = fieldDef.field;
          if (fieldDef.aggregate) {
            warn2(message_exports.cannotProjectAggregate(channel, fieldDef.aggregate));
            continue;
          } else if (!field3) {
            warn2(message_exports.cannotProjectOnChannelWithoutField(channel));
            continue;
          }
          if (fieldDef.timeUnit && !isBinnedTimeUnit(fieldDef.timeUnit)) {
            field3 = model.vgField(channel);
            const component = {
              timeUnit: fieldDef.timeUnit,
              as: field3,
              field: fieldDef.field
            };
            timeUnits2[hash(component)] = component;
          }
          if (!parsed[field3]) {
            const tplType = type3 === "interval" && isScaleChannel(channel) && hasContinuousDomain(model.getScaleComponent(channel).get("type")) ? "R" : fieldDef.bin ? "R-RE" : "E";
            const p2 = { field: field3, channel, type: tplType, index: proj.items.length };
            p2.signals = { ...signalName(p2, "data"), ...signalName(p2, "visual") };
            proj.items.push(parsed[field3] = p2);
            proj.hasField[field3] = parsed[field3];
            proj.hasSelectionId = proj.hasSelectionId || field3 === SELECTION_ID;
            if (isGeoPositionChannel(channel)) {
              p2.geoChannel = channel;
              p2.channel = getPositionChannelFromLatLong(channel);
              proj.hasChannel[p2.channel] = parsed[field3];
            } else {
              proj.hasChannel[channel] = parsed[field3];
            }
          }
        } else {
          warn2(message_exports.cannotProjectOnChannelWithoutField(channel));
        }
      }
      for (const field3 of fields ?? []) {
        if (proj.hasField[field3])
          continue;
        const p2 = { type: "E", field: field3, index: proj.items.length };
        p2.signals = { ...signalName(p2, "data") };
        proj.items.push(p2);
        proj.hasField[field3] = p2;
        proj.hasSelectionId = proj.hasSelectionId || field3 === SELECTION_ID;
      }
      if (init2) {
        selCmpt.init = init2.map((v3) => {
          return proj.items.map((p2) => isObject(v3) ? v3[p2.geoChannel || p2.channel] !== void 0 ? v3[p2.geoChannel || p2.channel] : v3[p2.field] : v3);
        });
      }
      if (!isEmpty(timeUnits2)) {
        proj.timeUnit = new TimeUnitNode(null, timeUnits2);
      }
    },
    signals: (model, selCmpt, allSignals) => {
      const name4 = selCmpt.name + TUPLE_FIELDS;
      const hasSignal2 = allSignals.filter((s2) => s2.name === name4);
      return hasSignal2.length > 0 || selCmpt.project.hasSelectionId ? allSignals : allSignals.concat({
        name: name4,
        value: selCmpt.project.items.map(assembleProjection)
      });
    }
  };
  var project_default = project2;

  // node_modules/vega-lite/build/src/compile/selection/point.js
  var CURR = "_curr";
  var ANIM_VALUE = "anim_value";
  var ANIM_CLOCK = "anim_clock";
  var EASED_ANIM_CLOCK = "eased_anim_clock";
  var MIN_EXTENT = "min_extent";
  var MAX_RANGE_EXTENT = "max_range_extent";
  var LAST_TICK = "last_tick_at";
  var IS_PLAYING = "is_playing";
  var THROTTLE = 1 / 60 * 1e3;
  var animationSignals = (selectionName, scaleName) => {
    return [
      // timer signals
      {
        name: EASED_ANIM_CLOCK,
        // update: 'easeLinear(anim_clock / max_range_extent) * max_range_extent'
        update: ANIM_CLOCK
        // TODO: replace with above once easing functions are implemented in vega-functions
      },
      // scale signals
      // TODO(jzong): uncomment commented signals below when implementing interpolation
      { name: `${selectionName}_domain`, init: `domain('${scaleName}')` },
      { name: MIN_EXTENT, init: `extent(${selectionName}_domain)[0]` },
      // {name: 'max_extent', init: `extent(${selectionName}_domain)[1]`},
      { name: MAX_RANGE_EXTENT, init: `extent(range('${scaleName}'))[1]` },
      // {name: 't_index', update: `indexof(${selectionName}_domain, anim_value)`},
      { name: ANIM_VALUE, update: `invert('${scaleName}', ${EASED_ANIM_CLOCK})` }
    ];
  };
  var point7 = {
    defined: (selCmpt) => selCmpt.type === "point",
    topLevelSignals: (model, selCmpt, signals) => {
      if (isTimerSelection(selCmpt)) {
        signals = signals.concat([
          {
            name: ANIM_CLOCK,
            init: "0",
            on: [
              {
                events: { type: "timer", throttle: THROTTLE },
                update: `${IS_PLAYING} ? (${ANIM_CLOCK} + (now() - ${LAST_TICK}) > ${MAX_RANGE_EXTENT} ? 0 : ${ANIM_CLOCK} + (now() - ${LAST_TICK})) : ${ANIM_CLOCK}`
              }
            ]
          },
          {
            name: LAST_TICK,
            init: "now()",
            on: [{ events: [{ signal: ANIM_CLOCK }, { signal: IS_PLAYING }], update: "now()" }]
          },
          {
            name: IS_PLAYING,
            init: "true"
          }
        ]);
      }
      return signals;
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const fieldsSg = name4 + TUPLE_FIELDS;
      const project3 = selCmpt.project;
      const datum2 = "(item().isVoronoi ? datum.datum : datum)";
      const brushes = vals(model.component.selection ?? {}).reduce((acc, cmpt) => {
        return cmpt.type === "interval" ? acc.concat(cmpt.name + BRUSH) : acc;
      }, []).map((b3) => `indexof(item().mark.name, '${b3}') < 0`).join(" && ");
      const test2 = `datum && item().mark.marktype !== 'group' && indexof(item().mark.role, 'legend') < 0${brushes ? ` && ${brushes}` : ""}`;
      let update3 = `unit: ${unitName(model)}, `;
      if (selCmpt.project.hasSelectionId) {
        update3 += `${SELECTION_ID}: ${datum2}[${$(SELECTION_ID)}]`;
      } else if (isTimerSelection(selCmpt)) {
        update3 += `fields: ${fieldsSg}, values: [${ANIM_VALUE} ? ${ANIM_VALUE} : ${MIN_EXTENT}]`;
      } else {
        const values4 = project3.items.map((p2) => {
          const fieldDef = model.fieldDef(p2.channel);
          return fieldDef?.bin ? `[${datum2}[${$(model.vgField(p2.channel, {}))}], ${datum2}[${$(model.vgField(p2.channel, { binSuffix: "end" }))}]]` : `${datum2}[${$(p2.field)}]`;
        }).join(", ");
        update3 += `fields: ${fieldsSg}, values: [${values4}]`;
      }
      if (isTimerSelection(selCmpt)) {
        return signals.concat(animationSignals(selCmpt.name, model.scaleName(TIME)), [
          {
            name: name4 + TUPLE,
            on: [
              {
                events: [{ signal: EASED_ANIM_CLOCK }, { signal: ANIM_VALUE }],
                update: `{${update3}}`,
                force: true
              }
            ]
          }
        ]);
      } else {
        const events3 = selCmpt.events;
        return signals.concat([
          {
            name: name4 + TUPLE,
            on: events3 ? [
              {
                events: events3,
                update: `${test2} ? {${update3}} : null`,
                force: true
              }
            ] : []
          }
        ]);
      }
    }
  };
  var point_default = point7;

  // node_modules/vega-lite/build/src/compile/selection/assemble.js
  function assembleProjection(proj) {
    const { signals, hasLegend, index: index4, ...rest } = proj;
    rest.field = replacePathInField(rest.field);
    return rest;
  }
  function assembleInit(init2, isExpr2 = true, wrap2 = identity) {
    if (isArray(init2)) {
      const assembled = init2.map((v3) => assembleInit(v3, isExpr2, wrap2));
      return isExpr2 ? `[${assembled.join(", ")}]` : assembled;
    } else if (isDateTime(init2)) {
      if (isExpr2) {
        return wrap2(dateTimeToExpr(init2));
      } else {
        return wrap2(dateTimeToTimestamp(init2));
      }
    }
    return isExpr2 ? wrap2(stringify2(init2)) : init2;
  }
  function assembleUnitSelectionSignals(model, signals) {
    for (const selCmpt of vals(model.component.selection ?? {})) {
      const name4 = selCmpt.name;
      let modifyExpr = `${name4}${TUPLE}, ${selCmpt.resolve === "global" ? "true" : `{unit: ${unitName(model)}}`}`;
      for (const c4 of selectionCompilers) {
        if (!c4.defined(selCmpt))
          continue;
        if (c4.signals)
          signals = c4.signals(model, selCmpt, signals);
        if (c4.modifyExpr)
          modifyExpr = c4.modifyExpr(model, selCmpt, modifyExpr);
      }
      signals.push({
        name: name4 + MODIFY,
        on: [
          {
            events: { signal: selCmpt.name + TUPLE },
            update: `modify(${$(selCmpt.name + STORE)}, ${modifyExpr})`
          }
        ]
      });
    }
    return cleanupEmptyOnArray(signals);
  }
  function assembleFacetSignals(model, signals) {
    if (model.component.selection && keys3(model.component.selection).length) {
      const name4 = $(model.getName("cell"));
      signals.unshift({
        name: "facet",
        value: {},
        on: [
          {
            events: eventSelector("pointermove", "scope"),
            update: `isTuple(facet) ? facet : group(${name4}).datum`
          }
        ]
      });
    }
    return cleanupEmptyOnArray(signals);
  }
  function assembleTopLevelSignals(model, signals) {
    let hasSelections = false;
    for (const selCmpt of vals(model.component.selection ?? {})) {
      const name4 = selCmpt.name;
      const store = $(name4 + STORE);
      const hasSg = signals.filter((s2) => s2.name === name4);
      if (hasSg.length === 0) {
        const resolve2 = selCmpt.resolve === "global" ? "union" : selCmpt.resolve;
        const isPoint2 = selCmpt.type === "point" ? ", true, true)" : ")";
        signals.push({
          name: selCmpt.name,
          update: `${VL_SELECTION_RESOLVE}(${store}, ${$(resolve2)}${isPoint2}`
        });
      }
      hasSelections = true;
      for (const c4 of selectionCompilers) {
        if (c4.defined(selCmpt) && c4.topLevelSignals) {
          signals = c4.topLevelSignals(model, selCmpt, signals);
        }
      }
    }
    if (hasSelections) {
      const hasUnit = signals.filter((s2) => s2.name === "unit");
      if (hasUnit.length === 0) {
        signals.unshift({
          name: "unit",
          value: {},
          on: [{ events: "pointermove", update: "isTuple(group()) ? group() : unit" }]
        });
      }
    }
    return cleanupEmptyOnArray(signals);
  }
  function assembleUnitSelectionData(model, data3) {
    const selectionData = [];
    const animationData = [];
    const unit2 = unitName(model, { escape: false });
    for (const selCmpt of vals(model.component.selection ?? {})) {
      const store = { name: selCmpt.name + STORE };
      if (selCmpt.project.hasSelectionId) {
        store.transform = [{ type: "collect", sort: { field: SELECTION_ID } }];
      }
      if (selCmpt.init) {
        const fields = selCmpt.project.items.map(assembleProjection);
        store.values = selCmpt.project.hasSelectionId ? selCmpt.init.map((i2) => ({ unit: unit2, [SELECTION_ID]: assembleInit(i2, false)[0] })) : selCmpt.init.map((i2) => ({ unit: unit2, fields, values: assembleInit(i2, false) }));
      }
      const contains3 = [...selectionData, ...data3].filter((d2) => d2.name === selCmpt.name + STORE);
      if (!contains3.length) {
        selectionData.push(store);
      }
      if (isTimerSelection(selCmpt) && data3.length) {
        const sourceName = model.lookupDataSource(model.getDataName(DataSourceType.Main));
        const sourceData = data3.find((d2) => d2.name === sourceName);
        const sourceDataFilter = sourceData.transform.find((t4) => t4.type === "filter" && t4.expr.includes("vlSelectionTest"));
        if (sourceDataFilter) {
          sourceData.transform = sourceData.transform.filter((t4) => t4 !== sourceDataFilter);
          const currentFrame = {
            name: sourceData.name + CURR,
            source: sourceData.name,
            transform: [sourceDataFilter]
            // add the selection filter to the animation dataset
          };
          animationData.push(currentFrame);
        }
      }
    }
    return selectionData.concat(data3, animationData);
  }
  function assembleUnitSelectionMarks(model, marks) {
    for (const selCmpt of vals(model.component.selection ?? {})) {
      for (const c4 of selectionCompilers) {
        if (c4.defined(selCmpt) && c4.marks) {
          marks = c4.marks(model, selCmpt, marks);
        }
      }
    }
    return marks;
  }
  function assembleLayerSelectionMarks(model, marks) {
    for (const child of model.children) {
      if (isUnitModel(child)) {
        marks = assembleUnitSelectionMarks(child, marks);
      }
    }
    return marks;
  }
  function assembleSelectionScaleDomain(model, extent2, scaleCmpt, domain4) {
    const parsedExtent = parseSelectionExtent(model, extent2.param, extent2);
    return {
      signal: hasContinuousDomain(scaleCmpt.get("type")) && isArray(domain4) && domain4[0] > domain4[1] ? `isValid(${parsedExtent}) && reverse(${parsedExtent})` : parsedExtent
    };
  }
  function cleanupEmptyOnArray(signals) {
    return signals.map((s2) => {
      if (s2.on && !s2.on.length)
        delete s2.on;
      return s2;
    });
  }

  // node_modules/vega-lite/build/src/compile/selection/scales.js
  var scaleBindings = {
    defined: (selCmpt) => {
      return selCmpt.type === "interval" && selCmpt.resolve === "global" && selCmpt.bind && selCmpt.bind === "scales";
    },
    parse: (model, selCmpt) => {
      const bound2 = selCmpt.scales = [];
      for (const proj of selCmpt.project.items) {
        const channel = proj.channel;
        if (!isScaleChannel(channel)) {
          continue;
        }
        const scale7 = model.getScaleComponent(channel);
        const scaleType2 = scale7 ? scale7.get("type") : void 0;
        if (scaleType2 == "sequential") {
          warn2(message_exports.SEQUENTIAL_SCALE_DEPRECATED);
        }
        if (!scale7 || !hasContinuousDomain(scaleType2)) {
          warn2(message_exports.SCALE_BINDINGS_CONTINUOUS);
          continue;
        }
        scale7.set("selectionExtent", { param: selCmpt.name, field: proj.field }, true);
        bound2.push(proj);
      }
    },
    topLevelSignals: (model, selCmpt, signals) => {
      const bound2 = selCmpt.scales.filter((proj) => signals.filter((s2) => s2.name === proj.signals.data).length === 0);
      if (!model.parent || isTopLevelLayer(model) || bound2.length === 0) {
        return signals;
      }
      const namedSg = signals.find((s2) => s2.name === selCmpt.name);
      let update3 = namedSg.update;
      if (update3.includes(VL_SELECTION_RESOLVE)) {
        namedSg.update = `{${bound2.map((proj) => `${$(replacePathInField(proj.field))}: ${proj.signals.data}`).join(", ")}}`;
      } else {
        for (const proj of bound2) {
          const mapping = `${$(replacePathInField(proj.field))}: ${proj.signals.data}`;
          if (!update3.includes(mapping)) {
            update3 = `${update3.substring(0, update3.length - 1)}, ${mapping}}`;
          }
        }
        namedSg.update = update3;
      }
      return signals.concat(bound2.map((proj) => ({ name: proj.signals.data })));
    },
    signals: (model, selCmpt, signals) => {
      if (model.parent && !isTopLevelLayer(model)) {
        for (const proj of selCmpt.scales) {
          const signal = signals.find((s2) => s2.name === proj.signals.data);
          signal.push = "outer";
          delete signal.value;
          delete signal.update;
        }
      }
      return signals;
    }
  };
  var scales_default = scaleBindings;
  function domain3(model, channel) {
    const scale7 = $(model.scaleName(channel));
    return `domain(${scale7})`;
  }
  function isTopLevelLayer(model) {
    return model.parent && isLayerModel(model.parent) && (!model.parent.parent || isTopLevelLayer(model.parent.parent));
  }

  // node_modules/vega-lite/build/src/compile/selection/interval.js
  var BRUSH = "_brush";
  var SCALE_TRIGGER = "_scale_trigger";
  var GEO_INIT_TICK = "geo_interval_init_tick";
  var INIT = "_init";
  var CENTER2 = "_center";
  var interval2 = {
    defined: (selCmpt) => selCmpt.type === "interval",
    parse: (model, selCmpt, selDef) => {
      var _a2;
      if (model.hasProjection) {
        const def2 = { ...isObject(selDef.select) ? selDef.select : {} };
        def2.fields = [SELECTION_ID];
        if (!def2.encodings) {
          def2.encodings = selDef.value ? keys3(selDef.value) : [LONGITUDE, LATITUDE];
        }
        selDef.select = { type: "interval", ...def2 };
      }
      if (selCmpt.translate && !scales_default.defined(selCmpt)) {
        const filterExpr = `!event.item || event.item.mark.name !== ${$(selCmpt.name + BRUSH)}`;
        for (const evt of selCmpt.events) {
          if (!evt.between) {
            warn2(`${evt} is not an ordered event stream for interval selections.`);
            continue;
          }
          const filters2 = array((_a2 = evt.between[0]).filter ?? (_a2.filter = []));
          if (!filters2.includes(filterExpr)) {
            filters2.push(filterExpr);
          }
        }
      }
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const tupleSg = name4 + TUPLE;
      const channels = vals(selCmpt.project.hasChannel).filter((p2) => p2.channel === X3 || p2.channel === Y3);
      const init2 = selCmpt.init ? selCmpt.init[0] : null;
      signals.push(...channels.reduce((arr, proj) => arr.concat(channelSignals(model, selCmpt, proj, init2 && init2[proj.index])), []));
      if (!model.hasProjection) {
        if (!scales_default.defined(selCmpt)) {
          const triggerSg = name4 + SCALE_TRIGGER;
          const scaleTriggers = channels.map((proj) => {
            const channel = proj.channel;
            const { data: dname, visual: vname } = proj.signals;
            const scaleName = $(model.scaleName(channel));
            const scaleType2 = model.getScaleComponent(channel).get("type");
            const toNum = hasContinuousDomain(scaleType2) ? "+" : "";
            return `(!isArray(${dname}) || (${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))`;
          });
          if (scaleTriggers.length) {
            signals.push({
              name: triggerSg,
              value: {},
              on: [
                {
                  events: channels.map((proj) => ({ scale: model.scaleName(proj.channel) })),
                  update: scaleTriggers.join(" && ") + ` ? ${triggerSg} : {}`
                }
              ]
            });
          }
        }
        const dataSignals = channels.map((proj) => proj.signals.data);
        const update3 = `unit: ${unitName(model)}, fields: ${name4 + TUPLE_FIELDS}, values`;
        return signals.concat({
          name: tupleSg,
          ...init2 ? { init: `{${update3}: ${assembleInit(init2)}}` } : {},
          ...dataSignals.length ? {
            on: [
              {
                events: [{ signal: dataSignals.join(" || ") }],
                // Prevents double invocation, see https://github.com/vega/vega/issues/1672.
                update: `${dataSignals.join(" && ")} ? {${update3}: [${dataSignals}]} : null`
              }
            ]
          } : {}
        });
      } else {
        const projection3 = $(model.projectionName());
        const centerSg = model.projectionName() + CENTER2;
        const { x: x5, y: y5 } = selCmpt.project.hasChannel;
        const xvname = x5 && x5.signals.visual;
        const yvname = y5 && y5.signals.visual;
        const xinit = x5 ? init2 && init2[x5.index] : `${centerSg}[0]`;
        const yinit = y5 ? init2 && init2[y5.index] : `${centerSg}[1]`;
        const sizeSg = (layout) => model.getSizeSignalRef(layout).signal;
        const bbox = `[[${xvname ? xvname + "[0]" : "0"}, ${yvname ? yvname + "[0]" : "0"}],[${xvname ? xvname + "[1]" : sizeSg("width")}, ${yvname ? yvname + "[1]" : sizeSg("height")}]]`;
        if (init2) {
          signals.unshift({
            name: name4 + INIT,
            init: `[scale(${projection3}, [${x5 ? xinit[0] : xinit}, ${y5 ? yinit[0] : yinit}]), scale(${projection3}, [${x5 ? xinit[1] : xinit}, ${y5 ? yinit[1] : yinit}])]`
          });
          if (!x5 || !y5) {
            const hasCenterSg = signals.find((s2) => s2.name === centerSg);
            if (!hasCenterSg) {
              signals.unshift({
                name: centerSg,
                update: `invert(${projection3}, [${sizeSg("width")}/2, ${sizeSg("height")}/2])`
              });
            }
          }
        }
        const intersect5 = `intersect(${bbox}, {markname: ${$(model.getName("marks"))}}, unit.mark)`;
        const base = `{unit: ${unitName(model)}}`;
        const update3 = `vlSelectionTuples(${intersect5}, ${base})`;
        const visualSignals = channels.map((proj) => proj.signals.visual);
        return signals.concat({
          name: tupleSg,
          on: [
            {
              events: [
                ...visualSignals.length ? [{ signal: visualSignals.join(" || ") }] : [],
                ...init2 ? [{ signal: GEO_INIT_TICK }] : []
              ],
              update: update3
            }
          ]
        });
      }
    },
    topLevelSignals: (model, selCmpt, signals) => {
      if (isUnitModel(model) && model.hasProjection && selCmpt.init) {
        const hasTick = signals.filter((s2) => s2.name === GEO_INIT_TICK);
        if (!hasTick.length) {
          signals.unshift({
            name: GEO_INIT_TICK,
            value: null,
            on: [
              {
                events: "timer{1}",
                update: `${GEO_INIT_TICK} === null ? {} : ${GEO_INIT_TICK}`
              }
            ]
          });
        }
      }
      return signals;
    },
    marks: (model, selCmpt, marks) => {
      const name4 = selCmpt.name;
      const { x: x5, y: y5 } = selCmpt.project.hasChannel;
      const xvname = x5?.signals.visual;
      const yvname = y5?.signals.visual;
      const store = `data(${$(selCmpt.name + STORE)})`;
      if (scales_default.defined(selCmpt) || !x5 && !y5) {
        return marks;
      }
      const update3 = {
        x: x5 !== void 0 ? { signal: `${xvname}[0]` } : { value: 0 },
        y: y5 !== void 0 ? { signal: `${yvname}[0]` } : { value: 0 },
        x2: x5 !== void 0 ? { signal: `${xvname}[1]` } : { field: { group: "width" } },
        y2: y5 !== void 0 ? { signal: `${yvname}[1]` } : { field: { group: "height" } }
      };
      if (selCmpt.resolve === "global") {
        for (const key2 of keys3(update3)) {
          update3[key2] = [
            {
              test: `${store}.length && ${store}[0].unit === ${unitName(model)}`,
              ...update3[key2]
            },
            { value: 0 }
          ];
        }
      }
      const { fill: fill2, fillOpacity, cursor: cursor3, ...stroke2 } = selCmpt.mark;
      const vgStroke = keys3(stroke2).reduce((def2, k2) => {
        def2[k2] = [
          {
            test: [
              x5 !== void 0 && `${xvname}[0] !== ${xvname}[1]`,
              y5 !== void 0 && `${yvname}[0] !== ${yvname}[1]`
            ].filter((t4) => t4).join(" && "),
            value: stroke2[k2]
          },
          { value: null }
        ];
        return def2;
      }, {});
      const vgCursor = cursor3 ?? (selCmpt.translate ? "move" : null);
      return [
        {
          name: `${name4 + BRUSH}_bg`,
          type: "rect",
          clip: true,
          encode: {
            enter: {
              fill: { value: fill2 },
              fillOpacity: { value: fillOpacity }
            },
            update: update3
          }
        },
        ...marks,
        {
          name: name4 + BRUSH,
          type: "rect",
          clip: true,
          encode: {
            enter: {
              ...vgCursor ? { cursor: { value: vgCursor } } : {},
              fill: { value: "transparent" }
            },
            update: { ...update3, ...vgStroke }
          }
        }
      ];
    }
  };
  var interval_default2 = interval2;
  function channelSignals(model, selCmpt, proj, init2) {
    const scaledInterval = !model.hasProjection;
    const channel = proj.channel;
    const vname = proj.signals.visual;
    const scaleName = $(scaledInterval ? model.scaleName(channel) : model.projectionName());
    const scaled = (str) => `scale(${scaleName}, ${str})`;
    const size = model.getSizeSignalRef(channel === X3 ? "width" : "height").signal;
    const coord = `${channel}(unit)`;
    const von = selCmpt.events.reduce((def2, evt) => {
      return [
        ...def2,
        { events: evt.between[0], update: `[${coord}, ${coord}]` },
        // Brush Start
        { events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]` }
        // Brush End
      ];
    }, []);
    if (scaledInterval) {
      const dname = proj.signals.data;
      const hasScales = scales_default.defined(selCmpt);
      const scale7 = model.getScaleComponent(channel);
      const scaleType2 = scale7 ? scale7.get("type") : void 0;
      const vinit = init2 ? { init: assembleInit(init2, true, scaled) } : { value: [] };
      von.push({
        events: { signal: selCmpt.name + SCALE_TRIGGER },
        update: hasContinuousDomain(scaleType2) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]`
      });
      return hasScales ? [{ name: dname, on: [] }] : [
        { name: vname, ...vinit, on: von },
        {
          name: dname,
          ...init2 ? { init: assembleInit(init2) } : {},
          // Cannot be `value` as `init` may require datetime exprs.
          on: [
            {
              events: { signal: vname },
              update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})`
            }
          ]
        }
      ];
    } else {
      const initIdx = channel === X3 ? 0 : 1;
      const initSg = selCmpt.name + INIT;
      const vinit = init2 ? { init: `[${initSg}[0][${initIdx}], ${initSg}[1][${initIdx}]]` } : { value: [] };
      return [{ name: vname, ...vinit, on: von }];
    }
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/conditional.js
  function wrapCondition({ model, channelDef, vgChannel, invalidValueRef, mainRefFn }) {
    const condition = isConditionalDef(channelDef) && channelDef.condition;
    let valueRefs = [];
    if (condition) {
      const conditions = array(condition);
      valueRefs = conditions.map((c4) => {
        const conditionValueRef = mainRefFn(c4);
        if (isConditionalParameter(c4)) {
          const { param: param2, empty } = c4;
          const test2 = parseSelectionPredicate(model, { param: param2, empty });
          return { test: test2, ...conditionValueRef };
        } else {
          const test2 = expression3(model, c4.test);
          return { test: test2, ...conditionValueRef };
        }
      });
    }
    if (invalidValueRef !== void 0) {
      valueRefs.push(invalidValueRef);
    }
    const mainValueRef = mainRefFn(channelDef);
    if (mainValueRef !== void 0) {
      valueRefs.push(mainValueRef);
    }
    if (valueRefs.length > 1 || valueRefs.length === 1 && Boolean(valueRefs[0].test)) {
      return { [vgChannel]: valueRefs };
    } else if (valueRefs.length === 1) {
      return { [vgChannel]: valueRefs[0] };
    }
    return {};
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/text.js
  function text2(model, channel = "text") {
    const channelDef = model.encoding[channel];
    return wrapCondition({
      model,
      channelDef,
      vgChannel: channel,
      mainRefFn: (cDef) => textRef(cDef, model.config),
      invalidValueRef: void 0
      // text encoding doesn't have continuous scales and thus can't have invalid values
    });
  }
  function textRef(channelDef, config, expr2 = "datum") {
    if (channelDef) {
      if (isValueDef(channelDef)) {
        return signalOrValueRef(channelDef.value);
      }
      if (isFieldOrDatumDef(channelDef)) {
        const { format: format5, formatType } = getFormatMixins(channelDef);
        return formatSignalRef({ fieldOrDatumDef: channelDef, format: format5, formatType, expr: expr2, config });
      }
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/tooltip.js
  function tooltip(model, opt = {}) {
    const { encoding, markDef, config, stack: stack2 } = model;
    const channelDef = encoding.tooltip;
    if (isArray(channelDef)) {
      return { tooltip: tooltipRefForEncoding({ tooltip: channelDef }, stack2, config, opt) };
    } else {
      const datum2 = opt.reactiveGeom ? "datum.datum" : "datum";
      const mainRefFn = (cDef) => {
        const tooltipRefFromChannelDef = textRef(cDef, config, datum2);
        if (tooltipRefFromChannelDef) {
          return tooltipRefFromChannelDef;
        }
        if (cDef === null) {
          return void 0;
        }
        let markTooltip = getMarkPropOrConfig("tooltip", markDef, config);
        if (markTooltip === true) {
          markTooltip = { content: "encoding" };
        }
        if (isString(markTooltip)) {
          return { value: markTooltip };
        } else if (isObject(markTooltip)) {
          if (isSignalRef(markTooltip)) {
            return markTooltip;
          } else if (markTooltip.content === "encoding") {
            return tooltipRefForEncoding(encoding, stack2, config, opt);
          } else {
            return { signal: datum2 };
          }
        }
        return void 0;
      };
      return wrapCondition({
        model,
        channelDef,
        vgChannel: "tooltip",
        mainRefFn,
        invalidValueRef: void 0
        // tooltip encoding doesn't have continuous scales and thus can't have invalid values
      });
    }
  }
  function tooltipData(encoding, stack2, config, { reactiveGeom } = {}) {
    const formatConfig = { ...config, ...config.tooltipFormat };
    const toSkip = /* @__PURE__ */ new Set();
    const expr2 = reactiveGeom ? "datum.datum" : "datum";
    const tuples = [];
    function add6(fDef, channel) {
      const mainChannel = getMainRangeChannel(channel);
      const fieldDef = isTypedFieldDef(fDef) ? fDef : {
        ...fDef,
        type: encoding[mainChannel].type
        // for secondary field def, copy type from main channel
      };
      const title2 = fieldDef.title || defaultTitle(fieldDef, formatConfig);
      const key2 = array(title2).join(", ").replaceAll(/"/g, '\\"');
      let value3;
      if (isXorY(channel)) {
        const channel2 = channel === "x" ? "x2" : "y2";
        const fieldDef2 = getFieldDef(encoding[channel2]);
        if (isBinned(fieldDef.bin) && fieldDef2) {
          const startField = vgField(fieldDef, { expr: expr2 });
          const endField = vgField(fieldDef2, { expr: expr2 });
          const { format: format5, formatType } = getFormatMixins(fieldDef);
          value3 = binFormatExpression(startField, endField, format5, formatType, formatConfig);
          toSkip.add(channel2);
        }
      }
      if ((isXorY(channel) || channel === THETA || channel === RADIUS) && stack2 && stack2.fieldChannel === channel && stack2.offset === "normalize") {
        const { format: format5, formatType } = getFormatMixins(fieldDef);
        value3 = formatSignalRef({
          fieldOrDatumDef: fieldDef,
          format: format5,
          formatType,
          expr: expr2,
          config: formatConfig,
          normalizeStack: true
        }).signal;
      }
      value3 ?? (value3 = textRef(fieldDef, formatConfig, expr2).signal);
      tuples.push({ channel, key: key2, value: value3 });
    }
    forEach(encoding, (channelDef, channel) => {
      if (isFieldDef(channelDef)) {
        add6(channelDef, channel);
      } else if (hasConditionalFieldDef(channelDef)) {
        add6(channelDef.condition, channel);
      }
    });
    const out = {};
    for (const { channel, key: key2, value: value3 } of tuples) {
      if (!toSkip.has(channel) && !out[key2]) {
        out[key2] = value3;
      }
    }
    return out;
  }
  function tooltipRefForEncoding(encoding, stack2, config, { reactiveGeom } = {}) {
    const data3 = tooltipData(encoding, stack2, config, { reactiveGeom });
    const keyValues = entries(data3).map(([key2, value3]) => `"${key2}": ${value3}`);
    return keyValues.length > 0 ? { signal: `{${keyValues.join(", ")}}` } : void 0;
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/aria.js
  function aria(model) {
    const { markDef, config } = model;
    const enableAria = getMarkPropOrConfig("aria", markDef, config);
    if (enableAria === false) {
      return {};
    }
    return {
      ...enableAria ? { aria: enableAria } : {},
      ...ariaRoleDescription(model),
      ...description(model)
    };
  }
  function ariaRoleDescription(model) {
    const { mark, markDef, config } = model;
    if (config.aria === false) {
      return {};
    }
    const ariaRoleDesc = getMarkPropOrConfig("ariaRoleDescription", markDef, config);
    if (ariaRoleDesc != null) {
      return { ariaRoleDescription: { value: ariaRoleDesc } };
    }
    return has(VG_MARK_INDEX, mark) ? {} : { ariaRoleDescription: { value: mark } };
  }
  function description(model) {
    const { encoding, markDef, config, stack: stack2 } = model;
    const channelDef = encoding.description;
    if (channelDef) {
      return wrapCondition({
        model,
        channelDef,
        vgChannel: "description",
        mainRefFn: (cDef) => textRef(cDef, model.config),
        invalidValueRef: void 0
        // aria encoding doesn't have continuous scales and thus can't have invalid values
      });
    }
    const descriptionValue = getMarkPropOrConfig("description", markDef, config);
    if (descriptionValue != null) {
      return {
        description: signalOrValueRef(descriptionValue)
      };
    }
    if (config.aria === false) {
      return {};
    }
    const data3 = tooltipData(encoding, stack2, config);
    if (isEmpty(data3)) {
      return void 0;
    }
    return {
      description: {
        signal: entries(data3).map(([key2, value3], index4) => `"${index4 > 0 ? "; " : ""}${key2}: " + (${value3})`).join(" + ")
      }
    };
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/nonposition.js
  function nonPosition(channel, model, opt = {}) {
    const { markDef, encoding, config } = model;
    const { vgChannel } = opt;
    let { defaultRef, defaultValue } = opt;
    const channelDef = encoding[channel];
    if (defaultRef === void 0) {
      defaultValue ?? (defaultValue = getMarkPropOrConfig(channel, markDef, config, {
        vgChannel,
        // If there is no conditonal def, we ignore vgConfig so the output spec is concise.
        // However, if there is a conditional def, we must include vgConfig so the default is respected.
        ignoreVgConfig: !isConditionalDef(channelDef)
      }));
      if (defaultValue !== void 0) {
        defaultRef = signalOrValueRef(defaultValue);
      }
    }
    const commonProps = {
      markDef,
      config,
      scaleName: model.scaleName(channel),
      scale: model.getScaleComponent(channel)
    };
    const invalidValueRef = getConditionalValueRefForIncludingInvalidValue({
      ...commonProps,
      scaleChannel: channel,
      channelDef
    });
    const mainRefFn = (cDef) => {
      return midPoint({
        ...commonProps,
        channel,
        channelDef: cDef,
        stack: null,
        // No need to provide stack for non-position as it does not affect mid point
        defaultRef
      });
    };
    return wrapCondition({
      model,
      channelDef,
      vgChannel: vgChannel ?? channel,
      invalidValueRef,
      mainRefFn
    });
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/color.js
  function color4(model, opt = { filled: void 0 }) {
    const { markDef, encoding, config } = model;
    const { type: markType2 } = markDef;
    const filled = opt.filled ?? getMarkPropOrConfig("filled", markDef, config);
    const transparentIfNeeded = contains2(["bar", "point", "circle", "square", "geoshape"], markType2) ? "transparent" : void 0;
    const defaultFill = getMarkPropOrConfig(filled === true ? "color" : void 0, markDef, config, { vgChannel: "fill" }) ?? // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
    config.mark[filled === true && "color"] ?? // If there is no fill, always fill symbols, bar, geoshape
    // with transparent fills https://github.com/vega/vega-lite/issues/1316
    transparentIfNeeded;
    const defaultStroke = getMarkPropOrConfig(filled === false ? "color" : void 0, markDef, config, { vgChannel: "stroke" }) ?? // need to add this manually as getMarkConfig normally drops config.mark[channel] if vgChannel is specified
    config.mark[filled === false && "color"];
    const colorVgChannel = filled ? "fill" : "stroke";
    const fillStrokeMarkDefAndConfig = {
      ...defaultFill ? { fill: signalOrValueRef(defaultFill) } : {},
      ...defaultStroke ? { stroke: signalOrValueRef(defaultStroke) } : {}
    };
    if (markDef.color && (filled ? markDef.fill : markDef.stroke)) {
      warn2(message_exports.droppingColor("property", { fill: "fill" in markDef, stroke: "stroke" in markDef }));
    }
    return {
      ...fillStrokeMarkDefAndConfig,
      ...nonPosition("color", model, {
        vgChannel: colorVgChannel,
        defaultValue: filled ? defaultFill : defaultStroke
      }),
      ...nonPosition("fill", model, {
        // if there is encoding.fill, include default fill just in case we have conditional-only fill encoding
        defaultValue: encoding.fill ? defaultFill : void 0
      }),
      ...nonPosition("stroke", model, {
        // if there is encoding.stroke, include default fill just in case we have conditional-only stroke encoding
        defaultValue: encoding.stroke ? defaultStroke : void 0
      })
    };
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/zindex.js
  function zindex(model) {
    const { encoding, mark } = model;
    const order = encoding.order;
    if (!isPathMark(mark) && isValueDef(order)) {
      return wrapCondition({
        model,
        channelDef: order,
        vgChannel: "zindex",
        mainRefFn: (cd2) => signalOrValueRef(cd2.value),
        invalidValueRef: void 0
        // zindex encoding doesn't have continuous scales and thus can't have invalid values
      });
    }
    return {};
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/offset.js
  function positionOffset({ channel: baseChannel, markDef, encoding = {}, model, bandPosition }) {
    const channel = `${baseChannel}Offset`;
    const defaultValue = markDef[channel];
    const channelDef = encoding[channel];
    if ((channel === "xOffset" || channel === "yOffset") && channelDef) {
      const ref2 = midPoint({
        channel,
        channelDef,
        markDef,
        config: model?.config,
        scaleName: model.scaleName(channel),
        scale: model.getScaleComponent(channel),
        stack: null,
        defaultRef: signalOrValueRef(defaultValue),
        bandPosition
      });
      return { offsetType: "encoding", offset: ref2 };
    }
    const markDefOffsetValue = markDef[channel];
    if (markDefOffsetValue) {
      return { offsetType: "visual", offset: markDefOffsetValue };
    }
    return {};
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/position-point.js
  function pointPosition(channel, model, { defaultPos, vgChannel }) {
    const { encoding, markDef, config, stack: stack2 } = model;
    const channelDef = encoding[channel];
    const channel2Def = encoding[getSecondaryRangeChannel(channel)];
    const scaleName = model.scaleName(channel);
    const scale7 = model.getScaleComponent(channel);
    const { offset: offset4, offsetType } = positionOffset({
      channel,
      markDef,
      encoding,
      model,
      bandPosition: 0.5
    });
    const defaultRef = pointPositionDefaultRef({
      model,
      defaultPos,
      channel,
      scaleName,
      scale: scale7
    });
    const valueRef = !channelDef && isXorY(channel) && (encoding.latitude || encoding.longitude) ? (
      // use geopoint output if there are lat/long and there is no point position overriding lat/long.
      { field: model.getName(channel) }
    ) : positionRef({
      channel,
      channelDef,
      channel2Def,
      markDef,
      config,
      scaleName,
      scale: scale7,
      stack: stack2,
      offset: offset4,
      defaultRef,
      bandPosition: offsetType === "encoding" ? 0 : void 0
    });
    return valueRef ? { [vgChannel || channel]: valueRef } : void 0;
  }
  function positionRef(params2) {
    const { channel, channelDef, scaleName, stack: stack2, offset: offset4, markDef } = params2;
    if (isFieldOrDatumDef(channelDef) && stack2 && channel === stack2.fieldChannel) {
      if (isFieldDef(channelDef)) {
        let bandPosition = channelDef.bandPosition;
        if (bandPosition === void 0 && markDef.type === "text" && (channel === "radius" || channel === "theta")) {
          bandPosition = 0.5;
        }
        if (bandPosition !== void 0) {
          return interpolatedSignalRef({
            scaleName,
            fieldOrDatumDef: channelDef,
            // positionRef always have type
            startSuffix: "start",
            bandPosition,
            offset: offset4
          });
        }
      }
      return valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: "end" }, { offset: offset4 });
    }
    return midPointRefWithPositionInvalidTest(params2);
  }
  function pointPositionDefaultRef({ model, defaultPos, channel, scaleName, scale: scale7 }) {
    const { markDef, config } = model;
    return () => {
      const mainChannel = getMainRangeChannel(channel);
      const vgChannel = getVgPositionChannel(channel);
      const definedValueOrConfig = getMarkPropOrConfig(channel, markDef, config, { vgChannel });
      if (definedValueOrConfig !== void 0) {
        return widthHeightValueOrSignalRef(channel, definedValueOrConfig);
      }
      switch (defaultPos) {
        case "zeroOrMin":
          return zeroOrMinOrMaxPosition({ scaleName, scale: scale7, mode: "zeroOrMin", mainChannel, config });
        case "zeroOrMax":
          return zeroOrMinOrMaxPosition({
            scaleName,
            scale: scale7,
            mode: { zeroOrMax: { widthSignal: model.width.signal, heightSignal: model.height.signal } },
            mainChannel,
            config
          });
        case "mid": {
          const sizeRef = model[getSizeChannel(channel)];
          return { ...sizeRef, mult: 0.5 };
        }
      }
      return void 0;
    };
  }
  function zeroOrMinOrMaxPosition({ mainChannel, config, ...otherProps }) {
    const scaledValueRef = scaledZeroOrMinOrMax(otherProps);
    const { mode } = otherProps;
    if (scaledValueRef) {
      return scaledValueRef;
    }
    switch (mainChannel) {
      case "radius": {
        if (mode === "zeroOrMin") {
          return { value: 0 };
        }
        const { widthSignal, heightSignal } = mode.zeroOrMax;
        return {
          signal: `min(${widthSignal},${heightSignal})/2`
        };
      }
      case "theta":
        return mode === "zeroOrMin" ? { value: 0 } : { signal: "2*PI" };
      case "x":
        return mode === "zeroOrMin" ? { value: 0 } : { field: { group: "width" } };
      case "y":
        return mode === "zeroOrMin" ? { field: { group: "height" } } : { value: 0 };
    }
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/position-align.js
  var ALIGNED_X_CHANNEL = {
    left: "x",
    center: "xc",
    right: "x2"
  };
  var BASELINED_Y_CHANNEL = {
    top: "y",
    middle: "yc",
    bottom: "y2"
  };
  function vgAlignedPositionChannel(channel, markDef, config, defaultAlign = "middle") {
    if (channel === "radius" || channel === "theta") {
      return getVgPositionChannel(channel);
    }
    const alignChannel = channel === "x" ? "align" : "baseline";
    const align2 = getMarkPropOrConfig(alignChannel, markDef, config);
    let alignExcludingSignal;
    if (isSignalRef(align2)) {
      warn2(message_exports.rangeMarkAlignmentCannotBeExpression(alignChannel));
      alignExcludingSignal = void 0;
    } else {
      alignExcludingSignal = align2;
    }
    if (channel === "x") {
      return ALIGNED_X_CHANNEL[alignExcludingSignal || (defaultAlign === "top" ? "left" : "center")];
    } else {
      return BASELINED_Y_CHANNEL[alignExcludingSignal || defaultAlign];
    }
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/position-range.js
  function pointOrRangePosition(channel, model, { defaultPos, defaultPos2, range: range7 }) {
    if (range7) {
      return rangePosition(channel, model, { defaultPos, defaultPos2 });
    }
    return pointPosition(channel, model, { defaultPos });
  }
  function rangePosition(channel, model, { defaultPos, defaultPos2 }) {
    const { markDef, config } = model;
    const channel2 = getSecondaryRangeChannel(channel);
    const sizeChannel = getSizeChannel(channel);
    const pos2Mixins = pointPosition2OrSize(model, defaultPos2, channel2);
    const vgChannel = pos2Mixins[sizeChannel] ? (
      // If there is width/height, we need to position the marks based on the alignment.
      vgAlignedPositionChannel(channel, markDef, config)
    ) : (
      // Otherwise, make sure to apply to the right Vg Channel (for arc mark)
      getVgPositionChannel(channel)
    );
    return {
      ...pointPosition(channel, model, { defaultPos, vgChannel }),
      ...pos2Mixins
    };
  }
  function pointPosition2OrSize(model, defaultPos, channel) {
    const { encoding, mark, markDef, stack: stack2, config } = model;
    const baseChannel = getMainRangeChannel(channel);
    const sizeChannel = getSizeChannel(channel);
    const vgChannel = getVgPositionChannel(channel);
    const channelDef = encoding[baseChannel];
    const scaleName = model.scaleName(baseChannel);
    const scale7 = model.getScaleComponent(baseChannel);
    const { offset: offset4 } = channel in encoding || channel in markDef ? positionOffset({ channel, markDef, encoding, model }) : positionOffset({ channel: baseChannel, markDef, encoding, model });
    if (!channelDef && (channel === "x2" || channel === "y2") && (encoding.latitude || encoding.longitude)) {
      const vgSizeChannel = getSizeChannel(channel);
      const size = model.markDef[vgSizeChannel];
      if (size != null) {
        return {
          [vgSizeChannel]: { value: size }
        };
      } else {
        return {
          [vgChannel]: { field: model.getName(channel) }
        };
      }
    }
    const valueRef = position2Ref({
      channel,
      channelDef,
      channel2Def: encoding[channel],
      markDef,
      config,
      scaleName,
      scale: scale7,
      stack: stack2,
      offset: offset4,
      defaultRef: void 0
    });
    if (valueRef !== void 0) {
      return { [vgChannel]: valueRef };
    }
    return position2orSize(channel, markDef) || position2orSize(channel, {
      [channel]: getMarkStyleConfig(channel, markDef, config.style),
      [sizeChannel]: getMarkStyleConfig(sizeChannel, markDef, config.style)
    }) || position2orSize(channel, config[mark]) || position2orSize(channel, config.mark) || {
      [vgChannel]: pointPositionDefaultRef({
        model,
        defaultPos,
        channel,
        scaleName,
        scale: scale7
      })()
    };
  }
  function position2Ref({ channel, channelDef, channel2Def, markDef, config, scaleName, scale: scale7, stack: stack2, offset: offset4, defaultRef }) {
    if (isFieldOrDatumDef(channelDef) && stack2 && // If fieldChannel is X and channel is X2 (or Y and Y2)
    channel.charAt(0) === stack2.fieldChannel.charAt(0)) {
      return valueRefForFieldOrDatumDef(channelDef, scaleName, { suffix: "start" }, { offset: offset4 });
    }
    return midPointRefWithPositionInvalidTest({
      channel,
      channelDef: channel2Def,
      scaleName,
      scale: scale7,
      stack: stack2,
      markDef,
      config,
      offset: offset4,
      defaultRef
    });
  }
  function position2orSize(channel, markDef) {
    const sizeChannel = getSizeChannel(channel);
    const vgChannel = getVgPositionChannel(channel);
    if (markDef[vgChannel] !== void 0) {
      return { [vgChannel]: widthHeightValueOrSignalRef(channel, markDef[vgChannel]) };
    } else if (markDef[channel] !== void 0) {
      return { [vgChannel]: widthHeightValueOrSignalRef(channel, markDef[channel]) };
    } else if (markDef[sizeChannel]) {
      const dimensionSize = markDef[sizeChannel];
      if (isRelativeBandSize(dimensionSize)) {
        warn2(message_exports.relativeBandSizeNotSupported(sizeChannel));
      } else {
        return { [sizeChannel]: widthHeightValueOrSignalRef(channel, dimensionSize) };
      }
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/position-rect.js
  function rectPosition(model, channel) {
    const { config, encoding, markDef } = model;
    const mark = markDef.type;
    const channel2 = getSecondaryRangeChannel(channel);
    const sizeChannel = getSizeChannel(channel);
    const channelDef = encoding[channel];
    const channelDef2 = encoding[channel2];
    const scale7 = model.getScaleComponent(channel);
    const scaleType2 = scale7 ? scale7.get("type") : void 0;
    const orient2 = markDef.orient;
    const hasSizeDef = encoding[sizeChannel] ?? encoding.size ?? getMarkPropOrConfig("size", markDef, config, { vgChannel: sizeChannel });
    const offsetScaleChannel = getOffsetChannel(channel);
    const isBarOrTickBand = mark === "bar" && (channel === "x" ? orient2 === "vertical" : orient2 === "horizontal") || mark === "tick" && (channel === "y" ? orient2 === "vertical" : orient2 === "horizontal");
    if (isFieldDef(channelDef) && (isBinning(channelDef.bin) || isBinned(channelDef.bin) || channelDef.timeUnit && !channelDef2) && !(hasSizeDef && !isRelativeBandSize(hasSizeDef)) && !encoding[offsetScaleChannel] && !hasDiscreteDomain(scaleType2)) {
      return rectBinPosition({
        fieldDef: channelDef,
        fieldDef2: channelDef2,
        channel,
        model
      });
    } else if ((isFieldOrDatumDef(channelDef) && hasDiscreteDomain(scaleType2) || isBarOrTickBand) && !channelDef2) {
      return positionAndSize(channelDef, channel, model);
    } else {
      return rangePosition(channel, model, { defaultPos: "zeroOrMax", defaultPos2: "zeroOrMin" });
    }
  }
  function defaultSizeRef(sizeChannel, scaleName, scale7, config, bandSize, hasFieldDef, mark) {
    if (isRelativeBandSize(bandSize)) {
      if (scale7) {
        const scaleType2 = scale7.get("type");
        if (scaleType2 === "band") {
          let bandWidth = `bandwidth('${scaleName}')`;
          if (bandSize.band !== 1) {
            bandWidth = `${bandSize.band} * ${bandWidth}`;
          }
          const minBandSize = getMarkConfig("minBandSize", { type: mark }, config);
          return { signal: minBandSize ? `max(${signalOrStringValue(minBandSize)}, ${bandWidth})` : bandWidth };
        } else if (bandSize.band !== 1) {
          warn2(message_exports.cannotUseRelativeBandSizeWithNonBandScale(scaleType2));
          bandSize = void 0;
        }
      } else {
        return {
          mult: bandSize.band,
          field: { group: sizeChannel }
        };
      }
    } else if (isSignalRef(bandSize)) {
      return bandSize;
    } else if (bandSize) {
      return { value: bandSize };
    }
    if (scale7) {
      const scaleRange = scale7.get("range");
      if (isVgRangeStep(scaleRange) && isNumber(scaleRange.step)) {
        return { value: scaleRange.step - 2 };
      }
    }
    if (!hasFieldDef) {
      const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner, tickBandPaddingInner } = config.scale;
      const padding3 = getFirstDefined(bandPaddingInner, mark === "tick" ? tickBandPaddingInner : mark === "bar" ? barBandPaddingInner : rectBandPaddingInner);
      if (isSignalRef(padding3)) {
        return { signal: `(1 - (${padding3.signal})) * ${sizeChannel}` };
      } else if (isNumber(padding3)) {
        return { signal: `${1 - padding3} * ${sizeChannel}` };
      }
    }
    const defaultStep = getViewConfigDiscreteStep(config.view, sizeChannel);
    return { value: defaultStep - 2 };
  }
  function positionAndSize(fieldDef, channel, model) {
    const { markDef, encoding, config, stack: stack2 } = model;
    const orient2 = markDef.orient;
    const scaleName = model.scaleName(channel);
    const scale7 = model.getScaleComponent(channel);
    const vgSizeChannel = getSizeChannel(channel);
    const channel2 = getSecondaryRangeChannel(channel);
    const offsetScaleChannel = getOffsetChannel(channel);
    const offsetScaleName = model.scaleName(offsetScaleChannel);
    const offsetScale = model.getScaleComponent(getOffsetScaleChannel(channel));
    const useVlSizeChannel = (
      // Always uses size channel for ticks, because tick only calls rectPosition() for the size channel
      markDef.type === "tick" || // use "size" channel for bars, if there is orient and the channel matches the right orientation
      orient2 === "horizontal" && channel === "y" || orient2 === "vertical" && channel === "x"
    );
    let sizeMixins;
    if (encoding.size || markDef.size) {
      if (useVlSizeChannel) {
        sizeMixins = nonPosition("size", model, {
          vgChannel: vgSizeChannel,
          defaultRef: signalOrValueRef(markDef.size)
        });
      } else {
        warn2(message_exports.cannotApplySizeToNonOrientedMark(markDef.type));
      }
    }
    const hasSizeFromMarkOrEncoding = !!sizeMixins;
    const bandSize = getBandSize({
      channel,
      fieldDef,
      markDef,
      config,
      scaleType: (scale7 || offsetScale)?.get("type"),
      useVlSizeChannel
    });
    sizeMixins = sizeMixins || {
      [vgSizeChannel]: defaultSizeRef(vgSizeChannel, offsetScaleName || scaleName, offsetScale || scale7, config, bandSize, !!fieldDef, markDef.type)
    };
    const defaultBandAlign = (scale7 || offsetScale)?.get("type") === "band" && isRelativeBandSize(bandSize) && !hasSizeFromMarkOrEncoding ? "top" : "middle";
    const vgChannel = vgAlignedPositionChannel(channel, markDef, config, defaultBandAlign);
    const center = vgChannel === "xc" || vgChannel === "yc";
    const { offset: offset4, offsetType } = positionOffset({ channel, markDef, encoding, model, bandPosition: center ? 0.5 : 0 });
    const posRef = midPointRefWithPositionInvalidTest({
      channel,
      channelDef: fieldDef,
      markDef,
      config,
      scaleName,
      scale: scale7,
      stack: stack2,
      offset: offset4,
      defaultRef: pointPositionDefaultRef({ model, defaultPos: "mid", channel, scaleName, scale: scale7 }),
      bandPosition: center ? offsetType === "encoding" ? 0 : 0.5 : isSignalRef(bandSize) ? { signal: `(1-${bandSize})/2` } : isRelativeBandSize(bandSize) ? (1 - bandSize.band) / 2 : 0
    });
    if (vgSizeChannel) {
      return { [vgChannel]: posRef, ...sizeMixins };
    } else {
      const vgChannel2 = getVgPositionChannel(channel2);
      const sizeRef = sizeMixins[vgSizeChannel];
      const sizeOffset = offset4 ? { ...sizeRef, offset: offset4 } : sizeRef;
      return {
        [vgChannel]: posRef,
        // posRef might be an array that wraps position invalid test
        [vgChannel2]: isArray(posRef) ? [posRef[0], { ...posRef[1], offset: sizeOffset }] : {
          ...posRef,
          offset: sizeOffset
        }
      };
    }
  }
  function getBinSpacing(channel, spacing, reverse3, axisTranslate, offset4, minBandSize, bandSizeExpr) {
    if (isPolarPositionChannel(channel)) {
      return 0;
    }
    const isEnd = channel === "x" || channel === "y2";
    const spacingOffset = isEnd ? -spacing / 2 : spacing / 2;
    if (isSignalRef(reverse3) || isSignalRef(offset4) || isSignalRef(axisTranslate) || minBandSize) {
      const reverseExpr = signalOrStringValue(reverse3);
      const offsetExpr2 = signalOrStringValue(offset4);
      const axisTranslateExpr = signalOrStringValue(axisTranslate);
      const minBandSizeExpr = signalOrStringValue(minBandSize);
      const sign3 = isEnd ? "" : "-";
      const spacingAndSizeOffset = minBandSize ? `(${bandSizeExpr} < ${minBandSizeExpr} ? ${sign3}0.5 * (${minBandSizeExpr} - (${bandSizeExpr})) : ${spacingOffset})` : spacingOffset;
      const t4 = axisTranslateExpr ? `${axisTranslateExpr} + ` : "";
      const r2 = reverseExpr ? `(${reverseExpr} ? -1 : 1) * ` : "";
      const o2 = offsetExpr2 ? `(${offsetExpr2} + ${spacingAndSizeOffset})` : spacingAndSizeOffset;
      return {
        signal: t4 + r2 + o2
      };
    } else {
      offset4 = offset4 || 0;
      return axisTranslate + (reverse3 ? -offset4 - spacingOffset : +offset4 + spacingOffset);
    }
  }
  function rectBinPosition({ fieldDef, fieldDef2, channel, model }) {
    const { config, markDef, encoding } = model;
    const scale7 = model.getScaleComponent(channel);
    const scaleName = model.scaleName(channel);
    const scaleType2 = scale7 ? scale7.get("type") : void 0;
    const reverse3 = scale7.get("reverse");
    const bandSize = getBandSize({ channel, fieldDef, markDef, config, scaleType: scaleType2 });
    const axis = model.component.axes[channel]?.[0];
    const axisTranslate = axis?.get("translate") ?? 0.5;
    const spacing = isXorY(channel) ? getMarkPropOrConfig("binSpacing", markDef, config) ?? 0 : 0;
    const channel2 = getSecondaryRangeChannel(channel);
    const vgChannel = getVgPositionChannel(channel);
    const vgChannel2 = getVgPositionChannel(channel2);
    const minBandSize = getMarkConfig("minBandSize", markDef, config);
    const { offset: offset4 } = positionOffset({ channel, markDef, encoding, model, bandPosition: 0 });
    const { offset: offset22 } = positionOffset({ channel: channel2, markDef, encoding, model, bandPosition: 0 });
    const bandSizeExpr = binSizeExpr({ fieldDef, scaleName });
    const binSpacingOffset = getBinSpacing(channel, spacing, reverse3, axisTranslate, offset4, minBandSize, bandSizeExpr);
    const binSpacingOffset2 = getBinSpacing(channel2, spacing, reverse3, axisTranslate, offset22 ?? offset4, minBandSize, bandSizeExpr);
    const bandPositionForBandSize = isSignalRef(bandSize) ? { signal: `(1-${bandSize.signal})/2` } : isRelativeBandSize(bandSize) ? (1 - bandSize.band) / 2 : 0.5;
    const bandPosition = getBandPosition({ fieldDef, fieldDef2, markDef, config });
    if (isBinning(fieldDef.bin) || fieldDef.timeUnit) {
      const useRectOffsetField = fieldDef.timeUnit && bandPosition !== 0.5;
      return {
        [vgChannel2]: rectBinRef({
          fieldDef,
          scaleName,
          bandPosition: bandPositionForBandSize,
          offset: binSpacingOffset2,
          useRectOffsetField
        }),
        [vgChannel]: rectBinRef({
          fieldDef,
          scaleName,
          bandPosition: isSignalRef(bandPositionForBandSize) ? { signal: `1-${bandPositionForBandSize.signal}` } : 1 - bandPositionForBandSize,
          offset: binSpacingOffset,
          useRectOffsetField
        })
      };
    } else if (isBinned(fieldDef.bin)) {
      const startRef = valueRefForFieldOrDatumDef(fieldDef, scaleName, {}, { offset: binSpacingOffset2 });
      if (isFieldDef(fieldDef2)) {
        return {
          [vgChannel2]: startRef,
          [vgChannel]: valueRefForFieldOrDatumDef(fieldDef2, scaleName, {}, { offset: binSpacingOffset })
        };
      } else if (isBinParams(fieldDef.bin) && fieldDef.bin.step) {
        return {
          [vgChannel2]: startRef,
          [vgChannel]: {
            signal: `scale("${scaleName}", ${vgField(fieldDef, { expr: "datum" })} + ${fieldDef.bin.step})`,
            offset: binSpacingOffset
          }
        };
      }
    }
    warn2(message_exports.channelRequiredForBinned(channel2));
    return void 0;
  }
  function rectBinRef({ fieldDef, scaleName, bandPosition, offset: offset4, useRectOffsetField }) {
    return interpolatedSignalRef({
      scaleName,
      fieldOrDatumDef: fieldDef,
      bandPosition,
      offset: offset4,
      ...useRectOffsetField ? {
        startSuffix: OFFSETTED_RECT_START_SUFFIX,
        endSuffix: OFFSETTED_RECT_END_SUFFIX
      } : {}
    });
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/base.js
  var ALWAYS_IGNORE = /* @__PURE__ */ new Set(["aria", "width", "height"]);
  function baseEncodeEntry(model, ignore) {
    const { fill: fill2 = void 0, stroke: stroke2 = void 0 } = ignore.color === "include" ? color4(model) : {};
    return {
      ...markDefProperties(model.markDef, ignore),
      ...colorRef("fill", fill2),
      ...colorRef("stroke", stroke2),
      ...nonPosition("opacity", model),
      ...nonPosition("fillOpacity", model),
      ...nonPosition("strokeOpacity", model),
      ...nonPosition("strokeWidth", model),
      ...nonPosition("strokeDash", model),
      ...zindex(model),
      ...tooltip(model),
      ...text2(model, "href"),
      ...aria(model)
    };
  }
  function colorRef(channel, valueRef) {
    return valueRef ? { [channel]: valueRef } : {};
  }
  function markDefProperties(mark, ignore) {
    return VG_MARK_CONFIGS.reduce((m4, prop) => {
      if (!ALWAYS_IGNORE.has(prop) && hasProperty(mark, prop) && ignore[prop] !== "ignore") {
        m4[prop] = signalOrValueRef(mark[prop]);
      }
      return m4;
    }, {});
  }

  // node_modules/vega-lite/build/src/compile/mark/encode/defined.js
  function defined(model) {
    const { config, markDef } = model;
    const fieldsToBreakPath = /* @__PURE__ */ new Set();
    model.forEachFieldDef((fieldDef, channel) => {
      let scaleType2;
      if (!isScaleChannel(channel) || !(scaleType2 = model.getScaleType(channel))) {
        return;
      }
      const isCountAggregate = isCountingAggregateOp(fieldDef.aggregate);
      const invalidDataMode = getScaleInvalidDataMode({
        scaleChannel: channel,
        markDef,
        config,
        scaleType: scaleType2,
        isCountAggregate
      });
      if (shouldBreakPath(invalidDataMode)) {
        const field3 = model.vgField(channel, { expr: "datum", binSuffix: model.stack?.impute ? "mid" : void 0 });
        if (field3) {
          fieldsToBreakPath.add(field3);
        }
      }
    });
    if (fieldsToBreakPath.size > 0) {
      const signal = [...fieldsToBreakPath].map((field3) => fieldValidPredicate(field3, true)).join(" && ");
      return { defined: { signal } };
    }
    return void 0;
  }
  function valueIfDefined(prop, value3) {
    if (value3 !== void 0) {
      return { [prop]: signalOrValueRef(value3) };
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/selection/nearest.js
  var VORONOI = "voronoi";
  var nearest = {
    defined: (selCmpt) => {
      return selCmpt.type === "point" && selCmpt.nearest;
    },
    parse: (model, selCmpt) => {
      if (selCmpt.events) {
        for (const s2 of selCmpt.events) {
          s2.markname = model.getName(VORONOI);
        }
      }
    },
    marks: (model, selCmpt, marks) => {
      const { x: x5, y: y5 } = selCmpt.project.hasChannel;
      const markType2 = model.mark;
      if (isPathMark(markType2)) {
        warn2(message_exports.nearestNotSupportForContinuous(markType2));
        return marks;
      }
      const cellDef = {
        name: model.getName(VORONOI),
        type: "path",
        interactive: true,
        from: { data: model.getName("marks") },
        encode: {
          update: {
            fill: { value: "transparent" },
            strokeWidth: { value: 0.35 },
            stroke: { value: "transparent" },
            isVoronoi: { value: true },
            ...tooltip(model, { reactiveGeom: true })
          }
        },
        transform: [
          {
            type: "voronoi",
            x: { expr: x5 || !y5 ? "datum.datum.x || 0" : "0" },
            y: { expr: y5 || !x5 ? "datum.datum.y || 0" : "0" },
            size: [model.getSizeSignalRef("width"), model.getSizeSignalRef("height")]
          }
        ]
      };
      let index4 = 0;
      let exists = false;
      marks.forEach((mark, i2) => {
        const name4 = mark.name ?? "";
        if (name4 === model.component.mark[0].name) {
          index4 = i2;
        } else if (name4.includes(VORONOI)) {
          exists = true;
        }
      });
      if (!exists) {
        marks.splice(index4 + 1, 0, cellDef);
      }
      return marks;
    }
  };
  var nearest_default = nearest;

  // node_modules/vega-lite/build/src/compile/selection/inputs.js
  var inputBindings = {
    defined: (selCmpt) => {
      return selCmpt.type === "point" && selCmpt.resolve === "global" && selCmpt.bind && selCmpt.bind !== "scales" && !isLegendBinding(selCmpt.bind);
    },
    parse: (model, selCmpt, selDef) => disableDirectManipulation(selCmpt, selDef),
    topLevelSignals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const proj = selCmpt.project;
      const bind3 = selCmpt.bind;
      const init2 = selCmpt.init && selCmpt.init[0];
      const datum2 = nearest_default.defined(selCmpt) ? "(item().isVoronoi ? datum.datum : datum)" : "datum";
      proj.items.forEach((p2, i2) => {
        const sgname = varName(`${name4}_${p2.field}`);
        const hasSignal2 = signals.filter((s2) => s2.name === sgname);
        if (!hasSignal2.length) {
          signals.unshift({
            name: sgname,
            ...init2 ? { init: assembleInit(init2[i2]) } : { value: null },
            on: selCmpt.events ? [
              {
                events: selCmpt.events,
                update: `datum && item().mark.marktype !== 'group' ? ${datum2}[${$(p2.field)}] : null`
              }
            ] : [],
            bind: bind3[p2.field] ?? bind3[p2.channel] ?? bind3
          });
        }
      });
      return signals;
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const proj = selCmpt.project;
      const signal = signals.find((s2) => s2.name === name4 + TUPLE);
      const fields = name4 + TUPLE_FIELDS;
      const values4 = proj.items.map((p2) => varName(`${name4}_${p2.field}`));
      const valid = values4.map((v3) => `${v3} !== null`).join(" && ");
      if (values4.length) {
        signal.update = `${valid} ? {fields: ${fields}, values: [${values4.join(", ")}]} : null`;
      }
      delete signal.value;
      delete signal.on;
      return signals;
    }
  };
  var inputs_default = inputBindings;

  // node_modules/vega-lite/build/src/compile/selection/toggle.js
  var TOGGLE = "_toggle";
  var toggle = {
    defined: (selCmpt) => {
      return selCmpt.type === "point" && !isTimerSelection(selCmpt) && !!selCmpt.toggle;
    },
    signals: (model, selCmpt, signals) => {
      return signals.concat({
        name: selCmpt.name + TOGGLE,
        value: false,
        on: [{ events: selCmpt.events, update: selCmpt.toggle }]
      });
    },
    modifyExpr: (model, selCmpt) => {
      const tpl = selCmpt.name + TUPLE;
      const signal = selCmpt.name + TOGGLE;
      return `${signal} ? null : ${tpl}, ` + (selCmpt.resolve === "global" ? `${signal} ? null : true, ` : `${signal} ? null : {unit: ${unitName(model)}}, `) + `${signal} ? ${tpl} : null`;
    }
  };
  var toggle_default = toggle;

  // node_modules/vega-lite/build/src/compile/selection/clear.js
  var clear = {
    defined: (selCmpt) => {
      return selCmpt.clear !== void 0 && selCmpt.clear !== false && !isTimerSelection(selCmpt);
    },
    parse: (model, selCmpt) => {
      if (selCmpt.clear) {
        selCmpt.clear = isString(selCmpt.clear) ? eventSelector(selCmpt.clear, "view") : selCmpt.clear;
      }
    },
    topLevelSignals: (model, selCmpt, signals) => {
      if (inputs_default.defined(selCmpt)) {
        for (const proj of selCmpt.project.items) {
          const idx = signals.findIndex((n2) => n2.name === varName(`${selCmpt.name}_${proj.field}`));
          if (idx !== -1) {
            signals[idx].on.push({ events: selCmpt.clear, update: "null" });
          }
        }
      }
      return signals;
    },
    signals: (model, selCmpt, signals) => {
      function addClear(idx, update3) {
        if (idx !== -1 && signals[idx].on) {
          signals[idx].on.push({ events: selCmpt.clear, update: update3 });
        }
      }
      if (selCmpt.type === "interval") {
        for (const proj of selCmpt.project.items) {
          const vIdx = signals.findIndex((n2) => n2.name === proj.signals.visual);
          addClear(vIdx, "[0, 0]");
          if (vIdx === -1) {
            const dIdx = signals.findIndex((n2) => n2.name === proj.signals.data);
            addClear(dIdx, "null");
          }
        }
      } else {
        let tIdx = signals.findIndex((n2) => n2.name === selCmpt.name + TUPLE);
        addClear(tIdx, "null");
        if (toggle_default.defined(selCmpt)) {
          tIdx = signals.findIndex((n2) => n2.name === selCmpt.name + TOGGLE);
          addClear(tIdx, "false");
        }
      }
      return signals;
    }
  };
  var clear_default = clear;

  // node_modules/vega-lite/build/src/compile/selection/legends.js
  var legendBindings = {
    defined: (selCmpt) => {
      const spec = selCmpt.resolve === "global" && selCmpt.bind && isLegendBinding(selCmpt.bind);
      const projLen = selCmpt.project.items.length === 1 && selCmpt.project.items[0].field !== SELECTION_ID;
      if (spec && !projLen) {
        warn2(message_exports.LEGEND_BINDINGS_MUST_HAVE_PROJECTION);
      }
      return spec && projLen;
    },
    parse: (model, selCmpt, selDef) => {
      const selDef_ = duplicate(selDef);
      selDef_.select = isString(selDef_.select) ? { type: selDef_.select, toggle: selCmpt.toggle } : { ...selDef_.select, toggle: selCmpt.toggle };
      disableDirectManipulation(selCmpt, selDef_);
      if (isObject(selDef.select) && (selDef.select.on || selDef.select.clear)) {
        const legendFilter = 'event.item && indexof(event.item.mark.role, "legend") < 0';
        for (const evt2 of selCmpt.events) {
          evt2.filter = array(evt2.filter ?? []);
          if (!evt2.filter.includes(legendFilter)) {
            evt2.filter.push(legendFilter);
          }
        }
      }
      const evt = isLegendStreamBinding(selCmpt.bind) ? selCmpt.bind.legend : "click";
      const stream2 = isString(evt) ? eventSelector(evt, "view") : array(evt);
      selCmpt.bind = { legend: { merge: stream2 } };
    },
    topLevelSignals: (model, selCmpt, signals) => {
      const selName = selCmpt.name;
      const stream2 = isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
      const markName = (name4) => (s2) => {
        const ds = duplicate(s2);
        ds.markname = name4;
        return ds;
      };
      for (const proj of selCmpt.project.items) {
        if (!proj.hasLegend)
          continue;
        const prefix = `${varName(proj.field)}_legend`;
        const sgName = `${selName}_${prefix}`;
        const hasSignal2 = signals.filter((s2) => s2.name === sgName);
        if (hasSignal2.length === 0) {
          const events3 = stream2.merge.map(markName(`${prefix}_symbols`)).concat(stream2.merge.map(markName(`${prefix}_labels`))).concat(stream2.merge.map(markName(`${prefix}_entries`)));
          signals.unshift({
            name: sgName,
            ...!selCmpt.init ? { value: null } : {},
            on: [
              // Legend entries do not store values, so we need to walk the scenegraph to the symbol datum.
              {
                events: events3,
                update: "isDefined(datum.value) ? datum.value : item().items[0].items[0].datum.value",
                force: true
              },
              { events: stream2.merge, update: `!event.item || !datum ? null : ${sgName}`, force: true }
            ]
          });
        }
      }
      return signals;
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const proj = selCmpt.project;
      const tuple = signals.find((s2) => s2.name === name4 + TUPLE);
      const fields = name4 + TUPLE_FIELDS;
      const values4 = proj.items.filter((p2) => p2.hasLegend).map((p2) => varName(`${name4}_${varName(p2.field)}_legend`));
      const valid = values4.map((v3) => `${v3} !== null`).join(" && ");
      const update3 = `${valid} ? {fields: ${fields}, values: [${values4.join(", ")}]} : null`;
      if (selCmpt.events && values4.length > 0) {
        tuple.on.push({
          events: values4.map((signal) => ({ signal })),
          update: update3
        });
      } else if (values4.length > 0) {
        tuple.update = update3;
        delete tuple.value;
        delete tuple.on;
      }
      const toggle2 = signals.find((s2) => s2.name === name4 + TOGGLE);
      const events3 = isLegendStreamBinding(selCmpt.bind) && selCmpt.bind.legend;
      if (toggle2) {
        if (!selCmpt.events)
          toggle2.on[0].events = events3;
        else
          toggle2.on.push({ ...toggle2.on[0], events: events3 });
      }
      return signals;
    }
  };
  var legends_default = legendBindings;
  function parseInteractiveLegend(model, channel, legendCmpt) {
    const field3 = model.fieldDef(channel)?.field;
    for (const selCmpt of vals(model.component.selection ?? {})) {
      const proj = selCmpt.project.hasField[field3] ?? selCmpt.project.hasChannel[channel];
      if (proj && legendBindings.defined(selCmpt)) {
        const legendSelections = legendCmpt.get("selections") ?? [];
        legendSelections.push(selCmpt.name);
        legendCmpt.set("selections", legendSelections, false);
        proj.hasLegend = true;
      }
    }
  }

  // node_modules/vega-lite/build/src/compile/selection/translate.js
  var ANCHOR = "_translate_anchor";
  var DELTA = "_translate_delta";
  var translate3 = {
    defined: (selCmpt) => {
      return selCmpt.type === "interval" && selCmpt.translate;
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const boundScales = scales_default.defined(selCmpt);
      const anchor = name4 + ANCHOR;
      const { x: x5, y: y5 } = selCmpt.project.hasChannel;
      let events3 = eventSelector(selCmpt.translate, "scope");
      if (!boundScales) {
        events3 = events3.map((e4) => (e4.between[0].markname = name4 + BRUSH, e4));
      }
      signals.push({
        name: anchor,
        value: {},
        on: [
          {
            events: events3.map((e4) => e4.between[0]),
            update: "{x: x(unit), y: y(unit)" + (x5 !== void 0 ? `, extent_x: ${boundScales ? domain3(model, X3) : `slice(${x5.signals.visual})`}` : "") + (y5 !== void 0 ? `, extent_y: ${boundScales ? domain3(model, Y3) : `slice(${y5.signals.visual})`}` : "") + "}"
          }
        ]
      }, {
        name: name4 + DELTA,
        value: {},
        on: [
          {
            events: events3,
            update: `{x: ${anchor}.x - x(unit), y: ${anchor}.y - y(unit)}`
          }
        ]
      });
      if (x5 !== void 0) {
        onDelta(model, selCmpt, x5, "width", signals);
      }
      if (y5 !== void 0) {
        onDelta(model, selCmpt, y5, "height", signals);
      }
      return signals;
    }
  };
  var translate_default = translate3;
  function onDelta(model, selCmpt, proj, size, signals) {
    const name4 = selCmpt.name;
    const anchor = name4 + ANCHOR;
    const delta = name4 + DELTA;
    const channel = proj.channel;
    const boundScales = scales_default.defined(selCmpt);
    const signal = signals.find((s2) => s2.name === proj.signals[boundScales ? "data" : "visual"]);
    const sizeSg = model.getSizeSignalRef(size).signal;
    const scaleCmpt = model.getScaleComponent(channel);
    const scaleType2 = scaleCmpt && scaleCmpt.get("type");
    const reversed = scaleCmpt && scaleCmpt.get("reverse");
    const sign3 = !boundScales ? "" : channel === X3 ? reversed ? "" : "-" : reversed ? "-" : "";
    const extent2 = `${anchor}.extent_${channel}`;
    const offset4 = `${sign3}${delta}.${channel} / ${boundScales ? `${sizeSg}` : `span(${extent2})`}`;
    const panFn = !boundScales || !scaleCmpt ? "panLinear" : scaleType2 === "log" ? "panLog" : scaleType2 === "symlog" ? "panSymlog" : scaleType2 === "pow" ? "panPow" : "panLinear";
    const arg = !boundScales ? "" : scaleType2 === "pow" ? `, ${scaleCmpt.get("exponent") ?? 1}` : scaleType2 === "symlog" ? `, ${scaleCmpt.get("constant") ?? 1}` : "";
    const update3 = `${panFn}(${extent2}, ${offset4}${arg})`;
    signal.on.push({
      events: { signal: delta },
      update: boundScales ? update3 : `clampRange(${update3}, 0, ${sizeSg})`
    });
  }

  // node_modules/vega-lite/build/src/compile/selection/zoom.js
  var ANCHOR2 = "_zoom_anchor";
  var DELTA2 = "_zoom_delta";
  var zoom2 = {
    defined: (selCmpt) => {
      return selCmpt.type === "interval" && selCmpt.zoom;
    },
    signals: (model, selCmpt, signals) => {
      const name4 = selCmpt.name;
      const boundScales = scales_default.defined(selCmpt);
      const delta = name4 + DELTA2;
      const { x: x5, y: y5 } = selCmpt.project.hasChannel;
      const sx = $(model.scaleName(X3));
      const sy = $(model.scaleName(Y3));
      let events3 = eventSelector(selCmpt.zoom, "scope");
      if (!boundScales) {
        events3 = events3.map((e4) => (e4.markname = name4 + BRUSH, e4));
      }
      signals.push({
        name: name4 + ANCHOR2,
        on: [
          {
            events: events3,
            update: !boundScales ? `{x: x(unit), y: y(unit)}` : "{" + [sx ? `x: invert(${sx}, x(unit))` : "", sy ? `y: invert(${sy}, y(unit))` : ""].filter((expr2) => expr2).join(", ") + "}"
          }
        ]
      }, {
        name: delta,
        on: [
          {
            events: events3,
            force: true,
            update: "pow(1.001, event.deltaY * pow(16, event.deltaMode))"
          }
        ]
      });
      if (x5 !== void 0) {
        onDelta2(model, selCmpt, x5, "width", signals);
      }
      if (y5 !== void 0) {
        onDelta2(model, selCmpt, y5, "height", signals);
      }
      return signals;
    }
  };
  var zoom_default2 = zoom2;
  function onDelta2(model, selCmpt, proj, size, signals) {
    const name4 = selCmpt.name;
    const channel = proj.channel;
    const boundScales = scales_default.defined(selCmpt);
    const signal = signals.find((s2) => s2.name === proj.signals[boundScales ? "data" : "visual"]);
    const sizeSg = model.getSizeSignalRef(size).signal;
    const scaleCmpt = model.getScaleComponent(channel);
    const scaleType2 = scaleCmpt && scaleCmpt.get("type");
    const base = boundScales ? domain3(model, channel) : signal.name;
    const delta = name4 + DELTA2;
    const anchor = `${name4}${ANCHOR2}.${channel}`;
    const zoomFn = !boundScales || !scaleCmpt ? "zoomLinear" : scaleType2 === "log" ? "zoomLog" : scaleType2 === "symlog" ? "zoomSymlog" : scaleType2 === "pow" ? "zoomPow" : "zoomLinear";
    const arg = !boundScales ? "" : scaleType2 === "pow" ? `, ${scaleCmpt.get("exponent") ?? 1}` : scaleType2 === "symlog" ? `, ${scaleCmpt.get("constant") ?? 1}` : "";
    const update3 = `${zoomFn}(${base}, ${anchor}, ${delta}${arg})`;
    signal.on.push({
      events: { signal: delta },
      update: boundScales ? update3 : `clampRange(${update3}, 0, ${sizeSg})`
    });
  }

  // node_modules/vega-lite/build/src/compile/selection/index.js
  var STORE = "_store";
  var TUPLE = "_tuple";
  var MODIFY = "_modify";
  var VL_SELECTION_RESOLVE = "vlSelectionResolve";
  var selectionCompilers = [
    point_default,
    interval_default2,
    project_default,
    toggle_default,
    // Bindings may disable direct manipulation.
    inputs_default,
    scales_default,
    legends_default,
    clear_default,
    translate_default,
    zoom_default2,
    nearest_default
  ];
  function getFacetModel(model) {
    let parent = model.parent;
    while (parent) {
      if (isFacetModel(parent))
        break;
      parent = parent.parent;
    }
    return parent;
  }
  function unitName(model, { escape: escape2 } = { escape: true }) {
    let name4 = escape2 ? $(model.name) : model.name;
    const facetModel = getFacetModel(model);
    if (facetModel) {
      const { facet } = facetModel;
      for (const channel of FACET_CHANNELS) {
        if (facet[channel]) {
          name4 += ` + '__facet_${channel}_' + (facet[${$(facetModel.vgField(channel))}])`;
        }
      }
    }
    return name4;
  }
  function requiresSelectionId(model) {
    return vals(model.component.selection ?? {}).reduce((identifier, selCmpt) => {
      return identifier || selCmpt.project.hasSelectionId;
    }, false);
  }
  function disableDirectManipulation(selCmpt, selDef) {
    if (isString(selDef.select) || !selDef.select.on)
      delete selCmpt.events;
    if (isString(selDef.select) || !selDef.select.clear)
      delete selCmpt.clear;
    if (isString(selDef.select) || !selDef.select.toggle)
      delete selCmpt.toggle;
  }
  function isTimerSelection(selCmpt) {
    return selCmpt.events?.find((e4) => "type" in e4 && e4.type === "timer");
  }

  // node_modules/vega-lite/node_modules/vega-expression/build/vega-expression.module.js
  var RawCode2 = "RawCode";
  var Literal2 = "Literal";
  var Property2 = "Property";
  var Identifier3 = "Identifier";
  var ArrayExpression2 = "ArrayExpression";
  var BinaryExpression2 = "BinaryExpression";
  var CallExpression2 = "CallExpression";
  var ConditionalExpression2 = "ConditionalExpression";
  var LogicalExpression2 = "LogicalExpression";
  var MemberExpression2 = "MemberExpression";
  var ObjectExpression2 = "ObjectExpression";
  var UnaryExpression2 = "UnaryExpression";
  function ASTNode2(type3) {
    this.type = type3;
  }
  ASTNode2.prototype.visit = function(visitor) {
    let c4, i2, n2;
    if (visitor(this)) return 1;
    for (c4 = children3(this), i2 = 0, n2 = c4.length; i2 < n2; ++i2) {
      if (c4[i2].visit(visitor)) return 1;
    }
  };
  function children3(node) {
    switch (node.type) {
      case ArrayExpression2:
        return node.elements;
      case BinaryExpression2:
      case LogicalExpression2:
        return [node.left, node.right];
      case CallExpression2:
        return [node.callee].concat(node.arguments);
      case ConditionalExpression2:
        return [node.test, node.consequent, node.alternate];
      case MemberExpression2:
        return [node.object, node.property];
      case ObjectExpression2:
        return node.properties;
      case Property2:
        return [node.key, node.value];
      case UnaryExpression2:
        return [node.argument];
      case Identifier3:
      case Literal2:
      case RawCode2:
      default:
        return [];
    }
  }
  var TokenName2;
  var source3;
  var index3;
  var length2;
  var lookahead2;
  var TokenBooleanLiteral2 = 1;
  var TokenEOF2 = 2;
  var TokenIdentifier2 = 3;
  var TokenKeyword2 = 4;
  var TokenNullLiteral2 = 5;
  var TokenNumericLiteral2 = 6;
  var TokenPunctuator2 = 7;
  var TokenStringLiteral2 = 8;
  var TokenRegularExpression2 = 9;
  TokenName2 = {};
  TokenName2[TokenBooleanLiteral2] = "Boolean";
  TokenName2[TokenEOF2] = "<end>";
  TokenName2[TokenIdentifier2] = "Identifier";
  TokenName2[TokenKeyword2] = "Keyword";
  TokenName2[TokenNullLiteral2] = "Null";
  TokenName2[TokenNumericLiteral2] = "Numeric";
  TokenName2[TokenPunctuator2] = "Punctuator";
  TokenName2[TokenStringLiteral2] = "String";
  TokenName2[TokenRegularExpression2] = "RegularExpression";
  var SyntaxArrayExpression2 = "ArrayExpression";
  var SyntaxBinaryExpression2 = "BinaryExpression";
  var SyntaxCallExpression2 = "CallExpression";
  var SyntaxConditionalExpression2 = "ConditionalExpression";
  var SyntaxIdentifier2 = "Identifier";
  var SyntaxLiteral2 = "Literal";
  var SyntaxLogicalExpression2 = "LogicalExpression";
  var SyntaxMemberExpression2 = "MemberExpression";
  var SyntaxObjectExpression2 = "ObjectExpression";
  var SyntaxProperty2 = "Property";
  var SyntaxUnaryExpression2 = "UnaryExpression";
  var MessageUnexpectedToken2 = "Unexpected token %0";
  var MessageUnexpectedNumber2 = "Unexpected number";
  var MessageUnexpectedString2 = "Unexpected string";
  var MessageUnexpectedIdentifier2 = "Unexpected identifier";
  var MessageUnexpectedReserved2 = "Unexpected reserved word";
  var MessageUnexpectedEOS2 = "Unexpected end of input";
  var MessageInvalidRegExp2 = "Invalid regular expression";
  var MessageUnterminatedRegExp2 = "Invalid regular expression: missing /";
  var MessageStrictOctalLiteral2 = "Octal literals are not allowed in strict mode.";
  var MessageStrictDuplicateProperty2 = "Duplicate data property in object literal not allowed in strict mode";
  var ILLEGAL3 = "ILLEGAL";
  var DISABLED2 = "Disabled.";
  var RegexNonAsciiIdentifierStart2 = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]");
  var RegexNonAsciiIdentifierPart2 = new RegExp("[\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u0487\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u0800-\\u082D\\u0840-\\u085B\\u08A0-\\u08B2\\u08E4-\\u0963\\u0966-\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BEF\\u0C00-\\u0C03\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58\\u0C59\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C81-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1\\u0CF2\\u0D01-\\u0D03\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D57\\u0D60-\\u0D63\\u0D66-\\u0D6F\\u0D7A-\\u0D7F\\u0D82\\u0D83\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB9\\u0EBB-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECD\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F29\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u180B-\\u180D\\u1810-\\u1819\\u1820-\\u1877\\u1880-\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19D9\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ABD\\u1B00-\\u1B4B\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1CD0-\\u1CD2\\u1CD4-\\u1CF6\\u1CF8\\u1CF9\\u1D00-\\u1DF5\\u1DFC-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u200C\\u200D\\u203F\\u2040\\u2054\\u2071\\u207F\\u2090-\\u209C\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA66F\\uA674-\\uA67D\\uA67F-\\uA69D\\uA69F-\\uA6F1\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA827\\uA840-\\uA873\\uA880-\\uA8C4\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA900-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2D\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF3F\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]");
  function assert2(condition, message) {
    if (!condition) {
      throw new Error("ASSERT: " + message);
    }
  }
  function isDecimalDigit2(ch2) {
    return ch2 >= 48 && ch2 <= 57;
  }
  function isHexDigit2(ch2) {
    return "0123456789abcdefABCDEF".includes(ch2);
  }
  function isOctalDigit2(ch2) {
    return "01234567".includes(ch2);
  }
  function isWhiteSpace2(ch2) {
    return ch2 === 32 || ch2 === 9 || ch2 === 11 || ch2 === 12 || ch2 === 160 || ch2 >= 5760 && [5760, 6158, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].includes(ch2);
  }
  function isLineTerminator2(ch2) {
    return ch2 === 10 || ch2 === 13 || ch2 === 8232 || ch2 === 8233;
  }
  function isIdentifierStart2(ch2) {
    return ch2 === 36 || ch2 === 95 || // $ (dollar) and _ (underscore)
    ch2 >= 65 && ch2 <= 90 || // A..Z
    ch2 >= 97 && ch2 <= 122 || // a..z
    ch2 === 92 || // \ (backslash)
    ch2 >= 128 && RegexNonAsciiIdentifierStart2.test(String.fromCharCode(ch2));
  }
  function isIdentifierPart2(ch2) {
    return ch2 === 36 || ch2 === 95 || // $ (dollar) and _ (underscore)
    ch2 >= 65 && ch2 <= 90 || // A..Z
    ch2 >= 97 && ch2 <= 122 || // a..z
    ch2 >= 48 && ch2 <= 57 || // 0..9
    ch2 === 92 || // \ (backslash)
    ch2 >= 128 && RegexNonAsciiIdentifierPart2.test(String.fromCharCode(ch2));
  }
  var keywords2 = {
    "if": 1,
    "in": 1,
    "do": 1,
    "var": 1,
    "for": 1,
    "new": 1,
    "try": 1,
    "let": 1,
    "this": 1,
    "else": 1,
    "case": 1,
    "void": 1,
    "with": 1,
    "enum": 1,
    "while": 1,
    "break": 1,
    "catch": 1,
    "throw": 1,
    "const": 1,
    "yield": 1,
    "class": 1,
    "super": 1,
    "return": 1,
    "typeof": 1,
    "delete": 1,
    "switch": 1,
    "export": 1,
    "import": 1,
    "public": 1,
    "static": 1,
    "default": 1,
    "finally": 1,
    "extends": 1,
    "package": 1,
    "private": 1,
    "function": 1,
    "continue": 1,
    "debugger": 1,
    "interface": 1,
    "protected": 1,
    "instanceof": 1,
    "implements": 1
  };
  function skipComment2() {
    while (index3 < length2) {
      const ch2 = source3.charCodeAt(index3);
      if (isWhiteSpace2(ch2) || isLineTerminator2(ch2)) {
        ++index3;
      } else {
        break;
      }
    }
  }
  function scanHexEscape2(prefix) {
    var i2, len, ch2, code = 0;
    len = prefix === "u" ? 4 : 2;
    for (i2 = 0; i2 < len; ++i2) {
      if (index3 < length2 && isHexDigit2(source3[index3])) {
        ch2 = source3[index3++];
        code = code * 16 + "0123456789abcdef".indexOf(ch2.toLowerCase());
      } else {
        throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
      }
    }
    return String.fromCharCode(code);
  }
  function scanUnicodeCodePointEscape2() {
    var ch2, code, cu1, cu2;
    ch2 = source3[index3];
    code = 0;
    if (ch2 === "}") {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    while (index3 < length2) {
      ch2 = source3[index3++];
      if (!isHexDigit2(ch2)) {
        break;
      }
      code = code * 16 + "0123456789abcdef".indexOf(ch2.toLowerCase());
    }
    if (code > 1114111 || ch2 !== "}") {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    if (code <= 65535) {
      return String.fromCharCode(code);
    }
    cu1 = (code - 65536 >> 10) + 55296;
    cu2 = (code - 65536 & 1023) + 56320;
    return String.fromCharCode(cu1, cu2);
  }
  function getEscapedIdentifier2() {
    var ch2, id2;
    ch2 = source3.charCodeAt(index3++);
    id2 = String.fromCharCode(ch2);
    if (ch2 === 92) {
      if (source3.charCodeAt(index3) !== 117) {
        throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
      }
      ++index3;
      ch2 = scanHexEscape2("u");
      if (!ch2 || ch2 === "\\" || !isIdentifierStart2(ch2.charCodeAt(0))) {
        throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
      }
      id2 = ch2;
    }
    while (index3 < length2) {
      ch2 = source3.charCodeAt(index3);
      if (!isIdentifierPart2(ch2)) {
        break;
      }
      ++index3;
      id2 += String.fromCharCode(ch2);
      if (ch2 === 92) {
        id2 = id2.substr(0, id2.length - 1);
        if (source3.charCodeAt(index3) !== 117) {
          throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
        }
        ++index3;
        ch2 = scanHexEscape2("u");
        if (!ch2 || ch2 === "\\" || !isIdentifierPart2(ch2.charCodeAt(0))) {
          throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
        }
        id2 += ch2;
      }
    }
    return id2;
  }
  function getIdentifier2() {
    var start, ch2;
    start = index3++;
    while (index3 < length2) {
      ch2 = source3.charCodeAt(index3);
      if (ch2 === 92) {
        index3 = start;
        return getEscapedIdentifier2();
      }
      if (isIdentifierPart2(ch2)) {
        ++index3;
      } else {
        break;
      }
    }
    return source3.slice(start, index3);
  }
  function scanIdentifier2() {
    var start, id2, type3;
    start = index3;
    id2 = source3.charCodeAt(index3) === 92 ? getEscapedIdentifier2() : getIdentifier2();
    if (id2.length === 1) {
      type3 = TokenIdentifier2;
    } else if (keywords2.hasOwnProperty(id2)) {
      type3 = TokenKeyword2;
    } else if (id2 === "null") {
      type3 = TokenNullLiteral2;
    } else if (id2 === "true" || id2 === "false") {
      type3 = TokenBooleanLiteral2;
    } else {
      type3 = TokenIdentifier2;
    }
    return {
      type: type3,
      value: id2,
      start,
      end: index3
    };
  }
  function scanPunctuator2() {
    var start = index3, code = source3.charCodeAt(index3), code2, ch1 = source3[index3], ch2, ch3, ch4;
    switch (code) {
      // Check for most common single-character punctuators.
      case 46:
      // . dot
      case 40:
      // ( open bracket
      case 41:
      // ) close bracket
      case 59:
      // ; semicolon
      case 44:
      // , comma
      case 123:
      // { open curly brace
      case 125:
      // } close curly brace
      case 91:
      // [
      case 93:
      // ]
      case 58:
      // :
      case 63:
      // ?
      case 126:
        ++index3;
        return {
          type: TokenPunctuator2,
          value: String.fromCharCode(code),
          start,
          end: index3
        };
      default:
        code2 = source3.charCodeAt(index3 + 1);
        if (code2 === 61) {
          switch (code) {
            case 43:
            // +
            case 45:
            // -
            case 47:
            // /
            case 60:
            // <
            case 62:
            // >
            case 94:
            // ^
            case 124:
            // |
            case 37:
            // %
            case 38:
            // &
            case 42:
              index3 += 2;
              return {
                type: TokenPunctuator2,
                value: String.fromCharCode(code) + String.fromCharCode(code2),
                start,
                end: index3
              };
            case 33:
            // !
            case 61:
              index3 += 2;
              if (source3.charCodeAt(index3) === 61) {
                ++index3;
              }
              return {
                type: TokenPunctuator2,
                value: source3.slice(start, index3),
                start,
                end: index3
              };
          }
        }
    }
    ch4 = source3.substr(index3, 4);
    if (ch4 === ">>>=") {
      index3 += 4;
      return {
        type: TokenPunctuator2,
        value: ch4,
        start,
        end: index3
      };
    }
    ch3 = ch4.substr(0, 3);
    if (ch3 === ">>>" || ch3 === "<<=" || ch3 === ">>=") {
      index3 += 3;
      return {
        type: TokenPunctuator2,
        value: ch3,
        start,
        end: index3
      };
    }
    ch2 = ch3.substr(0, 2);
    if (ch1 === ch2[1] && "+-<>&|".includes(ch1) || ch2 === "=>") {
      index3 += 2;
      return {
        type: TokenPunctuator2,
        value: ch2,
        start,
        end: index3
      };
    }
    if (ch2 === "//") {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    if ("<>=!+-*%&|^/".includes(ch1)) {
      ++index3;
      return {
        type: TokenPunctuator2,
        value: ch1,
        start,
        end: index3
      };
    }
    throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
  }
  function scanHexLiteral2(start) {
    let number8 = "";
    while (index3 < length2) {
      if (!isHexDigit2(source3[index3])) {
        break;
      }
      number8 += source3[index3++];
    }
    if (number8.length === 0) {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    if (isIdentifierStart2(source3.charCodeAt(index3))) {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    return {
      type: TokenNumericLiteral2,
      value: parseInt("0x" + number8, 16),
      start,
      end: index3
    };
  }
  function scanOctalLiteral2(start) {
    let number8 = "0" + source3[index3++];
    while (index3 < length2) {
      if (!isOctalDigit2(source3[index3])) {
        break;
      }
      number8 += source3[index3++];
    }
    if (isIdentifierStart2(source3.charCodeAt(index3)) || isDecimalDigit2(source3.charCodeAt(index3))) {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    return {
      type: TokenNumericLiteral2,
      value: parseInt(number8, 8),
      octal: true,
      start,
      end: index3
    };
  }
  function scanNumericLiteral2() {
    var number8, start, ch2;
    ch2 = source3[index3];
    assert2(isDecimalDigit2(ch2.charCodeAt(0)) || ch2 === ".", "Numeric literal must start with a decimal digit or a decimal point");
    start = index3;
    number8 = "";
    if (ch2 !== ".") {
      number8 = source3[index3++];
      ch2 = source3[index3];
      if (number8 === "0") {
        if (ch2 === "x" || ch2 === "X") {
          ++index3;
          return scanHexLiteral2(start);
        }
        if (isOctalDigit2(ch2)) {
          return scanOctalLiteral2(start);
        }
        if (ch2 && isDecimalDigit2(ch2.charCodeAt(0))) {
          throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
        }
      }
      while (isDecimalDigit2(source3.charCodeAt(index3))) {
        number8 += source3[index3++];
      }
      ch2 = source3[index3];
    }
    if (ch2 === ".") {
      number8 += source3[index3++];
      while (isDecimalDigit2(source3.charCodeAt(index3))) {
        number8 += source3[index3++];
      }
      ch2 = source3[index3];
    }
    if (ch2 === "e" || ch2 === "E") {
      number8 += source3[index3++];
      ch2 = source3[index3];
      if (ch2 === "+" || ch2 === "-") {
        number8 += source3[index3++];
      }
      if (isDecimalDigit2(source3.charCodeAt(index3))) {
        while (isDecimalDigit2(source3.charCodeAt(index3))) {
          number8 += source3[index3++];
        }
      } else {
        throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
      }
    }
    if (isIdentifierStart2(source3.charCodeAt(index3))) {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    return {
      type: TokenNumericLiteral2,
      value: parseFloat(number8),
      start,
      end: index3
    };
  }
  function scanStringLiteral2() {
    var str = "", quote, start, ch2, code, octal = false;
    quote = source3[index3];
    assert2(quote === "'" || quote === '"', "String literal must starts with a quote");
    start = index3;
    ++index3;
    while (index3 < length2) {
      ch2 = source3[index3++];
      if (ch2 === quote) {
        quote = "";
        break;
      } else if (ch2 === "\\") {
        ch2 = source3[index3++];
        if (!ch2 || !isLineTerminator2(ch2.charCodeAt(0))) {
          switch (ch2) {
            case "u":
            case "x":
              if (source3[index3] === "{") {
                ++index3;
                str += scanUnicodeCodePointEscape2();
              } else {
                str += scanHexEscape2(ch2);
              }
              break;
            case "n":
              str += "\n";
              break;
            case "r":
              str += "\r";
              break;
            case "t":
              str += "	";
              break;
            case "b":
              str += "\b";
              break;
            case "f":
              str += "\f";
              break;
            case "v":
              str += "\v";
              break;
            default:
              if (isOctalDigit2(ch2)) {
                code = "01234567".indexOf(ch2);
                if (code !== 0) {
                  octal = true;
                }
                if (index3 < length2 && isOctalDigit2(source3[index3])) {
                  octal = true;
                  code = code * 8 + "01234567".indexOf(source3[index3++]);
                  if ("0123".includes(ch2) && index3 < length2 && isOctalDigit2(source3[index3])) {
                    code = code * 8 + "01234567".indexOf(source3[index3++]);
                  }
                }
                str += String.fromCharCode(code);
              } else {
                str += ch2;
              }
              break;
          }
        } else {
          if (ch2 === "\r" && source3[index3] === "\n") {
            ++index3;
          }
        }
      } else if (isLineTerminator2(ch2.charCodeAt(0))) {
        break;
      } else {
        str += ch2;
      }
    }
    if (quote !== "") {
      throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
    }
    return {
      type: TokenStringLiteral2,
      value: str,
      octal,
      start,
      end: index3
    };
  }
  function testRegExp2(pattern, flags) {
    let tmp = pattern;
    if (flags.includes("u")) {
      tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, ($0, $1) => {
        if (parseInt($1, 16) <= 1114111) {
          return "x";
        }
        throwError2({}, MessageInvalidRegExp2);
      }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
    }
    try {
      new RegExp(tmp);
    } catch (e4) {
      throwError2({}, MessageInvalidRegExp2);
    }
    try {
      return new RegExp(pattern, flags);
    } catch (exception) {
      return null;
    }
  }
  function scanRegExpBody2() {
    var ch2, str, classMarker, terminated, body;
    ch2 = source3[index3];
    assert2(ch2 === "/", "Regular expression literal must start with a slash");
    str = source3[index3++];
    classMarker = false;
    terminated = false;
    while (index3 < length2) {
      ch2 = source3[index3++];
      str += ch2;
      if (ch2 === "\\") {
        ch2 = source3[index3++];
        if (isLineTerminator2(ch2.charCodeAt(0))) {
          throwError2({}, MessageUnterminatedRegExp2);
        }
        str += ch2;
      } else if (isLineTerminator2(ch2.charCodeAt(0))) {
        throwError2({}, MessageUnterminatedRegExp2);
      } else if (classMarker) {
        if (ch2 === "]") {
          classMarker = false;
        }
      } else {
        if (ch2 === "/") {
          terminated = true;
          break;
        } else if (ch2 === "[") {
          classMarker = true;
        }
      }
    }
    if (!terminated) {
      throwError2({}, MessageUnterminatedRegExp2);
    }
    body = str.substr(1, str.length - 2);
    return {
      value: body,
      literal: str
    };
  }
  function scanRegExpFlags2() {
    var ch2, str, flags;
    str = "";
    flags = "";
    while (index3 < length2) {
      ch2 = source3[index3];
      if (!isIdentifierPart2(ch2.charCodeAt(0))) {
        break;
      }
      ++index3;
      if (ch2 === "\\" && index3 < length2) {
        throwError2({}, MessageUnexpectedToken2, ILLEGAL3);
      } else {
        flags += ch2;
        str += ch2;
      }
    }
    if (flags.search(/[^gimuy]/g) >= 0) {
      throwError2({}, MessageInvalidRegExp2, flags);
    }
    return {
      value: flags,
      literal: str
    };
  }
  function scanRegExp2() {
    var start, body, flags, value3;
    lookahead2 = null;
    skipComment2();
    start = index3;
    body = scanRegExpBody2();
    flags = scanRegExpFlags2();
    value3 = testRegExp2(body.value, flags.value);
    return {
      literal: body.literal + flags.literal,
      value: value3,
      regex: {
        pattern: body.value,
        flags: flags.value
      },
      start,
      end: index3
    };
  }
  function isIdentifierName2(token) {
    return token.type === TokenIdentifier2 || token.type === TokenKeyword2 || token.type === TokenBooleanLiteral2 || token.type === TokenNullLiteral2;
  }
  function advance2() {
    skipComment2();
    if (index3 >= length2) {
      return {
        type: TokenEOF2,
        start: index3,
        end: index3
      };
    }
    const ch2 = source3.charCodeAt(index3);
    if (isIdentifierStart2(ch2)) {
      return scanIdentifier2();
    }
    if (ch2 === 40 || ch2 === 41 || ch2 === 59) {
      return scanPunctuator2();
    }
    if (ch2 === 39 || ch2 === 34) {
      return scanStringLiteral2();
    }
    if (ch2 === 46) {
      if (isDecimalDigit2(source3.charCodeAt(index3 + 1))) {
        return scanNumericLiteral2();
      }
      return scanPunctuator2();
    }
    if (isDecimalDigit2(ch2)) {
      return scanNumericLiteral2();
    }
    return scanPunctuator2();
  }
  function lex2() {
    const token = lookahead2;
    index3 = token.end;
    lookahead2 = advance2();
    index3 = token.end;
    return token;
  }
  function peek3() {
    const pos = index3;
    lookahead2 = advance2();
    index3 = pos;
  }
  function finishArrayExpression2(elements) {
    const node = new ASTNode2(SyntaxArrayExpression2);
    node.elements = elements;
    return node;
  }
  function finishBinaryExpression2(operator2, left, right) {
    const node = new ASTNode2(operator2 === "||" || operator2 === "&&" ? SyntaxLogicalExpression2 : SyntaxBinaryExpression2);
    node.operator = operator2;
    node.left = left;
    node.right = right;
    return node;
  }
  function finishCallExpression2(callee, args) {
    const node = new ASTNode2(SyntaxCallExpression2);
    node.callee = callee;
    node.arguments = args;
    return node;
  }
  function finishConditionalExpression2(test2, consequent, alternate) {
    const node = new ASTNode2(SyntaxConditionalExpression2);
    node.test = test2;
    node.consequent = consequent;
    node.alternate = alternate;
    return node;
  }
  function finishIdentifier2(name4) {
    const node = new ASTNode2(SyntaxIdentifier2);
    node.name = name4;
    return node;
  }
  function finishLiteral2(token) {
    const node = new ASTNode2(SyntaxLiteral2);
    node.value = token.value;
    node.raw = source3.slice(token.start, token.end);
    if (token.regex) {
      if (node.raw === "//") {
        node.raw = "/(?:)/";
      }
      node.regex = token.regex;
    }
    return node;
  }
  function finishMemberExpression2(accessor2, object2, property2) {
    const node = new ASTNode2(SyntaxMemberExpression2);
    node.computed = accessor2 === "[";
    node.object = object2;
    node.property = property2;
    if (!node.computed) property2.member = true;
    return node;
  }
  function finishObjectExpression2(properties) {
    const node = new ASTNode2(SyntaxObjectExpression2);
    node.properties = properties;
    return node;
  }
  function finishProperty2(kind, key2, value3) {
    const node = new ASTNode2(SyntaxProperty2);
    node.key = key2;
    node.value = value3;
    node.kind = kind;
    return node;
  }
  function finishUnaryExpression2(operator2, argument) {
    const node = new ASTNode2(SyntaxUnaryExpression2);
    node.operator = operator2;
    node.argument = argument;
    node.prefix = true;
    return node;
  }
  function throwError2(token, messageFormat) {
    var error3, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace(/%(\d)/g, (whole, index4) => {
      assert2(index4 < args.length, "Message reference must be in range");
      return args[index4];
    });
    error3 = new Error(msg);
    error3.index = index3;
    error3.description = msg;
    throw error3;
  }
  function throwUnexpected2(token) {
    if (token.type === TokenEOF2) {
      throwError2(token, MessageUnexpectedEOS2);
    }
    if (token.type === TokenNumericLiteral2) {
      throwError2(token, MessageUnexpectedNumber2);
    }
    if (token.type === TokenStringLiteral2) {
      throwError2(token, MessageUnexpectedString2);
    }
    if (token.type === TokenIdentifier2) {
      throwError2(token, MessageUnexpectedIdentifier2);
    }
    if (token.type === TokenKeyword2) {
      throwError2(token, MessageUnexpectedReserved2);
    }
    throwError2(token, MessageUnexpectedToken2, token.value);
  }
  function expect2(value3) {
    const token = lex2();
    if (token.type !== TokenPunctuator2 || token.value !== value3) {
      throwUnexpected2(token);
    }
  }
  function match2(value3) {
    return lookahead2.type === TokenPunctuator2 && lookahead2.value === value3;
  }
  function matchKeyword2(keyword) {
    return lookahead2.type === TokenKeyword2 && lookahead2.value === keyword;
  }
  function parseArrayInitialiser2() {
    const elements = [];
    index3 = lookahead2.start;
    expect2("[");
    while (!match2("]")) {
      if (match2(",")) {
        lex2();
        elements.push(null);
      } else {
        elements.push(parseConditionalExpression2());
        if (!match2("]")) {
          expect2(",");
        }
      }
    }
    lex2();
    return finishArrayExpression2(elements);
  }
  function parseObjectPropertyKey2() {
    index3 = lookahead2.start;
    const token = lex2();
    if (token.type === TokenStringLiteral2 || token.type === TokenNumericLiteral2) {
      if (token.octal) {
        throwError2(token, MessageStrictOctalLiteral2);
      }
      return finishLiteral2(token);
    }
    return finishIdentifier2(token.value);
  }
  function parseObjectProperty2() {
    var token, key2, id2, value3;
    index3 = lookahead2.start;
    token = lookahead2;
    if (token.type === TokenIdentifier2) {
      id2 = parseObjectPropertyKey2();
      expect2(":");
      value3 = parseConditionalExpression2();
      return finishProperty2("init", id2, value3);
    }
    if (token.type === TokenEOF2 || token.type === TokenPunctuator2) {
      throwUnexpected2(token);
    } else {
      key2 = parseObjectPropertyKey2();
      expect2(":");
      value3 = parseConditionalExpression2();
      return finishProperty2("init", key2, value3);
    }
  }
  function parseObjectInitialiser2() {
    var properties = [], property2, name4, key2, map4 = {}, toString2 = String;
    index3 = lookahead2.start;
    expect2("{");
    while (!match2("}")) {
      property2 = parseObjectProperty2();
      if (property2.key.type === SyntaxIdentifier2) {
        name4 = property2.key.name;
      } else {
        name4 = toString2(property2.key.value);
      }
      key2 = "$" + name4;
      if (Object.prototype.hasOwnProperty.call(map4, key2)) {
        throwError2({}, MessageStrictDuplicateProperty2);
      } else {
        map4[key2] = true;
      }
      properties.push(property2);
      if (!match2("}")) {
        expect2(",");
      }
    }
    expect2("}");
    return finishObjectExpression2(properties);
  }
  function parseGroupExpression2() {
    expect2("(");
    const expr2 = parseExpression2();
    expect2(")");
    return expr2;
  }
  var legalKeywords2 = {
    "if": 1
  };
  function parsePrimaryExpression2() {
    var type3, token, expr2;
    if (match2("(")) {
      return parseGroupExpression2();
    }
    if (match2("[")) {
      return parseArrayInitialiser2();
    }
    if (match2("{")) {
      return parseObjectInitialiser2();
    }
    type3 = lookahead2.type;
    index3 = lookahead2.start;
    if (type3 === TokenIdentifier2 || legalKeywords2[lookahead2.value]) {
      expr2 = finishIdentifier2(lex2().value);
    } else if (type3 === TokenStringLiteral2 || type3 === TokenNumericLiteral2) {
      if (lookahead2.octal) {
        throwError2(lookahead2, MessageStrictOctalLiteral2);
      }
      expr2 = finishLiteral2(lex2());
    } else if (type3 === TokenKeyword2) {
      throw new Error(DISABLED2);
    } else if (type3 === TokenBooleanLiteral2) {
      token = lex2();
      token.value = token.value === "true";
      expr2 = finishLiteral2(token);
    } else if (type3 === TokenNullLiteral2) {
      token = lex2();
      token.value = null;
      expr2 = finishLiteral2(token);
    } else if (match2("/") || match2("/=")) {
      expr2 = finishLiteral2(scanRegExp2());
      peek3();
    } else {
      throwUnexpected2(lex2());
    }
    return expr2;
  }
  function parseArguments2() {
    const args = [];
    expect2("(");
    if (!match2(")")) {
      while (index3 < length2) {
        args.push(parseConditionalExpression2());
        if (match2(")")) {
          break;
        }
        expect2(",");
      }
    }
    expect2(")");
    return args;
  }
  function parseNonComputedProperty2() {
    index3 = lookahead2.start;
    const token = lex2();
    if (!isIdentifierName2(token)) {
      throwUnexpected2(token);
    }
    return finishIdentifier2(token.value);
  }
  function parseNonComputedMember2() {
    expect2(".");
    return parseNonComputedProperty2();
  }
  function parseComputedMember2() {
    expect2("[");
    const expr2 = parseExpression2();
    expect2("]");
    return expr2;
  }
  function parseLeftHandSideExpressionAllowCall2() {
    var expr2, args, property2;
    expr2 = parsePrimaryExpression2();
    for (; ; ) {
      if (match2(".")) {
        property2 = parseNonComputedMember2();
        expr2 = finishMemberExpression2(".", expr2, property2);
      } else if (match2("(")) {
        args = parseArguments2();
        expr2 = finishCallExpression2(expr2, args);
      } else if (match2("[")) {
        property2 = parseComputedMember2();
        expr2 = finishMemberExpression2("[", expr2, property2);
      } else {
        break;
      }
    }
    return expr2;
  }
  function parsePostfixExpression2() {
    const expr2 = parseLeftHandSideExpressionAllowCall2();
    if (lookahead2.type === TokenPunctuator2) {
      if (match2("++") || match2("--")) {
        throw new Error(DISABLED2);
      }
    }
    return expr2;
  }
  function parseUnaryExpression2() {
    var token, expr2;
    if (lookahead2.type !== TokenPunctuator2 && lookahead2.type !== TokenKeyword2) {
      expr2 = parsePostfixExpression2();
    } else if (match2("++") || match2("--")) {
      throw new Error(DISABLED2);
    } else if (match2("+") || match2("-") || match2("~") || match2("!")) {
      token = lex2();
      expr2 = parseUnaryExpression2();
      expr2 = finishUnaryExpression2(token.value, expr2);
    } else if (matchKeyword2("delete") || matchKeyword2("void") || matchKeyword2("typeof")) {
      throw new Error(DISABLED2);
    } else {
      expr2 = parsePostfixExpression2();
    }
    return expr2;
  }
  function binaryPrecedence2(token) {
    let prec = 0;
    if (token.type !== TokenPunctuator2 && token.type !== TokenKeyword2) {
      return 0;
    }
    switch (token.value) {
      case "||":
        prec = 1;
        break;
      case "&&":
        prec = 2;
        break;
      case "|":
        prec = 3;
        break;
      case "^":
        prec = 4;
        break;
      case "&":
        prec = 5;
        break;
      case "==":
      case "!=":
      case "===":
      case "!==":
        prec = 6;
        break;
      case "<":
      case ">":
      case "<=":
      case ">=":
      case "instanceof":
      case "in":
        prec = 7;
        break;
      case "<<":
      case ">>":
      case ">>>":
        prec = 8;
        break;
      case "+":
      case "-":
        prec = 9;
        break;
      case "*":
      case "/":
      case "%":
        prec = 11;
        break;
    }
    return prec;
  }
  function parseBinaryExpression2() {
    var marker, markers, expr2, token, prec, stack2, right, operator2, left, i2;
    marker = lookahead2;
    left = parseUnaryExpression2();
    token = lookahead2;
    prec = binaryPrecedence2(token);
    if (prec === 0) {
      return left;
    }
    token.prec = prec;
    lex2();
    markers = [marker, lookahead2];
    right = parseUnaryExpression2();
    stack2 = [left, token, right];
    while ((prec = binaryPrecedence2(lookahead2)) > 0) {
      while (stack2.length > 2 && prec <= stack2[stack2.length - 2].prec) {
        right = stack2.pop();
        operator2 = stack2.pop().value;
        left = stack2.pop();
        markers.pop();
        expr2 = finishBinaryExpression2(operator2, left, right);
        stack2.push(expr2);
      }
      token = lex2();
      token.prec = prec;
      stack2.push(token);
      markers.push(lookahead2);
      expr2 = parseUnaryExpression2();
      stack2.push(expr2);
    }
    i2 = stack2.length - 1;
    expr2 = stack2[i2];
    markers.pop();
    while (i2 > 1) {
      markers.pop();
      expr2 = finishBinaryExpression2(stack2[i2 - 1].value, stack2[i2 - 2], expr2);
      i2 -= 2;
    }
    return expr2;
  }
  function parseConditionalExpression2() {
    var expr2, consequent, alternate;
    expr2 = parseBinaryExpression2();
    if (match2("?")) {
      lex2();
      consequent = parseConditionalExpression2();
      expect2(":");
      alternate = parseConditionalExpression2();
      expr2 = finishConditionalExpression2(expr2, consequent, alternate);
    }
    return expr2;
  }
  function parseExpression2() {
    const expr2 = parseConditionalExpression2();
    if (match2(",")) {
      throw new Error(DISABLED2);
    }
    return expr2;
  }
  function parser3(code) {
    source3 = code;
    index3 = 0;
    length2 = source3.length;
    lookahead2 = null;
    peek3();
    const expr2 = parseExpression2();
    if (lookahead2.type !== TokenEOF2) {
      throw new Error("Unexpect token after expression.");
    }
    return expr2;
  }

  // node_modules/vega-lite/build/src/compile/data/expressions.js
  function getName(node) {
    const name4 = [];
    if (node.type === "Identifier") {
      return [node.name];
    }
    if (node.type === "Literal") {
      return [node.value];
    }
    if (node.type === "MemberExpression") {
      name4.push(...getName(node.object));
      name4.push(...getName(node.property));
    }
    return name4;
  }
  function startsWithDatum(node) {
    if (node.object.type === "MemberExpression") {
      return startsWithDatum(node.object);
    }
    return node.object.name === "datum";
  }
  function getDependentFields(expression4) {
    const ast = parser3(expression4);
    const dependents = /* @__PURE__ */ new Set();
    ast.visit((node) => {
      if (node.type === "MemberExpression" && startsWithDatum(node)) {
        dependents.add(getName(node).slice(1).join("."));
      }
    });
    return dependents;
  }

  // node_modules/vega-lite/build/src/compile/data/filter.js
  var FilterNode = class _FilterNode extends DataFlowNode {
    clone() {
      return new _FilterNode(null, this.model, duplicate(this.filter));
    }
    constructor(parent, model, filter3) {
      super(parent);
      this.model = model;
      this.filter = filter3;
      this.expr = expression3(this.model, this.filter, this);
      this._dependentFields = getDependentFields(this.expr);
    }
    dependentFields() {
      return this._dependentFields;
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    assemble() {
      return {
        type: "filter",
        expr: this.expr
      };
    }
    hash() {
      return `Filter ${this.expr}`;
    }
  };

  // node_modules/vega-lite/build/src/compile/selection/parse.js
  function parseUnitSelection(model, selDefs) {
    const selCmpts = {};
    const selectionConfig = model.config.selection;
    if (!selDefs || !selDefs.length)
      return selCmpts;
    let nTimerSelections = 0;
    for (const def2 of selDefs) {
      const name4 = varName(def2.name);
      const selDef = def2.select;
      const type3 = isString(selDef) ? selDef : selDef.type;
      const defaults2 = isObject(selDef) ? duplicate(selDef) : { type: type3 };
      const cfg = selectionConfig[type3];
      for (const key2 in cfg) {
        if (key2 === "fields" || key2 === "encodings") {
          continue;
        }
        if (key2 === "mark") {
          defaults2.mark = { ...cfg.mark, ...defaults2.mark };
        }
        if (defaults2[key2] === void 0 || defaults2[key2] === true) {
          defaults2[key2] = duplicate(cfg[key2] ?? defaults2[key2]);
        }
      }
      const selCmpt = selCmpts[name4] = {
        ...defaults2,
        name: name4,
        type: type3,
        init: def2.value,
        bind: def2.bind,
        events: isString(defaults2.on) ? eventSelector(defaults2.on, "scope") : array(duplicate(defaults2.on))
      };
      if (isTimerSelection(selCmpt)) {
        nTimerSelections++;
        if (nTimerSelections > 1) {
          delete selCmpts[name4];
          continue;
        }
      }
      const def_ = duplicate(def2);
      for (const c4 of selectionCompilers) {
        if (c4.defined(selCmpt) && c4.parse) {
          c4.parse(model, selCmpt, def_);
        }
      }
    }
    if (nTimerSelections > 1) {
      warn2(MULTIPLE_TIMER_ANIMATION_SELECTION);
    }
    return selCmpts;
  }
  function parseSelectionPredicate(model, pred, dfnode, datum2 = "datum") {
    const name4 = isString(pred) ? pred : pred.param;
    const vname = varName(name4);
    const store = $(vname + STORE);
    let selCmpt;
    try {
      selCmpt = model.getSelectionComponent(vname, name4);
    } catch (e4) {
      return `!!${vname}`;
    }
    if (selCmpt.project.timeUnit) {
      const child = dfnode ?? model.component.data.raw;
      const tunode = selCmpt.project.timeUnit.clone();
      if (child.parent) {
        tunode.insertAsParentOf(child);
      } else {
        child.parent = tunode;
      }
    }
    const fn = selCmpt.project.hasSelectionId ? "vlSelectionIdTest(" : "vlSelectionTest(";
    const resolve2 = selCmpt.resolve === "global" ? ")" : `, ${$(selCmpt.resolve)})`;
    const test2 = `${fn}${store}, ${datum2}${resolve2}`;
    const length3 = `length(data(${store}))`;
    return pred.empty === false ? `${length3} && ${test2}` : `!${length3} || ${test2}`;
  }
  function parseSelectionExtent(model, name4, extent2) {
    const vname = varName(name4);
    const encoding = extent2.encoding;
    let field3 = extent2.field;
    let selCmpt;
    try {
      selCmpt = model.getSelectionComponent(vname, name4);
    } catch (e4) {
      return vname;
    }
    if (!encoding && !field3) {
      field3 = selCmpt.project.items[0].field;
      if (selCmpt.project.items.length > 1) {
        warn2(selectionAsScaleDomainWithoutField(field3));
      }
    } else if (encoding && !field3) {
      const encodings = selCmpt.project.items.filter((p2) => p2.channel === encoding);
      if (!encodings.length || encodings.length > 1) {
        field3 = selCmpt.project.items[0].field;
        warn2(selectionAsScaleDomainWrongEncodings(encodings, encoding, extent2, field3));
      } else {
        field3 = encodings[0].field;
      }
    }
    return `${selCmpt.name}[${$(replacePathInField(field3))}]`;
  }
  function materializeSelections(model, main5) {
    for (const [selection, selCmpt] of entries(model.component.selection ?? {})) {
      const lookupName = model.getName(`lookup_${selection}`);
      model.component.data.outputNodes[lookupName] = selCmpt.materialized = new OutputNode(new FilterNode(main5, model, { param: selection }), lookupName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
    }
  }

  // node_modules/vega-lite/build/src/compile/predicate.js
  function expression3(model, filterOp, node) {
    return logicalExpr(filterOp, (predicate) => {
      if (isString(predicate)) {
        return predicate;
      } else if (isSelectionPredicate(predicate)) {
        return parseSelectionPredicate(model, predicate, node);
      } else {
        return fieldFilterExpression(predicate);
      }
    });
  }

  // node_modules/vega-lite/build/src/compile/axis/assemble.js
  function assembleTitle(title2, config) {
    if (!title2) {
      return void 0;
    }
    if (isArray(title2) && !isText(title2)) {
      return title2.map((fieldDef) => defaultTitle(fieldDef, config)).join(", ");
    }
    return title2;
  }
  function setAxisEncode(axis, part, vgProp, vgRef) {
    var _a2, _b;
    axis.encode ?? (axis.encode = {});
    (_a2 = axis.encode)[part] ?? (_a2[part] = {});
    (_b = axis.encode[part]).update ?? (_b.update = {});
    axis.encode[part].update[vgProp] = vgRef;
  }
  function assembleAxis(axisCmpt, kind, config, opt = { header: false }) {
    const { disable, orient: orient2, scale: scale7, labelExpr, title: title2, zindex: zindex2, ...axis } = axisCmpt.combine();
    if (disable) {
      return void 0;
    }
    for (const p2 in axis) {
      const prop = p2;
      const propType = AXIS_PROPERTY_TYPE[prop];
      const propValue = axis[prop];
      if (propType && propType !== kind && propType !== "both") {
        delete axis[prop];
      } else if (isConditionalAxisValue(propValue)) {
        const { condition, ...valueOrSignalRef } = propValue;
        const conditions = array(condition);
        const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];
        if (propIndex) {
          const { vgProp, part } = propIndex;
          const vgRef = [
            ...conditions.map((c4) => {
              const { test: test2, ...valueOrSignalCRef } = c4;
              return {
                test: expression3(null, test2),
                ...valueOrSignalCRef
              };
            }),
            valueOrSignalRef
          ];
          setAxisEncode(axis, part, vgProp, vgRef);
          delete axis[prop];
        } else if (propIndex === null) {
          const signalRef = {
            signal: conditions.map((c4) => {
              const { test: test2, ...valueOrSignalCRef } = c4;
              return `${expression3(null, test2)} ? ${exprFromValueRefOrSignalRef(valueOrSignalCRef)} : `;
            }).join("") + exprFromValueRefOrSignalRef(valueOrSignalRef)
          };
          axis[prop] = signalRef;
        }
      } else if (isSignalRef(propValue)) {
        const propIndex = CONDITIONAL_AXIS_PROP_INDEX[prop];
        if (propIndex) {
          const { vgProp, part } = propIndex;
          setAxisEncode(axis, part, vgProp, propValue);
          delete axis[prop];
        }
      }
      if (contains2(["labelAlign", "labelBaseline"], prop) && axis[prop] === null) {
        delete axis[prop];
      }
    }
    if (kind === "grid") {
      if (!axis.grid) {
        return void 0;
      }
      if (axis.encode) {
        const { grid } = axis.encode;
        axis.encode = {
          ...grid ? { grid } : {}
        };
        if (isEmpty(axis.encode)) {
          delete axis.encode;
        }
      }
      return {
        scale: scale7,
        orient: orient2,
        ...axis,
        domain: false,
        labels: false,
        aria: false,
        // always hide grid axis
        // Always set min/maxExtent to 0 to ensure that `config.axis*.minExtent` and `config.axis*.maxExtent`
        // would not affect gridAxis
        maxExtent: 0,
        minExtent: 0,
        ticks: false,
        zindex: getFirstDefined(zindex2, 0)
        // put grid behind marks by default
      };
    } else {
      if (!opt.header && axisCmpt.mainExtracted) {
        return void 0;
      }
      if (labelExpr !== void 0) {
        let expr2 = labelExpr;
        if (axis.encode?.labels?.update && isSignalRef(axis.encode.labels.update.text)) {
          expr2 = replaceAll(labelExpr, "datum.label", axis.encode.labels.update.text.signal);
        }
        setAxisEncode(axis, "labels", "text", { signal: expr2 });
      }
      if (axis.labelAlign === null) {
        delete axis.labelAlign;
      }
      if (axis.encode) {
        for (const part of AXIS_PARTS) {
          if (!axisCmpt.hasAxisPart(part)) {
            delete axis.encode[part];
          }
        }
        if (isEmpty(axis.encode)) {
          delete axis.encode;
        }
      }
      const titleString = assembleTitle(title2, config);
      return {
        scale: scale7,
        orient: orient2,
        grid: false,
        ...titleString ? { title: titleString } : {},
        ...axis,
        ...config.aria === false ? { aria: false } : {},
        zindex: getFirstDefined(zindex2, 0)
        // put axis line above marks by default
      };
    }
  }
  function assembleAxisSignals(model) {
    const { axes } = model.component;
    const signals = [];
    for (const channel of POSITION_SCALE_CHANNELS) {
      if (axes[channel]) {
        for (const axis of axes[channel]) {
          if (!axis.get("disable") && !axis.get("gridScale")) {
            const sizeType = channel === "x" ? "height" : "width";
            const update3 = model.getSizeSignalRef(sizeType).signal;
            if (sizeType !== update3) {
              signals.push({
                name: sizeType,
                update: update3
              });
            }
          }
        }
      }
    }
    return signals;
  }
  function assembleAxes(axisComponents, config) {
    const { x: x5 = [], y: y5 = [] } = axisComponents;
    return [
      ...x5.map((a4) => assembleAxis(a4, "grid", config)),
      ...y5.map((a4) => assembleAxis(a4, "grid", config)),
      ...x5.map((a4) => assembleAxis(a4, "main", config)),
      ...y5.map((a4) => assembleAxis(a4, "main", config))
    ].filter((a4) => a4);
  }

  // node_modules/vega-lite/build/src/compile/axis/config.js
  function getAxisConfigFromConfigTypes(configTypes, config, channel, orient2) {
    return Object.assign.apply(null, [
      {},
      ...configTypes.map((configType) => {
        if (configType === "axisOrient") {
          const orient1 = channel === "x" ? "bottom" : "left";
          const orientConfig1 = config[channel === "x" ? "axisBottom" : "axisLeft"] || {};
          const orientConfig2 = config[channel === "x" ? "axisTop" : "axisRight"] || {};
          const props = /* @__PURE__ */ new Set([...keys3(orientConfig1), ...keys3(orientConfig2)]);
          const conditionalOrientAxisConfig = {};
          for (const prop of props.values()) {
            conditionalOrientAxisConfig[prop] = {
              // orient is surely signal in this case
              signal: `${orient2["signal"]} === "${orient1}" ? ${signalOrStringValue(orientConfig1[prop])} : ${signalOrStringValue(orientConfig2[prop])}`
            };
          }
          return conditionalOrientAxisConfig;
        }
        return config[configType];
      })
    ]);
  }
  function getAxisConfigs(channel, scaleType2, orient2, config) {
    const typeBasedConfigTypes = scaleType2 === "band" ? ["axisDiscrete", "axisBand"] : scaleType2 === "point" ? ["axisDiscrete", "axisPoint"] : isQuantitative(scaleType2) ? ["axisQuantitative"] : scaleType2 === "time" || scaleType2 === "utc" ? ["axisTemporal"] : [];
    const axisChannel = channel === "x" ? "axisX" : "axisY";
    const axisOrient = isSignalRef(orient2) ? "axisOrient" : `axis${titleCase(orient2)}`;
    const vlOnlyConfigTypes = [
      // technically Vega does have axisBand, but if we make another separation here,
      // it will further introduce complexity in the code
      ...typeBasedConfigTypes,
      ...typeBasedConfigTypes.map((c4) => axisChannel + c4.substr(4))
    ];
    const vgConfigTypes = ["axis", axisOrient, axisChannel];
    return {
      vlOnlyAxisConfig: getAxisConfigFromConfigTypes(vlOnlyConfigTypes, config, channel, orient2),
      vgAxisConfig: getAxisConfigFromConfigTypes(vgConfigTypes, config, channel, orient2),
      axisConfigStyle: getAxisConfigStyle([...vgConfigTypes, ...vlOnlyConfigTypes], config)
    };
  }
  function getAxisConfigStyle(axisConfigTypes, config) {
    const toMerge = [{}];
    for (const configType of axisConfigTypes) {
      let style2 = config[configType]?.style;
      if (style2) {
        style2 = array(style2);
        for (const s2 of style2) {
          toMerge.push(config.style[s2]);
        }
      }
    }
    return Object.assign.apply(null, toMerge);
  }
  function getAxisConfig(property2, styleConfigIndex, style2, axisConfigs = {}) {
    const styleConfig = getStyleConfig(property2, style2, styleConfigIndex);
    if (styleConfig !== void 0) {
      return {
        configFrom: "style",
        configValue: styleConfig
      };
    }
    for (const configFrom of ["vlOnlyAxisConfig", "vgAxisConfig", "axisConfigStyle"]) {
      if (axisConfigs[configFrom]?.[property2] !== void 0) {
        return { configFrom, configValue: axisConfigs[configFrom][property2] };
      }
    }
    return {};
  }

  // node_modules/vega-lite/build/src/compile/axis/properties.js
  var axisRules = {
    scale: ({ model, channel }) => model.scaleName(channel),
    format: ({ format: format5 }) => format5,
    // we already calculate this in parse
    formatType: ({ formatType }) => formatType,
    // we already calculate this in parse
    grid: ({ fieldOrDatumDef, axis, scaleType: scaleType2 }) => axis.grid ?? defaultGrid(scaleType2, fieldOrDatumDef),
    gridScale: ({ model, channel }) => gridScale(model, channel),
    labelAlign: ({ axis, labelAngle, orient: orient2, channel }) => axis.labelAlign || defaultLabelAlign(labelAngle, orient2, channel),
    labelAngle: ({ labelAngle }) => labelAngle,
    // we already calculate this in parse
    labelBaseline: ({ axis, labelAngle, orient: orient2, channel }) => axis.labelBaseline || defaultLabelBaseline(labelAngle, orient2, channel),
    labelFlush: ({ axis, fieldOrDatumDef, channel }) => axis.labelFlush ?? defaultLabelFlush(fieldOrDatumDef.type, channel),
    labelOverlap: ({ axis, fieldOrDatumDef, scaleType: scaleType2 }) => axis.labelOverlap ?? defaultLabelOverlap(fieldOrDatumDef.type, scaleType2, isFieldDef(fieldOrDatumDef) && !!fieldOrDatumDef.timeUnit, isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : void 0),
    // we already calculate orient in parse
    orient: ({ orient: orient2 }) => orient2,
    // Need to cast until Vega supports signal
    tickCount: ({ channel, model, axis, fieldOrDatumDef, scaleType: scaleType2 }) => {
      const sizeType = channel === "x" ? "width" : channel === "y" ? "height" : void 0;
      const size = sizeType ? model.getSizeSignalRef(sizeType) : void 0;
      return axis.tickCount ?? defaultTickCount({ fieldOrDatumDef, scaleType: scaleType2, size, values: axis.values });
    },
    tickMinStep: defaultTickMinStep,
    title: ({ axis, model, channel }) => {
      if (axis.title !== void 0) {
        return axis.title;
      }
      const fieldDefTitle = getFieldDefTitle(model, channel);
      if (fieldDefTitle !== void 0) {
        return fieldDefTitle;
      }
      const fieldDef = model.typedFieldDef(channel);
      const channel2 = channel === "x" ? "x2" : "y2";
      const fieldDef2 = model.fieldDef(channel2);
      return mergeTitleFieldDefs(fieldDef ? [toFieldDefBase(fieldDef)] : [], isFieldDef(fieldDef2) ? [toFieldDefBase(fieldDef2)] : []);
    },
    values: ({ axis, fieldOrDatumDef }) => values2(axis, fieldOrDatumDef),
    zindex: ({ axis, fieldOrDatumDef, mark }) => axis.zindex ?? defaultZindex(mark, fieldOrDatumDef)
  };
  function defaultGrid(scaleType2, fieldDef) {
    return !hasDiscreteDomain(scaleType2) && isFieldDef(fieldDef) && !isBinning(fieldDef?.bin) && !isBinned(fieldDef?.bin);
  }
  function gridScale(model, channel) {
    const gridChannel = channel === "x" ? "y" : "x";
    if (model.getScaleComponent(gridChannel)) {
      return model.scaleName(gridChannel);
    }
    return void 0;
  }
  function getLabelAngle(fieldOrDatumDef, axis, channel, styleConfig, axisConfigs) {
    const labelAngle = axis?.labelAngle;
    if (labelAngle !== void 0) {
      return isSignalRef(labelAngle) ? labelAngle : normalizeAngle(labelAngle);
    } else {
      const { configValue: angle2 } = getAxisConfig("labelAngle", styleConfig, axis?.style, axisConfigs);
      if (angle2 !== void 0) {
        return normalizeAngle(angle2);
      } else {
        if (channel === X3 && contains2([NOMINAL, ORDINAL], fieldOrDatumDef.type) && !(isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit)) {
          return 270;
        }
        return void 0;
      }
    }
  }
  function normalizeAngleExpr(angle2) {
    return `(((${angle2.signal} % 360) + 360) % 360)`;
  }
  function defaultLabelBaseline(angle2, orient2, channel, alwaysIncludeMiddle) {
    if (angle2 !== void 0) {
      if (channel === "x") {
        if (isSignalRef(angle2)) {
          const a4 = normalizeAngleExpr(angle2);
          const orientIsTop = isSignalRef(orient2) ? `(${orient2.signal} === "top")` : orient2 === "top";
          return {
            signal: `(45 < ${a4} && ${a4} < 135) || (225 < ${a4} && ${a4} < 315) ? "middle" :(${a4} <= 45 || 315 <= ${a4}) === ${orientIsTop} ? "bottom" : "top"`
          };
        }
        if (45 < angle2 && angle2 < 135 || 225 < angle2 && angle2 < 315) {
          return "middle";
        }
        if (isSignalRef(orient2)) {
          const op = angle2 <= 45 || 315 <= angle2 ? "===" : "!==";
          return { signal: `${orient2.signal} ${op} "top" ? "bottom" : "top"` };
        }
        return (angle2 <= 45 || 315 <= angle2) === (orient2 === "top") ? "bottom" : "top";
      } else {
        if (isSignalRef(angle2)) {
          const a4 = normalizeAngleExpr(angle2);
          const orientIsLeft = isSignalRef(orient2) ? `(${orient2.signal} === "left")` : orient2 === "left";
          const middle = alwaysIncludeMiddle ? '"middle"' : "null";
          return {
            signal: `${a4} <= 45 || 315 <= ${a4} || (135 <= ${a4} && ${a4} <= 225) ? ${middle} : (45 <= ${a4} && ${a4} <= 135) === ${orientIsLeft} ? "top" : "bottom"`
          };
        }
        if (angle2 <= 45 || 315 <= angle2 || 135 <= angle2 && angle2 <= 225) {
          return alwaysIncludeMiddle ? "middle" : null;
        }
        if (isSignalRef(orient2)) {
          const op = 45 <= angle2 && angle2 <= 135 ? "===" : "!==";
          return { signal: `${orient2.signal} ${op} "left" ? "top" : "bottom"` };
        }
        return (45 <= angle2 && angle2 <= 135) === (orient2 === "left") ? "top" : "bottom";
      }
    }
    return void 0;
  }
  function defaultLabelAlign(angle2, orient2, channel) {
    if (angle2 === void 0) {
      return void 0;
    }
    const isX2 = channel === "x";
    const startAngle = isX2 ? 0 : 90;
    const mainOrient = isX2 ? "bottom" : "left";
    if (isSignalRef(angle2)) {
      const a4 = normalizeAngleExpr(angle2);
      const orientIsMain = isSignalRef(orient2) ? `(${orient2.signal} === "${mainOrient}")` : orient2 === mainOrient;
      return {
        signal: `(${startAngle ? `(${a4} + 90)` : a4} % 180 === 0) ? ${isX2 ? null : '"center"'} :(${startAngle} < ${a4} && ${a4} < ${180 + startAngle}) === ${orientIsMain} ? "left" : "right"`
      };
    }
    if ((angle2 + startAngle) % 180 === 0) {
      return isX2 ? null : "center";
    }
    if (isSignalRef(orient2)) {
      const op = startAngle < angle2 && angle2 < 180 + startAngle ? "===" : "!==";
      const orientIsMain = `${orient2.signal} ${op} "${mainOrient}"`;
      return {
        signal: `${orientIsMain} ? "left" : "right"`
      };
    }
    if ((startAngle < angle2 && angle2 < 180 + startAngle) === (orient2 === mainOrient)) {
      return "left";
    }
    return "right";
  }
  function defaultLabelFlush(type3, channel) {
    if (channel === "x" && contains2(["quantitative", "temporal"], type3)) {
      return true;
    }
    return void 0;
  }
  function defaultLabelOverlap(type3, scaleType2, hasTimeUnit, sort3) {
    if (hasTimeUnit && !isObject(sort3) || type3 !== "nominal" && type3 !== "ordinal") {
      if (scaleType2 === "log" || scaleType2 === "symlog") {
        return "greedy";
      }
      return true;
    }
    return void 0;
  }
  function defaultOrient(channel) {
    return channel === "x" ? "bottom" : "left";
  }
  function defaultTickCount({ fieldOrDatumDef, scaleType: scaleType2, size, values: vals2 }) {
    if (!vals2 && !hasDiscreteDomain(scaleType2) && scaleType2 !== "log") {
      if (isFieldDef(fieldOrDatumDef)) {
        if (isBinning(fieldOrDatumDef.bin)) {
          return { signal: `ceil(${size.signal}/10)` };
        }
        if (fieldOrDatumDef.timeUnit && contains2(["month", "hours", "day", "quarter"], normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit)) {
          return void 0;
        }
      }
      return { signal: `ceil(${size.signal}/40)` };
    }
    return void 0;
  }
  function defaultTickMinStep({ format: format5, fieldOrDatumDef }) {
    if (format5 === "d") {
      return 1;
    }
    if (isFieldDef(fieldOrDatumDef)) {
      const { timeUnit } = fieldOrDatumDef;
      if (timeUnit) {
        const signal = durationExpr(timeUnit);
        if (signal) {
          return { signal };
        }
      }
    }
    return void 0;
  }
  function getFieldDefTitle(model, channel) {
    const channel2 = channel === "x" ? "x2" : "y2";
    const fieldDef = model.fieldDef(channel);
    const fieldDef2 = model.fieldDef(channel2);
    const title1 = fieldDef ? fieldDef.title : void 0;
    const title2 = fieldDef2 ? fieldDef2.title : void 0;
    if (title1 && title2) {
      return mergeTitle(title1, title2);
    } else if (title1) {
      return title1;
    } else if (title2) {
      return title2;
    } else if (title1 !== void 0) {
      return title1;
    } else if (title2 !== void 0) {
      return title2;
    }
    return void 0;
  }
  function values2(axis, fieldOrDatumDef) {
    const vals2 = axis.values;
    if (isArray(vals2)) {
      return valueArray(fieldOrDatumDef, vals2);
    } else if (isSignalRef(vals2)) {
      return vals2;
    }
    return void 0;
  }
  function defaultZindex(mark, fieldDef) {
    if (mark === "rect" && isDiscrete3(fieldDef)) {
      return 1;
    }
    return 0;
  }

  // node_modules/vega-lite/build/src/compile/data/calculate.js
  var CalculateNode = class _CalculateNode extends DataFlowNode {
    clone() {
      return new _CalculateNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this._dependentFields = getDependentFields(this.transform.calculate);
    }
    static parseAllForSortIndex(parent, model) {
      model.forEachFieldDef((fieldDef, channel) => {
        if (!isScaleFieldDef(fieldDef)) {
          return;
        }
        if (isSortArray(fieldDef.sort)) {
          const { field: field3, timeUnit } = fieldDef;
          const sort3 = fieldDef.sort;
          const calculate = sort3.map((sortValue, i2) => {
            return `${fieldFilterExpression({ field: field3, timeUnit, equal: sortValue })} ? ${i2} : `;
          }).join("") + sort3.length;
          parent = new _CalculateNode(parent, {
            calculate,
            as: sortArrayIndexField(fieldDef, channel, { forAs: true })
          });
        }
      });
      return parent;
    }
    producedFields() {
      return /* @__PURE__ */ new Set([this.transform.as]);
    }
    dependentFields() {
      return this._dependentFields;
    }
    assemble() {
      return {
        type: "formula",
        expr: this.transform.calculate,
        as: this.transform.as
      };
    }
    hash() {
      return `Calculate ${hash(this.transform)}`;
    }
  };
  function sortArrayIndexField(fieldDef, channel, opt) {
    return vgField(fieldDef, { prefix: channel, suffix: "sort_index", ...opt });
  }

  // node_modules/vega-lite/build/src/compile/header/common.js
  function getHeaderChannel(channel, orient2) {
    if (contains2(["top", "bottom"], orient2)) {
      return "column";
    } else if (contains2(["left", "right"], orient2)) {
      return "row";
    }
    return channel === "row" ? "row" : "column";
  }
  function getHeaderProperty(prop, header, config, channel) {
    const headerSpecificConfig = channel === "row" ? config.headerRow : channel === "column" ? config.headerColumn : config.headerFacet;
    return getFirstDefined((header || {})[prop], headerSpecificConfig[prop], config.header[prop]);
  }
  function getHeaderProperties(properties, header, config, channel) {
    const props = {};
    for (const prop of properties) {
      const value3 = getHeaderProperty(prop, header || {}, config, channel);
      if (value3 !== void 0) {
        props[prop] = value3;
      }
    }
    return props;
  }

  // node_modules/vega-lite/build/src/compile/header/component.js
  var HEADER_CHANNELS = ["row", "column"];
  var HEADER_TYPES = ["header", "footer"];

  // node_modules/vega-lite/build/src/compile/header/assemble.js
  function assembleTitleGroup(model, channel) {
    const title2 = model.component.layoutHeaders[channel].title;
    const config = model.config ? model.config : void 0;
    const facetFieldDef = model.component.layoutHeaders[channel].facetFieldDef ? model.component.layoutHeaders[channel].facetFieldDef : void 0;
    const { titleAnchor, titleAngle: ta, titleOrient } = getHeaderProperties(["titleAnchor", "titleAngle", "titleOrient"], facetFieldDef.header, config, channel);
    const headerChannel = getHeaderChannel(channel, titleOrient);
    const titleAngle = normalizeAngle(ta);
    return {
      name: `${channel}-title`,
      type: "group",
      role: `${headerChannel}-title`,
      title: {
        text: title2,
        ...channel === "row" ? { orient: "left" } : {},
        style: "guide-title",
        ...defaultHeaderGuideBaseline(titleAngle, headerChannel),
        ...defaultHeaderGuideAlign(headerChannel, titleAngle, titleAnchor),
        ...assembleHeaderProperties(config, facetFieldDef, channel, HEADER_TITLE_PROPERTIES, HEADER_TITLE_PROPERTIES_MAP)
      }
    };
  }
  function defaultHeaderGuideAlign(headerChannel, angle2, anchor = "middle") {
    switch (anchor) {
      case "start":
        return { align: "left" };
      case "end":
        return { align: "right" };
    }
    const align2 = defaultLabelAlign(angle2, headerChannel === "row" ? "left" : "top", headerChannel === "row" ? "y" : "x");
    return align2 ? { align: align2 } : {};
  }
  function defaultHeaderGuideBaseline(angle2, channel) {
    const baseline3 = defaultLabelBaseline(angle2, channel === "row" ? "left" : "top", channel === "row" ? "y" : "x", true);
    return baseline3 ? { baseline: baseline3 } : {};
  }
  function assembleHeaderGroups(model, channel) {
    const layoutHeader = model.component.layoutHeaders[channel];
    const groups = [];
    for (const headerType of HEADER_TYPES) {
      if (layoutHeader[headerType]) {
        for (const headerComponent of layoutHeader[headerType]) {
          const group2 = assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent);
          if (group2 != null) {
            groups.push(group2);
          }
        }
      }
    }
    return groups;
  }
  function getSort(facetFieldDef, channel) {
    const { sort: sort3 } = facetFieldDef;
    if (isSortField(sort3)) {
      return {
        field: vgField(sort3, { expr: "datum" }),
        order: sort3.order ?? "ascending"
      };
    } else if (isArray(sort3)) {
      return {
        field: sortArrayIndexField(facetFieldDef, channel, { expr: "datum" }),
        order: "ascending"
      };
    } else {
      return {
        field: vgField(facetFieldDef, { expr: "datum" }),
        order: sort3 ?? "ascending"
      };
    }
  }
  function assembleLabelTitle(facetFieldDef, channel, config) {
    const { format: format5, formatType, labelAngle, labelAnchor, labelOrient, labelExpr } = getHeaderProperties(["format", "formatType", "labelAngle", "labelAnchor", "labelOrient", "labelExpr"], facetFieldDef.header, config, channel);
    const titleTextExpr = formatSignalRef({
      fieldOrDatumDef: facetFieldDef,
      format: format5,
      formatType,
      expr: "parent",
      config
    }).signal;
    const headerChannel = getHeaderChannel(channel, labelOrient);
    return {
      text: {
        signal: labelExpr ? replaceAll(replaceAll(labelExpr, "datum.label", titleTextExpr), "datum.value", vgField(facetFieldDef, { expr: "parent" })) : titleTextExpr
      },
      ...channel === "row" ? { orient: "left" } : {},
      style: "guide-label",
      frame: "group",
      ...defaultHeaderGuideBaseline(labelAngle, headerChannel),
      ...defaultHeaderGuideAlign(headerChannel, labelAngle, labelAnchor),
      ...assembleHeaderProperties(config, facetFieldDef, channel, HEADER_LABEL_PROPERTIES, HEADER_LABEL_PROPERTIES_MAP)
    };
  }
  function assembleHeaderGroup(model, channel, headerType, layoutHeader, headerComponent) {
    if (headerComponent) {
      let title2 = null;
      const { facetFieldDef } = layoutHeader;
      const config = model.config ? model.config : void 0;
      if (facetFieldDef && headerComponent.labels) {
        const { labelOrient } = getHeaderProperties(["labelOrient"], facetFieldDef.header, config, channel);
        if (channel === "row" && !contains2(["top", "bottom"], labelOrient) || channel === "column" && !contains2(["left", "right"], labelOrient)) {
          title2 = assembleLabelTitle(facetFieldDef, channel, config);
        }
      }
      const isFacetWithoutRowCol = isFacetModel(model) && !isFacetMapping(model.facet);
      const axes = headerComponent.axes;
      const hasAxes = axes?.length > 0;
      if (title2 || hasAxes) {
        const sizeChannel = channel === "row" ? "height" : "width";
        return {
          name: model.getName(`${channel}_${headerType}`),
          type: "group",
          role: `${channel}-${headerType}`,
          ...layoutHeader.facetFieldDef ? {
            from: { data: model.getName(`${channel}_domain`) },
            sort: getSort(facetFieldDef, channel)
          } : {},
          ...hasAxes && isFacetWithoutRowCol ? {
            from: { data: model.getName(`facet_domain_${channel}`) }
          } : {},
          ...title2 ? { title: title2 } : {},
          ...headerComponent.sizeSignal ? {
            encode: {
              update: {
                [sizeChannel]: headerComponent.sizeSignal
              }
            }
          } : {},
          ...hasAxes ? { axes } : {}
        };
      }
    }
    return null;
  }
  var LAYOUT_TITLE_BAND = {
    column: {
      start: 0,
      end: 1
    },
    row: {
      start: 1,
      end: 0
    }
  };
  function getLayoutTitleBand(titleAnchor, headerChannel) {
    return LAYOUT_TITLE_BAND[headerChannel][titleAnchor];
  }
  function assembleLayoutTitleBand(headerComponentIndex, config) {
    const titleBand = {};
    for (const channel of FACET_CHANNELS) {
      const headerComponent = headerComponentIndex[channel];
      if (headerComponent?.facetFieldDef) {
        const { titleAnchor, titleOrient } = getHeaderProperties(["titleAnchor", "titleOrient"], headerComponent.facetFieldDef.header, config, channel);
        const headerChannel = getHeaderChannel(channel, titleOrient);
        const band2 = getLayoutTitleBand(titleAnchor, headerChannel);
        if (band2 !== void 0) {
          titleBand[headerChannel] = band2;
        }
      }
    }
    return isEmpty(titleBand) ? void 0 : titleBand;
  }
  function assembleHeaderProperties(config, facetFieldDef, channel, properties, propertiesMap) {
    const props = {};
    for (const prop of properties) {
      if (!propertiesMap[prop]) {
        continue;
      }
      const value3 = getHeaderProperty(prop, facetFieldDef?.header, config, channel);
      if (value3 !== void 0) {
        props[propertiesMap[prop]] = value3;
      }
    }
    return props;
  }

  // node_modules/vega-lite/build/src/compile/layoutsize/assemble.js
  function assembleLayoutSignals(model) {
    return [
      ...sizeSignals(model, "width"),
      ...sizeSignals(model, "height"),
      ...sizeSignals(model, "childWidth"),
      ...sizeSignals(model, "childHeight")
    ];
  }
  function sizeSignals(model, sizeType) {
    const channel = sizeType === "width" ? "x" : "y";
    const size = model.component.layoutSize.get(sizeType);
    if (!size || size === "merged") {
      return [];
    }
    const name4 = model.getSizeSignalRef(sizeType).signal;
    if (size === "step") {
      const scaleComponent = model.getScaleComponent(channel);
      if (scaleComponent) {
        const type3 = scaleComponent.get("type");
        const range7 = scaleComponent.get("range");
        if (hasDiscreteDomain(type3) && isVgRangeStep(range7)) {
          const scaleName = model.scaleName(channel);
          if (isFacetModel(model.parent)) {
            const parentResolve = model.parent.component.resolve;
            if (parentResolve.scale[channel] === "independent") {
              return [stepSignal(scaleName, range7)];
            }
          }
          return [
            stepSignal(scaleName, range7),
            {
              name: name4,
              update: sizeExpr(scaleName, scaleComponent, `domain('${scaleName}').length`)
            }
          ];
        }
      }
      throw new Error("layout size is step although width/height is not step.");
    } else if (size == "container") {
      const isWidth = name4.endsWith("width");
      const expr2 = isWidth ? "containerSize()[0]" : "containerSize()[1]";
      const defaultValue = getViewConfigContinuousSize(model.config.view, isWidth ? "width" : "height");
      const safeExpr = `isFinite(${expr2}) ? ${expr2} : ${defaultValue}`;
      return [{ name: name4, init: safeExpr, on: [{ update: safeExpr, events: "window:resize" }] }];
    } else {
      return [
        {
          name: name4,
          value: size
        }
      ];
    }
  }
  function stepSignal(scaleName, range7) {
    const name4 = `${scaleName}_step`;
    if (isSignalRef(range7.step)) {
      return { name: name4, update: range7.step.signal };
    } else {
      return { name: name4, value: range7.step };
    }
  }
  function sizeExpr(scaleName, scaleComponent, cardinality) {
    const type3 = scaleComponent.get("type");
    const padding3 = scaleComponent.get("padding");
    const paddingOuter2 = getFirstDefined(scaleComponent.get("paddingOuter"), padding3);
    let paddingInner2 = scaleComponent.get("paddingInner");
    paddingInner2 = type3 === "band" ? (
      // only band has real paddingInner
      paddingInner2 !== void 0 ? paddingInner2 : padding3
    ) : (
      // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128,
      // it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points.
      1
    );
    return `bandspace(${cardinality}, ${signalOrStringValue(paddingInner2)}, ${signalOrStringValue(paddingOuter2)}) * ${scaleName}_step`;
  }

  // node_modules/vega-lite/build/src/compile/layoutsize/component.js
  function getSizeTypeFromLayoutSizeType(layoutSizeType) {
    return layoutSizeType === "childWidth" ? "width" : layoutSizeType === "childHeight" ? "height" : layoutSizeType;
  }

  // node_modules/vega-lite/build/src/compile/guide.js
  function guideEncodeEntry(encoding, model) {
    return keys3(encoding).reduce((encode2, channel) => {
      return {
        ...encode2,
        ...wrapCondition({
          model,
          channelDef: encoding[channel],
          vgChannel: channel,
          mainRefFn: (def2) => signalOrValueRef(def2.value),
          invalidValueRef: void 0
          // guide encoding won't show invalid values for the scale
        })
      };
    }, {});
  }

  // node_modules/vega-lite/build/src/compile/resolve.js
  function defaultScaleResolve(channel, model) {
    if (isFacetModel(model)) {
      return channel === "theta" ? "independent" : "shared";
    } else if (isLayerModel(model)) {
      return "shared";
    } else if (isConcatModel(model)) {
      return isXorY(channel) || channel === "theta" || channel === "radius" ? "independent" : "shared";
    }
    throw new Error("invalid model type for resolve");
  }
  function parseGuideResolve(resolve2, channel) {
    const channelScaleResolve = resolve2.scale[channel];
    const guide = isXorY(channel) ? "axis" : "legend";
    if (channelScaleResolve === "independent") {
      if (resolve2[guide][channel] === "shared") {
        warn2(message_exports.independentScaleMeansIndependentGuide(channel));
      }
      return "independent";
    }
    return resolve2[guide][channel] || "shared";
  }

  // node_modules/vega-lite/build/src/compile/legend/component.js
  var LEGEND_COMPONENT_PROPERTY_INDEX = {
    ...COMMON_LEGEND_PROPERTY_INDEX,
    disable: 1,
    labelExpr: 1,
    selections: 1,
    // channel scales
    opacity: 1,
    shape: 1,
    stroke: 1,
    fill: 1,
    size: 1,
    strokeWidth: 1,
    strokeDash: 1,
    // encode
    encode: 1
  };
  var LEGEND_COMPONENT_PROPERTIES = keys3(LEGEND_COMPONENT_PROPERTY_INDEX);
  var LegendComponent = class extends Split {
  };

  // node_modules/vega-lite/build/src/compile/legend/encode.js
  var legendEncodeRules = {
    symbols: symbols3,
    gradient: gradient3,
    labels,
    entries: entries2
  };
  function symbols3(symbolsSpec, { fieldOrDatumDef, model, channel, legendCmpt, legendType: legendType2 }) {
    if (legendType2 !== "symbol") {
      return void 0;
    }
    const { markDef, encoding, config, mark } = model;
    const filled = markDef.filled && mark !== "trail";
    let out = {
      ...applyMarkConfig({}, model, FILL_STROKE_CONFIG),
      ...color4(model, { filled })
    };
    const symbolOpacity = legendCmpt.get("symbolOpacity") ?? config.legend.symbolOpacity;
    const symbolFillColor = legendCmpt.get("symbolFillColor") ?? config.legend.symbolFillColor;
    const symbolStrokeColor = legendCmpt.get("symbolStrokeColor") ?? config.legend.symbolStrokeColor;
    const opacity2 = symbolOpacity === void 0 ? getMaxValue(encoding.opacity) ?? markDef.opacity : void 0;
    if (out.fill) {
      if (channel === "fill" || filled && channel === COLOR) {
        delete out.fill;
      } else if (hasProperty(out.fill, "field")) {
        if (symbolFillColor) {
          delete out.fill;
        } else {
          out.fill = signalOrValueRef(config.legend.symbolBaseFillColor ?? "black");
          out.fillOpacity = signalOrValueRef(opacity2 ?? 1);
        }
      } else if (isArray(out.fill)) {
        const fill2 = getFirstConditionValue(encoding.fill ?? encoding.color) ?? markDef.fill ?? (filled && markDef.color);
        if (fill2) {
          out.fill = signalOrValueRef(fill2);
        }
      }
    }
    if (out.stroke) {
      if (channel === "stroke" || !filled && channel === COLOR) {
        delete out.stroke;
      } else if (hasProperty(out.stroke, "field") || symbolStrokeColor) {
        delete out.stroke;
      } else if (isArray(out.stroke)) {
        const stroke2 = getFirstDefined(getFirstConditionValue(encoding.stroke || encoding.color), markDef.stroke, filled ? markDef.color : void 0);
        if (stroke2) {
          out.stroke = { value: stroke2 };
        }
      }
    }
    if (channel !== OPACITY) {
      const condition = isFieldDef(fieldOrDatumDef) && selectedCondition(model, legendCmpt, fieldOrDatumDef);
      if (condition) {
        out.opacity = [
          { test: condition, ...signalOrValueRef(opacity2 ?? 1) },
          signalOrValueRef(config.legend.unselectedOpacity)
        ];
      } else if (opacity2) {
        out.opacity = signalOrValueRef(opacity2);
      }
    }
    out = { ...out, ...symbolsSpec };
    return isEmpty(out) ? void 0 : out;
  }
  function gradient3(gradientSpec, { model, legendType: legendType2, legendCmpt }) {
    if (legendType2 !== "gradient") {
      return void 0;
    }
    const { config, markDef, encoding } = model;
    let out = {};
    const gradientOpacity = legendCmpt.get("gradientOpacity") ?? config.legend.gradientOpacity;
    const opacity2 = gradientOpacity === void 0 ? getMaxValue(encoding.opacity) || markDef.opacity : void 0;
    if (opacity2) {
      out.opacity = signalOrValueRef(opacity2);
    }
    out = { ...out, ...gradientSpec };
    return isEmpty(out) ? void 0 : out;
  }
  function labels(specifiedlabelsSpec, { fieldOrDatumDef, model, channel, legendCmpt }) {
    const legend = model.legend(channel) || {};
    const config = model.config;
    const condition = isFieldDef(fieldOrDatumDef) ? selectedCondition(model, legendCmpt, fieldOrDatumDef) : void 0;
    const opacity2 = condition ? [{ test: condition, value: 1 }, { value: config.legend.unselectedOpacity }] : void 0;
    const { format: format5, formatType } = legend;
    let text4 = void 0;
    if (isCustomFormatType(formatType)) {
      text4 = formatCustomType({
        fieldOrDatumDef,
        field: "datum.value",
        format: format5,
        formatType,
        config
      });
    } else if (format5 === void 0 && formatType === void 0 && config.customFormatTypes) {
      if (fieldOrDatumDef.type === "quantitative" && config.numberFormatType) {
        text4 = formatCustomType({
          fieldOrDatumDef,
          field: "datum.value",
          format: config.numberFormat,
          formatType: config.numberFormatType,
          config
        });
      } else if (fieldOrDatumDef.type === "temporal" && config.timeFormatType && isFieldDef(fieldOrDatumDef) && fieldOrDatumDef.timeUnit === void 0) {
        text4 = formatCustomType({
          fieldOrDatumDef,
          field: "datum.value",
          format: config.timeFormat,
          formatType: config.timeFormatType,
          config
        });
      }
    }
    const labelsSpec = {
      ...opacity2 ? { opacity: opacity2 } : {},
      ...text4 ? { text: text4 } : {},
      ...specifiedlabelsSpec
    };
    return isEmpty(labelsSpec) ? void 0 : labelsSpec;
  }
  function entries2(entriesSpec, { legendCmpt }) {
    const selections = legendCmpt.get("selections");
    return selections?.length ? { ...entriesSpec, fill: { value: "transparent" } } : entriesSpec;
  }
  function getMaxValue(channelDef) {
    return getConditionValue(channelDef, (v3, conditionalDef) => Math.max(v3, conditionalDef.value));
  }
  function getFirstConditionValue(channelDef) {
    return getConditionValue(channelDef, (v3, conditionalDef) => {
      return getFirstDefined(v3, conditionalDef.value);
    });
  }
  function getConditionValue(channelDef, reducer) {
    if (hasConditionalValueDef(channelDef)) {
      return array(channelDef.condition).reduce(reducer, channelDef.value);
    } else if (isValueDef(channelDef)) {
      return channelDef.value;
    }
    return void 0;
  }
  function selectedCondition(model, legendCmpt, fieldDef) {
    const selections = legendCmpt.get("selections");
    if (!selections?.length)
      return void 0;
    const field3 = $(fieldDef.field);
    return selections.map((name4) => {
      const store = $(varName(name4) + STORE);
      return `(!length(data(${store})) || (${name4}[${field3}] && indexof(${name4}[${field3}], datum.value) >= 0))`;
    }).join(" || ");
  }

  // node_modules/vega-lite/build/src/compile/legend/properties.js
  var legendRules = {
    direction: ({ direction }) => direction,
    format: ({ fieldOrDatumDef, legend, config }) => {
      const { format: format5, formatType } = legend;
      return guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, format5, formatType, config, false);
    },
    formatType: ({ legend, fieldOrDatumDef, scaleType: scaleType2 }) => {
      const { formatType } = legend;
      return guideFormatType(formatType, fieldOrDatumDef, scaleType2);
    },
    gradientLength: (params2) => {
      const { legend, legendConfig } = params2;
      return legend.gradientLength ?? legendConfig.gradientLength ?? defaultGradientLength(params2);
    },
    labelOverlap: ({ legend, legendConfig, scaleType: scaleType2 }) => legend.labelOverlap ?? legendConfig.labelOverlap ?? defaultLabelOverlap2(scaleType2),
    symbolType: ({ legend, markDef, channel, encoding }) => legend.symbolType ?? defaultSymbolType(markDef.type, channel, encoding.shape, markDef.shape),
    title: ({ fieldOrDatumDef, config }) => title(fieldOrDatumDef, config, { allowDisabling: true }),
    type: ({ legendType: legendType2, scaleType: scaleType2, channel }) => {
      if (isColorChannel(channel) && isContinuousToContinuous(scaleType2)) {
        if (legendType2 === "gradient") {
          return void 0;
        }
      } else if (legendType2 === "symbol") {
        return void 0;
      }
      return legendType2;
    },
    // depended by other property, let's define upfront
    values: ({ fieldOrDatumDef, legend }) => values3(legend, fieldOrDatumDef)
  };
  function values3(legend, fieldOrDatumDef) {
    const vals2 = legend.values;
    if (isArray(vals2)) {
      return valueArray(fieldOrDatumDef, vals2);
    } else if (isSignalRef(vals2)) {
      return vals2;
    }
    return void 0;
  }
  function defaultSymbolType(mark, channel, shapeChannelDef, markShape) {
    if (channel !== "shape") {
      const shape2 = getFirstConditionValue(shapeChannelDef) ?? markShape;
      if (shape2) {
        return shape2;
      }
    }
    switch (mark) {
      case "bar":
      case "rect":
      case "image":
      case "square":
        return "square";
      case "line":
      case "trail":
      case "rule":
        return "stroke";
      case "arc":
      case "point":
      case "circle":
      case "tick":
      case "geoshape":
      case "area":
      case "text":
        return "circle";
    }
  }
  function getLegendType(params2) {
    const { legend } = params2;
    return getFirstDefined(legend.type, defaultType2(params2));
  }
  function defaultType2({ channel, timeUnit, scaleType: scaleType2 }) {
    if (isColorChannel(channel)) {
      if (contains2(["quarter", "month", "day"], timeUnit)) {
        return "symbol";
      }
      if (isContinuousToContinuous(scaleType2)) {
        return "gradient";
      }
    }
    return "symbol";
  }
  function getDirection({ legendConfig, legendType: legendType2, orient: orient2, legend }) {
    return legend.direction ?? legendConfig[legendType2 ? "gradientDirection" : "symbolDirection"] ?? defaultDirection(orient2, legendType2);
  }
  function defaultDirection(orient2, legendType2) {
    switch (orient2) {
      case "top":
      case "bottom":
        return "horizontal";
      case "left":
      case "right":
      case "none":
      case void 0:
        return void 0;
      // vertical is Vega's default
      default:
        return legendType2 === "gradient" ? "horizontal" : void 0;
    }
  }
  function defaultGradientLength({ legendConfig, model, direction, orient: orient2, scaleType: scaleType2 }) {
    const { gradientHorizontalMaxLength, gradientHorizontalMinLength, gradientVerticalMaxLength, gradientVerticalMinLength } = legendConfig;
    if (isContinuousToContinuous(scaleType2)) {
      if (direction === "horizontal") {
        if (orient2 === "top" || orient2 === "bottom") {
          return gradientLengthSignal(model, "width", gradientHorizontalMinLength, gradientHorizontalMaxLength);
        } else {
          return gradientHorizontalMinLength;
        }
      } else {
        return gradientLengthSignal(model, "height", gradientVerticalMinLength, gradientVerticalMaxLength);
      }
    }
    return void 0;
  }
  function gradientLengthSignal(model, sizeType, min4, max4) {
    const sizeSignal = model.getSizeSignalRef(sizeType).signal;
    return { signal: `clamp(${sizeSignal}, ${min4}, ${max4})` };
  }
  function defaultLabelOverlap2(scaleType2) {
    if (contains2(["quantile", "threshold", "log", "symlog"], scaleType2)) {
      return "greedy";
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/legend/parse.js
  function parseLegend2(model) {
    const legendComponent = isUnitModel(model) ? parseUnitLegend(model) : parseNonUnitLegend(model);
    model.component.legends = legendComponent;
    return legendComponent;
  }
  function parseUnitLegend(model) {
    const { encoding } = model;
    const legendComponent = {};
    for (const channel of [COLOR, ...LEGEND_SCALE_CHANNELS]) {
      const def2 = getFieldOrDatumDef(encoding[channel]);
      if (!def2 || !model.getScaleComponent(channel)) {
        continue;
      }
      if (channel === SHAPE && isFieldDef(def2) && def2.type === GEOJSON) {
        continue;
      }
      legendComponent[channel] = parseLegendForChannel(model, channel);
    }
    return legendComponent;
  }
  function getLegendDefWithScale(model, channel) {
    const scale7 = model.scaleName(channel);
    if (model.mark === "trail") {
      if (channel === "color") {
        return { stroke: scale7 };
      } else if (channel === "size") {
        return { strokeWidth: scale7 };
      }
    }
    if (channel === "color") {
      return model.markDef.filled ? { fill: scale7 } : { stroke: scale7 };
    }
    return { [channel]: scale7 };
  }
  function isExplicit(value3, property2, legend, fieldDef) {
    switch (property2) {
      case "disable":
        return legend !== void 0;
      // if axis is specified or null/false, then its enable/disable state is explicit
      case "values":
        return !!legend?.values;
      case "title":
        if (property2 === "title" && value3 === fieldDef?.title) {
          return true;
        }
    }
    return value3 === (legend || {})[property2];
  }
  function parseLegendForChannel(model, channel) {
    let legend = model.legend(channel);
    const { markDef, encoding, config } = model;
    const legendConfig = config.legend;
    const legendCmpt = new LegendComponent({}, getLegendDefWithScale(model, channel));
    parseInteractiveLegend(model, channel, legendCmpt);
    const disable = legend !== void 0 ? !legend : legendConfig.disable;
    legendCmpt.set("disable", disable, legend !== void 0);
    if (disable) {
      return legendCmpt;
    }
    legend = legend || {};
    const scaleType2 = model.getScaleComponent(channel).get("type");
    const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
    const timeUnit = isFieldDef(fieldOrDatumDef) ? normalizeTimeUnit(fieldOrDatumDef.timeUnit)?.unit : void 0;
    const orient2 = legend.orient || config.legend.orient || "right";
    const legendType2 = getLegendType({ legend, channel, timeUnit, scaleType: scaleType2 });
    const direction = getDirection({ legend, legendType: legendType2, orient: orient2, legendConfig });
    const ruleParams = {
      legend,
      channel,
      model,
      markDef,
      encoding,
      fieldOrDatumDef,
      legendConfig,
      config,
      scaleType: scaleType2,
      orient: orient2,
      legendType: legendType2,
      direction
    };
    for (const property2 of LEGEND_COMPONENT_PROPERTIES) {
      if (legendType2 === "gradient" && property2.startsWith("symbol") || legendType2 === "symbol" && property2.startsWith("gradient")) {
        continue;
      }
      const value3 = property2 in legendRules ? legendRules[property2](ruleParams) : legend[property2];
      if (value3 !== void 0) {
        const explicit = isExplicit(value3, property2, legend, model.fieldDef(channel));
        if (explicit || config.legend[property2] === void 0) {
          legendCmpt.set(property2, value3, explicit);
        }
      }
    }
    const legendEncoding = legend?.encoding ?? {};
    const selections = legendCmpt.get("selections");
    const legendEncode = {};
    const legendEncodeParams = { fieldOrDatumDef, model, channel, legendCmpt, legendType: legendType2 };
    for (const part of ["labels", "legend", "title", "symbols", "gradient", "entries"]) {
      const legendEncodingPart = guideEncodeEntry(legendEncoding[part] ?? {}, model);
      const value3 = part in legendEncodeRules ? legendEncodeRules[part](legendEncodingPart, legendEncodeParams) : legendEncodingPart;
      if (value3 !== void 0 && !isEmpty(value3)) {
        legendEncode[part] = {
          ...selections?.length && isFieldDef(fieldOrDatumDef) ? { name: `${varName(fieldOrDatumDef.field)}_legend_${part}` } : {},
          ...selections?.length ? { interactive: !!selections } : {},
          update: value3
        };
      }
    }
    if (!isEmpty(legendEncode)) {
      legendCmpt.set("encode", legendEncode, !!legend?.encoding);
    }
    return legendCmpt;
  }
  function parseNonUnitLegend(model) {
    const { legends, resolve: resolve2 } = model.component;
    for (const child of model.children) {
      parseLegend2(child);
      for (const channel of keys3(child.component.legends)) {
        resolve2.legend[channel] = parseGuideResolve(model.component.resolve, channel);
        if (resolve2.legend[channel] === "shared") {
          legends[channel] = mergeLegendComponent(legends[channel], child.component.legends[channel]);
          if (!legends[channel]) {
            resolve2.legend[channel] = "independent";
            delete legends[channel];
          }
        }
      }
    }
    for (const channel of keys3(legends)) {
      for (const child of model.children) {
        if (!child.component.legends[channel]) {
          continue;
        }
        if (resolve2.legend[channel] === "shared") {
          delete child.component.legends[channel];
        }
      }
    }
    return legends;
  }
  function mergeLegendComponent(mergedLegend, childLegend) {
    if (!mergedLegend) {
      return childLegend.clone();
    }
    const mergedOrient = mergedLegend.getWithExplicit("orient");
    const childOrient = childLegend.getWithExplicit("orient");
    if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
      return void 0;
    }
    let typeMerged = false;
    for (const prop of LEGEND_COMPONENT_PROPERTIES) {
      const mergedValueWithExplicit = mergeValuesWithExplicit(
        mergedLegend.getWithExplicit(prop),
        childLegend.getWithExplicit(prop),
        prop,
        "legend",
        // Tie breaker function
        (v1, v22) => {
          switch (prop) {
            case "symbolType":
              return mergeSymbolType(v1, v22);
            case "title":
              return mergeTitleComponent(v1, v22);
            case "type":
              typeMerged = true;
              return makeImplicit("symbol");
          }
          return defaultTieBreaker(v1, v22, prop, "legend");
        }
      );
      mergedLegend.setWithExplicit(prop, mergedValueWithExplicit);
    }
    if (typeMerged) {
      if (mergedLegend.implicit?.encode?.gradient) {
        deleteNestedProperty(mergedLegend.implicit, ["encode", "gradient"]);
      }
      if (mergedLegend.explicit?.encode?.gradient) {
        deleteNestedProperty(mergedLegend.explicit, ["encode", "gradient"]);
      }
    }
    return mergedLegend;
  }
  function mergeSymbolType(st1, st2) {
    if (st2.value === "circle") {
      return st2;
    }
    return st1;
  }

  // node_modules/vega-lite/build/src/compile/legend/assemble.js
  function setLegendEncode(legend, part, vgProp, vgRef) {
    var _a2, _b;
    legend.encode ?? (legend.encode = {});
    (_a2 = legend.encode)[part] ?? (_a2[part] = {});
    (_b = legend.encode[part]).update ?? (_b.update = {});
    legend.encode[part].update[vgProp] = vgRef;
  }
  function assembleLegends(model) {
    const legendComponentIndex = model.component.legends;
    const legendByDomain = {};
    for (const channel of keys3(legendComponentIndex)) {
      const scaleComponent = model.getScaleComponent(channel);
      const domainHash = stringify2(scaleComponent.get("domains"));
      if (legendByDomain[domainHash]) {
        for (const mergedLegendComponent of legendByDomain[domainHash]) {
          const merged = mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]);
          if (!merged) {
            legendByDomain[domainHash].push(legendComponentIndex[channel]);
          }
        }
      } else {
        legendByDomain[domainHash] = [legendComponentIndex[channel].clone()];
      }
    }
    const legends = vals(legendByDomain).flat().map((l2) => assembleLegend(l2, model.config)).filter((l2) => l2 !== void 0);
    return legends;
  }
  function assembleLegend(legendCmpt, config) {
    const { disable, labelExpr, selections, ...legend } = legendCmpt.combine();
    if (disable) {
      return void 0;
    }
    if (config.aria === false && legend.aria == void 0) {
      legend.aria = false;
    }
    if (legend.encode?.symbols) {
      const out = legend.encode.symbols.update;
      if (out.fill && out.fill["value"] !== "transparent" && !out.stroke && !legend.stroke) {
        out.stroke = { value: "transparent" };
      }
      for (const property2 of LEGEND_SCALE_CHANNELS) {
        if (legend[property2]) {
          delete out[property2];
        }
      }
    }
    if (!legend.title) {
      delete legend.title;
    }
    if (labelExpr !== void 0) {
      let expr2 = labelExpr;
      if (legend.encode?.labels?.update && isSignalRef(legend.encode.labels.update.text)) {
        expr2 = replaceAll(labelExpr, "datum.label", legend.encode.labels.update.text.signal);
      }
      setLegendEncode(legend, "labels", "text", { signal: expr2 });
    }
    return legend;
  }

  // node_modules/vega-lite/build/src/compile/projection/assemble.js
  function assembleProjections(model) {
    if (isLayerModel(model) || isConcatModel(model)) {
      return assembleProjectionsForModelAndChildren(model);
    } else {
      return assembleProjectionForModel(model);
    }
  }
  function assembleProjectionsForModelAndChildren(model) {
    return model.children.reduce((projections2, child) => {
      return projections2.concat(child.assembleProjections());
    }, assembleProjectionForModel(model));
  }
  function assembleProjectionForModel(model) {
    const component = model.component.projection;
    if (!component || component.merged) {
      return [];
    }
    const projection3 = component.combine();
    const { name: name4 } = projection3;
    if (!component.data) {
      return [
        {
          name: name4,
          // translate to center by default
          translate: { signal: "[width / 2, height / 2]" },
          // parameters, overwrite default translate if specified
          ...projection3
        }
      ];
    } else {
      const size = {
        signal: `[${component.size.map((ref2) => ref2.signal).join(", ")}]`
      };
      const fits = component.data.reduce((sources, data3) => {
        const source4 = isSignalRef(data3) ? data3.signal : `data('${model.lookupDataSource(data3)}')`;
        if (!contains2(sources, source4)) {
          sources.push(source4);
        }
        return sources;
      }, []);
      if (fits.length <= 0) {
        throw new Error("Projection's fit didn't find any data sources");
      }
      return [
        {
          name: name4,
          size,
          fit: {
            signal: fits.length > 1 ? `[${fits.join(", ")}]` : fits[0]
          },
          ...projection3
        }
      ];
    }
  }

  // node_modules/vega-lite/build/src/projection.js
  var PROJECTION_PROPERTIES = [
    "type",
    "clipAngle",
    "clipExtent",
    "center",
    "rotate",
    "precision",
    "reflectX",
    "reflectY",
    "coefficient",
    "distance",
    "fraction",
    "lobes",
    "parallel",
    "radius",
    "ratio",
    "spacing",
    "tilt"
  ];

  // node_modules/vega-lite/build/src/compile/projection/component.js
  var ProjectionComponent = class extends Split {
    constructor(name4, specifiedProjection, size, data3) {
      super(
        { ...specifiedProjection },
        // all explicit properties of projection
        { name: name4 }
        // name as initial implicit property
      );
      this.specifiedProjection = specifiedProjection;
      this.size = size;
      this.data = data3;
      this.merged = false;
    }
    /**
     * Whether the projection parameters should fit provided data.
     */
    get isFit() {
      return !!this.data;
    }
  };

  // node_modules/vega-lite/build/src/compile/projection/parse.js
  function parseProjection2(model) {
    model.component.projection = isUnitModel(model) ? parseUnitProjection(model) : parseNonUnitProjections(model);
  }
  function parseUnitProjection(model) {
    if (model.hasProjection) {
      const proj = replaceExprRef(model.specifiedProjection);
      const fit3 = !(proj && (proj.scale != null || proj.translate != null));
      const size = fit3 ? [model.getSizeSignalRef("width"), model.getSizeSignalRef("height")] : void 0;
      const data3 = fit3 ? gatherFitData(model) : void 0;
      const projComp = new ProjectionComponent(model.projectionName(true), {
        ...replaceExprRef(model.config.projection),
        ...proj
      }, size, data3);
      if (!projComp.get("type")) {
        projComp.set("type", "equalEarth", false);
      }
      return projComp;
    }
    return void 0;
  }
  function gatherFitData(model) {
    const data3 = [];
    const { encoding } = model;
    for (const posssiblePair of [
      [LONGITUDE, LATITUDE],
      [LONGITUDE2, LATITUDE2]
    ]) {
      if (getFieldOrDatumDef(encoding[posssiblePair[0]]) || getFieldOrDatumDef(encoding[posssiblePair[1]])) {
        data3.push({
          signal: model.getName(`geojson_${data3.length}`)
        });
      }
    }
    if (model.channelHasField(SHAPE) && model.typedFieldDef(SHAPE).type === GEOJSON) {
      data3.push({
        signal: model.getName(`geojson_${data3.length}`)
      });
    }
    if (data3.length === 0) {
      data3.push(model.requestDataName(DataSourceType.Main));
    }
    return data3;
  }
  function mergeIfNoConflict(first, second2) {
    const allPropertiesShared = every(PROJECTION_PROPERTIES, (prop) => {
      if (!has(first.explicit, prop) && !has(second2.explicit, prop)) {
        return true;
      }
      if (has(first.explicit, prop) && has(second2.explicit, prop) && // some properties might be signals or objects and require hashing for comparison
      deepEqual(first.get(prop), second2.get(prop))) {
        return true;
      }
      return false;
    });
    const size = deepEqual(first.size, second2.size);
    if (size) {
      if (allPropertiesShared) {
        return first;
      } else if (deepEqual(first.explicit, {})) {
        return second2;
      } else if (deepEqual(second2.explicit, {})) {
        return first;
      }
    }
    return null;
  }
  function parseNonUnitProjections(model) {
    if (model.children.length === 0) {
      return void 0;
    }
    let nonUnitProjection;
    for (const child of model.children) {
      parseProjection2(child);
    }
    const mergable = every(model.children, (child) => {
      const projection3 = child.component.projection;
      if (!projection3) {
        return true;
      } else if (!nonUnitProjection) {
        nonUnitProjection = projection3;
        return true;
      } else {
        const merge5 = mergeIfNoConflict(nonUnitProjection, projection3);
        if (merge5) {
          nonUnitProjection = merge5;
        }
        return !!merge5;
      }
    });
    if (nonUnitProjection && mergable) {
      const name4 = model.projectionName(true);
      const modelProjection = new ProjectionComponent(name4, nonUnitProjection.specifiedProjection, nonUnitProjection.size, duplicate(nonUnitProjection.data));
      for (const child of model.children) {
        const projection3 = child.component.projection;
        if (projection3) {
          if (projection3.isFit) {
            modelProjection.data.push(...child.component.projection.data);
          }
          child.renameProjection(projection3.get("name"), name4);
          projection3.merged = true;
        }
      }
      return modelProjection;
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/data/bin.js
  function rangeFormula(model, fieldDef, channel, config) {
    if (binRequiresRange(fieldDef, channel)) {
      const guide = isUnitModel(model) ? model.axis(channel) ?? model.legend(channel) ?? {} : {};
      const startField = vgField(fieldDef, { expr: "datum" });
      const endField = vgField(fieldDef, { expr: "datum", binSuffix: "end" });
      return {
        formulaAs: vgField(fieldDef, { binSuffix: "range", forAs: true }),
        formula: binFormatExpression(startField, endField, guide.format, guide.formatType, config)
      };
    }
    return {};
  }
  function binKey(bin3, field3) {
    return `${binToString(bin3)}_${field3}`;
  }
  function getSignalsFromModel(model, key2) {
    return {
      signal: model.getName(`${key2}_bins`),
      extentSignal: model.getName(`${key2}_extent`)
    };
  }
  function getBinSignalName(model, field3, bin3) {
    const normalizedBin = normalizeBin(bin3, void 0) ?? {};
    const key2 = binKey(normalizedBin, field3);
    return model.getName(`${key2}_bins`);
  }
  function isBinTransform(t4) {
    return "as" in t4;
  }
  function createBinComponent(t4, bin3, model) {
    let as;
    let span2;
    if (isBinTransform(t4)) {
      as = isString(t4.as) ? [t4.as, `${t4.as}_end`] : [t4.as[0], t4.as[1]];
    } else {
      as = [vgField(t4, { forAs: true }), vgField(t4, { binSuffix: "end", forAs: true })];
    }
    const normalizedBin = { ...normalizeBin(bin3, void 0) };
    const key2 = binKey(normalizedBin, t4.field);
    const { signal, extentSignal } = getSignalsFromModel(model, key2);
    if (isParameterExtent(normalizedBin.extent)) {
      const ext = normalizedBin.extent;
      span2 = parseSelectionExtent(model, ext.param, ext);
      delete normalizedBin.extent;
    }
    const binComponent = {
      bin: normalizedBin,
      field: t4.field,
      as: [as],
      ...signal ? { signal } : {},
      ...extentSignal ? { extentSignal } : {},
      ...span2 ? { span: span2 } : {}
    };
    return { key: key2, binComponent };
  }
  var BinNode = class _BinNode extends DataFlowNode {
    clone() {
      return new _BinNode(null, duplicate(this.bins));
    }
    constructor(parent, bins2) {
      super(parent);
      this.bins = bins2;
    }
    static makeFromEncoding(parent, model) {
      const bins2 = model.reduceFieldDef((binComponentIndex, fieldDef, channel) => {
        if (isTypedFieldDef(fieldDef) && isBinning(fieldDef.bin)) {
          const { key: key2, binComponent } = createBinComponent(fieldDef, fieldDef.bin, model);
          binComponentIndex[key2] = {
            ...binComponent,
            ...binComponentIndex[key2],
            ...rangeFormula(model, fieldDef, channel, model.config)
          };
        }
        return binComponentIndex;
      }, {});
      if (isEmpty(bins2)) {
        return null;
      }
      return new _BinNode(parent, bins2);
    }
    /**
     * Creates a bin node from BinTransform.
     * The optional parameter should provide
     */
    static makeFromTransform(parent, t4, model) {
      const { key: key2, binComponent } = createBinComponent(t4, t4.bin, model);
      return new _BinNode(parent, {
        [key2]: binComponent
      });
    }
    /**
     * Merge bin nodes. This method either integrates the bin config from the other node
     * or if this node already has a bin config, renames the corresponding signal in the model.
     */
    merge(other, renameSignal) {
      for (const key2 of keys3(other.bins)) {
        if (key2 in this.bins) {
          renameSignal(other.bins[key2].signal, this.bins[key2].signal);
          this.bins[key2].as = unique([...this.bins[key2].as, ...other.bins[key2].as], hash);
        } else {
          this.bins[key2] = other.bins[key2];
        }
      }
      for (const child of other.children) {
        other.removeChild(child);
        child.parent = this;
      }
      other.remove();
    }
    producedFields() {
      return new Set(vals(this.bins).map((c4) => c4.as).flat(2));
    }
    dependentFields() {
      return new Set(vals(this.bins).map((c4) => c4.field));
    }
    hash() {
      return `Bin ${hash(this.bins)}`;
    }
    assemble() {
      return vals(this.bins).flatMap((bin3) => {
        const transform4 = [];
        const [binAs, ...remainingAs] = bin3.as;
        const { extent: extent2, ...params2 } = bin3.bin;
        const binTrans = {
          type: "bin",
          field: replacePathInField(bin3.field),
          as: binAs,
          signal: bin3.signal,
          ...!isParameterExtent(extent2) ? { extent: extent2 } : { extent: null },
          ...bin3.span ? { span: { signal: `span(${bin3.span})` } } : {},
          ...params2
        };
        if (!extent2 && bin3.extentSignal) {
          transform4.push({
            type: "extent",
            field: replacePathInField(bin3.field),
            signal: bin3.extentSignal
          });
          binTrans.extent = { signal: bin3.extentSignal };
        }
        transform4.push(binTrans);
        for (const as of remainingAs) {
          for (let i2 = 0; i2 < 2; i2++) {
            transform4.push({
              type: "formula",
              expr: vgField({ field: binAs[i2] }, { expr: "datum" }),
              as: as[i2]
            });
          }
        }
        if (bin3.formula) {
          transform4.push({
            type: "formula",
            expr: bin3.formula,
            as: bin3.formulaAs
          });
        }
        return transform4;
      });
    }
  };

  // node_modules/vega-lite/build/src/compile/data/aggregate.js
  function addDimension(dims, channel, fieldDef, model) {
    const channelDef2 = isUnitModel(model) ? model.encoding[getSecondaryRangeChannel(channel)] : void 0;
    if (isTypedFieldDef(fieldDef) && isUnitModel(model) && hasBandEnd(fieldDef, channelDef2, model.markDef, model.config)) {
      dims.add(vgField(fieldDef, {}));
      dims.add(vgField(fieldDef, { suffix: "end" }));
      const { mark, markDef, config } = model;
      const bandPosition = getBandPosition({ fieldDef, markDef, config });
      if (isRectBasedMark(mark) && bandPosition !== 0.5 && isXorY(channel)) {
        dims.add(vgField(fieldDef, { suffix: OFFSETTED_RECT_START_SUFFIX }));
        dims.add(vgField(fieldDef, { suffix: OFFSETTED_RECT_END_SUFFIX }));
      }
      if (fieldDef.bin && binRequiresRange(fieldDef, channel)) {
        dims.add(vgField(fieldDef, { binSuffix: "range" }));
      }
    } else if (isGeoPositionChannel(channel)) {
      const posChannel = getPositionChannelFromLatLong(channel);
      dims.add(model.getName(posChannel));
    } else {
      dims.add(vgField(fieldDef));
    }
    if (isScaleFieldDef(fieldDef) && isFieldRange(fieldDef.scale?.range)) {
      dims.add(fieldDef.scale.range.field);
    }
    return dims;
  }
  function mergeMeasures(parentMeasures, childMeasures) {
    for (const field3 of keys3(childMeasures)) {
      const ops2 = childMeasures[field3];
      for (const op of keys3(ops2)) {
        if (field3 in parentMeasures) {
          parentMeasures[field3][op] = /* @__PURE__ */ new Set([...parentMeasures[field3][op] ?? [], ...ops2[op]]);
        } else {
          parentMeasures[field3] = { [op]: ops2[op] };
        }
      }
    }
  }
  var AggregateNode = class _AggregateNode extends DataFlowNode {
    clone() {
      return new _AggregateNode(null, new Set(this.dimensions), duplicate(this.measures));
    }
    /**
     * @param dimensions string set for dimensions
     * @param measures dictionary mapping field name => dict of aggregation functions and names to use
     */
    constructor(parent, dimensions, measures) {
      super(parent);
      this.dimensions = dimensions;
      this.measures = measures;
    }
    get groupBy() {
      return this.dimensions;
    }
    static makeFromEncoding(parent, model) {
      let isAggregate3 = false;
      model.forEachFieldDef((fd) => {
        if (fd.aggregate) {
          isAggregate3 = true;
        }
      });
      const meas = {};
      const dims = /* @__PURE__ */ new Set();
      if (!isAggregate3) {
        return null;
      }
      model.forEachFieldDef((fieldDef, channel) => {
        const { aggregate, field: field3 } = fieldDef;
        if (aggregate) {
          if (aggregate === "count") {
            meas["*"] ?? (meas["*"] = {});
            meas["*"]["count"] = /* @__PURE__ */ new Set([vgField(fieldDef, { forAs: true })]);
          } else {
            if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {
              const op = isArgminDef(aggregate) ? "argmin" : "argmax";
              const argField = aggregate[op];
              meas[argField] ?? (meas[argField] = {});
              meas[argField][op] = /* @__PURE__ */ new Set([vgField({ op, field: argField }, { forAs: true })]);
            } else {
              meas[field3] ?? (meas[field3] = {});
              meas[field3][aggregate] = /* @__PURE__ */ new Set([vgField(fieldDef, { forAs: true })]);
            }
            if (isScaleChannel(channel) && model.scaleDomain(channel) === "unaggregated") {
              meas[field3] ?? (meas[field3] = {});
              meas[field3]["min"] = /* @__PURE__ */ new Set([vgField({ field: field3, aggregate: "min" }, { forAs: true })]);
              meas[field3]["max"] = /* @__PURE__ */ new Set([vgField({ field: field3, aggregate: "max" }, { forAs: true })]);
            }
          }
        } else {
          addDimension(dims, channel, fieldDef, model);
        }
      });
      if (dims.size + keys3(meas).length === 0) {
        return null;
      }
      return new _AggregateNode(parent, dims, meas);
    }
    static makeFromTransform(parent, t4) {
      var _a2;
      const dims = /* @__PURE__ */ new Set();
      const meas = {};
      for (const s2 of t4.aggregate) {
        const { op, field: field3, as } = s2;
        if (op) {
          if (op === "count") {
            meas["*"] ?? (meas["*"] = {});
            meas["*"]["count"] = /* @__PURE__ */ new Set([as ? as : vgField(s2, { forAs: true })]);
          } else {
            meas[field3] ?? (meas[field3] = {});
            (_a2 = meas[field3])[op] ?? (_a2[op] = /* @__PURE__ */ new Set());
            meas[field3][op].add(as ? as : vgField(s2, { forAs: true }));
          }
        }
      }
      for (const s2 of t4.groupby ?? []) {
        dims.add(s2);
      }
      if (dims.size + keys3(meas).length === 0) {
        return null;
      }
      return new _AggregateNode(parent, dims, meas);
    }
    merge(other) {
      if (setEqual(this.dimensions, other.dimensions)) {
        mergeMeasures(this.measures, other.measures);
        return true;
      }
      debug2("different dimensions, cannot merge");
      return false;
    }
    addDimensions(fields) {
      fields.forEach(this.dimensions.add, this.dimensions);
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([...this.dimensions, ...keys3(this.measures)]);
    }
    producedFields() {
      const out = /* @__PURE__ */ new Set();
      for (const field3 of keys3(this.measures)) {
        for (const op of keys3(this.measures[field3])) {
          const m4 = this.measures[field3][op];
          if (m4.size === 0) {
            out.add(`${op}_${field3}`);
          } else {
            m4.forEach(out.add, out);
          }
        }
      }
      return out;
    }
    hash() {
      return `Aggregate ${hash({ dimensions: this.dimensions, measures: this.measures })}`;
    }
    assemble() {
      const ops2 = [];
      const fields = [];
      const as = [];
      for (const field3 of keys3(this.measures)) {
        for (const op of keys3(this.measures[field3])) {
          for (const alias of this.measures[field3][op]) {
            as.push(alias);
            ops2.push(op);
            fields.push(field3 === "*" ? null : replacePathInField(field3));
          }
        }
      }
      const result = {
        type: "aggregate",
        groupby: [...this.dimensions].map(replacePathInField),
        ops: ops2,
        fields,
        as
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/facet.js
  var FacetNode = class extends DataFlowNode {
    /**
     * @param model The facet model.
     * @param name The name that this facet source will have.
     * @param data The source data for this facet data.
     */
    constructor(parent, model, name4, data3) {
      super(parent);
      this.model = model;
      this.name = name4;
      this.data = data3;
      for (const channel of FACET_CHANNELS) {
        const fieldDef = model.facet[channel];
        if (fieldDef) {
          const { bin: bin3, sort: sort3 } = fieldDef;
          this[channel] = {
            name: model.getName(`${channel}_domain`),
            fields: [vgField(fieldDef), ...isBinning(bin3) ? [vgField(fieldDef, { binSuffix: "end" })] : []],
            ...isSortField(sort3) ? { sortField: sort3 } : isArray(sort3) ? { sortIndexField: sortArrayIndexField(fieldDef, channel) } : {}
          };
        }
      }
      this.childModel = model.child;
    }
    hash() {
      let out = `Facet`;
      for (const channel of FACET_CHANNELS) {
        if (this[channel]) {
          out += ` ${channel.charAt(0)}:${hash(this[channel])}`;
        }
      }
      return out;
    }
    get fields() {
      const f2 = [];
      for (const channel of FACET_CHANNELS) {
        if (this[channel]?.fields) {
          f2.push(...this[channel].fields);
        }
      }
      return f2;
    }
    dependentFields() {
      const depFields = new Set(this.fields);
      for (const channel of FACET_CHANNELS) {
        if (this[channel]) {
          if (this[channel].sortField) {
            depFields.add(this[channel].sortField.field);
          }
          if (this[channel].sortIndexField) {
            depFields.add(this[channel].sortIndexField);
          }
        }
      }
      return depFields;
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    /**
     * The name to reference this source is its name.
     */
    getSource() {
      return this.name;
    }
    getChildIndependentFieldsWithStep() {
      const childIndependentFieldsWithStep = {};
      for (const channel of POSITION_SCALE_CHANNELS) {
        const childScaleComponent = this.childModel.component.scales[channel];
        if (childScaleComponent && !childScaleComponent.merged) {
          const type3 = childScaleComponent.get("type");
          const range7 = childScaleComponent.get("range");
          if (hasDiscreteDomain(type3) && isVgRangeStep(range7)) {
            const domain4 = assembleDomain(this.childModel, channel);
            const field3 = getFieldFromDomain(domain4);
            if (field3) {
              childIndependentFieldsWithStep[channel] = field3;
            } else {
              warn2(message_exports.unknownField(channel));
            }
          }
        }
      }
      return childIndependentFieldsWithStep;
    }
    assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep) {
      const childChannel = { row: "y", column: "x", facet: void 0 }[channel];
      const fields = [];
      const ops2 = [];
      const as = [];
      if (childChannel && childIndependentFieldsWithStep && childIndependentFieldsWithStep[childChannel]) {
        if (crossedDataName) {
          fields.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
          ops2.push("max");
        } else {
          fields.push(childIndependentFieldsWithStep[childChannel]);
          ops2.push("distinct");
        }
        as.push(`distinct_${childIndependentFieldsWithStep[childChannel]}`);
      }
      const { sortField, sortIndexField } = this[channel];
      if (sortField) {
        const { op = DEFAULT_SORT_OP, field: field3 } = sortField;
        fields.push(field3);
        ops2.push(op);
        as.push(vgField(sortField, { forAs: true }));
      } else if (sortIndexField) {
        fields.push(sortIndexField);
        ops2.push("max");
        as.push(sortIndexField);
      }
      return {
        name: this[channel].name,
        // Use data from the crossed one if it exist
        source: crossedDataName ?? this.data,
        transform: [
          {
            type: "aggregate",
            groupby: this[channel].fields,
            ...fields.length ? {
              fields,
              ops: ops2,
              as
            } : {}
          }
        ]
      };
    }
    assembleFacetHeaderData(childIndependentFieldsWithStep) {
      const { columns: columns2 } = this.model.layout;
      const { layoutHeaders: layoutHeaders2 } = this.model.component;
      const data3 = [];
      const hasSharedAxis = {};
      for (const headerChannel of HEADER_CHANNELS) {
        for (const headerType of HEADER_TYPES) {
          const headers = (layoutHeaders2[headerChannel] && layoutHeaders2[headerChannel][headerType]) ?? [];
          for (const header of headers) {
            if (header.axes?.length > 0) {
              hasSharedAxis[headerChannel] = true;
              break;
            }
          }
        }
        if (hasSharedAxis[headerChannel]) {
          const cardinality = `length(data("${this.facet.name}"))`;
          const stop2 = headerChannel === "row" ? columns2 ? { signal: `ceil(${cardinality} / ${columns2})` } : 1 : columns2 ? { signal: `min(${cardinality}, ${columns2})` } : { signal: cardinality };
          data3.push({
            name: `${this.facet.name}_${headerChannel}`,
            transform: [
              {
                type: "sequence",
                start: 0,
                stop: stop2
              }
            ]
          });
        }
      }
      const { row, column } = hasSharedAxis;
      if (row || column) {
        data3.unshift(this.assembleRowColumnHeaderData("facet", null, childIndependentFieldsWithStep));
      }
      return data3;
    }
    assemble() {
      const data3 = [];
      let crossedDataName = null;
      const childIndependentFieldsWithStep = this.getChildIndependentFieldsWithStep();
      const { column, row, facet } = this;
      if (column && row && (childIndependentFieldsWithStep.x || childIndependentFieldsWithStep.y)) {
        crossedDataName = `cross_${this.column.name}_${this.row.name}`;
        const fields = [].concat(childIndependentFieldsWithStep.x ?? [], childIndependentFieldsWithStep.y ?? []);
        const ops2 = fields.map(() => "distinct");
        data3.push({
          name: crossedDataName,
          source: this.data,
          transform: [
            {
              type: "aggregate",
              groupby: this.fields,
              fields,
              ops: ops2
            }
          ]
        });
      }
      for (const channel of [COLUMN, ROW]) {
        if (this[channel]) {
          data3.push(this.assembleRowColumnHeaderData(channel, crossedDataName, childIndependentFieldsWithStep));
        }
      }
      if (facet) {
        const facetData = this.assembleFacetHeaderData(childIndependentFieldsWithStep);
        if (facetData) {
          data3.push(...facetData);
        }
      }
      return data3;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/formatparse.js
  function unquote(pattern) {
    if (pattern.startsWith("'") && pattern.endsWith("'") || pattern.startsWith('"') && pattern.endsWith('"')) {
      return pattern.slice(1, -1);
    }
    return pattern;
  }
  function parseExpression3(field3, parse7) {
    const f2 = accessPathWithDatum(field3);
    if (parse7 === "number") {
      return `toNumber(${f2})`;
    } else if (parse7 === "boolean") {
      return `toBoolean(${f2})`;
    } else if (parse7 === "string") {
      return `toString(${f2})`;
    } else if (parse7 === "date") {
      return `toDate(${f2})`;
    } else if (parse7 === "flatten") {
      return f2;
    } else if (parse7.startsWith("date:")) {
      const specifier = unquote(parse7.slice(5, parse7.length));
      return `timeParse(${f2},'${specifier}')`;
    } else if (parse7.startsWith("utc:")) {
      const specifier = unquote(parse7.slice(4, parse7.length));
      return `utcParse(${f2},'${specifier}')`;
    } else {
      warn2(message_exports.unrecognizedParse(parse7));
      return null;
    }
  }
  function getImplicitFromFilterTransform(transform4) {
    const implicit2 = {};
    forEachLeaf(transform4.filter, (filter3) => {
      if (isFieldPredicate(filter3)) {
        let val = null;
        if (isFieldEqualPredicate(filter3)) {
          val = signalRefOrValue(filter3.equal);
        } else if (isFieldLTEPredicate(filter3)) {
          val = signalRefOrValue(filter3.lte);
        } else if (isFieldLTPredicate(filter3)) {
          val = signalRefOrValue(filter3.lt);
        } else if (isFieldGTPredicate(filter3)) {
          val = signalRefOrValue(filter3.gt);
        } else if (isFieldGTEPredicate(filter3)) {
          val = signalRefOrValue(filter3.gte);
        } else if (isFieldRangePredicate(filter3)) {
          val = filter3.range[0];
        } else if (isFieldOneOfPredicate(filter3)) {
          val = (filter3.oneOf ?? filter3.in)[0];
        }
        if (val) {
          if (isDateTime(val)) {
            implicit2[filter3.field] = "date";
          } else if (isNumber(val)) {
            implicit2[filter3.field] = "number";
          } else if (isString(val)) {
            implicit2[filter3.field] = "string";
          }
        }
        if (filter3.timeUnit) {
          implicit2[filter3.field] = "date";
        }
      }
    });
    return implicit2;
  }
  function getImplicitFromEncoding(model) {
    const implicit2 = {};
    function add6(fieldDef) {
      if (isFieldOrDatumDefForTimeFormat(fieldDef)) {
        implicit2[fieldDef.field] = "date";
      } else if (fieldDef.type === "quantitative" && isMinMaxOp(fieldDef.aggregate)) {
        implicit2[fieldDef.field] = "number";
      } else if (accessPathDepth(fieldDef.field) > 1) {
        if (!(fieldDef.field in implicit2)) {
          implicit2[fieldDef.field] = "flatten";
        }
      } else if (isScaleFieldDef(fieldDef) && isSortField(fieldDef.sort) && accessPathDepth(fieldDef.sort.field) > 1) {
        if (!(fieldDef.sort.field in implicit2)) {
          implicit2[fieldDef.sort.field] = "flatten";
        }
      }
    }
    if (isUnitModel(model) || isFacetModel(model)) {
      model.forEachFieldDef((fieldDef, channel) => {
        if (isTypedFieldDef(fieldDef)) {
          add6(fieldDef);
        } else {
          const mainChannel = getMainRangeChannel(channel);
          const mainFieldDef = model.fieldDef(mainChannel);
          add6({
            ...fieldDef,
            type: mainFieldDef.type
          });
        }
      });
    }
    if (isUnitModel(model)) {
      const { mark, markDef, encoding } = model;
      if (isPathMark(mark) && // No need to sort by dimension if we have a connected scatterplot (order channel is present)
      !model.encoding.order) {
        const dimensionChannel = markDef.orient === "horizontal" ? "y" : "x";
        const dimensionChannelDef = encoding[dimensionChannel];
        if (isFieldDef(dimensionChannelDef) && dimensionChannelDef.type === "quantitative" && !(dimensionChannelDef.field in implicit2)) {
          implicit2[dimensionChannelDef.field] = "number";
        }
      }
    }
    return implicit2;
  }
  function getImplicitFromSelection(model) {
    const implicit2 = {};
    if (isUnitModel(model) && model.component.selection) {
      for (const name4 of keys3(model.component.selection)) {
        const selCmpt = model.component.selection[name4];
        for (const proj of selCmpt.project.items) {
          if (!proj.channel && accessPathDepth(proj.field) > 1) {
            implicit2[proj.field] = "flatten";
          }
        }
      }
    }
    return implicit2;
  }
  var ParseNode = class _ParseNode extends DataFlowNode {
    clone() {
      return new _ParseNode(null, duplicate(this._parse));
    }
    constructor(parent, parse7) {
      super(parent);
      this._parse = parse7;
    }
    hash() {
      return `Parse ${hash(this._parse)}`;
    }
    /**
     * Creates a parse node from a data.format.parse and updates ancestorParse.
     */
    static makeExplicit(parent, model, ancestorParse) {
      let explicit = {};
      const data3 = model.data;
      if (!isGenerator(data3) && data3?.format?.parse) {
        explicit = data3.format.parse;
      }
      return this.makeWithAncestors(parent, explicit, {}, ancestorParse);
    }
    /**
     * Creates a parse node from "explicit" parse and "implicit" parse and updates ancestorParse.
     */
    static makeWithAncestors(parent, explicit, implicit2, ancestorParse) {
      for (const field3 of keys3(implicit2)) {
        const parsedAs = ancestorParse.getWithExplicit(field3);
        if (parsedAs.value !== void 0) {
          if (parsedAs.explicit || parsedAs.value === implicit2[field3] || parsedAs.value === "derived" || implicit2[field3] === "flatten") {
            delete implicit2[field3];
          } else {
            warn2(message_exports.differentParse(field3, implicit2[field3], parsedAs.value));
          }
        }
      }
      for (const field3 of keys3(explicit)) {
        const parsedAs = ancestorParse.get(field3);
        if (parsedAs !== void 0) {
          if (parsedAs === explicit[field3]) {
            delete explicit[field3];
          } else {
            warn2(message_exports.differentParse(field3, explicit[field3], parsedAs));
          }
        }
      }
      const parse7 = new Split(explicit, implicit2);
      ancestorParse.copyAll(parse7);
      const p2 = {};
      for (const key2 of keys3(parse7.combine())) {
        const val = parse7.get(key2);
        if (val !== null) {
          p2[key2] = val;
        }
      }
      if (keys3(p2).length === 0 || ancestorParse.parseNothing) {
        return null;
      }
      return new _ParseNode(parent, p2);
    }
    get parse() {
      return this._parse;
    }
    merge(other) {
      this._parse = { ...this._parse, ...other.parse };
      other.remove();
    }
    /**
     * Assemble an object for Vega's format.parse property.
     */
    assembleFormatParse() {
      const formatParse = {};
      for (const field3 of keys3(this._parse)) {
        const p2 = this._parse[field3];
        if (accessPathDepth(field3) === 1) {
          formatParse[field3] = p2;
        }
      }
      return formatParse;
    }
    // format parse depends and produces all fields in its parse
    producedFields() {
      return new Set(keys3(this._parse));
    }
    dependentFields() {
      return new Set(keys3(this._parse));
    }
    assembleTransforms(onlyNested = false) {
      return keys3(this._parse).filter((field3) => onlyNested ? accessPathDepth(field3) > 1 : true).map((field3) => {
        const expr2 = parseExpression3(field3, this._parse[field3]);
        if (!expr2) {
          return null;
        }
        const formula = {
          type: "formula",
          expr: expr2,
          as: removePathFromField(field3)
          // Vega output is always flattened
        };
        return formula;
      }).filter((t4) => t4 !== null);
    }
  };

  // node_modules/vega-lite/build/src/compile/data/identifier.js
  var IdentifierNode = class _IdentifierNode extends DataFlowNode {
    clone() {
      return new _IdentifierNode(null);
    }
    constructor(parent) {
      super(parent);
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return /* @__PURE__ */ new Set([SELECTION_ID]);
    }
    hash() {
      return "Identifier";
    }
    assemble() {
      return { type: "identifier", as: SELECTION_ID };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/graticule.js
  var GraticuleNode = class _GraticuleNode extends DataFlowNode {
    clone() {
      return new _GraticuleNode(null, this.params);
    }
    constructor(parent, params2) {
      super(parent);
      this.params = params2;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return void 0;
    }
    hash() {
      return `Graticule ${hash(this.params)}`;
    }
    assemble() {
      return {
        type: "graticule",
        ...this.params === true ? {} : this.params
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/sequence.js
  var SequenceNode = class _SequenceNode extends DataFlowNode {
    clone() {
      return new _SequenceNode(null, this.params);
    }
    constructor(parent, params2) {
      super(parent);
      this.params = params2;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return /* @__PURE__ */ new Set([this.params.as ?? "data"]);
    }
    hash() {
      return `Hash ${hash(this.params)}`;
    }
    assemble() {
      return {
        type: "sequence",
        ...this.params
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/source.js
  var SourceNode = class extends DataFlowNode {
    constructor(data3) {
      super(null);
      data3 ?? (data3 = { name: "source" });
      let format5;
      if (!isGenerator(data3)) {
        format5 = data3.format ? { ...omit(data3.format, ["parse"]) } : {};
      }
      if (isInlineData(data3)) {
        this._data = { values: data3.values };
      } else if (isUrlData(data3)) {
        this._data = { url: data3.url };
        if (!format5.type) {
          let defaultExtension = /(?:\.([^.]+))?$/.exec(data3.url)[1];
          if (!contains2(["json", "csv", "tsv", "dsv", "topojson"], defaultExtension)) {
            defaultExtension = "json";
          }
          format5.type = defaultExtension;
        }
      } else if (isSphereGenerator(data3)) {
        this._data = { values: [{ type: "Sphere" }] };
      } else if (isNamedData(data3) || isGenerator(data3)) {
        this._data = {};
      }
      this._generator = isGenerator(data3);
      if (data3.name) {
        this._name = data3.name;
      }
      if (format5 && !isEmpty(format5)) {
        this._data.format = format5;
      }
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return void 0;
    }
    get data() {
      return this._data;
    }
    hasName() {
      return !!this._name;
    }
    get isGenerator() {
      return this._generator;
    }
    get dataName() {
      return this._name;
    }
    set dataName(name4) {
      this._name = name4;
    }
    set parent(parent) {
      throw new Error("Source nodes have to be roots.");
    }
    remove() {
      throw new Error("Source nodes are roots and cannot be removed.");
    }
    hash() {
      throw new Error("Cannot hash sources");
    }
    assemble() {
      return {
        name: this._name,
        ...this._data,
        transform: []
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/optimizer.js
  var __classPrivateFieldSet = function(receiver, state, value3, kind, f2) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return kind === "a" ? f2.call(receiver, value3) : f2 ? f2.value = value3 : state.set(receiver, value3), value3;
  };
  var __classPrivateFieldGet = function(receiver, state, kind, f2) {
    if (kind === "a" && !f2) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f2 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f2 : kind === "a" ? f2.call(receiver) : f2 ? f2.value : state.get(receiver);
  };
  var _Optimizer_modified;
  function isDataSourceNode(node) {
    return node instanceof SourceNode || node instanceof GraticuleNode || node instanceof SequenceNode;
  }
  var Optimizer = class {
    constructor() {
      _Optimizer_modified.set(this, void 0);
      __classPrivateFieldSet(this, _Optimizer_modified, false, "f");
    }
    // Once true, #modified is never set to false
    setModified() {
      __classPrivateFieldSet(this, _Optimizer_modified, true, "f");
    }
    get modifiedFlag() {
      return __classPrivateFieldGet(this, _Optimizer_modified, "f");
    }
  };
  _Optimizer_modified = /* @__PURE__ */ new WeakMap();
  var BottomUpOptimizer = class extends Optimizer {
    /**
     * Compute a map of node depths that we can use to determine a topological sort order.
     */
    getNodeDepths(node, depth, depths) {
      depths.set(node, depth);
      for (const child of node.children) {
        this.getNodeDepths(child, depth + 1, depths);
      }
      return depths;
    }
    /**
     * Run the optimizer on all nodes starting from the leaves.
     */
    optimize(node) {
      const depths = this.getNodeDepths(node, 0, /* @__PURE__ */ new Map());
      const topologicalSort = [...depths.entries()].sort((a4, b3) => b3[1] - a4[1]);
      for (const tuple of topologicalSort) {
        this.run(tuple[0]);
      }
      return this.modifiedFlag;
    }
  };
  var TopDownOptimizer = class extends Optimizer {
    /**
     * Run the optimizer depth first on all nodes starting from the roots.
     */
    optimize(node) {
      this.run(node);
      for (const child of node.children) {
        this.optimize(child);
      }
      return this.modifiedFlag;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/optimizers.js
  var MergeIdenticalNodes = class extends TopDownOptimizer {
    mergeNodes(parent, nodes) {
      const mergedNode = nodes.shift();
      for (const node of nodes) {
        parent.removeChild(node);
        node.parent = mergedNode;
        node.remove();
      }
    }
    run(node) {
      const hashes = node.children.map((x5) => x5.hash());
      const buckets = {};
      for (let i2 = 0; i2 < hashes.length; i2++) {
        if (buckets[hashes[i2]] === void 0) {
          buckets[hashes[i2]] = [node.children[i2]];
        } else {
          buckets[hashes[i2]].push(node.children[i2]);
        }
      }
      for (const k2 of keys3(buckets)) {
        if (buckets[k2].length > 1) {
          this.setModified();
          this.mergeNodes(node, buckets[k2]);
        }
      }
    }
  };
  var RemoveUnnecessaryIdentifierNodes = class extends TopDownOptimizer {
    constructor(model) {
      super();
      this.requiresSelectionId = model && requiresSelectionId(model);
    }
    run(node) {
      if (node instanceof IdentifierNode) {
        if (!(this.requiresSelectionId && (isDataSourceNode(node.parent) || node.parent instanceof AggregateNode || node.parent instanceof ParseNode))) {
          this.setModified();
          node.remove();
        }
      }
    }
  };
  var RemoveDuplicateTimeUnits = class extends Optimizer {
    optimize(node) {
      this.run(node, /* @__PURE__ */ new Set());
      return this.modifiedFlag;
    }
    run(node, timeUnitFields) {
      let producedFields = /* @__PURE__ */ new Set();
      if (node instanceof TimeUnitNode) {
        producedFields = node.producedFields();
        if (hasIntersection(producedFields, timeUnitFields)) {
          this.setModified();
          node.removeFormulas(timeUnitFields);
          if (node.producedFields.length === 0) {
            node.remove();
          }
        }
      }
      for (const child of node.children) {
        this.run(child, /* @__PURE__ */ new Set([...timeUnitFields, ...producedFields]));
      }
    }
  };
  var RemoveUnnecessaryOutputNodes = class extends TopDownOptimizer {
    constructor() {
      super();
    }
    run(node) {
      if (node instanceof OutputNode && !node.isRequired()) {
        this.setModified();
        node.remove();
      }
    }
  };
  var MoveParseUp = class extends BottomUpOptimizer {
    run(node) {
      if (isDataSourceNode(node)) {
        return;
      }
      if (node.numChildren() > 1) {
        return;
      }
      for (const child of node.children) {
        if (child instanceof ParseNode) {
          if (node instanceof ParseNode) {
            this.setModified();
            node.merge(child);
          } else {
            if (fieldIntersection(node.producedFields(), child.dependentFields())) {
              continue;
            }
            this.setModified();
            child.swapWithParent();
          }
        }
      }
      return;
    }
  };
  var MergeParse = class extends BottomUpOptimizer {
    run(node) {
      const originalChildren = [...node.children];
      const parseChildren = node.children.filter((child) => child instanceof ParseNode);
      if (node.numChildren() > 1 && parseChildren.length >= 1) {
        const commonParse = {};
        const conflictingParse = /* @__PURE__ */ new Set();
        for (const parseNode of parseChildren) {
          const parse7 = parseNode.parse;
          for (const k2 of keys3(parse7)) {
            if (!(k2 in commonParse)) {
              commonParse[k2] = parse7[k2];
            } else if (commonParse[k2] !== parse7[k2]) {
              conflictingParse.add(k2);
            }
          }
        }
        for (const field3 of conflictingParse) {
          delete commonParse[field3];
        }
        if (!isEmpty(commonParse)) {
          this.setModified();
          const mergedParseNode = new ParseNode(node, commonParse);
          for (const childNode of originalChildren) {
            if (childNode instanceof ParseNode) {
              for (const key2 of keys3(commonParse)) {
                delete childNode.parse[key2];
              }
            }
            node.removeChild(childNode);
            childNode.parent = mergedParseNode;
            if (childNode instanceof ParseNode && keys3(childNode.parse).length === 0) {
              childNode.remove();
            }
          }
        }
      }
    }
  };
  var RemoveUnusedSubtrees = class extends BottomUpOptimizer {
    run(node) {
      if (node instanceof OutputNode || node.numChildren() > 0 || node instanceof FacetNode) {
      } else if (node instanceof SourceNode) {
      } else {
        this.setModified();
        node.remove();
      }
    }
  };
  var MergeTimeUnits = class extends BottomUpOptimizer {
    run(node) {
      const timeUnitChildren = node.children.filter((x5) => x5 instanceof TimeUnitNode);
      const combination = timeUnitChildren.pop();
      for (const timeUnit of timeUnitChildren) {
        this.setModified();
        combination.merge(timeUnit);
      }
    }
  };
  var MergeAggregates = class extends BottomUpOptimizer {
    run(node) {
      const aggChildren = node.children.filter((child) => child instanceof AggregateNode);
      const groupedAggregates = {};
      for (const agg of aggChildren) {
        const groupBys = hash(agg.groupBy);
        if (!(groupBys in groupedAggregates)) {
          groupedAggregates[groupBys] = [];
        }
        groupedAggregates[groupBys].push(agg);
      }
      for (const group2 of keys3(groupedAggregates)) {
        const mergeableAggs = groupedAggregates[group2];
        if (mergeableAggs.length > 1) {
          const mergedAggs = mergeableAggs.pop();
          for (const agg of mergeableAggs) {
            if (mergedAggs.merge(agg)) {
              node.removeChild(agg);
              agg.parent = mergedAggs;
              agg.remove();
              this.setModified();
            }
          }
        }
      }
    }
  };
  var MergeBins = class extends BottomUpOptimizer {
    constructor(model) {
      super();
      this.model = model;
    }
    run(node) {
      const moveBinsUp = !(isDataSourceNode(node) || node instanceof FilterNode || node instanceof ParseNode || node instanceof IdentifierNode);
      const promotableBins = [];
      const remainingBins = [];
      for (const child of node.children) {
        if (child instanceof BinNode) {
          if (moveBinsUp && !fieldIntersection(node.producedFields(), child.dependentFields())) {
            promotableBins.push(child);
          } else {
            remainingBins.push(child);
          }
        }
      }
      if (promotableBins.length > 0) {
        const promotedBin = promotableBins.pop();
        for (const bin3 of promotableBins) {
          promotedBin.merge(bin3, this.model.renameSignal.bind(this.model));
        }
        this.setModified();
        if (node instanceof BinNode) {
          node.merge(promotedBin, this.model.renameSignal.bind(this.model));
        } else {
          promotedBin.swapWithParent();
        }
      }
      if (remainingBins.length > 1) {
        const remainingBin = remainingBins.pop();
        for (const bin3 of remainingBins) {
          remainingBin.merge(bin3, this.model.renameSignal.bind(this.model));
        }
        this.setModified();
      }
    }
  };
  var MergeOutputs = class extends BottomUpOptimizer {
    run(node) {
      const children4 = [...node.children];
      const hasOutputChild = some(children4, (child) => child instanceof OutputNode);
      if (!hasOutputChild || node.numChildren() <= 1) {
        return;
      }
      const otherChildren = [];
      let mainOutput;
      for (const child of children4) {
        if (child instanceof OutputNode) {
          let lastOutput = child;
          while (lastOutput.numChildren() === 1) {
            const [theChild] = lastOutput.children;
            if (theChild instanceof OutputNode) {
              lastOutput = theChild;
            } else {
              break;
            }
          }
          otherChildren.push(...lastOutput.children);
          if (mainOutput) {
            node.removeChild(child);
            child.parent = mainOutput.parent;
            mainOutput.parent.removeChild(mainOutput);
            mainOutput.parent = lastOutput;
            this.setModified();
          } else {
            mainOutput = lastOutput;
          }
        } else {
          otherChildren.push(child);
        }
      }
      if (otherChildren.length) {
        this.setModified();
        for (const child of otherChildren) {
          child.parent.removeChild(child);
          child.parent = mainOutput;
        }
      }
    }
  };

  // node_modules/vega-lite/build/src/compile/data/joinaggregate.js
  var JoinAggregateTransformNode = class _JoinAggregateTransformNode extends DataFlowNode {
    clone() {
      return new _JoinAggregateTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
    }
    addDimensions(fields) {
      this.transform.groupby = unique(this.transform.groupby.concat(fields), (d2) => d2);
    }
    dependentFields() {
      const out = /* @__PURE__ */ new Set();
      if (this.transform.groupby) {
        this.transform.groupby.forEach(out.add, out);
      }
      this.transform.joinaggregate.map((w3) => w3.field).filter((f2) => f2 !== void 0).forEach(out.add, out);
      return out;
    }
    producedFields() {
      return new Set(this.transform.joinaggregate.map(this.getDefaultName));
    }
    getDefaultName(joinAggregateFieldDef) {
      return joinAggregateFieldDef.as ?? vgField(joinAggregateFieldDef);
    }
    hash() {
      return `JoinAggregateTransform ${hash(this.transform)}`;
    }
    assemble() {
      const fields = [];
      const ops2 = [];
      const as = [];
      for (const joinaggregate of this.transform.joinaggregate) {
        ops2.push(joinaggregate.op);
        as.push(this.getDefaultName(joinaggregate));
        fields.push(joinaggregate.field === void 0 ? null : joinaggregate.field);
      }
      const groupby = this.transform.groupby;
      return {
        type: "joinaggregate",
        as,
        ops: ops2,
        fields,
        ...groupby !== void 0 ? { groupby } : {}
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/filterinvalid.js
  var FilterInvalidNode = class _FilterInvalidNode extends DataFlowNode {
    clone() {
      return new _FilterInvalidNode(null, { ...this.filter });
    }
    constructor(parent, filter3) {
      super(parent);
      this.filter = filter3;
    }
    static make(parent, model, dataSourcesForHandlingInvalidValues) {
      const { config, markDef } = model;
      const { marks, scales: scales2 } = dataSourcesForHandlingInvalidValues;
      if (marks === "include-invalid-values" && scales2 === "include-invalid-values") {
        return null;
      }
      const filter3 = model.reduceFieldDef((aggregator, fieldDef, channel) => {
        const scaleComponent = isScaleChannel(channel) && model.getScaleComponent(channel);
        if (scaleComponent) {
          const scaleType2 = scaleComponent.get("type");
          const { aggregate } = fieldDef;
          const invalidDataMode = getScaleInvalidDataMode({
            scaleChannel: channel,
            markDef,
            config,
            scaleType: scaleType2,
            isCountAggregate: isCountingAggregateOp(aggregate)
          });
          if (invalidDataMode !== "show" && invalidDataMode !== "always-valid") {
            aggregator[fieldDef.field] = fieldDef;
          }
        }
        return aggregator;
      }, {});
      if (!keys3(filter3).length) {
        return null;
      }
      return new _FilterInvalidNode(parent, filter3);
    }
    dependentFields() {
      return new Set(keys3(this.filter));
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    hash() {
      return `FilterInvalid ${hash(this.filter)}`;
    }
    /**
     * Create the VgTransforms for each of the filtered fields.
     */
    assemble() {
      const filters2 = keys3(this.filter).reduce((vegaFilters, field3) => {
        const fieldDef = this.filter[field3];
        const ref2 = vgField(fieldDef, { expr: "datum" });
        if (fieldDef !== null) {
          if (fieldDef.type === "temporal") {
            vegaFilters.push(`(isDate(${ref2}) || (${isValidFiniteNumberExpr(ref2)}))`);
          } else if (fieldDef.type === "quantitative") {
            vegaFilters.push(isValidFiniteNumberExpr(ref2));
          } else {
          }
        }
        return vegaFilters;
      }, []);
      return filters2.length > 0 ? {
        type: "filter",
        expr: filters2.join(" && ")
      } : null;
    }
  };
  function isValidFiniteNumberExpr(ref2) {
    return `isValid(${ref2}) && isFinite(+${ref2})`;
  }

  // node_modules/vega-lite/build/src/compile/data/stack.js
  function getStackByFields(model) {
    return model.stack.stackBy.reduce((fields, by) => {
      const fieldDef = by.fieldDef;
      const _field = vgField(fieldDef);
      if (_field) {
        fields.push(_field);
      }
      return fields;
    }, []);
  }
  function isValidAsArray(as) {
    return isArray(as) && as.every((s2) => isString(s2)) && as.length > 1;
  }
  var StackNode = class _StackNode extends DataFlowNode {
    clone() {
      return new _StackNode(null, duplicate(this._stack));
    }
    constructor(parent, stack2) {
      super(parent);
      this._stack = stack2;
    }
    static makeFromTransform(parent, stackTransform) {
      const { stack: stack2, groupby, as, offset: offset4 = "zero" } = stackTransform;
      const sortFields = [];
      const sortOrder = [];
      if (stackTransform.sort !== void 0) {
        for (const sortField of stackTransform.sort) {
          sortFields.push(sortField.field);
          sortOrder.push(getFirstDefined(sortField.order, "ascending"));
        }
      }
      const sort3 = {
        field: sortFields,
        order: sortOrder
      };
      let normalizedAs;
      if (isValidAsArray(as)) {
        normalizedAs = as;
      } else if (isString(as)) {
        normalizedAs = [as, `${as}_end`];
      } else {
        normalizedAs = [`${stackTransform.stack}_start`, `${stackTransform.stack}_end`];
      }
      return new _StackNode(parent, {
        dimensionFieldDefs: [],
        stackField: stack2,
        groupby,
        offset: offset4,
        sort: sort3,
        facetby: [],
        as: normalizedAs
      });
    }
    static makeFromEncoding(parent, model) {
      const stackProperties = model.stack;
      const { encoding } = model;
      if (!stackProperties) {
        return null;
      }
      const { groupbyChannels, fieldChannel, offset: offset4, impute } = stackProperties;
      const dimensionFieldDefs = groupbyChannels.map((groupbyChannel) => {
        const cDef = encoding[groupbyChannel];
        return getFieldDef(cDef);
      }).filter((def2) => !!def2);
      const stackby = getStackByFields(model);
      const orderDef = model.encoding.order;
      let sort3;
      if (isArray(orderDef) || isFieldDef(orderDef)) {
        sort3 = sortParams(orderDef);
      } else {
        const sortOrder = isOrderOnlyDef(orderDef) ? orderDef.sort : fieldChannel === "y" ? "descending" : "ascending";
        sort3 = stackby.reduce((s2, field3) => {
          if (!s2.field.includes(field3)) {
            s2.field.push(field3);
            s2.order.push(sortOrder);
          }
          return s2;
        }, { field: [], order: [] });
      }
      return new _StackNode(parent, {
        dimensionFieldDefs,
        stackField: model.vgField(fieldChannel),
        facetby: [],
        stackby,
        sort: sort3,
        offset: offset4,
        impute,
        as: [
          model.vgField(fieldChannel, { suffix: "start", forAs: true }),
          model.vgField(fieldChannel, { suffix: "end", forAs: true })
        ]
      });
    }
    get stack() {
      return this._stack;
    }
    addDimensions(fields) {
      this._stack.facetby.push(...fields);
    }
    dependentFields() {
      const out = /* @__PURE__ */ new Set();
      out.add(this._stack.stackField);
      this.getGroupbyFields().forEach(out.add, out);
      this._stack.facetby.forEach(out.add, out);
      this._stack.sort.field.forEach(out.add, out);
      return out;
    }
    producedFields() {
      return new Set(this._stack.as);
    }
    hash() {
      return `Stack ${hash(this._stack)}`;
    }
    getGroupbyFields() {
      const { dimensionFieldDefs, impute, groupby } = this._stack;
      if (dimensionFieldDefs.length > 0) {
        return dimensionFieldDefs.map((dimensionFieldDef) => {
          if (dimensionFieldDef.bin) {
            if (impute) {
              return [vgField(dimensionFieldDef, { binSuffix: "mid" })];
            }
            return [
              // For binned group by field without impute, we need both bin (start) and bin_end
              vgField(dimensionFieldDef, {}),
              vgField(dimensionFieldDef, { binSuffix: "end" })
            ];
          }
          return [vgField(dimensionFieldDef)];
        }).flat();
      }
      return groupby ?? [];
    }
    assemble() {
      const transform4 = [];
      const { facetby, dimensionFieldDefs, stackField: field3, stackby, sort: sort3, offset: offset4, impute, as } = this._stack;
      if (impute) {
        for (const dimensionFieldDef of dimensionFieldDefs) {
          const { bandPosition = 0.5, bin: bin3 } = dimensionFieldDef;
          if (bin3) {
            const binStart = vgField(dimensionFieldDef, { expr: "datum" });
            const binEnd = vgField(dimensionFieldDef, { expr: "datum", binSuffix: "end" });
            transform4.push({
              type: "formula",
              expr: `${isValidFiniteNumberExpr(binStart)} ? ${bandPosition}*${binStart}+${1 - bandPosition}*${binEnd} : ${binStart}`,
              as: vgField(dimensionFieldDef, { binSuffix: "mid", forAs: true })
            });
          }
          transform4.push({
            type: "impute",
            field: field3,
            groupby: [...stackby, ...facetby],
            key: vgField(dimensionFieldDef, { binSuffix: "mid" }),
            method: "value",
            value: 0
          });
        }
      }
      transform4.push({
        type: "stack",
        groupby: [...this.getGroupbyFields(), ...facetby],
        field: field3,
        sort: sort3,
        as,
        offset: offset4
      });
      return transform4;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/window.js
  var WindowTransformNode = class _WindowTransformNode extends DataFlowNode {
    clone() {
      return new _WindowTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
    }
    addDimensions(fields) {
      this.transform.groupby = unique(this.transform.groupby.concat(fields), (d2) => d2);
    }
    dependentFields() {
      const out = /* @__PURE__ */ new Set();
      (this.transform.groupby ?? []).forEach(out.add, out);
      (this.transform.sort ?? []).forEach((m4) => out.add(m4.field));
      this.transform.window.map((w3) => w3.field).filter((f2) => f2 !== void 0).forEach(out.add, out);
      return out;
    }
    producedFields() {
      return new Set(this.transform.window.map(this.getDefaultName));
    }
    getDefaultName(windowFieldDef) {
      return windowFieldDef.as ?? vgField(windowFieldDef);
    }
    hash() {
      return `WindowTransform ${hash(this.transform)}`;
    }
    assemble() {
      const fields = [];
      const ops2 = [];
      const as = [];
      const params2 = [];
      for (const window2 of this.transform.window) {
        ops2.push(window2.op);
        as.push(this.getDefaultName(window2));
        params2.push(window2.param === void 0 ? null : window2.param);
        fields.push(window2.field === void 0 ? null : window2.field);
      }
      const frame2 = this.transform.frame;
      const groupby = this.transform.groupby;
      if (frame2 && frame2[0] === null && frame2[1] === null && ops2.every((o2) => isAggregateOp(o2))) {
        return {
          type: "joinaggregate",
          as,
          ops: ops2,
          fields,
          ...groupby !== void 0 ? { groupby } : {}
        };
      }
      const sortFields = [];
      const sortOrder = [];
      if (this.transform.sort !== void 0) {
        for (const sortField of this.transform.sort) {
          sortFields.push(sortField.field);
          sortOrder.push(sortField.order ?? "ascending");
        }
      }
      const sort3 = {
        field: sortFields,
        order: sortOrder
      };
      const ignorePeers = this.transform.ignorePeers;
      return {
        type: "window",
        params: params2,
        as,
        ops: ops2,
        fields,
        sort: sort3,
        ...ignorePeers !== void 0 ? { ignorePeers } : {},
        ...groupby !== void 0 ? { groupby } : {},
        ...frame2 !== void 0 ? { frame: frame2 } : {}
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/subtree.js
  function cloneSubtree(facet) {
    function clone(node) {
      if (!(node instanceof FacetNode)) {
        const copy4 = node.clone();
        if (copy4 instanceof OutputNode) {
          const newName = FACET_SCALE_PREFIX + copy4.getSource();
          copy4.setSource(newName);
          facet.model.component.data.outputNodes[newName] = copy4;
        } else if (copy4 instanceof AggregateNode || copy4 instanceof StackNode || copy4 instanceof WindowTransformNode || copy4 instanceof JoinAggregateTransformNode) {
          copy4.addDimensions(facet.fields);
        }
        for (const n2 of node.children.flatMap(clone)) {
          n2.parent = copy4;
        }
        return [copy4];
      }
      return node.children.flatMap(clone);
    }
    return clone;
  }
  function moveFacetDown(node) {
    if (node instanceof FacetNode) {
      if (node.numChildren() === 1 && !(node.children[0] instanceof OutputNode)) {
        const child = node.children[0];
        if (child instanceof AggregateNode || child instanceof StackNode || child instanceof WindowTransformNode || child instanceof JoinAggregateTransformNode) {
          child.addDimensions(node.fields);
        }
        child.swapWithParent();
        moveFacetDown(node);
      } else {
        const facetMain = node.model.component.data.main;
        moveMainDownToFacet(facetMain);
        const cloner = cloneSubtree(node);
        const copy4 = node.children.map(cloner).flat();
        for (const c4 of copy4) {
          c4.parent = facetMain;
        }
      }
    } else {
      node.children.map(moveFacetDown);
    }
  }
  function moveMainDownToFacet(node) {
    if (node instanceof OutputNode && node.type === DataSourceType.Main) {
      if (node.numChildren() === 1) {
        const child = node.children[0];
        if (!(child instanceof FacetNode)) {
          child.swapWithParent();
          moveMainDownToFacet(node);
        }
      }
    }
  }

  // node_modules/vega-lite/build/src/compile/data/optimize.js
  var FACET_SCALE_PREFIX = "scale_";
  var MAX_OPTIMIZATION_RUNS = 5;
  function checkLinks(nodes) {
    for (const node of nodes) {
      for (const child of node.children) {
        if (child.parent !== node) {
          return false;
        }
      }
      if (!checkLinks(node.children)) {
        return false;
      }
    }
    return true;
  }
  function runOptimizer(optimizer, nodes) {
    let modified2 = false;
    for (const node of nodes) {
      modified2 = optimizer.optimize(node) || modified2;
    }
    return modified2;
  }
  function optimizationDataflowHelper(dataComponent, model, firstPass) {
    let roots = dataComponent.sources;
    let modified2 = false;
    modified2 = runOptimizer(new RemoveUnnecessaryOutputNodes(), roots) || modified2;
    modified2 = runOptimizer(new RemoveUnnecessaryIdentifierNodes(model), roots) || modified2;
    roots = roots.filter((r2) => r2.numChildren() > 0);
    modified2 = runOptimizer(new RemoveUnusedSubtrees(), roots) || modified2;
    roots = roots.filter((r2) => r2.numChildren() > 0);
    if (!firstPass) {
      modified2 = runOptimizer(new MoveParseUp(), roots) || modified2;
      modified2 = runOptimizer(new MergeBins(model), roots) || modified2;
      modified2 = runOptimizer(new RemoveDuplicateTimeUnits(), roots) || modified2;
      modified2 = runOptimizer(new MergeParse(), roots) || modified2;
      modified2 = runOptimizer(new MergeAggregates(), roots) || modified2;
      modified2 = runOptimizer(new MergeTimeUnits(), roots) || modified2;
      modified2 = runOptimizer(new MergeIdenticalNodes(), roots) || modified2;
      modified2 = runOptimizer(new MergeOutputs(), roots) || modified2;
    }
    dataComponent.sources = roots;
    return modified2;
  }
  function optimizeDataflow(data3, model) {
    checkLinks(data3.sources);
    let firstPassCounter = 0;
    let secondPassCounter = 0;
    for (let i2 = 0; i2 < MAX_OPTIMIZATION_RUNS; i2++) {
      if (!optimizationDataflowHelper(data3, model, true)) {
        break;
      }
      firstPassCounter++;
    }
    data3.sources.map(moveFacetDown);
    for (let i2 = 0; i2 < MAX_OPTIMIZATION_RUNS; i2++) {
      if (!optimizationDataflowHelper(data3, model, false)) {
        break;
      }
      secondPassCounter++;
    }
    checkLinks(data3.sources);
    if (Math.max(firstPassCounter, secondPassCounter) === MAX_OPTIMIZATION_RUNS) {
      warn2(`Maximum optimization runs(${MAX_OPTIMIZATION_RUNS}) reached.`);
    }
  }

  // node_modules/vega-lite/build/src/compile/signal.js
  var SignalRefWrapper = class _SignalRefWrapper {
    constructor(exprGenerator) {
      Object.defineProperty(this, "signal", {
        enumerable: true,
        get: exprGenerator
      });
    }
    static fromName(rename, signalName) {
      return new _SignalRefWrapper(() => rename(signalName));
    }
  };

  // node_modules/vega-lite/build/src/compile/scale/domain.js
  function parseScaleDomain2(model) {
    if (isUnitModel(model)) {
      parseUnitScaleDomain(model);
    } else {
      parseNonUnitScaleDomain(model);
    }
  }
  function parseUnitScaleDomain(model) {
    const localScaleComponents = model.component.scales;
    for (const channel of keys3(localScaleComponents)) {
      const domains = parseDomainForChannel(model, channel);
      const localScaleCmpt = localScaleComponents[channel];
      localScaleCmpt.setWithExplicit("domains", domains);
      parseSelectionDomain(model, channel);
      if (model.component.data.isFaceted) {
        let facetParent = model;
        while (!isFacetModel(facetParent) && facetParent.parent) {
          facetParent = facetParent.parent;
        }
        const resolve2 = facetParent.component.resolve.scale[channel];
        if (resolve2 === "shared") {
          for (const domain4 of domains.value) {
            if (isDataRefDomain(domain4)) {
              domain4.data = FACET_SCALE_PREFIX + domain4.data.replace(FACET_SCALE_PREFIX, "");
            }
          }
        }
      }
    }
  }
  function parseNonUnitScaleDomain(model) {
    for (const child of model.children) {
      parseScaleDomain2(child);
    }
    const localScaleComponents = model.component.scales;
    for (const channel of keys3(localScaleComponents)) {
      let domains;
      let selectionExtent = null;
      for (const child of model.children) {
        const childComponent = child.component.scales[channel];
        if (childComponent) {
          if (domains === void 0) {
            domains = childComponent.getWithExplicit("domains");
          } else {
            domains = mergeValuesWithExplicit(domains, childComponent.getWithExplicit("domains"), "domains", "scale", domainsTieBreaker);
          }
          const se = childComponent.get("selectionExtent");
          if (selectionExtent && se && selectionExtent.param !== se.param) {
            warn2(message_exports.NEEDS_SAME_SELECTION);
          }
          selectionExtent = se;
        }
      }
      localScaleComponents[channel].setWithExplicit("domains", domains);
      if (selectionExtent) {
        localScaleComponents[channel].set("selectionExtent", selectionExtent, true);
      }
    }
  }
  function normalizeUnaggregatedDomain(domain4, fieldDef, scaleType2, scaleConfig) {
    if (domain4 === "unaggregated") {
      const { valid, reason } = canUseUnaggregatedDomain(fieldDef, scaleType2);
      if (!valid) {
        warn2(reason);
        return void 0;
      }
    } else if (domain4 === void 0 && scaleConfig.useUnaggregatedDomain) {
      const { valid } = canUseUnaggregatedDomain(fieldDef, scaleType2);
      if (valid) {
        return "unaggregated";
      }
    }
    return domain4;
  }
  function parseDomainForChannel(model, channel) {
    const scaleType2 = model.getScaleComponent(channel).get("type");
    const { encoding } = model;
    const domain4 = normalizeUnaggregatedDomain(model.scaleDomain(channel), model.typedFieldDef(channel), scaleType2, model.config.scale);
    if (domain4 !== model.scaleDomain(channel)) {
      model.specifiedScales[channel] = {
        ...model.specifiedScales[channel],
        domain: domain4
      };
    }
    if (channel === "x" && getFieldOrDatumDef(encoding.x2)) {
      if (getFieldOrDatumDef(encoding.x)) {
        return mergeValuesWithExplicit(parseSingleChannelDomain(scaleType2, domain4, model, "x"), parseSingleChannelDomain(scaleType2, domain4, model, "x2"), "domain", "scale", domainsTieBreaker);
      } else {
        return parseSingleChannelDomain(scaleType2, domain4, model, "x2");
      }
    } else if (channel === "y" && getFieldOrDatumDef(encoding.y2)) {
      if (getFieldOrDatumDef(encoding.y)) {
        return mergeValuesWithExplicit(parseSingleChannelDomain(scaleType2, domain4, model, "y"), parseSingleChannelDomain(scaleType2, domain4, model, "y2"), "domain", "scale", domainsTieBreaker);
      } else {
        return parseSingleChannelDomain(scaleType2, domain4, model, "y2");
      }
    }
    return parseSingleChannelDomain(scaleType2, domain4, model, channel);
  }
  function mapDomainToDataSignal(domain4, type3, timeUnit) {
    return domain4.map((v3) => {
      const data3 = valueExpr(v3, { timeUnit, type: type3 });
      return { signal: `{data: ${data3}}` };
    });
  }
  function convertDomainIfItIsDateTime(domain4, type3, timeUnit) {
    const normalizedTimeUnit = normalizeTimeUnit(timeUnit)?.unit;
    if (type3 === "temporal" || normalizedTimeUnit) {
      return mapDomainToDataSignal(domain4, type3, normalizedTimeUnit);
    }
    return [domain4];
  }
  function parseSingleChannelDomain(scaleType2, domain4, model, channel) {
    const { encoding, markDef, mark, config, stack: stack2 } = model;
    const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
    const { type: type3 } = fieldOrDatumDef;
    const timeUnit = fieldOrDatumDef["timeUnit"];
    const dataSourceTypeForScaleDomain = getScaleDataSourceForHandlingInvalidValues({
      invalid: getMarkConfig("invalid", markDef, config),
      isPath: isPathMark(mark)
    });
    if (isDomainUnionWith(domain4)) {
      const defaultDomain = parseSingleChannelDomain(scaleType2, void 0, model, channel);
      const unionWith = convertDomainIfItIsDateTime(domain4.unionWith, type3, timeUnit);
      return makeExplicit([...unionWith, ...defaultDomain.value]);
    } else if (isSignalRef(domain4)) {
      return makeExplicit([domain4]);
    } else if (domain4 && domain4 !== "unaggregated" && !isParameterDomain(domain4)) {
      return makeExplicit(convertDomainIfItIsDateTime(domain4, type3, timeUnit));
    }
    if (stack2 && channel === stack2.fieldChannel) {
      if (stack2.offset === "normalize") {
        return makeImplicit([[0, 1]]);
      }
      const data3 = model.requestDataName(dataSourceTypeForScaleDomain);
      return makeImplicit([
        {
          data: data3,
          field: model.vgField(channel, { suffix: "start" })
        },
        {
          data: data3,
          field: model.vgField(channel, { suffix: "end" })
        }
      ]);
    }
    const sort3 = isScaleChannel(channel) && isFieldDef(fieldOrDatumDef) ? domainSort(model, channel, scaleType2) : void 0;
    if (isDatumDef(fieldOrDatumDef)) {
      const d2 = convertDomainIfItIsDateTime([fieldOrDatumDef.datum], type3, timeUnit);
      return makeImplicit(d2);
    }
    const fieldDef = fieldOrDatumDef;
    if (domain4 === "unaggregated") {
      const { field: field3 } = fieldOrDatumDef;
      return makeImplicit([
        {
          data: model.requestDataName(dataSourceTypeForScaleDomain),
          field: vgField({ field: field3, aggregate: "min" })
        },
        {
          data: model.requestDataName(dataSourceTypeForScaleDomain),
          field: vgField({ field: field3, aggregate: "max" })
        }
      ]);
    } else if (isBinning(fieldDef.bin)) {
      if (hasDiscreteDomain(scaleType2)) {
        if (scaleType2 === "bin-ordinal") {
          return makeImplicit([]);
        }
        return makeImplicit([
          {
            // If sort by aggregation of a specified sort field, we need to use RAW table,
            // so we can aggregate values for the scale independently from the main aggregation.
            data: isBoolean3(sort3) ? model.requestDataName(dataSourceTypeForScaleDomain) : model.requestDataName(DataSourceType.Raw),
            // Use range if we added it and the scale does not support computing a range as a signal.
            field: model.vgField(channel, binRequiresRange(fieldDef, channel) ? { binSuffix: "range" } : {}),
            // we have to use a sort object if sort = true to make the sort correct by bin start
            sort: sort3 === true || !isObject(sort3) ? {
              field: model.vgField(channel, {}),
              op: "min"
              // min or max doesn't matter since we sort by the start of the bin range
            } : sort3
          }
        ]);
      } else {
        const { bin: bin3 } = fieldDef;
        if (isBinning(bin3)) {
          const binSignal = getBinSignalName(model, fieldDef.field, bin3);
          return makeImplicit([
            new SignalRefWrapper(() => {
              const signal = model.getSignalName(binSignal);
              return `[${signal}.start, ${signal}.stop]`;
            })
          ]);
        } else {
          return makeImplicit([
            {
              data: model.requestDataName(dataSourceTypeForScaleDomain),
              field: model.vgField(channel, {})
            }
          ]);
        }
      }
    } else if (fieldDef.timeUnit && contains2(["time", "utc"], scaleType2)) {
      const fieldDef2 = encoding[getSecondaryRangeChannel(channel)];
      if (hasBandEnd(fieldDef, fieldDef2, markDef, config)) {
        const data3 = model.requestDataName(dataSourceTypeForScaleDomain);
        const bandPosition = getBandPosition({ fieldDef, fieldDef2, markDef, config });
        const isRectWithOffset = isRectBasedMark(mark) && bandPosition !== 0.5 && isXorY(channel);
        return makeImplicit([
          {
            data: data3,
            field: model.vgField(channel, isRectWithOffset ? { suffix: OFFSETTED_RECT_START_SUFFIX } : {})
          },
          {
            data: data3,
            field: model.vgField(channel, { suffix: isRectWithOffset ? OFFSETTED_RECT_END_SUFFIX : "end" })
          }
        ]);
      }
    }
    if (sort3) {
      return makeImplicit([
        {
          // If sort by aggregation of a specified sort field, we need to use RAW table,
          // so we can aggregate values for the scale independently from the main aggregation.
          data: isBoolean3(sort3) ? model.requestDataName(dataSourceTypeForScaleDomain) : model.requestDataName(DataSourceType.Raw),
          field: model.vgField(channel),
          sort: sort3
        }
      ]);
    } else {
      return makeImplicit([
        {
          data: model.requestDataName(dataSourceTypeForScaleDomain),
          field: model.vgField(channel)
        }
      ]);
    }
  }
  function normalizeSortField(sort3, isStackedMeasure) {
    const { op, field: field3, order } = sort3;
    return {
      // Apply default op
      op: op ?? (isStackedMeasure ? "sum" : DEFAULT_SORT_OP),
      // flatten nested fields
      ...field3 ? { field: replacePathInField(field3) } : {},
      ...order ? { order } : {}
    };
  }
  function parseSelectionDomain(model, channel) {
    const scale7 = model.component.scales[channel];
    const spec = model.specifiedScales[channel].domain;
    const bin3 = model.fieldDef(channel)?.bin;
    const domain4 = isParameterDomain(spec) ? spec : void 0;
    const extent2 = isBinParams(bin3) && isParameterExtent(bin3.extent) ? bin3.extent : void 0;
    if (domain4 || extent2) {
      scale7.set("selectionExtent", domain4 ?? extent2, true);
    }
  }
  function domainSort(model, channel, scaleType2) {
    if (!hasDiscreteDomain(scaleType2)) {
      return void 0;
    }
    const fieldDef = model.fieldDef(channel);
    const sort3 = fieldDef.sort;
    if (isSortArray(sort3)) {
      return {
        op: "min",
        field: sortArrayIndexField(fieldDef, channel),
        order: "ascending"
      };
    }
    const { stack: stack2 } = model;
    const stackDimensions = stack2 ? /* @__PURE__ */ new Set([...stack2.groupbyFields, ...stack2.stackBy.map((s2) => s2.fieldDef.field)]) : void 0;
    if (isSortField(sort3)) {
      const isStackedMeasure = stack2 && !stackDimensions.has(sort3.field);
      return normalizeSortField(sort3, isStackedMeasure);
    } else if (isSortByEncoding(sort3)) {
      const { encoding, order } = sort3;
      const fieldDefToSortBy = model.fieldDef(encoding);
      const { aggregate, field: field3 } = fieldDefToSortBy;
      const isStackedMeasure = stack2 && !stackDimensions.has(field3);
      if (isArgminDef(aggregate) || isArgmaxDef(aggregate)) {
        return normalizeSortField({
          field: vgField(fieldDefToSortBy),
          order
        }, isStackedMeasure);
      } else if (isAggregateOp(aggregate) || !aggregate) {
        return normalizeSortField({
          op: aggregate,
          // can't be argmin/argmax since we don't support them in encoding field def
          field: field3,
          order
        }, isStackedMeasure);
      }
    } else if (sort3 === "descending") {
      return {
        op: "min",
        field: model.vgField(channel),
        order: "descending"
      };
    } else if (contains2([
      "ascending",
      void 0
      /* default =ascending*/
    ], sort3)) {
      return true;
    }
    return void 0;
  }
  function canUseUnaggregatedDomain(fieldDef, scaleType2) {
    const { aggregate, type: type3 } = fieldDef;
    if (!aggregate) {
      return {
        valid: false,
        reason: message_exports.unaggregateDomainHasNoEffectForRawField(fieldDef)
      };
    }
    if (isString(aggregate) && !SHARED_DOMAIN_OPS.has(aggregate)) {
      return {
        valid: false,
        reason: message_exports.unaggregateDomainWithNonSharedDomainOp(aggregate)
      };
    }
    if (type3 === "quantitative") {
      if (scaleType2 === "log") {
        return {
          valid: false,
          reason: message_exports.unaggregatedDomainWithLogScale(fieldDef)
        };
      }
    }
    return { valid: true };
  }
  function domainsTieBreaker(v1, v22, property2, propertyOf) {
    if (v1.explicit && v22.explicit) {
      warn2(message_exports.mergeConflictingDomainProperty(property2, propertyOf, v1.value, v22.value));
    }
    return { explicit: v1.explicit, value: [...v1.value, ...v22.value] };
  }
  function mergeDomains(domains) {
    const uniqueDomains = unique(domains.map((domain4) => {
      if (isDataRefDomain(domain4)) {
        const { sort: _s, ...domainWithoutSort } = domain4;
        return domainWithoutSort;
      }
      return domain4;
    }), hash);
    const sorts = unique(domains.map((d2) => {
      if (isDataRefDomain(d2)) {
        const s2 = d2.sort;
        if (s2 !== void 0 && !isBoolean3(s2)) {
          if ("op" in s2 && s2.op === "count") {
            delete s2.field;
          }
          if (s2.order === "ascending") {
            delete s2.order;
          }
        }
        return s2;
      }
      return void 0;
    }).filter((s2) => s2 !== void 0), hash);
    if (uniqueDomains.length === 0) {
      return void 0;
    } else if (uniqueDomains.length === 1) {
      const domain4 = domains[0];
      if (isDataRefDomain(domain4) && sorts.length > 0) {
        let sort4 = sorts[0];
        if (sorts.length > 1) {
          warn2(message_exports.MORE_THAN_ONE_SORT);
          const filteredSorts = sorts.filter((s2) => isObject(s2) && "op" in s2 && s2.op !== "min");
          if (sorts.every((s2) => isObject(s2) && "op" in s2) && filteredSorts.length === 1) {
            sort4 = filteredSorts[0];
          } else {
            sort4 = true;
          }
        } else {
          if (isObject(sort4) && "field" in sort4) {
            const sortField = sort4.field;
            if (domain4.field === sortField) {
              sort4 = sort4.order ? { order: sort4.order } : true;
            }
          }
        }
        return {
          ...domain4,
          sort: sort4
        };
      }
      return domain4;
    }
    const unionDomainSorts = unique(sorts.map((s2) => {
      if (isBoolean3(s2) || !("op" in s2) || isString(s2.op) && has(MULTIDOMAIN_SORT_OP_INDEX, s2.op)) {
        return s2;
      }
      warn2(message_exports.domainSortDropped(s2));
      return true;
    }), hash);
    let sort3;
    if (unionDomainSorts.length === 1) {
      sort3 = unionDomainSorts[0];
    } else if (unionDomainSorts.length > 1) {
      warn2(message_exports.MORE_THAN_ONE_SORT);
      sort3 = true;
    }
    const allData = unique(domains.map((d2) => {
      if (isDataRefDomain(d2)) {
        return d2.data;
      }
      return null;
    }), (x5) => x5);
    if (allData.length === 1 && allData[0] !== null) {
      const domain4 = {
        data: allData[0],
        fields: uniqueDomains.map((d2) => d2.field),
        ...sort3 ? { sort: sort3 } : {}
      };
      return domain4;
    }
    return { fields: uniqueDomains, ...sort3 ? { sort: sort3 } : {} };
  }
  function getFieldFromDomain(domain4) {
    if (isDataRefDomain(domain4) && isString(domain4.field)) {
      return domain4.field;
    } else if (isDataRefUnionedDomain(domain4)) {
      let field3;
      for (const nonUnionDomain of domain4.fields) {
        if (isDataRefDomain(nonUnionDomain) && isString(nonUnionDomain.field)) {
          if (!field3) {
            field3 = nonUnionDomain.field;
          } else if (field3 !== nonUnionDomain.field) {
            warn2(message_exports.FACETED_INDEPENDENT_DIFFERENT_SOURCES);
            return field3;
          }
        }
      }
      warn2(message_exports.FACETED_INDEPENDENT_SAME_FIELDS_DIFFERENT_SOURCES);
      return field3;
    } else if (isFieldRefUnionDomain(domain4)) {
      warn2(message_exports.FACETED_INDEPENDENT_SAME_SOURCE);
      const field3 = domain4.fields[0];
      return isString(field3) ? field3 : void 0;
    }
    return void 0;
  }
  function assembleDomain(model, channel) {
    const scaleComponent = model.component.scales[channel];
    const domains = scaleComponent.get("domains").map((domain4) => {
      if (isDataRefDomain(domain4)) {
        domain4.data = model.lookupDataSource(domain4.data);
      }
      return domain4;
    });
    return mergeDomains(domains);
  }

  // node_modules/vega-lite/build/src/compile/scale/assemble.js
  function assembleScales(model) {
    if (isLayerModel(model) || isConcatModel(model)) {
      return model.children.reduce((scales2, child) => {
        return scales2.concat(assembleScales(child));
      }, assembleScalesForModel(model));
    } else {
      return assembleScalesForModel(model);
    }
  }
  function assembleScalesForModel(model) {
    return keys3(model.component.scales).reduce((scales2, channel) => {
      const scaleComponent = model.component.scales[channel];
      if (scaleComponent.merged) {
        return scales2;
      }
      const scale7 = scaleComponent.combine();
      const { name: name4, type: type3, selectionExtent, domains: _d2, range: _r2, reverse: reverse3, ...otherScaleProps } = scale7;
      const range7 = assembleScaleRange(scale7.range, name4, channel, model);
      const domain4 = assembleDomain(model, channel);
      const domainRaw = selectionExtent ? assembleSelectionScaleDomain(model, selectionExtent, scaleComponent, domain4) : null;
      scales2.push({
        name: name4,
        type: type3,
        ...domain4 ? { domain: domain4 } : {},
        ...domainRaw ? { domainRaw } : {},
        range: range7,
        ...reverse3 !== void 0 ? { reverse: reverse3 } : {},
        ...otherScaleProps
      });
      return scales2;
    }, []);
  }
  function assembleScaleRange(scaleRange, scaleName, channel, model) {
    if (isXorY(channel)) {
      if (isVgRangeStep(scaleRange)) {
        return {
          step: { signal: `${scaleName}_step` }
        };
      }
    } else if (isObject(scaleRange) && isDataRefDomain(scaleRange)) {
      return {
        ...scaleRange,
        data: model.lookupDataSource(scaleRange.data)
      };
    }
    return scaleRange;
  }

  // node_modules/vega-lite/build/src/compile/scale/component.js
  var ScaleComponent = class extends Split {
    constructor(name4, typeWithExplicit) {
      super(
        {},
        // no initial explicit property
        { name: name4 }
        // name as initial implicit property
      );
      this.merged = false;
      this.setWithExplicit("type", typeWithExplicit);
    }
    /**
     * Whether the scale definitely includes or not include zero in the domain
     */
    domainHasZero() {
      const scaleType2 = this.get("type");
      if (contains2([ScaleType.LOG, ScaleType.TIME, ScaleType.UTC], scaleType2)) {
        return "definitely-not";
      }
      const scaleZero = this.get("zero");
      if (scaleZero === true || // If zero is undefined, linear/sqrt/pow scales have zero by default.
      scaleZero === void 0 && contains2([ScaleType.LINEAR, ScaleType.SQRT, ScaleType.POW], scaleType2)) {
        return "definitely";
      }
      const domains = this.get("domains");
      if (domains.length > 0) {
        let hasExplicitDomainWithZero = false;
        let hasExplicitDomainWithoutZero = false;
        let hasDomainBasedOnField = false;
        for (const d2 of domains) {
          if (isArray(d2)) {
            const first = d2[0];
            const last = d2[d2.length - 1];
            if (isNumber(first) && isNumber(last)) {
              if (first <= 0 && last >= 0) {
                hasExplicitDomainWithZero = true;
                continue;
              } else {
                hasExplicitDomainWithoutZero = true;
                continue;
              }
            }
          }
          hasDomainBasedOnField = true;
        }
        if (hasExplicitDomainWithZero) {
          return "definitely";
        } else if (hasExplicitDomainWithoutZero && !hasDomainBasedOnField) {
          return "definitely-not";
        }
      }
      return "maybe";
    }
  };

  // node_modules/vega-lite/build/src/compile/scale/range.js
  var RANGE_PROPERTIES = ["range", "scheme"];
  function parseUnitScaleRange(model) {
    const localScaleComponents = model.component.scales;
    for (const channel of SCALE_CHANNELS) {
      const localScaleCmpt = localScaleComponents[channel];
      if (!localScaleCmpt) {
        continue;
      }
      const rangeWithExplicit = parseRangeForChannel(channel, model);
      localScaleCmpt.setWithExplicit("range", rangeWithExplicit);
    }
  }
  function getBinStepSignal(model, channel) {
    const fieldDef = model.fieldDef(channel);
    if (fieldDef?.bin) {
      const { bin: bin3, field: field3 } = fieldDef;
      const sizeType = getSizeChannel(channel);
      const sizeSignal = model.getName(sizeType);
      if (isObject(bin3) && bin3.binned && bin3.step !== void 0) {
        return new SignalRefWrapper(() => {
          const scaleName = model.scaleName(channel);
          const binCount = `(domain("${scaleName}")[1] - domain("${scaleName}")[0]) / ${bin3.step}`;
          return `${model.getSignalName(sizeSignal)} / (${binCount})`;
        });
      } else if (isBinning(bin3)) {
        const binSignal = getBinSignalName(model, field3, bin3);
        return new SignalRefWrapper(() => {
          const updatedName = model.getSignalName(binSignal);
          const binCount = `(${updatedName}.stop - ${updatedName}.start) / ${updatedName}.step`;
          return `${model.getSignalName(sizeSignal)} / (${binCount})`;
        });
      }
    }
    return void 0;
  }
  function parseRangeForChannel(channel, model) {
    const specifiedScale = model.specifiedScales[channel];
    const { size } = model;
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const scaleType2 = mergedScaleCmpt.get("type");
    for (const property2 of RANGE_PROPERTIES) {
      if (specifiedScale[property2] !== void 0) {
        const supportedByScaleType = scaleTypeSupportProperty(scaleType2, property2);
        const channelIncompatability = channelScalePropertyIncompatability(channel, property2);
        if (!supportedByScaleType) {
          warn2(message_exports.scalePropertyNotWorkWithScaleType(scaleType2, property2, channel));
        } else if (channelIncompatability) {
          warn2(channelIncompatability);
        } else {
          switch (property2) {
            case "range": {
              const range7 = specifiedScale.range;
              if (isArray(range7)) {
                if (isXorY(channel)) {
                  return makeExplicit(range7.map((v3) => {
                    if (v3 === "width" || v3 === "height") {
                      const sizeSignal = model.getName(v3);
                      const getSignalName = model.getSignalName.bind(model);
                      return SignalRefWrapper.fromName(getSignalName, sizeSignal);
                    }
                    return v3;
                  }));
                }
              } else if (isObject(range7)) {
                return makeExplicit({
                  data: model.requestDataName(DataSourceType.Main),
                  field: range7.field,
                  sort: { op: "min", field: model.vgField(channel) }
                });
              }
              return makeExplicit(range7);
            }
            case "scheme":
              return makeExplicit(parseScheme(specifiedScale[property2]));
          }
        }
      }
    }
    const sizeChannel = channel === X3 || channel === "xOffset" ? "width" : "height";
    const sizeValue = size[sizeChannel];
    if (isStep(sizeValue)) {
      if (isXorY(channel)) {
        if (hasDiscreteDomain(scaleType2)) {
          const step = getPositionStep(sizeValue, model, channel);
          if (step) {
            return makeExplicit({ step });
          }
        } else {
          warn2(message_exports.stepDropped(sizeChannel));
        }
      } else if (isXorYOffset(channel)) {
        const positionChannel = channel === XOFFSET ? "x" : "y";
        const positionScaleCmpt = model.getScaleComponent(positionChannel);
        const positionScaleType = positionScaleCmpt.get("type");
        if (positionScaleType === "band") {
          const step = getOffsetStep(sizeValue, scaleType2);
          if (step) {
            return makeExplicit(step);
          }
        }
      }
    }
    const { rangeMin: rangeMin2, rangeMax: rangeMax2 } = specifiedScale;
    const d2 = defaultRange(channel, model);
    if ((rangeMin2 !== void 0 || rangeMax2 !== void 0) && // it's ok to check just rangeMin's compatibility since rangeMin/rangeMax are the same
    scaleTypeSupportProperty(scaleType2, "rangeMin") && isArray(d2) && d2.length === 2) {
      return makeExplicit([rangeMin2 ?? d2[0], rangeMax2 ?? d2[1]]);
    }
    return makeImplicit(d2);
  }
  function parseScheme(scheme3) {
    if (isExtendedScheme(scheme3)) {
      return {
        scheme: scheme3.name,
        ...omit(scheme3, ["name"])
      };
    }
    return { scheme: scheme3 };
  }
  function fullWidthOrHeightRange(channel, model, scaleType2, { center } = {}) {
    const sizeType = getSizeChannel(channel);
    const sizeSignal = model.getName(sizeType);
    const getSignalName = model.getSignalName.bind(model);
    if (channel === Y3 && hasContinuousDomain(scaleType2)) {
      return center ? [
        SignalRefWrapper.fromName((name4) => `${getSignalName(name4)}/2`, sizeSignal),
        SignalRefWrapper.fromName((name4) => `-${getSignalName(name4)}/2`, sizeSignal)
      ] : [SignalRefWrapper.fromName(getSignalName, sizeSignal), 0];
    } else {
      return center ? [
        SignalRefWrapper.fromName((name4) => `-${getSignalName(name4)}/2`, sizeSignal),
        SignalRefWrapper.fromName((name4) => `${getSignalName(name4)}/2`, sizeSignal)
      ] : [0, SignalRefWrapper.fromName(getSignalName, sizeSignal)];
    }
  }
  function defaultRange(channel, model) {
    const { size, config, mark, encoding } = model;
    const { type: type3 } = getFieldOrDatumDef(encoding[channel]);
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const scaleType2 = mergedScaleCmpt.get("type");
    const { domain: domain4, domainMid } = model.specifiedScales[channel];
    switch (channel) {
      case X3:
      case Y3: {
        if (contains2(["point", "band"], scaleType2)) {
          const positionSize = getDiscretePositionSize(channel, size, config.view);
          if (isStep(positionSize)) {
            const step = getPositionStep(positionSize, model, channel);
            return { step };
          }
        }
        return fullWidthOrHeightRange(channel, model, scaleType2);
      }
      case XOFFSET:
      case YOFFSET:
        return getOffsetRange(channel, model, scaleType2);
      case SIZE2: {
        const rangeMin2 = sizeRangeMin(mark, config);
        const rangeMax2 = sizeRangeMax(mark, size, model, config);
        if (isContinuousToDiscrete(scaleType2)) {
          return interpolateRange2(rangeMin2, rangeMax2, defaultContinuousToDiscreteCount(scaleType2, config, domain4, channel));
        } else {
          return [rangeMin2, rangeMax2];
        }
      }
      case THETA:
        return [0, Math.PI * 2];
      case ANGLE:
        return [0, 360];
      case RADIUS: {
        return [
          0,
          new SignalRefWrapper(() => {
            const w3 = model.getSignalName(isFacetModel(model.parent) ? "child_width" : "width");
            const h3 = model.getSignalName(isFacetModel(model.parent) ? "child_height" : "height");
            return `min(${w3},${h3})/2`;
          })
        ];
      }
      case TIME: {
        return { step: 1e3 / config.scale.framesPerSecond };
      }
      case STROKEWIDTH:
        return [config.scale.minStrokeWidth, config.scale.maxStrokeWidth];
      case STROKEDASH:
        return [
          // TODO: add this to Vega's config.range?
          [1, 0],
          [4, 2],
          [2, 1],
          [1, 1],
          [1, 2, 4, 2]
        ];
      case SHAPE:
        return "symbol";
      case COLOR:
      case FILL:
      case STROKE:
        if (scaleType2 === "ordinal") {
          return type3 === "nominal" ? "category" : "ordinal";
        } else {
          if (domainMid !== void 0) {
            return "diverging";
          } else {
            return mark === "rect" || mark === "geoshape" ? "heatmap" : "ramp";
          }
        }
      case OPACITY:
      case FILLOPACITY:
      case STROKEOPACITY:
        return [config.scale.minOpacity, config.scale.maxOpacity];
    }
  }
  function getPositionStep(step, model, channel) {
    const { encoding } = model;
    const mergedScaleCmpt = model.getScaleComponent(channel);
    const offsetChannel = getOffsetScaleChannel(channel);
    const offsetDef = encoding[offsetChannel];
    const stepFor = getStepFor({ step, offsetIsDiscrete: isFieldOrDatumDef(offsetDef) && isDiscrete2(offsetDef.type) });
    if (stepFor === "offset" && channelHasFieldOrDatum(encoding, offsetChannel)) {
      const offsetScaleCmpt = model.getScaleComponent(offsetChannel);
      const offsetScaleName = model.scaleName(offsetChannel);
      let stepCount = `domain('${offsetScaleName}').length`;
      if (offsetScaleCmpt.get("type") === "band") {
        const offsetPaddingInner = offsetScaleCmpt.get("paddingInner") ?? offsetScaleCmpt.get("padding") ?? 0;
        const offsetPaddingOuter = offsetScaleCmpt.get("paddingOuter") ?? offsetScaleCmpt.get("padding") ?? 0;
        stepCount = `bandspace(${stepCount}, ${offsetPaddingInner}, ${offsetPaddingOuter})`;
      }
      const paddingInner2 = mergedScaleCmpt.get("paddingInner") ?? mergedScaleCmpt.get("padding");
      return {
        signal: `${step.step} * ${stepCount} / (1-${exprFromSignalRefOrValue(paddingInner2)})`
      };
    } else {
      return step.step;
    }
  }
  function getOffsetStep(step, offsetScaleType) {
    const stepFor = getStepFor({ step, offsetIsDiscrete: hasDiscreteDomain(offsetScaleType) });
    if (stepFor === "offset") {
      return { step: step.step };
    }
    return void 0;
  }
  function getOffsetRange(channel, model, offsetScaleType) {
    const positionChannel = channel === XOFFSET ? "x" : "y";
    const positionScaleCmpt = model.getScaleComponent(positionChannel);
    if (!positionScaleCmpt) {
      return fullWidthOrHeightRange(positionChannel, model, offsetScaleType, { center: true });
    }
    const positionScaleType = positionScaleCmpt.get("type");
    const positionScaleName = model.scaleName(positionChannel);
    const { markDef, config } = model;
    if (positionScaleType === "band") {
      const size = getDiscretePositionSize(positionChannel, model.size, model.config.view);
      if (isStep(size)) {
        const step = getOffsetStep(size, offsetScaleType);
        if (step) {
          return step;
        }
      }
      return [0, { signal: `bandwidth('${positionScaleName}')` }];
    } else {
      const positionDef = model.encoding[positionChannel];
      if (isFieldDef(positionDef) && positionDef.timeUnit) {
        const duration = durationExpr(positionDef.timeUnit, (expr2) => `scale('${positionScaleName}', ${expr2})`);
        const padding3 = model.config.scale.bandWithNestedOffsetPaddingInner;
        const bandPositionOffset = getBandPosition({
          fieldDef: positionDef,
          markDef,
          config
        }) - 0.5;
        const bandPositionOffsetExpr = bandPositionOffset !== 0 ? ` + ${bandPositionOffset}` : "";
        if (padding3) {
          const startRatio = isSignalRef(padding3) ? `${padding3.signal}/2` + bandPositionOffsetExpr : `${padding3 / 2 + bandPositionOffset}`;
          const endRatio = isSignalRef(padding3) ? `(1 - ${padding3.signal}/2)` + bandPositionOffsetExpr : `${1 - padding3 / 2 + bandPositionOffset}`;
          return [{ signal: `${startRatio} * (${duration})` }, { signal: `${endRatio} * (${duration})` }];
        }
        return [0, { signal: duration }];
      }
      return never(`Cannot use ${channel} scale if ${positionChannel} scale is not discrete.`);
    }
  }
  function getDiscretePositionSize(channel, size, viewConfig) {
    const sizeChannel = channel === X3 ? "width" : "height";
    const sizeValue = size[sizeChannel];
    if (sizeValue) {
      return sizeValue;
    }
    return getViewConfigDiscreteSize(viewConfig, sizeChannel);
  }
  function defaultContinuousToDiscreteCount(scaleType2, config, domain4, channel) {
    switch (scaleType2) {
      case "quantile":
        return config.scale.quantileCount;
      case "quantize":
        return config.scale.quantizeCount;
      case "threshold":
        if (domain4 !== void 0 && isArray(domain4)) {
          return domain4.length + 1;
        } else {
          warn2(message_exports.domainRequiredForThresholdScale(channel));
          return 3;
        }
    }
  }
  function interpolateRange2(rangeMin2, rangeMax2, cardinality) {
    const f2 = () => {
      const rMax = signalOrStringValue(rangeMax2);
      const rMin = signalOrStringValue(rangeMin2);
      const step = `(${rMax} - ${rMin}) / (${cardinality} - 1)`;
      return `sequence(${rMin}, ${rMax} + ${step}, ${step})`;
    };
    if (isSignalRef(rangeMax2)) {
      return new SignalRefWrapper(f2);
    } else {
      return { signal: f2() };
    }
  }
  function sizeRangeMin(mark, config) {
    switch (mark) {
      case "bar":
      case "tick":
        return config.scale.minBandSize;
      case "line":
      case "trail":
      case "rule":
        return config.scale.minStrokeWidth;
      case "text":
        return config.scale.minFontSize;
      case "point":
      case "square":
      case "circle":
        return config.scale.minSize;
    }
    throw new Error(message_exports.incompatibleChannel("size", mark));
  }
  var MAX_SIZE_RANGE_STEP_RATIO = 0.95;
  function sizeRangeMax(mark, size, model, config) {
    const xyStepSignals = {
      x: getBinStepSignal(model, "x"),
      y: getBinStepSignal(model, "y")
    };
    switch (mark) {
      case "bar":
      case "tick": {
        if (config.scale.maxBandSize !== void 0) {
          return config.scale.maxBandSize;
        }
        const min4 = minXYStep(size, xyStepSignals, config.view);
        if (isNumber(min4)) {
          return min4 - 1;
        } else {
          return new SignalRefWrapper(() => `${min4.signal} - 1`);
        }
      }
      case "line":
      case "trail":
      case "rule":
        return config.scale.maxStrokeWidth;
      case "text":
        return config.scale.maxFontSize;
      case "point":
      case "square":
      case "circle": {
        if (config.scale.maxSize) {
          return config.scale.maxSize;
        }
        const pointStep = minXYStep(size, xyStepSignals, config.view);
        if (isNumber(pointStep)) {
          return Math.pow(MAX_SIZE_RANGE_STEP_RATIO * pointStep, 2);
        } else {
          return new SignalRefWrapper(() => `pow(${MAX_SIZE_RANGE_STEP_RATIO} * ${pointStep.signal}, 2)`);
        }
      }
    }
    throw new Error(message_exports.incompatibleChannel("size", mark));
  }
  function minXYStep(size, xyStepSignals, viewConfig) {
    const widthStep = isStep(size.width) ? size.width.step : getViewConfigDiscreteStep(viewConfig, "width");
    const heightStep = isStep(size.height) ? size.height.step : getViewConfigDiscreteStep(viewConfig, "height");
    if (xyStepSignals.x || xyStepSignals.y) {
      return new SignalRefWrapper(() => {
        const exprs = [
          xyStepSignals.x ? xyStepSignals.x.signal : widthStep,
          xyStepSignals.y ? xyStepSignals.y.signal : heightStep
        ];
        return `min(${exprs.join(", ")})`;
      });
    }
    return Math.min(widthStep, heightStep);
  }

  // node_modules/vega-lite/build/src/compile/scale/properties.js
  function parseScaleProperty(model, property2) {
    if (isUnitModel(model)) {
      parseUnitScaleProperty(model, property2);
    } else {
      parseNonUnitScaleProperty(model, property2);
    }
  }
  function parseUnitScaleProperty(model, property2) {
    const localScaleComponents = model.component.scales;
    const { config, encoding, markDef, specifiedScales } = model;
    for (const channel of keys3(localScaleComponents)) {
      const specifiedScale = specifiedScales[channel];
      const localScaleCmpt = localScaleComponents[channel];
      const mergedScaleCmpt = model.getScaleComponent(channel);
      const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
      const specifiedValue = specifiedScale[property2];
      const scaleType2 = mergedScaleCmpt.get("type");
      const scalePadding = mergedScaleCmpt.get("padding");
      const scalePaddingInner = mergedScaleCmpt.get("paddingInner");
      const supportedByScaleType = scaleTypeSupportProperty(scaleType2, property2);
      const channelIncompatability = channelScalePropertyIncompatability(channel, property2);
      if (specifiedValue !== void 0) {
        if (!supportedByScaleType) {
          warn2(message_exports.scalePropertyNotWorkWithScaleType(scaleType2, property2, channel));
        } else if (channelIncompatability) {
          warn2(channelIncompatability);
        }
      }
      if (supportedByScaleType && channelIncompatability === void 0) {
        if (specifiedValue !== void 0) {
          const timeUnit = fieldOrDatumDef.timeUnit;
          const type3 = fieldOrDatumDef.type;
          switch (property2) {
            // domainMax/Min to signal if the value is a datetime object
            case "domainMax":
            case "domainMin":
              if (isDateTime(specifiedScale[property2]) || type3 === "temporal" || timeUnit) {
                localScaleCmpt.set(property2, { signal: valueExpr(specifiedScale[property2], { type: type3, timeUnit }) }, true);
              } else {
                localScaleCmpt.set(property2, specifiedScale[property2], true);
              }
              break;
            default:
              localScaleCmpt.copyKeyFromObject(property2, specifiedScale);
          }
        } else {
          const value3 = hasProperty(scaleRules, property2) ? scaleRules[property2]({
            model,
            channel,
            fieldOrDatumDef,
            scaleType: scaleType2,
            scalePadding,
            scalePaddingInner,
            domain: specifiedScale.domain,
            domainMin: specifiedScale.domainMin,
            domainMax: specifiedScale.domainMax,
            markDef,
            config,
            hasNestedOffsetScale: channelHasNestedOffsetScale(encoding, channel),
            hasSecondaryRangeChannel: !!encoding[getSecondaryRangeChannel(channel)]
          }) : config.scale[property2];
          if (value3 !== void 0) {
            localScaleCmpt.set(property2, value3, false);
          }
        }
      }
    }
  }
  var scaleRules = {
    bins: ({ model, fieldOrDatumDef }) => isFieldDef(fieldOrDatumDef) ? bins(model, fieldOrDatumDef) : void 0,
    interpolate: ({ channel, fieldOrDatumDef }) => interpolate2(channel, fieldOrDatumDef.type),
    nice: ({ scaleType: scaleType2, channel, domain: domain4, domainMin, domainMax, fieldOrDatumDef }) => nice2(scaleType2, channel, domain4, domainMin, domainMax, fieldOrDatumDef),
    padding: ({ channel, scaleType: scaleType2, fieldOrDatumDef, markDef, config }) => padding2(channel, scaleType2, config.scale, fieldOrDatumDef, markDef, config.bar),
    paddingInner: ({ scalePadding, channel, markDef, scaleType: scaleType2, config, hasNestedOffsetScale }) => paddingInner(scalePadding, channel, markDef.type, scaleType2, config.scale, hasNestedOffsetScale),
    paddingOuter: ({ scalePadding, channel, scaleType: scaleType2, scalePaddingInner, config, hasNestedOffsetScale }) => paddingOuter(scalePadding, channel, scaleType2, scalePaddingInner, config.scale, hasNestedOffsetScale),
    reverse: ({ fieldOrDatumDef, scaleType: scaleType2, channel, config }) => {
      const sort3 = isFieldDef(fieldOrDatumDef) ? fieldOrDatumDef.sort : void 0;
      return reverse2(scaleType2, sort3, channel, config.scale);
    },
    zero: ({ channel, fieldOrDatumDef, domain: domain4, markDef, scaleType: scaleType2, config, hasSecondaryRangeChannel }) => zero5(channel, fieldOrDatumDef, domain4, markDef, scaleType2, config.scale, hasSecondaryRangeChannel)
  };
  function parseScaleRange2(model) {
    if (isUnitModel(model)) {
      parseUnitScaleRange(model);
    } else {
      parseNonUnitScaleProperty(model, "range");
    }
  }
  function parseNonUnitScaleProperty(model, property2) {
    const localScaleComponents = model.component.scales;
    for (const child of model.children) {
      if (property2 === "range") {
        parseScaleRange2(child);
      } else {
        parseScaleProperty(child, property2);
      }
    }
    for (const channel of keys3(localScaleComponents)) {
      let valueWithExplicit;
      for (const child of model.children) {
        const childComponent = child.component.scales[channel];
        if (childComponent) {
          const childValueWithExplicit = childComponent.getWithExplicit(property2);
          valueWithExplicit = mergeValuesWithExplicit(valueWithExplicit, childValueWithExplicit, property2, "scale", tieBreakByComparing((v1, v22) => {
            switch (property2) {
              case "range":
                if (v1.step && v22.step) {
                  return v1.step - v22.step;
                }
                return 0;
            }
            return 0;
          }));
        }
      }
      localScaleComponents[channel].setWithExplicit(property2, valueWithExplicit);
    }
  }
  function bins(model, fieldDef) {
    const bin3 = fieldDef.bin;
    if (isBinning(bin3)) {
      const binSignal = getBinSignalName(model, fieldDef.field, bin3);
      return new SignalRefWrapper(() => {
        return model.getSignalName(binSignal);
      });
    } else if (isBinned(bin3) && isBinParams(bin3) && bin3.step !== void 0) {
      return {
        step: bin3.step
      };
    }
    return void 0;
  }
  function interpolate2(channel, type3) {
    if (contains2([COLOR, FILL, STROKE], channel) && type3 !== "nominal") {
      return "hcl";
    }
    return void 0;
  }
  function nice2(scaleType2, channel, specifiedDomain, domainMin, domainMax, fieldOrDatumDef) {
    if (getFieldDef(fieldOrDatumDef)?.bin || isArray(specifiedDomain) || domainMax != null || domainMin != null || contains2([ScaleType.TIME, ScaleType.UTC], scaleType2)) {
      return void 0;
    }
    return isXorY(channel) ? true : void 0;
  }
  function padding2(channel, scaleType2, scaleConfig, fieldOrDatumDef, markDef, barConfig) {
    if (isXorY(channel)) {
      if (isContinuousToContinuous(scaleType2)) {
        if (scaleConfig.continuousPadding !== void 0) {
          return scaleConfig.continuousPadding;
        }
        const { type: type3, orient: orient2 } = markDef;
        if (type3 === "bar" && !(isFieldDef(fieldOrDatumDef) && (fieldOrDatumDef.bin || fieldOrDatumDef.timeUnit))) {
          if (orient2 === "vertical" && channel === "x" || orient2 === "horizontal" && channel === "y") {
            return barConfig.continuousBandSize;
          }
        }
      }
      if (scaleType2 === ScaleType.POINT) {
        return scaleConfig.pointPadding;
      }
    }
    return void 0;
  }
  function paddingInner(paddingValue, channel, mark, scaleType2, scaleConfig, hasNestedOffsetScale = false) {
    if (paddingValue !== void 0) {
      return void 0;
    }
    if (isXorY(channel)) {
      const { bandPaddingInner, barBandPaddingInner, rectBandPaddingInner, tickBandPaddingInner, bandWithNestedOffsetPaddingInner } = scaleConfig;
      if (hasNestedOffsetScale) {
        return bandWithNestedOffsetPaddingInner;
      }
      return getFirstDefined(bandPaddingInner, mark === "bar" ? barBandPaddingInner : mark === "tick" ? tickBandPaddingInner : rectBandPaddingInner);
    } else if (isXorYOffset(channel)) {
      if (scaleType2 === ScaleType.BAND) {
        return scaleConfig.offsetBandPaddingInner;
      }
    }
    return void 0;
  }
  function paddingOuter(paddingValue, channel, scaleType2, paddingInnerValue, scaleConfig, hasNestedOffsetScale = false) {
    if (paddingValue !== void 0) {
      return void 0;
    }
    if (isXorY(channel)) {
      const { bandPaddingOuter, bandWithNestedOffsetPaddingOuter } = scaleConfig;
      if (hasNestedOffsetScale) {
        return bandWithNestedOffsetPaddingOuter;
      }
      if (scaleType2 === ScaleType.BAND) {
        return getFirstDefined(
          bandPaddingOuter,
          /* By default, paddingOuter is paddingInner / 2. The reason is that
            size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter).
            and we want the width/height to be integer by default.
            Note that step (by default) and cardinality are integers.) */
          isSignalRef(paddingInnerValue) ? { signal: `${paddingInnerValue.signal}/2` } : paddingInnerValue / 2
        );
      }
    } else if (isXorYOffset(channel)) {
      if (scaleType2 === ScaleType.POINT) {
        return 0.5;
      } else if (scaleType2 === ScaleType.BAND) {
        return scaleConfig.offsetBandPaddingOuter;
      }
    }
    return void 0;
  }
  function reverse2(scaleType2, sort3, channel, scaleConfig) {
    if (channel === "x" && scaleConfig.xReverse !== void 0) {
      if (hasContinuousDomain(scaleType2) && sort3 === "descending") {
        if (isSignalRef(scaleConfig.xReverse)) {
          return { signal: `!${scaleConfig.xReverse.signal}` };
        } else {
          return !scaleConfig.xReverse;
        }
      }
      return scaleConfig.xReverse;
    }
    if (hasContinuousDomain(scaleType2) && sort3 === "descending") {
      return true;
    }
    return void 0;
  }
  function zero5(channel, fieldDef, specifiedDomain, markDef, scaleType2, scaleConfig, hasSecondaryRangeChannel) {
    const hasCustomDomain = !!specifiedDomain && specifiedDomain !== "unaggregated";
    if (hasCustomDomain) {
      if (hasContinuousDomain(scaleType2)) {
        if (isArray(specifiedDomain)) {
          const first = specifiedDomain[0];
          const last = specifiedDomain[specifiedDomain.length - 1];
          if (isNumber(first) && first <= 0 && isNumber(last) && last >= 0) {
            return true;
          }
        }
        return false;
      }
    }
    if (channel === "size" && fieldDef.type === "quantitative" && !isContinuousToDiscrete(scaleType2)) {
      return true;
    }
    if (!(isFieldDef(fieldDef) && fieldDef.bin) && contains2([...POSITION_SCALE_CHANNELS, ...POLAR_POSITION_SCALE_CHANNELS], channel)) {
      const { orient: orient2, type: type3 } = markDef;
      if (contains2(["bar", "area", "line", "trail"], type3)) {
        if (orient2 === "horizontal" && channel === "y" || orient2 === "vertical" && channel === "x") {
          return false;
        }
      }
      if (contains2(["bar", "area"], type3) && !hasSecondaryRangeChannel) {
        return true;
      }
      return scaleConfig?.zero;
    }
    return false;
  }

  // node_modules/vega-lite/build/src/compile/scale/type.js
  function scaleType(specifiedScale, channel, fieldDef, mark, hasNestedOffsetScale = false) {
    const defaultScaleType = defaultType3(channel, fieldDef, mark, hasNestedOffsetScale);
    const { type: type3 } = specifiedScale;
    if (!isScaleChannel(channel)) {
      return null;
    }
    if (type3 !== void 0) {
      if (!channelSupportScaleType(channel, type3)) {
        warn2(message_exports.scaleTypeNotWorkWithChannel(channel, type3, defaultScaleType));
        return defaultScaleType;
      }
      if (isFieldDef(fieldDef) && !scaleTypeSupportDataType(type3, fieldDef.type)) {
        warn2(message_exports.scaleTypeNotWorkWithFieldDef(type3, defaultScaleType));
        return defaultScaleType;
      }
      return type3;
    }
    return defaultScaleType;
  }
  function defaultType3(channel, fieldDef, mark, hasNestedOffsetScale) {
    switch (fieldDef.type) {
      case "nominal":
      case "ordinal": {
        if (isColorChannel(channel) || rangeType(channel) === "discrete") {
          if (channel === "shape" && fieldDef.type === "ordinal") {
            warn2(message_exports.discreteChannelCannotEncode(channel, "ordinal"));
          }
          return "ordinal";
        }
        if (isTime(channel)) {
          return "band";
        }
        if (isXorY(channel) || isXorYOffset(channel)) {
          if (contains2(["rect", "bar", "image", "rule", "tick"], mark.type)) {
            return "band";
          }
          if (hasNestedOffsetScale) {
            return "band";
          }
        } else if (mark.type === "arc" && channel in POLAR_POSITION_SCALE_CHANNEL_INDEX) {
          return "band";
        }
        const dimensionSize = mark[getSizeChannel(channel)];
        if (isRelativeBandSize(dimensionSize)) {
          return "band";
        }
        if (isPositionFieldOrDatumDef(fieldDef) && fieldDef.axis?.tickBand) {
          return "band";
        }
        return "point";
      }
      case "temporal":
        if (isColorChannel(channel)) {
          return "time";
        } else if (rangeType(channel) === "discrete") {
          warn2(message_exports.discreteChannelCannotEncode(channel, "temporal"));
          return "ordinal";
        } else if (isFieldDef(fieldDef) && fieldDef.timeUnit && normalizeTimeUnit(fieldDef.timeUnit).utc) {
          return "utc";
        } else if (isTime(channel)) {
          return "band";
        }
        return "time";
      case "quantitative":
        if (isColorChannel(channel)) {
          if (isFieldDef(fieldDef) && isBinning(fieldDef.bin)) {
            return "bin-ordinal";
          }
          return "linear";
        } else if (rangeType(channel) === "discrete") {
          warn2(message_exports.discreteChannelCannotEncode(channel, "quantitative"));
          return "ordinal";
        } else if (isTime(channel)) {
          return "band";
        }
        return "linear";
      case "geojson":
        return void 0;
    }
    throw new Error(message_exports.invalidFieldType(fieldDef.type));
  }

  // node_modules/vega-lite/build/src/compile/scale/parse.js
  function parseScales(model, { ignoreRange } = {}) {
    parseScaleCore(model);
    parseScaleDomain2(model);
    for (const prop of NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES) {
      parseScaleProperty(model, prop);
    }
    if (!ignoreRange) {
      parseScaleRange2(model);
    }
  }
  function parseScaleCore(model) {
    if (isUnitModel(model)) {
      model.component.scales = parseUnitScaleCore(model);
    } else {
      model.component.scales = parseNonUnitScaleCore(model);
    }
  }
  function parseUnitScaleCore(model) {
    const { encoding, mark, markDef } = model;
    const scaleComponents = {};
    for (const channel of SCALE_CHANNELS) {
      const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
      if (fieldOrDatumDef && mark === GEOSHAPE && channel === SHAPE && fieldOrDatumDef.type === GEOJSON) {
        continue;
      }
      let specifiedScale = fieldOrDatumDef && fieldOrDatumDef.scale;
      if (fieldOrDatumDef && specifiedScale !== null && specifiedScale !== false) {
        specifiedScale ?? (specifiedScale = {});
        const hasNestedOffsetScale = channelHasNestedOffsetScale(encoding, channel);
        const sType = scaleType(specifiedScale, channel, fieldOrDatumDef, markDef, hasNestedOffsetScale);
        scaleComponents[channel] = new ScaleComponent(model.scaleName(`${channel}`, true), {
          value: sType,
          explicit: specifiedScale.type === sType
        });
      }
    }
    return scaleComponents;
  }
  var scaleTypeTieBreaker = tieBreakByComparing((st1, st2) => scaleTypePrecedence(st1) - scaleTypePrecedence(st2));
  function parseNonUnitScaleCore(model) {
    var _a2;
    const scaleComponents = model.component.scales = {};
    const scaleTypeWithExplicitIndex = {};
    const resolve2 = model.component.resolve;
    for (const child of model.children) {
      parseScaleCore(child);
      for (const channel of keys3(child.component.scales)) {
        (_a2 = resolve2.scale)[channel] ?? (_a2[channel] = defaultScaleResolve(channel, model));
        if (resolve2.scale[channel] === "shared") {
          const explicitScaleType = scaleTypeWithExplicitIndex[channel];
          const childScaleType = child.component.scales[channel].getWithExplicit("type");
          if (explicitScaleType) {
            if (scaleCompatible(explicitScaleType.value, childScaleType.value)) {
              scaleTypeWithExplicitIndex[channel] = mergeValuesWithExplicit(explicitScaleType, childScaleType, "type", "scale", scaleTypeTieBreaker);
            } else {
              resolve2.scale[channel] = "independent";
              delete scaleTypeWithExplicitIndex[channel];
            }
          } else {
            scaleTypeWithExplicitIndex[channel] = childScaleType;
          }
        }
      }
    }
    for (const channel of keys3(scaleTypeWithExplicitIndex)) {
      const name4 = model.scaleName(channel, true);
      const typeWithExplicit = scaleTypeWithExplicitIndex[channel];
      scaleComponents[channel] = new ScaleComponent(name4, typeWithExplicit);
      for (const child of model.children) {
        const childScale = child.component.scales[channel];
        if (childScale) {
          child.renameScale(childScale.get("name"), name4);
          childScale.merged = true;
        }
      }
    }
    return scaleComponents;
  }

  // node_modules/vega-lite/build/src/compile/model.js
  var NameMap = class {
    constructor() {
      this.nameMap = {};
    }
    rename(oldName, newName) {
      this.nameMap[oldName] = newName;
    }
    has(name4) {
      return this.nameMap[name4] !== void 0;
    }
    get(name4) {
      while (this.nameMap[name4] && name4 !== this.nameMap[name4]) {
        name4 = this.nameMap[name4];
      }
      return name4;
    }
  };
  function isUnitModel(model) {
    return model?.type === "unit";
  }
  function isFacetModel(model) {
    return model?.type === "facet";
  }
  function isConcatModel(model) {
    return model?.type === "concat";
  }
  function isLayerModel(model) {
    return model?.type === "layer";
  }
  var Model = class {
    constructor(spec, type3, parent, parentGivenName, config, resolve2, view) {
      this.type = type3;
      this.parent = parent;
      this.config = config;
      this.parent = parent;
      this.config = config;
      this.view = replaceExprRef(view);
      this.name = spec.name ?? parentGivenName;
      this.title = isText(spec.title) ? { text: spec.title } : spec.title ? replaceExprRef(spec.title) : void 0;
      this.scaleNameMap = parent ? parent.scaleNameMap : new NameMap();
      this.projectionNameMap = parent ? parent.projectionNameMap : new NameMap();
      this.signalNameMap = parent ? parent.signalNameMap : new NameMap();
      this.data = spec.data;
      this.description = spec.description;
      this.transforms = normalizeTransform(spec.transform ?? []);
      this.layout = type3 === "layer" || type3 === "unit" ? {} : extractCompositionLayout(spec, type3, config);
      this.component = {
        data: {
          sources: parent ? parent.component.data.sources : [],
          outputNodes: parent ? parent.component.data.outputNodes : {},
          outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {},
          // data is faceted if the spec is a facet spec or the parent has faceted data and data is undefined
          isFaceted: isFacetSpec(spec) || parent?.component.data.isFaceted && spec.data === void 0
        },
        layoutSize: new Split(),
        layoutHeaders: { row: {}, column: {}, facet: {} },
        mark: null,
        resolve: {
          scale: {},
          axis: {},
          legend: {},
          ...resolve2 ? duplicate(resolve2) : {}
        },
        selection: null,
        scales: null,
        projection: null,
        axes: {},
        legends: {}
      };
    }
    get width() {
      return this.getSizeSignalRef("width");
    }
    get height() {
      return this.getSizeSignalRef("height");
    }
    parse() {
      this.parseScale();
      this.parseLayoutSize();
      this.renameTopLevelLayoutSizeSignal();
      this.parseSelections();
      this.parseProjection();
      this.parseData();
      this.parseAxesAndHeaders();
      this.parseLegends();
      this.parseMarkGroup();
    }
    parseScale() {
      parseScales(this);
    }
    parseProjection() {
      parseProjection2(this);
    }
    /**
     * Rename top-level spec's size to be just width / height, ignoring model name.
     * This essentially merges the top-level spec's width/height signals with the width/height signals
     * to help us reduce redundant signals declaration.
     */
    renameTopLevelLayoutSizeSignal() {
      if (this.getName("width") !== "width") {
        this.renameSignal(this.getName("width"), "width");
      }
      if (this.getName("height") !== "height") {
        this.renameSignal(this.getName("height"), "height");
      }
    }
    parseLegends() {
      parseLegend2(this);
    }
    assembleEncodeFromView(view) {
      const { style: _, ...baseView } = view;
      const e4 = {};
      for (const property2 of keys3(baseView)) {
        const value3 = baseView[property2];
        if (value3 !== void 0) {
          e4[property2] = signalOrValueRef(value3);
        }
      }
      return e4;
    }
    assembleGroupEncodeEntry(isTopLevel) {
      let encodeEntry2 = {};
      if (this.view) {
        encodeEntry2 = this.assembleEncodeFromView(this.view);
      }
      if (!isTopLevel) {
        if (this.description) {
          encodeEntry2["description"] = signalOrValueRef(this.description);
        }
        if (this.type === "unit" || this.type === "layer") {
          return {
            width: this.getSizeSignalRef("width"),
            height: this.getSizeSignalRef("height"),
            ...encodeEntry2
          };
        }
      }
      return isEmpty(encodeEntry2) ? void 0 : encodeEntry2;
    }
    assembleLayout() {
      if (!this.layout) {
        return void 0;
      }
      const { spacing, ...layout } = this.layout;
      const { component, config } = this;
      const titleBand = assembleLayoutTitleBand(component.layoutHeaders, config);
      return {
        padding: spacing,
        ...this.assembleDefaultLayout(),
        ...layout,
        ...titleBand ? { titleBand } : {}
      };
    }
    assembleDefaultLayout() {
      return {};
    }
    assembleHeaderMarks() {
      const { layoutHeaders: layoutHeaders2 } = this.component;
      let headerMarks = [];
      for (const channel of FACET_CHANNELS) {
        if (layoutHeaders2[channel].title) {
          headerMarks.push(assembleTitleGroup(this, channel));
        }
      }
      for (const channel of HEADER_CHANNELS) {
        headerMarks = headerMarks.concat(assembleHeaderGroups(this, channel));
      }
      return headerMarks;
    }
    assembleAxes() {
      return assembleAxes(this.component.axes, this.config);
    }
    assembleLegends() {
      return assembleLegends(this);
    }
    assembleProjections() {
      return assembleProjections(this);
    }
    assembleTitle() {
      const { encoding, ...titleNoEncoding } = this.title ?? {};
      const title2 = {
        ...extractTitleConfig(this.config.title).nonMarkTitleProperties,
        ...titleNoEncoding,
        ...encoding ? { encode: { update: encoding } } : {}
      };
      if (title2.text) {
        if (contains2(["unit", "layer"], this.type)) {
          if (contains2(["middle", void 0], title2.anchor)) {
            title2.frame ?? (title2.frame = "group");
          }
        } else {
          title2.anchor ?? (title2.anchor = "start");
        }
        return isEmpty(title2) ? void 0 : title2;
      }
      return void 0;
    }
    /**
     * Assemble the mark group for this model. We accept optional `signals` so that we can include concat top-level signals with the top-level model's local signals.
     */
    assembleGroup(signals = []) {
      const group2 = {};
      signals = signals.concat(this.assembleSignals());
      if (signals.length > 0) {
        group2.signals = signals;
      }
      const layout = this.assembleLayout();
      if (layout) {
        group2.layout = layout;
      }
      group2.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks());
      const scales2 = !this.parent || isFacetModel(this.parent) ? assembleScales(this) : [];
      if (scales2.length > 0) {
        group2.scales = scales2;
      }
      const axes = this.assembleAxes();
      if (axes.length > 0) {
        group2.axes = axes;
      }
      const legends = this.assembleLegends();
      if (legends.length > 0) {
        group2.legends = legends;
      }
      return group2;
    }
    getName(text4) {
      return varName((this.name ? `${this.name}_` : "") + text4);
    }
    getDataName(type3) {
      return this.getName(DataSourceType[type3].toLowerCase());
    }
    /**
     * Request a data source name for the given data source type and mark that data source as required.
     * This method should be called in parse, so that all used data source can be correctly instantiated in assembleData().
     * You can lookup the correct dataset name in assemble with `lookupDataSource`.
     */
    requestDataName(name4) {
      const fullName = this.getDataName(name4);
      const refCounts = this.component.data.outputNodeRefCounts;
      refCounts[fullName] = (refCounts[fullName] || 0) + 1;
      return fullName;
    }
    getSizeSignalRef(layoutSizeType) {
      if (isFacetModel(this.parent)) {
        const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);
        const channel = getPositionScaleChannel(sizeType);
        const scaleComponent = this.component.scales[channel];
        if (scaleComponent && !scaleComponent.merged) {
          const type3 = scaleComponent.get("type");
          const range7 = scaleComponent.get("range");
          if (hasDiscreteDomain(type3) && isVgRangeStep(range7)) {
            const scaleName = scaleComponent.get("name");
            const domain4 = assembleDomain(this, channel);
            const field3 = getFieldFromDomain(domain4);
            if (field3) {
              const fieldRef2 = vgField({ aggregate: "distinct", field: field3 }, { expr: "datum" });
              return {
                signal: sizeExpr(scaleName, scaleComponent, fieldRef2)
              };
            } else {
              warn2(message_exports.unknownField(channel));
              return null;
            }
          }
        }
      }
      return {
        signal: this.signalNameMap.get(this.getName(layoutSizeType))
      };
    }
    /**
     * Lookup the name of the datasource for an output node. You probably want to call this in assemble.
     */
    lookupDataSource(name4) {
      const node = this.component.data.outputNodes[name4];
      if (!node) {
        return name4;
      }
      return node.getSource();
    }
    getSignalName(oldSignalName) {
      return this.signalNameMap.get(oldSignalName);
    }
    renameSignal(oldName, newName) {
      this.signalNameMap.rename(oldName, newName);
    }
    renameScale(oldName, newName) {
      this.scaleNameMap.rename(oldName, newName);
    }
    renameProjection(oldName, newName) {
      this.projectionNameMap.rename(oldName, newName);
    }
    /**
     * @return scale name for a given channel after the scale has been parsed and named.
     */
    scaleName(originalScaleName, parse7) {
      if (parse7) {
        return this.getName(originalScaleName);
      }
      if (
        // If there is a scale for the channel, there should be a local scale component for it
        isChannel(originalScaleName) && isScaleChannel(originalScaleName) && this.component.scales[originalScaleName] || // in the scale name map (the scale get merged by its parent)
        this.scaleNameMap.has(this.getName(originalScaleName))
      ) {
        return this.scaleNameMap.get(this.getName(originalScaleName));
      }
      return void 0;
    }
    /**
     * @return projection name after the projection has been parsed and named.
     */
    projectionName(parse7) {
      if (parse7) {
        return this.getName("projection");
      }
      if (this.component.projection && !this.component.projection.merged || this.projectionNameMap.has(this.getName("projection"))) {
        return this.projectionNameMap.get(this.getName("projection"));
      }
      return void 0;
    }
    /**
     * Traverse a model's hierarchy to get the scale component for a particular channel.
     */
    getScaleComponent(channel) {
      if (!this.component.scales) {
        throw new Error("getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().");
      }
      const localScaleComponent = this.component.scales[channel];
      if (localScaleComponent && !localScaleComponent.merged) {
        return localScaleComponent;
      }
      return this.parent ? this.parent.getScaleComponent(channel) : void 0;
    }
    getScaleType(channel) {
      const scaleComponent = this.getScaleComponent(channel);
      return scaleComponent ? scaleComponent.get("type") : void 0;
    }
    /**
     * Traverse a model's hierarchy to get a particular selection component.
     */
    getSelectionComponent(variableName, origName) {
      let sel = this.component.selection[variableName];
      if (!sel && this.parent) {
        sel = this.parent.getSelectionComponent(variableName, origName);
      }
      if (!sel) {
        throw new Error(message_exports.selectionNotFound(origName));
      }
      return sel;
    }
    /**
     * Returns true if the model has a signalRef for an axis orient.
     */
    hasAxisOrientSignalRef() {
      return this.component.axes.x?.some((a4) => a4.hasOrientSignalRef()) || this.component.axes.y?.some((a4) => a4.hasOrientSignalRef());
    }
  };
  var ModelWithField = class extends Model {
    /** Get "field" reference for Vega */
    vgField(channel, opt = {}) {
      const fieldDef = this.fieldDef(channel);
      if (!fieldDef) {
        return void 0;
      }
      return vgField(fieldDef, opt);
    }
    reduceFieldDef(f2, init2) {
      return reduce(this.getMapping(), (acc, cd2, c4) => {
        const fieldDef = getFieldDef(cd2);
        if (fieldDef) {
          return f2(acc, fieldDef, c4);
        }
        return acc;
      }, init2);
    }
    forEachFieldDef(f2, t4) {
      forEach(this.getMapping(), (cd2, c4) => {
        const fieldDef = getFieldDef(cd2);
        if (fieldDef) {
          f2(fieldDef, c4);
        }
      }, t4);
    }
  };

  // node_modules/vega-lite/build/src/compile/data/density.js
  var DensityTransformNode = class _DensityTransformNode extends DataFlowNode {
    clone() {
      return new _DensityTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const specifiedAs = this.transform.as ?? [void 0, void 0];
      this.transform.as = [specifiedAs[0] ?? "value", specifiedAs[1] ?? "density"];
      const resolve2 = this.transform.resolve ?? "shared";
      this.transform.resolve = resolve2;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.density, ...this.transform.groupby ?? []]);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `DensityTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { density, ...rest } = this.transform;
      const result = {
        type: "kde",
        field: density,
        ...rest
      };
      result.resolve = this.transform.resolve;
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/extent.js
  var ExtentTransformNode = class _ExtentTransformNode extends DataFlowNode {
    clone() {
      return new _ExtentTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.extent]);
    }
    producedFields() {
      return /* @__PURE__ */ new Set([]);
    }
    hash() {
      return `ExtentTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { extent: extent2, param: param2 } = this.transform;
      const result = {
        type: "extent",
        field: extent2,
        signal: param2
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/flatten.js
  var FlattenTransformNode = class _FlattenTransformNode extends DataFlowNode {
    clone() {
      return new _FlattenTransformNode(this.parent, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const { flatten: flatten2, as = [] } = this.transform;
      this.transform.as = flatten2.map((f2, i2) => as[i2] ?? f2);
    }
    dependentFields() {
      return new Set(this.transform.flatten);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `FlattenTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { flatten: fields, as } = this.transform;
      const result = {
        type: "flatten",
        fields,
        as
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/fold.js
  var FoldTransformNode = class _FoldTransformNode extends DataFlowNode {
    clone() {
      return new _FoldTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const specifiedAs = this.transform.as ?? [void 0, void 0];
      this.transform.as = [specifiedAs[0] ?? "key", specifiedAs[1] ?? "value"];
    }
    dependentFields() {
      return new Set(this.transform.fold);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `FoldTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { fold, as } = this.transform;
      const result = {
        type: "fold",
        fields: fold,
        as
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/geojson.js
  var GeoJSONNode = class _GeoJSONNode extends DataFlowNode {
    clone() {
      return new _GeoJSONNode(null, duplicate(this.fields), this.geojson, this.signal);
    }
    static parseAll(parent, model) {
      if (model.component.projection && !model.component.projection.isFit) {
        return parent;
      }
      let geoJsonCounter = 0;
      for (const coordinates of [
        [LONGITUDE, LATITUDE],
        [LONGITUDE2, LATITUDE2]
      ]) {
        const pair = coordinates.map((channel) => {
          const def2 = getFieldOrDatumDef(model.encoding[channel]);
          return isFieldDef(def2) ? def2.field : isDatumDef(def2) ? { expr: `${def2.datum}` } : isValueDef(def2) ? { expr: `${def2["value"]}` } : void 0;
        });
        if (pair[0] || pair[1]) {
          parent = new _GeoJSONNode(parent, pair, null, model.getName(`geojson_${geoJsonCounter++}`));
        }
      }
      if (model.channelHasField(SHAPE)) {
        const fieldDef = model.typedFieldDef(SHAPE);
        if (fieldDef.type === GEOJSON) {
          parent = new _GeoJSONNode(parent, null, fieldDef.field, model.getName(`geojson_${geoJsonCounter++}`));
        }
      }
      return parent;
    }
    constructor(parent, fields, geojson, signal) {
      super(parent);
      this.fields = fields;
      this.geojson = geojson;
      this.signal = signal;
    }
    dependentFields() {
      const fields = (this.fields ?? []).filter(isString);
      return /* @__PURE__ */ new Set([...this.geojson ? [this.geojson] : [], ...fields]);
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    hash() {
      return `GeoJSON ${this.geojson} ${this.signal} ${hash(this.fields)}`;
    }
    assemble() {
      return [
        ...this.geojson ? [
          {
            type: "filter",
            expr: `isValid(datum["${this.geojson}"])`
          }
        ] : [],
        {
          type: "geojson",
          ...this.fields ? { fields: this.fields } : {},
          ...this.geojson ? { geojson: this.geojson } : {},
          signal: this.signal
        }
      ];
    }
  };

  // node_modules/vega-lite/build/src/compile/data/geopoint.js
  var GeoPointNode = class _GeoPointNode extends DataFlowNode {
    clone() {
      return new _GeoPointNode(null, this.projection, duplicate(this.fields), duplicate(this.as));
    }
    constructor(parent, projection3, fields, as) {
      super(parent);
      this.projection = projection3;
      this.fields = fields;
      this.as = as;
    }
    static parseAll(parent, model) {
      if (!model.projectionName()) {
        return parent;
      }
      for (const coordinates of [
        [LONGITUDE, LATITUDE],
        [LONGITUDE2, LATITUDE2]
      ]) {
        const pair = coordinates.map((channel) => {
          const def2 = getFieldOrDatumDef(model.encoding[channel]);
          return isFieldDef(def2) ? def2.field : isDatumDef(def2) ? { expr: `${def2.datum}` } : isValueDef(def2) ? { expr: `${def2["value"]}` } : void 0;
        });
        const suffix = coordinates[0] === LONGITUDE2 ? "2" : "";
        if (pair[0] || pair[1]) {
          parent = new _GeoPointNode(parent, model.projectionName(), pair, [
            model.getName(`x${suffix}`),
            model.getName(`y${suffix}`)
          ]);
        }
      }
      return parent;
    }
    dependentFields() {
      return new Set(this.fields.filter(isString));
    }
    producedFields() {
      return new Set(this.as);
    }
    hash() {
      return `Geopoint ${this.projection} ${hash(this.fields)} ${hash(this.as)}`;
    }
    assemble() {
      return {
        type: "geopoint",
        projection: this.projection,
        fields: this.fields,
        as: this.as
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/impute.js
  var ImputeNode = class _ImputeNode extends DataFlowNode {
    clone() {
      return new _ImputeNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.impute, this.transform.key, ...this.transform.groupby ?? []]);
    }
    producedFields() {
      return /* @__PURE__ */ new Set([this.transform.impute]);
    }
    processSequence(keyvals) {
      const { start = 0, stop: stop2, step } = keyvals;
      const result = [start, stop2, ...step ? [step] : []].join(",");
      return { signal: `sequence(${result})` };
    }
    static makeFromTransform(parent, imputeTransform) {
      return new _ImputeNode(parent, imputeTransform);
    }
    static makeFromEncoding(parent, model) {
      const encoding = model.encoding;
      const xDef = encoding.x;
      const yDef = encoding.y;
      if (isFieldDef(xDef) && isFieldDef(yDef)) {
        const imputedChannel = xDef.impute ? xDef : yDef.impute ? yDef : void 0;
        if (imputedChannel === void 0) {
          return void 0;
        }
        const keyChannel = xDef.impute ? yDef : yDef.impute ? xDef : void 0;
        const { method: method2, value: value3, frame: frame2, keyvals } = imputedChannel.impute;
        const groupbyFields = pathGroupingFields(model.mark, encoding);
        return new _ImputeNode(parent, {
          impute: imputedChannel.field,
          key: keyChannel.field,
          ...method2 ? { method: method2 } : {},
          ...value3 !== void 0 ? { value: value3 } : {},
          ...frame2 ? { frame: frame2 } : {},
          ...keyvals !== void 0 ? { keyvals } : {},
          ...groupbyFields.length ? { groupby: groupbyFields } : {}
        });
      }
      return null;
    }
    hash() {
      return `Impute ${hash(this.transform)}`;
    }
    assemble() {
      const { impute, key: key2, keyvals, method: method2, groupby, value: value3, frame: frame2 = [null, null] } = this.transform;
      const imputeTransform = {
        type: "impute",
        field: impute,
        key: key2,
        ...keyvals ? { keyvals: isImputeSequence(keyvals) ? this.processSequence(keyvals) : keyvals } : {},
        method: "value",
        ...groupby ? { groupby } : {},
        value: !method2 || method2 === "value" ? value3 : null
      };
      if (method2 && method2 !== "value") {
        const deriveNewField = {
          type: "window",
          as: [`imputed_${impute}_value`],
          ops: [method2],
          fields: [impute],
          frame: frame2,
          ignorePeers: false,
          ...groupby ? { groupby } : {}
        };
        const replaceOriginal = {
          type: "formula",
          expr: `datum.${impute} === null ? datum.imputed_${impute}_value : datum.${impute}`,
          as: impute
        };
        return [imputeTransform, deriveNewField, replaceOriginal];
      } else {
        return [imputeTransform];
      }
    }
  };

  // node_modules/vega-lite/build/src/compile/data/loess.js
  var LoessTransformNode = class _LoessTransformNode extends DataFlowNode {
    clone() {
      return new _LoessTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const specifiedAs = this.transform.as ?? [void 0, void 0];
      this.transform.as = [specifiedAs[0] ?? transform4.on, specifiedAs[1] ?? transform4.loess];
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.loess, this.transform.on, ...this.transform.groupby ?? []]);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `LoessTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { loess: loess2, on: on2, ...rest } = this.transform;
      const result = {
        type: "loess",
        x: on2,
        y: loess2,
        ...rest
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/lookup.js
  var LookupNode = class _LookupNode extends DataFlowNode {
    clone() {
      return new _LookupNode(null, duplicate(this.transform), this.secondary);
    }
    constructor(parent, transform4, secondary) {
      super(parent);
      this.transform = transform4;
      this.secondary = secondary;
    }
    static make(parent, model, transform4, counter) {
      const sources = model.component.data.sources;
      const { from } = transform4;
      let fromOutputNode = null;
      if (isLookupData(from)) {
        let fromSource = findSource(from.data, sources);
        if (!fromSource) {
          fromSource = new SourceNode(from.data);
          sources.push(fromSource);
        }
        const fromOutputName = model.getName(`lookup_${counter}`);
        fromOutputNode = new OutputNode(fromSource, fromOutputName, DataSourceType.Lookup, model.component.data.outputNodeRefCounts);
        model.component.data.outputNodes[fromOutputName] = fromOutputNode;
      } else if (isLookupSelection(from)) {
        const selName = from.param;
        transform4 = { as: selName, ...transform4 };
        let selCmpt;
        try {
          selCmpt = model.getSelectionComponent(varName(selName), selName);
        } catch (e4) {
          throw new Error(message_exports.cannotLookupVariableParameter(selName));
        }
        fromOutputNode = selCmpt.materialized;
        if (!fromOutputNode) {
          throw new Error(message_exports.noSameUnitLookup(selName));
        }
      }
      return new _LookupNode(parent, transform4, fromOutputNode.getSource());
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.lookup]);
    }
    producedFields() {
      return new Set(this.transform.as ? array(this.transform.as) : this.transform.from.fields);
    }
    hash() {
      return `Lookup ${hash({ transform: this.transform, secondary: this.secondary })}`;
    }
    assemble() {
      let foreign;
      if (this.transform.from.fields) {
        foreign = {
          values: this.transform.from.fields,
          ...this.transform.as ? { as: array(this.transform.as) } : {}
        };
      } else {
        let asName = this.transform.as;
        if (!isString(asName)) {
          warn2(message_exports.NO_FIELDS_NEEDS_AS);
          asName = "_lookup";
        }
        foreign = {
          as: [asName]
        };
      }
      return {
        type: "lookup",
        from: this.secondary,
        key: this.transform.from.key,
        fields: [this.transform.lookup],
        ...foreign,
        ...this.transform.default ? { default: this.transform.default } : {}
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/quantile.js
  var QuantileTransformNode = class _QuantileTransformNode extends DataFlowNode {
    clone() {
      return new _QuantileTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const specifiedAs = this.transform.as ?? [void 0, void 0];
      this.transform.as = [specifiedAs[0] ?? "prob", specifiedAs[1] ?? "value"];
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.quantile, ...this.transform.groupby ?? []]);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `QuantileTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { quantile: quantile3, ...rest } = this.transform;
      const result = {
        type: "quantile",
        field: quantile3,
        ...rest
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/regression.js
  var RegressionTransformNode = class _RegressionTransformNode extends DataFlowNode {
    clone() {
      return new _RegressionTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
      this.transform = duplicate(transform4);
      const specifiedAs = this.transform.as ?? [void 0, void 0];
      this.transform.as = [specifiedAs[0] ?? transform4.on, specifiedAs[1] ?? transform4.regression];
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.regression, this.transform.on, ...this.transform.groupby ?? []]);
    }
    producedFields() {
      return new Set(this.transform.as);
    }
    hash() {
      return `RegressionTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { regression, on: on2, ...rest } = this.transform;
      const result = {
        type: "regression",
        x: on2,
        y: regression,
        ...rest
      };
      return result;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/pivot.js
  var PivotTransformNode = class _PivotTransformNode extends DataFlowNode {
    clone() {
      return new _PivotTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
    }
    addDimensions(fields) {
      this.transform.groupby = unique((this.transform.groupby ?? []).concat(fields), (d2) => d2);
    }
    producedFields() {
      return void 0;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set([this.transform.pivot, this.transform.value, ...this.transform.groupby ?? []]);
    }
    hash() {
      return `PivotTransform ${hash(this.transform)}`;
    }
    assemble() {
      const { pivot, value: value3, groupby, limit, op } = this.transform;
      return {
        type: "pivot",
        field: pivot,
        value: value3,
        ...limit !== void 0 ? { limit } : {},
        ...op !== void 0 ? { op } : {},
        ...groupby !== void 0 ? { groupby } : {}
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/sample.js
  var SampleTransformNode = class _SampleTransformNode extends DataFlowNode {
    clone() {
      return new _SampleTransformNode(null, duplicate(this.transform));
    }
    constructor(parent, transform4) {
      super(parent);
      this.transform = transform4;
    }
    dependentFields() {
      return /* @__PURE__ */ new Set();
    }
    producedFields() {
      return /* @__PURE__ */ new Set();
    }
    hash() {
      return `SampleTransform ${hash(this.transform)}`;
    }
    assemble() {
      return {
        type: "sample",
        size: this.transform.sample
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/data/assemble.js
  function makeWalkTree(data3) {
    let datasetIndex = 0;
    function walkTree(node, dataSource) {
      if (node instanceof SourceNode) {
        if (!node.isGenerator && !isUrlData(node.data)) {
          data3.push(dataSource);
          const newData = {
            name: null,
            source: dataSource.name,
            transform: []
          };
          dataSource = newData;
        }
      }
      if (node instanceof ParseNode) {
        if (node.parent instanceof SourceNode && !dataSource.source) {
          dataSource.format = {
            ...dataSource.format,
            parse: node.assembleFormatParse()
          };
          dataSource.transform.push(...node.assembleTransforms(true));
        } else {
          dataSource.transform.push(...node.assembleTransforms());
        }
      }
      if (node instanceof FacetNode) {
        if (!dataSource.name) {
          dataSource.name = `data_${datasetIndex++}`;
        }
        if (!dataSource.source || dataSource.transform.length > 0) {
          data3.push(dataSource);
          node.data = dataSource.name;
        } else {
          node.data = dataSource.source;
        }
        data3.push(...node.assemble());
        return;
      }
      if (node instanceof GraticuleNode || node instanceof SequenceNode || node instanceof FilterInvalidNode || node instanceof FilterNode || node instanceof CalculateNode || node instanceof GeoPointNode || node instanceof AggregateNode || node instanceof LookupNode || node instanceof WindowTransformNode || node instanceof JoinAggregateTransformNode || node instanceof FoldTransformNode || node instanceof FlattenTransformNode || node instanceof DensityTransformNode || node instanceof LoessTransformNode || node instanceof QuantileTransformNode || node instanceof RegressionTransformNode || node instanceof IdentifierNode || node instanceof SampleTransformNode || node instanceof PivotTransformNode || node instanceof ExtentTransformNode) {
        dataSource.transform.push(node.assemble());
      }
      if (node instanceof BinNode || node instanceof TimeUnitNode || node instanceof ImputeNode || node instanceof StackNode || node instanceof GeoJSONNode) {
        dataSource.transform.push(...node.assemble());
      }
      if (node instanceof OutputNode) {
        if (dataSource.source && dataSource.transform.length === 0) {
          node.setSource(dataSource.source);
        } else if (node.parent instanceof OutputNode) {
          node.setSource(dataSource.name);
        } else {
          if (!dataSource.name) {
            dataSource.name = `data_${datasetIndex++}`;
          }
          node.setSource(dataSource.name);
          if (node.numChildren() === 1) {
            data3.push(dataSource);
            const newData = {
              name: null,
              source: dataSource.name,
              transform: []
            };
            dataSource = newData;
          }
        }
      }
      switch (node.numChildren()) {
        case 0:
          if (node instanceof OutputNode && (!dataSource.source || dataSource.transform.length > 0)) {
            data3.push(dataSource);
          }
          break;
        case 1:
          walkTree(node.children[0], dataSource);
          break;
        default: {
          if (!dataSource.name) {
            dataSource.name = `data_${datasetIndex++}`;
          }
          let source4 = dataSource.name;
          if (!dataSource.source || dataSource.transform.length > 0) {
            data3.push(dataSource);
          } else {
            source4 = dataSource.source;
          }
          for (const child of node.children) {
            const newData = {
              name: null,
              source: source4,
              transform: []
            };
            walkTree(child, newData);
          }
          break;
        }
      }
    }
    return walkTree;
  }
  function assembleFacetData(root) {
    const data3 = [];
    const walkTree = makeWalkTree(data3);
    for (const child of root.children) {
      walkTree(child, {
        source: root.name,
        name: null,
        transform: []
      });
    }
    return data3;
  }
  function assembleRootData(dataComponent, datasets) {
    const data3 = [];
    const walkTree = makeWalkTree(data3);
    let sourceIndex = 0;
    for (const root of dataComponent.sources) {
      if (!root.hasName()) {
        root.dataName = `source_${sourceIndex++}`;
      }
      const newData = root.assemble();
      walkTree(root, newData);
    }
    for (const d2 of data3) {
      if (d2.transform.length === 0) {
        delete d2.transform;
      }
    }
    let whereTo = 0;
    for (const [i2, d2] of data3.entries()) {
      if ((d2.transform ?? []).length === 0 && !d2.source) {
        data3.splice(whereTo++, 0, data3.splice(i2, 1)[0]);
      }
    }
    for (const d2 of data3) {
      for (const t4 of d2.transform ?? []) {
        if (t4.type === "lookup") {
          t4.from = dataComponent.outputNodes[t4.from].getSource();
        }
      }
    }
    for (const d2 of data3) {
      if (d2.name in datasets) {
        d2.values = datasets[d2.name];
      }
    }
    return data3;
  }

  // node_modules/vega-lite/build/src/compile/header/parse.js
  function getHeaderType(orient2) {
    if (orient2 === "top" || orient2 === "left" || isSignalRef(orient2)) {
      return "header";
    }
    return "footer";
  }
  function parseFacetHeaders(model) {
    for (const channel of FACET_CHANNELS) {
      parseFacetHeader(model, channel);
    }
    mergeChildAxis(model, "x");
    mergeChildAxis(model, "y");
  }
  function parseFacetHeader(model, channel) {
    const { facet, config, child, component } = model;
    if (model.channelHasField(channel)) {
      const fieldDef = facet[channel];
      const titleConfig = getHeaderProperty("title", null, config, channel);
      let title2 = title(fieldDef, config, {
        allowDisabling: true,
        includeDefault: titleConfig === void 0 || !!titleConfig
      });
      if (child.component.layoutHeaders[channel].title) {
        title2 = isArray(title2) ? title2.join(", ") : title2;
        title2 += ` / ${child.component.layoutHeaders[channel].title}`;
        child.component.layoutHeaders[channel].title = null;
      }
      const labelOrient = getHeaderProperty("labelOrient", fieldDef.header, config, channel);
      const labels3 = fieldDef.header !== null ? getFirstDefined(fieldDef.header?.labels, config.header.labels, true) : false;
      const headerType = contains2(["bottom", "right"], labelOrient) ? "footer" : "header";
      component.layoutHeaders[channel] = {
        title: fieldDef.header !== null ? title2 : null,
        facetFieldDef: fieldDef,
        [headerType]: channel === "facet" ? [] : [makeHeaderComponent(model, channel, labels3)]
      };
    }
  }
  function makeHeaderComponent(model, channel, labels3) {
    const sizeType = channel === "row" ? "height" : "width";
    return {
      labels: labels3,
      sizeSignal: model.child.component.layoutSize.get(sizeType) ? model.child.getSizeSignalRef(sizeType) : void 0,
      axes: []
    };
  }
  function mergeChildAxis(model, channel) {
    const { child } = model;
    if (child.component.axes[channel]) {
      const { layoutHeaders: layoutHeaders2, resolve: resolve2 } = model.component;
      resolve2.axis[channel] = parseGuideResolve(resolve2, channel);
      if (resolve2.axis[channel] === "shared") {
        const headerChannel = channel === "x" ? "column" : "row";
        const layoutHeader = layoutHeaders2[headerChannel];
        for (const axisComponent of child.component.axes[channel]) {
          const headerType = getHeaderType(axisComponent.get("orient"));
          layoutHeader[headerType] ?? (layoutHeader[headerType] = [makeHeaderComponent(model, headerChannel, false)]);
          const mainAxis = assembleAxis(axisComponent, "main", model.config, { header: true });
          if (mainAxis) {
            layoutHeader[headerType][0].axes.push(mainAxis);
          }
          axisComponent.mainExtracted = true;
        }
      } else {
      }
    }
  }

  // node_modules/vega-lite/build/src/compile/layoutsize/parse.js
  function parseLayerLayoutSize(model) {
    parseChildrenLayoutSize(model);
    parseNonUnitLayoutSizeForChannel(model, "width");
    parseNonUnitLayoutSizeForChannel(model, "height");
  }
  function parseConcatLayoutSize(model) {
    parseChildrenLayoutSize(model);
    const widthType = model.layout.columns === 1 ? "width" : "childWidth";
    const heightType = model.layout.columns === void 0 ? "height" : "childHeight";
    parseNonUnitLayoutSizeForChannel(model, widthType);
    parseNonUnitLayoutSizeForChannel(model, heightType);
  }
  function parseChildrenLayoutSize(model) {
    for (const child of model.children) {
      child.parseLayoutSize();
    }
  }
  function parseNonUnitLayoutSizeForChannel(model, layoutSizeType) {
    const sizeType = getSizeTypeFromLayoutSizeType(layoutSizeType);
    const channel = getPositionScaleChannel(sizeType);
    const resolve2 = model.component.resolve;
    const layoutSizeCmpt = model.component.layoutSize;
    let mergedSize;
    for (const child of model.children) {
      const childSize = child.component.layoutSize.getWithExplicit(sizeType);
      const scaleResolve = resolve2.scale[channel] ?? defaultScaleResolve(channel, model);
      if (scaleResolve === "independent" && childSize.value === "step") {
        mergedSize = void 0;
        break;
      }
      if (mergedSize) {
        if (scaleResolve === "independent" && mergedSize.value !== childSize.value) {
          mergedSize = void 0;
          break;
        }
        mergedSize = mergeValuesWithExplicit(mergedSize, childSize, sizeType, "");
      } else {
        mergedSize = childSize;
      }
    }
    if (mergedSize) {
      for (const child of model.children) {
        model.renameSignal(child.getName(sizeType), model.getName(layoutSizeType));
        child.component.layoutSize.set(sizeType, "merged", false);
      }
      layoutSizeCmpt.setWithExplicit(layoutSizeType, mergedSize);
    } else {
      layoutSizeCmpt.setWithExplicit(layoutSizeType, {
        explicit: false,
        value: void 0
      });
    }
  }
  function parseUnitLayoutSize(model) {
    const { size, component } = model;
    for (const channel of POSITION_SCALE_CHANNELS) {
      const sizeType = getSizeChannel(channel);
      if (size[sizeType]) {
        const specifiedSize = size[sizeType];
        component.layoutSize.set(sizeType, isStep(specifiedSize) ? "step" : specifiedSize, true);
      } else {
        const defaultSize = defaultUnitSize(model, sizeType);
        component.layoutSize.set(sizeType, defaultSize, false);
      }
    }
  }
  function defaultUnitSize(model, sizeType) {
    const channel = sizeType === "width" ? "x" : "y";
    const config = model.config;
    const scaleComponent = model.getScaleComponent(channel);
    if (scaleComponent) {
      const scaleType2 = scaleComponent.get("type");
      const range7 = scaleComponent.get("range");
      if (hasDiscreteDomain(scaleType2)) {
        const size = getViewConfigDiscreteSize(config.view, sizeType);
        if (isVgRangeStep(range7) || isStep(size)) {
          return "step";
        } else {
          return size;
        }
      } else {
        return getViewConfigContinuousSize(config.view, sizeType);
      }
    } else if (model.hasProjection || model.mark === "arc") {
      return getViewConfigContinuousSize(config.view, sizeType);
    } else {
      const size = getViewConfigDiscreteSize(config.view, sizeType);
      return isStep(size) ? size.step : size;
    }
  }

  // node_modules/vega-lite/build/src/compile/facet.js
  function facetSortFieldName(fieldDef, sort3, opt) {
    return vgField(sort3, { suffix: `by_${vgField(fieldDef)}`, ...opt });
  }
  var FacetModel = class _FacetModel extends ModelWithField {
    constructor(spec, parent, parentGivenName, config) {
      super(spec, "facet", parent, parentGivenName, config, spec.resolve);
      this.child = buildModel(spec.spec, this, this.getName("child"), void 0, config);
      this.children = [this.child];
      this.facet = this.initFacet(spec.facet);
    }
    initFacet(facet) {
      if (!isFacetMapping(facet)) {
        return { facet: this.initFacetFieldDef(facet, "facet") };
      }
      const channels = keys3(facet);
      const normalizedFacet = {};
      for (const channel of channels) {
        if (![ROW, COLUMN].includes(channel)) {
          warn2(message_exports.incompatibleChannel(channel, "facet"));
          break;
        }
        const fieldDef = facet[channel];
        if (fieldDef.field === void 0) {
          warn2(message_exports.emptyFieldDef(fieldDef, channel));
          break;
        }
        normalizedFacet[channel] = this.initFacetFieldDef(fieldDef, channel);
      }
      return normalizedFacet;
    }
    initFacetFieldDef(fieldDef, channel) {
      const facetFieldDef = initFieldDef(fieldDef, channel);
      if (facetFieldDef.header) {
        facetFieldDef.header = replaceExprRef(facetFieldDef.header);
      } else if (facetFieldDef.header === null) {
        facetFieldDef.header = null;
      }
      return facetFieldDef;
    }
    channelHasField(channel) {
      return hasProperty(this.facet, channel);
    }
    fieldDef(channel) {
      return this.facet[channel];
    }
    parseData() {
      this.component.data = parseData2(this);
      this.child.parseData();
    }
    parseLayoutSize() {
      parseChildrenLayoutSize(this);
    }
    parseSelections() {
      this.child.parseSelections();
      this.component.selection = this.child.component.selection;
      if (Object.values(this.component.selection).some((selCmpt) => isTimerSelection(selCmpt))) {
        error2(MULTI_VIEW_ANIMATION_UNSUPPORTED);
      }
    }
    parseMarkGroup() {
      this.child.parseMarkGroup();
    }
    parseAxesAndHeaders() {
      this.child.parseAxesAndHeaders();
      parseFacetHeaders(this);
    }
    assembleSelectionTopLevelSignals(signals) {
      return this.child.assembleSelectionTopLevelSignals(signals);
    }
    assembleSignals() {
      this.child.assembleSignals();
      return [];
    }
    assembleSelectionData(data3) {
      return this.child.assembleSelectionData(data3);
    }
    getHeaderLayoutMixins() {
      const layoutMixins = {};
      for (const channel of FACET_CHANNELS) {
        for (const headerType of HEADER_TYPES) {
          const layoutHeaderComponent = this.component.layoutHeaders[channel];
          const headerComponent = layoutHeaderComponent[headerType];
          const { facetFieldDef } = layoutHeaderComponent;
          if (facetFieldDef) {
            const titleOrient = getHeaderProperty("titleOrient", facetFieldDef.header, this.config, channel);
            if (["right", "bottom"].includes(titleOrient)) {
              const headerChannel = getHeaderChannel(channel, titleOrient);
              layoutMixins.titleAnchor ?? (layoutMixins.titleAnchor = {});
              layoutMixins.titleAnchor[headerChannel] = "end";
            }
          }
          if (headerComponent?.[0]) {
            const sizeType = channel === "row" ? "height" : "width";
            const bandType = headerType === "header" ? "headerBand" : "footerBand";
            if (channel !== "facet" && !this.child.component.layoutSize.get(sizeType)) {
              layoutMixins[bandType] ?? (layoutMixins[bandType] = {});
              layoutMixins[bandType][channel] = 0.5;
            }
            if (layoutHeaderComponent.title) {
              layoutMixins.offset ?? (layoutMixins.offset = {});
              layoutMixins.offset[channel === "row" ? "rowTitle" : "columnTitle"] = 10;
            }
          }
        }
      }
      return layoutMixins;
    }
    assembleDefaultLayout() {
      const { column, row } = this.facet;
      const columns2 = column ? this.columnDistinctSignal() : row ? 1 : void 0;
      let align2 = "all";
      if (!row && this.component.resolve.scale.x === "independent") {
        align2 = "none";
      } else if (!column && this.component.resolve.scale.y === "independent") {
        align2 = "none";
      }
      return {
        ...this.getHeaderLayoutMixins(),
        ...columns2 ? { columns: columns2 } : {},
        bounds: "full",
        align: align2
      };
    }
    assembleLayoutSignals() {
      return this.child.assembleLayoutSignals();
    }
    columnDistinctSignal() {
      if (this.parent && this.parent instanceof _FacetModel) {
        return void 0;
      } else {
        const facetLayoutDataName = this.getName("column_domain");
        return { signal: `length(data('${facetLayoutDataName}'))` };
      }
    }
    assembleGroupStyle() {
      return void 0;
    }
    assembleGroup(signals) {
      if (this.parent && this.parent instanceof _FacetModel) {
        return {
          ...this.channelHasField("column") ? {
            encode: {
              update: {
                // TODO(https://github.com/vega/vega-lite/issues/2759):
                // Correct the signal for facet of concat of facet_column
                columns: { field: vgField(this.facet.column, { prefix: "distinct" }) }
              }
            }
          } : {},
          ...super.assembleGroup(signals)
        };
      }
      return super.assembleGroup(signals);
    }
    /**
     * Aggregate cardinality for calculating size
     */
    getCardinalityAggregateForChild() {
      const fields = [];
      const ops2 = [];
      const as = [];
      if (this.child instanceof _FacetModel) {
        if (this.child.channelHasField("column")) {
          const field3 = vgField(this.child.facet.column);
          fields.push(field3);
          ops2.push("distinct");
          as.push(`distinct_${field3}`);
        }
      } else {
        for (const channel of POSITION_SCALE_CHANNELS) {
          const childScaleComponent = this.child.component.scales[channel];
          if (childScaleComponent && !childScaleComponent.merged) {
            const type3 = childScaleComponent.get("type");
            const range7 = childScaleComponent.get("range");
            if (hasDiscreteDomain(type3) && isVgRangeStep(range7)) {
              const domain4 = assembleDomain(this.child, channel);
              const field3 = getFieldFromDomain(domain4);
              if (field3) {
                fields.push(field3);
                ops2.push("distinct");
                as.push(`distinct_${field3}`);
              } else {
                warn2(message_exports.unknownField(channel));
              }
            }
          }
        }
      }
      return { fields, ops: ops2, as };
    }
    assembleFacet() {
      const { name: name4, data: data3 } = this.component.data.facetRoot;
      const { row, column } = this.facet;
      const { fields, ops: ops2, as } = this.getCardinalityAggregateForChild();
      const groupby = [];
      for (const channel of FACET_CHANNELS) {
        const fieldDef = this.facet[channel];
        if (fieldDef) {
          groupby.push(vgField(fieldDef));
          const { bin: bin3, sort: sort3 } = fieldDef;
          if (isBinning(bin3)) {
            groupby.push(vgField(fieldDef, { binSuffix: "end" }));
          }
          if (isSortField(sort3)) {
            const { field: field3, op = DEFAULT_SORT_OP } = sort3;
            const outputName = facetSortFieldName(fieldDef, sort3);
            if (row && column) {
              fields.push(outputName);
              ops2.push("max");
              as.push(outputName);
            } else {
              fields.push(field3);
              ops2.push(op);
              as.push(outputName);
            }
          } else if (isArray(sort3)) {
            const outputName = sortArrayIndexField(fieldDef, channel);
            fields.push(outputName);
            ops2.push("max");
            as.push(outputName);
          }
        }
      }
      const cross2 = !!row && !!column;
      return {
        name: name4,
        data: data3,
        groupby,
        ...cross2 || fields.length > 0 ? {
          aggregate: {
            ...cross2 ? { cross: cross2 } : {},
            ...fields.length ? { fields, ops: ops2, as } : {}
          }
        } : {}
      };
    }
    facetSortFields(channel) {
      const { facet } = this;
      const fieldDef = facet[channel];
      if (fieldDef) {
        if (isSortField(fieldDef.sort)) {
          return [facetSortFieldName(fieldDef, fieldDef.sort, { expr: "datum" })];
        } else if (isArray(fieldDef.sort)) {
          return [sortArrayIndexField(fieldDef, channel, { expr: "datum" })];
        }
        return [vgField(fieldDef, { expr: "datum" })];
      }
      return [];
    }
    facetSortOrder(channel) {
      const { facet } = this;
      const fieldDef = facet[channel];
      if (fieldDef) {
        const { sort: sort3 } = fieldDef;
        const order = (isSortField(sort3) ? sort3.order : !isArray(sort3) && sort3) || "ascending";
        return [order];
      }
      return [];
    }
    assembleLabelTitle() {
      const { facet, config } = this;
      if (facet.facet) {
        return assembleLabelTitle(facet.facet, "facet", config);
      }
      const ORTHOGONAL_ORIENT = {
        row: ["top", "bottom"],
        column: ["left", "right"]
      };
      for (const channel of HEADER_CHANNELS) {
        if (facet[channel]) {
          const labelOrient = getHeaderProperty("labelOrient", facet[channel]?.header, config, channel);
          if (ORTHOGONAL_ORIENT[channel].includes(labelOrient)) {
            return assembleLabelTitle(facet[channel], channel, config);
          }
        }
      }
      return void 0;
    }
    assembleMarks() {
      const { child } = this;
      const facetRoot = this.component.data.facetRoot;
      const data3 = assembleFacetData(facetRoot);
      const encodeEntry2 = child.assembleGroupEncodeEntry(false);
      const title2 = this.assembleLabelTitle() || child.assembleTitle();
      const style2 = child.assembleGroupStyle();
      const markGroup = {
        name: this.getName("cell"),
        type: "group",
        ...title2 ? { title: title2 } : {},
        ...style2 ? { style: style2 } : {},
        from: {
          facet: this.assembleFacet()
        },
        // TODO: move this to after data
        sort: {
          field: FACET_CHANNELS.map((c4) => this.facetSortFields(c4)).flat(),
          order: FACET_CHANNELS.map((c4) => this.facetSortOrder(c4)).flat()
        },
        ...data3.length > 0 ? { data: data3 } : {},
        ...encodeEntry2 ? { encode: { update: encodeEntry2 } } : {},
        ...child.assembleGroup(assembleFacetSignals(this, []))
      };
      return [markGroup];
    }
    getMapping() {
      return this.facet;
    }
  };

  // node_modules/vega-lite/build/src/compile/data/joinaggregatefacet.js
  function makeJoinAggregateFromFacet(parent, facet) {
    const { row, column } = facet;
    if (row && column) {
      let newParent = null;
      for (const fieldDef of [row, column]) {
        if (isSortField(fieldDef.sort)) {
          const { field: field3, op = DEFAULT_SORT_OP } = fieldDef.sort;
          parent = newParent = new JoinAggregateTransformNode(parent, {
            joinaggregate: [
              {
                op,
                field: field3,
                as: facetSortFieldName(fieldDef, fieldDef.sort, { forAs: true })
              }
            ],
            groupby: [vgField(fieldDef)]
          });
        }
      }
      return newParent;
    }
    return null;
  }

  // node_modules/vega-lite/build/src/compile/data/parse.js
  function findSource(data3, sources) {
    for (const other of sources) {
      const otherData = other.data;
      if (data3.name && other.hasName() && data3.name !== other.dataName) {
        continue;
      }
      const formatMesh = data3.format?.mesh;
      const otherFeature = otherData.format?.feature;
      if (formatMesh && otherFeature) {
        continue;
      }
      const formatFeature = data3.format?.feature;
      if ((formatFeature || otherFeature) && formatFeature !== otherFeature) {
        continue;
      }
      const otherMesh = otherData.format?.mesh;
      if ((formatMesh || otherMesh) && formatMesh !== otherMesh) {
        continue;
      }
      if (isInlineData(data3) && isInlineData(otherData)) {
        if (deepEqual(data3.values, otherData.values)) {
          return other;
        }
      } else if (isUrlData(data3) && isUrlData(otherData)) {
        if (data3.url === otherData.url) {
          return other;
        }
      } else if (isNamedData(data3)) {
        if (data3.name === other.dataName) {
          return other;
        }
      }
    }
    return null;
  }
  function parseRoot(model, sources) {
    if (model.data || !model.parent) {
      if (model.data === null) {
        const source4 = new SourceNode({ values: [] });
        sources.push(source4);
        return source4;
      }
      const existingSource = findSource(model.data, sources);
      if (existingSource) {
        if (!isGenerator(model.data)) {
          existingSource.data.format = mergeDeep({}, model.data.format, existingSource.data.format);
        }
        if (!existingSource.hasName() && model.data.name) {
          existingSource.dataName = model.data.name;
        }
        return existingSource;
      } else {
        const source4 = new SourceNode(model.data);
        sources.push(source4);
        return source4;
      }
    } else {
      return model.parent.component.data.facetRoot ? model.parent.component.data.facetRoot : model.parent.component.data.main;
    }
  }
  function parseTransformArray(head, model, ancestorParse) {
    let lookupCounter = 0;
    for (const t4 of model.transforms) {
      let derivedType = void 0;
      let transformNode;
      if (isCalculate(t4)) {
        transformNode = head = new CalculateNode(head, t4);
        derivedType = "derived";
      } else if (isFilter(t4)) {
        const implicit2 = getImplicitFromFilterTransform(t4);
        transformNode = head = ParseNode.makeWithAncestors(head, {}, implicit2, ancestorParse) ?? head;
        head = new FilterNode(head, model, t4.filter);
      } else if (isBin(t4)) {
        transformNode = head = BinNode.makeFromTransform(head, t4, model);
        derivedType = "number";
      } else if (isTimeUnit(t4)) {
        derivedType = "date";
        const parsedAs = ancestorParse.getWithExplicit(t4.field);
        if (parsedAs.value === void 0) {
          head = new ParseNode(head, { [t4.field]: derivedType });
          ancestorParse.set(t4.field, derivedType, false);
        }
        transformNode = head = TimeUnitNode.makeFromTransform(head, t4);
      } else if (isAggregate2(t4)) {
        transformNode = head = AggregateNode.makeFromTransform(head, t4);
        derivedType = "number";
        if (requiresSelectionId(model)) {
          head = new IdentifierNode(head);
        }
      } else if (isLookup(t4)) {
        transformNode = head = LookupNode.make(head, model, t4, lookupCounter++);
        derivedType = "derived";
      } else if (isWindow(t4)) {
        transformNode = head = new WindowTransformNode(head, t4);
        derivedType = "number";
      } else if (isJoinAggregate(t4)) {
        transformNode = head = new JoinAggregateTransformNode(head, t4);
        derivedType = "number";
      } else if (isStack(t4)) {
        transformNode = head = StackNode.makeFromTransform(head, t4);
        derivedType = "derived";
      } else if (isFold(t4)) {
        transformNode = head = new FoldTransformNode(head, t4);
        derivedType = "derived";
      } else if (isExtent(t4)) {
        transformNode = head = new ExtentTransformNode(head, t4);
        derivedType = "derived";
      } else if (isFlatten(t4)) {
        transformNode = head = new FlattenTransformNode(head, t4);
        derivedType = "derived";
      } else if (isPivot(t4)) {
        transformNode = head = new PivotTransformNode(head, t4);
        derivedType = "derived";
      } else if (isSample(t4)) {
        head = new SampleTransformNode(head, t4);
      } else if (isImpute(t4)) {
        transformNode = head = ImputeNode.makeFromTransform(head, t4);
        derivedType = "derived";
      } else if (isDensity(t4)) {
        transformNode = head = new DensityTransformNode(head, t4);
        derivedType = "derived";
      } else if (isQuantile2(t4)) {
        transformNode = head = new QuantileTransformNode(head, t4);
        derivedType = "derived";
      } else if (isRegression(t4)) {
        transformNode = head = new RegressionTransformNode(head, t4);
        derivedType = "derived";
      } else if (isLoess(t4)) {
        transformNode = head = new LoessTransformNode(head, t4);
        derivedType = "derived";
      } else {
        warn2(message_exports.invalidTransformIgnored(t4));
        continue;
      }
      if (transformNode && derivedType !== void 0) {
        for (const field3 of transformNode.producedFields() ?? []) {
          ancestorParse.set(field3, derivedType, false);
        }
      }
    }
    return head;
  }
  function parseData2(model) {
    let head = parseRoot(model, model.component.data.sources);
    const { outputNodes, outputNodeRefCounts } = model.component.data;
    const data3 = model.data;
    const newData = data3 && (isGenerator(data3) || isUrlData(data3) || isInlineData(data3));
    const ancestorParse = !newData && model.parent ? model.parent.component.data.ancestorParse.clone() : new AncestorParse();
    if (isGenerator(data3)) {
      if (isSequenceGenerator(data3)) {
        head = new SequenceNode(head, data3.sequence);
      } else if (isGraticuleGenerator(data3)) {
        head = new GraticuleNode(head, data3.graticule);
      }
      ancestorParse.parseNothing = true;
    } else if (data3?.format?.parse === null) {
      ancestorParse.parseNothing = true;
    }
    head = ParseNode.makeExplicit(head, model, ancestorParse) ?? head;
    head = new IdentifierNode(head);
    const parentIsLayer = model.parent && isLayerModel(model.parent);
    if (isUnitModel(model) || isFacetModel(model)) {
      if (parentIsLayer) {
        head = BinNode.makeFromEncoding(head, model) ?? head;
      }
    }
    if (model.transforms.length > 0) {
      head = parseTransformArray(head, model, ancestorParse);
    }
    const implicitSelection = getImplicitFromSelection(model);
    const implicitEncoding = getImplicitFromEncoding(model);
    head = ParseNode.makeWithAncestors(head, {}, { ...implicitSelection, ...implicitEncoding }, ancestorParse) ?? head;
    if (isUnitModel(model)) {
      head = GeoJSONNode.parseAll(head, model);
      head = GeoPointNode.parseAll(head, model);
    }
    if (isUnitModel(model) || isFacetModel(model)) {
      if (!parentIsLayer) {
        head = BinNode.makeFromEncoding(head, model) ?? head;
      }
      head = TimeUnitNode.makeFromEncoding(head, model) ?? head;
      head = CalculateNode.parseAllForSortIndex(head, model);
    }
    const raw = head = makeOutputNode(DataSourceType.Raw, model, head);
    if (isUnitModel(model)) {
      const agg = AggregateNode.makeFromEncoding(head, model);
      if (agg) {
        head = agg;
        if (requiresSelectionId(model)) {
          head = new IdentifierNode(head);
        }
      }
      head = ImputeNode.makeFromEncoding(head, model) ?? head;
      head = StackNode.makeFromEncoding(head, model) ?? head;
    }
    let preFilterInvalid;
    let dataSourcesForHandlingInvalidValues;
    if (isUnitModel(model)) {
      const { markDef, mark, config } = model;
      const invalid = getMarkPropOrConfig("invalid", markDef, config);
      const { marks, scales: scales2 } = dataSourcesForHandlingInvalidValues = getDataSourcesForHandlingInvalidValues({
        invalid,
        isPath: isPathMark(mark)
      });
      if (marks !== scales2 && scales2 === "include-invalid-values") {
        preFilterInvalid = head = makeOutputNode(DataSourceType.PreFilterInvalid, model, head);
      }
      if (marks === "exclude-invalid-values") {
        head = FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;
      }
    }
    const main5 = head = makeOutputNode(DataSourceType.Main, model, head);
    let postFilterInvalid;
    if (isUnitModel(model) && dataSourcesForHandlingInvalidValues) {
      const { marks, scales: scales2 } = dataSourcesForHandlingInvalidValues;
      if (marks === "include-invalid-values" && scales2 === "exclude-invalid-values") {
        head = FilterInvalidNode.make(head, model, dataSourcesForHandlingInvalidValues) ?? head;
        postFilterInvalid = head = makeOutputNode(DataSourceType.PostFilterInvalid, model, head);
      }
    }
    if (isUnitModel(model)) {
      materializeSelections(model, main5);
    }
    let facetRoot = null;
    if (isFacetModel(model)) {
      const facetName = model.getName("facet");
      head = makeJoinAggregateFromFacet(head, model.facet) ?? head;
      facetRoot = new FacetNode(head, model, facetName, main5.getSource());
      outputNodes[facetName] = facetRoot;
    }
    return {
      ...model.component.data,
      outputNodes,
      outputNodeRefCounts,
      raw,
      main: main5,
      facetRoot,
      ancestorParse,
      preFilterInvalid,
      postFilterInvalid
    };
  }
  function makeOutputNode(dataSourceType, model, head) {
    const { outputNodes, outputNodeRefCounts } = model.component.data;
    const name4 = model.getDataName(dataSourceType);
    const node = new OutputNode(head, name4, dataSourceType, outputNodeRefCounts);
    outputNodes[name4] = node;
    return node;
  }

  // node_modules/vega-lite/build/src/compile/concat.js
  var ConcatModel = class extends Model {
    constructor(spec, parent, parentGivenName, config) {
      super(spec, "concat", parent, parentGivenName, config, spec.resolve);
      if (spec.resolve?.axis?.x === "shared" || spec.resolve?.axis?.y === "shared") {
        warn2(message_exports.CONCAT_CANNOT_SHARE_AXIS);
      }
      this.children = this.getChildren(spec).map((child, i2) => {
        return buildModel(child, this, this.getName(`concat_${i2}`), void 0, config);
      });
    }
    parseData() {
      this.component.data = parseData2(this);
      for (const child of this.children) {
        child.parseData();
      }
    }
    parseSelections() {
      this.component.selection = {};
      for (const child of this.children) {
        child.parseSelections();
        for (const key2 of keys3(child.component.selection)) {
          this.component.selection[key2] = child.component.selection[key2];
        }
      }
      if (Object.values(this.component.selection).some((selCmpt) => isTimerSelection(selCmpt))) {
        error2(MULTI_VIEW_ANIMATION_UNSUPPORTED);
      }
    }
    parseMarkGroup() {
      for (const child of this.children) {
        child.parseMarkGroup();
      }
    }
    parseAxesAndHeaders() {
      for (const child of this.children) {
        child.parseAxesAndHeaders();
      }
    }
    getChildren(spec) {
      if (isVConcatSpec(spec)) {
        return spec.vconcat;
      } else if (isHConcatSpec(spec)) {
        return spec.hconcat;
      }
      return spec.concat;
    }
    parseLayoutSize() {
      parseConcatLayoutSize(this);
    }
    parseAxisGroup() {
      return null;
    }
    assembleSelectionTopLevelSignals(signals) {
      return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
    }
    assembleSignals() {
      this.children.forEach((child) => child.assembleSignals());
      return [];
    }
    assembleLayoutSignals() {
      const layoutSignals = assembleLayoutSignals(this);
      for (const child of this.children) {
        layoutSignals.push(...child.assembleLayoutSignals());
      }
      return layoutSignals;
    }
    assembleSelectionData(data3) {
      return this.children.reduce((db, child) => child.assembleSelectionData(db), data3);
    }
    assembleMarks() {
      return this.children.map((child) => {
        const title2 = child.assembleTitle();
        const style2 = child.assembleGroupStyle();
        const encodeEntry2 = child.assembleGroupEncodeEntry(false);
        return {
          type: "group",
          name: child.getName("group"),
          ...title2 ? { title: title2 } : {},
          ...style2 ? { style: style2 } : {},
          ...encodeEntry2 ? { encode: { update: encodeEntry2 } } : {},
          ...child.assembleGroup()
        };
      });
    }
    assembleGroupStyle() {
      return void 0;
    }
    assembleDefaultLayout() {
      const columns2 = this.layout.columns;
      return {
        ...columns2 != null ? { columns: columns2 } : {},
        bounds: "full",
        // Use align each so it can work with multiple plots with different size
        align: "each"
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/axis/component.js
  function isFalseOrNull(v3) {
    return v3 === false || v3 === null;
  }
  var AXIS_COMPONENT_PROPERTIES_INDEX = {
    disable: 1,
    gridScale: 1,
    scale: 1,
    ...COMMON_AXIS_PROPERTIES_INDEX,
    labelExpr: 1,
    encode: 1
  };
  var AXIS_COMPONENT_PROPERTIES = keys3(AXIS_COMPONENT_PROPERTIES_INDEX);
  var AxisComponent = class _AxisComponent extends Split {
    constructor(explicit = {}, implicit2 = {}, mainExtracted = false) {
      super();
      this.explicit = explicit;
      this.implicit = implicit2;
      this.mainExtracted = mainExtracted;
    }
    clone() {
      return new _AxisComponent(duplicate(this.explicit), duplicate(this.implicit), this.mainExtracted);
    }
    hasAxisPart(part) {
      if (part === "axis") {
        return true;
      }
      if (part === "grid" || part === "title") {
        return !!this.get(part);
      }
      return !isFalseOrNull(this.get(part));
    }
    hasOrientSignalRef() {
      return isSignalRef(this.explicit.orient);
    }
  };

  // node_modules/vega-lite/build/src/compile/axis/encode.js
  function labels2(model, channel, specifiedLabelsSpec) {
    const { encoding, config } = model;
    const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]) ?? getFieldOrDatumDef(encoding[getSecondaryRangeChannel(channel)]);
    const axis = model.axis(channel) || {};
    const { format: format5, formatType } = axis;
    if (isCustomFormatType(formatType)) {
      return {
        text: formatCustomType({
          fieldOrDatumDef,
          field: "datum.value",
          format: format5,
          formatType,
          config
        }),
        ...specifiedLabelsSpec
      };
    } else if (format5 === void 0 && formatType === void 0 && config.customFormatTypes) {
      if (channelDefType(fieldOrDatumDef) === "quantitative") {
        if (isPositionFieldOrDatumDef(fieldOrDatumDef) && fieldOrDatumDef.stack === "normalize" && config.normalizedNumberFormatType) {
          return {
            text: formatCustomType({
              fieldOrDatumDef,
              field: "datum.value",
              format: config.normalizedNumberFormat,
              formatType: config.normalizedNumberFormatType,
              config
            }),
            ...specifiedLabelsSpec
          };
        } else if (config.numberFormatType) {
          return {
            text: formatCustomType({
              fieldOrDatumDef,
              field: "datum.value",
              format: config.numberFormat,
              formatType: config.numberFormatType,
              config
            }),
            ...specifiedLabelsSpec
          };
        }
      }
      if (channelDefType(fieldOrDatumDef) === "temporal" && config.timeFormatType && isFieldDef(fieldOrDatumDef) && !fieldOrDatumDef.timeUnit) {
        return {
          text: formatCustomType({
            fieldOrDatumDef,
            field: "datum.value",
            format: config.timeFormat,
            formatType: config.timeFormatType,
            config
          }),
          ...specifiedLabelsSpec
        };
      }
    }
    return specifiedLabelsSpec;
  }

  // node_modules/vega-lite/build/src/compile/axis/parse.js
  function parseUnitAxes(model) {
    return POSITION_SCALE_CHANNELS.reduce((axis, channel) => {
      if (model.component.scales[channel]) {
        axis[channel] = [parseAxis2(channel, model)];
      }
      return axis;
    }, {});
  }
  var OPPOSITE_ORIENT = {
    bottom: "top",
    top: "bottom",
    left: "right",
    right: "left"
  };
  function parseLayerAxes(model) {
    const { axes, resolve: resolve2 } = model.component;
    const axisCount = { top: 0, bottom: 0, right: 0, left: 0 };
    for (const child of model.children) {
      child.parseAxesAndHeaders();
      for (const channel of keys3(child.component.axes)) {
        resolve2.axis[channel] = parseGuideResolve(model.component.resolve, channel);
        if (resolve2.axis[channel] === "shared") {
          axes[channel] = mergeAxisComponents(axes[channel], child.component.axes[channel]);
          if (!axes[channel]) {
            resolve2.axis[channel] = "independent";
            delete axes[channel];
          }
        }
      }
    }
    for (const channel of POSITION_SCALE_CHANNELS) {
      for (const child of model.children) {
        if (!child.component.axes[channel]) {
          continue;
        }
        if (resolve2.axis[channel] === "independent") {
          axes[channel] = (axes[channel] ?? []).concat(child.component.axes[channel]);
          for (const axisComponent of child.component.axes[channel]) {
            const { value: orient2, explicit } = axisComponent.getWithExplicit("orient");
            if (isSignalRef(orient2)) {
              continue;
            }
            if (axisCount[orient2] > 0 && !explicit) {
              const oppositeOrient = OPPOSITE_ORIENT[orient2];
              if (axisCount[orient2] > axisCount[oppositeOrient]) {
                axisComponent.set("orient", oppositeOrient, false);
              }
            }
            axisCount[orient2]++;
          }
        }
        delete child.component.axes[channel];
      }
      if (resolve2.axis[channel] === "independent" && axes[channel] && axes[channel].length > 1) {
        for (const [index4, axisCmpt] of (axes[channel] || []).entries()) {
          if (index4 > 0 && !!axisCmpt.get("grid") && !axisCmpt.explicit.grid) {
            axisCmpt.implicit.grid = false;
          }
        }
      }
    }
  }
  function mergeAxisComponents(mergedAxisCmpts, childAxisCmpts) {
    if (mergedAxisCmpts) {
      if (mergedAxisCmpts.length !== childAxisCmpts.length) {
        return void 0;
      }
      const length3 = mergedAxisCmpts.length;
      for (let i2 = 0; i2 < length3; i2++) {
        const merged = mergedAxisCmpts[i2];
        const child = childAxisCmpts[i2];
        if (!!merged !== !!child) {
          return void 0;
        } else if (merged && child) {
          const mergedOrient = merged.getWithExplicit("orient");
          const childOrient = child.getWithExplicit("orient");
          if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) {
            return void 0;
          } else {
            mergedAxisCmpts[i2] = mergeAxisComponent(merged, child);
          }
        }
      }
    } else {
      return childAxisCmpts.map((axisComponent) => axisComponent.clone());
    }
    return mergedAxisCmpts;
  }
  function mergeAxisComponent(merged, child) {
    for (const prop of AXIS_COMPONENT_PROPERTIES) {
      const mergedValueWithExplicit = mergeValuesWithExplicit(
        merged.getWithExplicit(prop),
        child.getWithExplicit(prop),
        prop,
        "axis",
        // Tie breaker function
        (v1, v22) => {
          switch (prop) {
            case "title":
              return mergeTitleComponent(v1, v22);
            case "gridScale":
              return {
                explicit: v1.explicit,
                // keep the old explicit
                value: getFirstDefined(v1.value, v22.value)
              };
          }
          return defaultTieBreaker(v1, v22, prop, "axis");
        }
      );
      merged.setWithExplicit(prop, mergedValueWithExplicit);
    }
    return merged;
  }
  function isExplicit2(value3, property2, axis, model, channel) {
    if (property2 === "disable") {
      return axis !== void 0;
    }
    axis = axis || {};
    switch (property2) {
      case "titleAngle":
      case "labelAngle":
        return value3 === (isSignalRef(axis.labelAngle) ? axis.labelAngle : normalizeAngle(axis.labelAngle));
      case "values":
        return !!axis.values;
      // specified axis.values is already respected, but may get transformed.
      case "encode":
        return !!axis.encoding || !!axis.labelAngle;
      case "title":
        if (value3 === getFieldDefTitle(model, channel)) {
          return true;
        }
    }
    return value3 === axis[property2];
  }
  var propsToAlwaysIncludeConfig = /* @__PURE__ */ new Set([
    "grid",
    // Grid is an exception because we need to set grid = true to generate another grid axis
    "translate",
    // translate has dependent logic for bar's bin position and it's 0.5 by default in Vega. If a config overrides this value, we need to know.
    // the rest are not axis configs in Vega, but are in VL, so we need to set too.
    "format",
    "formatType",
    "orient",
    "labelExpr",
    "tickCount",
    "position",
    "tickMinStep"
  ]);
  function parseAxis2(channel, model) {
    let axis = model.axis(channel);
    const axisComponent = new AxisComponent();
    const fieldOrDatumDef = getFieldOrDatumDef(model.encoding[channel]);
    const { mark, config } = model;
    const orient2 = axis?.orient || config[channel === "x" ? "axisX" : "axisY"]?.orient || config.axis?.orient || defaultOrient(channel);
    const scaleType2 = model.getScaleComponent(channel).get("type");
    const axisConfigs = getAxisConfigs(channel, scaleType2, orient2, model.config);
    const disable = axis !== void 0 ? !axis : getAxisConfig("disable", config.style, axis?.style, axisConfigs).configValue;
    axisComponent.set("disable", disable, axis !== void 0);
    if (disable) {
      return axisComponent;
    }
    axis = axis || {};
    const labelAngle = getLabelAngle(fieldOrDatumDef, axis, channel, config.style, axisConfigs);
    const formatType = guideFormatType(axis.formatType, fieldOrDatumDef, scaleType2);
    const format5 = guideFormat(fieldOrDatumDef, fieldOrDatumDef.type, axis.format, axis.formatType, config, true);
    const ruleParams = {
      fieldOrDatumDef,
      axis,
      channel,
      model,
      scaleType: scaleType2,
      orient: orient2,
      labelAngle,
      format: format5,
      formatType,
      mark,
      config
    };
    for (const property2 of AXIS_COMPONENT_PROPERTIES) {
      const value3 = property2 in axisRules ? axisRules[property2](ruleParams) : isAxisProperty(property2) ? axis[property2] : void 0;
      const hasValue = value3 !== void 0;
      const explicit = isExplicit2(value3, property2, axis, model, channel);
      if (hasValue && explicit) {
        axisComponent.set(property2, value3, explicit);
      } else {
        const { configValue = void 0, configFrom = void 0 } = isAxisProperty(property2) && property2 !== "values" ? getAxisConfig(property2, config.style, axis.style, axisConfigs) : {};
        const hasConfigValue = configValue !== void 0;
        if (hasValue && !hasConfigValue) {
          axisComponent.set(property2, value3, explicit);
        } else if (
          // Cases need implicit values
          // 1. Axis config that aren't available in Vega
          !(configFrom === "vgAxisConfig") || // 2. Certain properties are always included (see `propsToAlwaysIncludeConfig`'s declaration for more details)
          propsToAlwaysIncludeConfig.has(property2) && hasConfigValue || // 3. Conditional axis values and signals
          isConditionalAxisValue(configValue) || isSignalRef(configValue)
        ) {
          axisComponent.set(property2, configValue, false);
        }
      }
    }
    const axisEncoding = axis.encoding ?? {};
    const axisEncode = AXIS_PARTS.reduce((e4, part) => {
      if (!axisComponent.hasAxisPart(part)) {
        return e4;
      }
      const axisEncodingPart = guideEncodeEntry(axisEncoding[part] ?? {}, model);
      const value3 = part === "labels" ? labels2(model, channel, axisEncodingPart) : axisEncodingPart;
      if (value3 !== void 0 && !isEmpty(value3)) {
        e4[part] = { update: value3 };
      }
      return e4;
    }, {});
    if (!isEmpty(axisEncode)) {
      axisComponent.set("encode", axisEncode, !!axis.encoding || axis.labelAngle !== void 0);
    }
    return axisComponent;
  }

  // node_modules/vega-lite/build/src/compile/layoutsize/init.js
  function initLayoutSize({ encoding, size }) {
    for (const channel of POSITION_SCALE_CHANNELS) {
      const sizeType = getSizeChannel(channel);
      if (isStep(size[sizeType])) {
        if (isContinuousFieldOrDatumDef(encoding[channel])) {
          delete size[sizeType];
          warn2(message_exports.stepDropped(sizeType));
        }
      }
    }
    return size;
  }

  // node_modules/vega-lite/build/src/compile/mark/arc.js
  var arc3 = {
    vgMark: "arc",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          size: "ignore",
          orient: "ignore",
          theta: "ignore"
        }),
        ...pointPosition("x", model, { defaultPos: "mid" }),
        ...pointPosition("y", model, { defaultPos: "mid" }),
        // arcs are rectangles in polar coordinates
        ...rectPosition(model, "radius"),
        ...rectPosition(model, "theta")
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/area.js
  var area3 = {
    vgMark: "area",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          orient: "include",
          size: "ignore",
          theta: "ignore"
        }),
        ...pointOrRangePosition("x", model, {
          defaultPos: "zeroOrMin",
          defaultPos2: "zeroOrMin",
          range: model.markDef.orient === "horizontal"
        }),
        ...pointOrRangePosition("y", model, {
          defaultPos: "zeroOrMin",
          defaultPos2: "zeroOrMin",
          range: model.markDef.orient === "vertical"
        }),
        ...defined(model)
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/bar.js
  var bar = {
    vgMark: "rect",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          orient: "ignore",
          size: "ignore",
          theta: "ignore"
        }),
        ...rectPosition(model, "x"),
        ...rectPosition(model, "y")
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/geoshape.js
  var geoshape = {
    vgMark: "shape",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          size: "ignore",
          orient: "ignore",
          theta: "ignore"
        })
      };
    },
    postEncodingTransform: (model) => {
      const { encoding } = model;
      const shapeDef = encoding.shape;
      const transform4 = {
        type: "geoshape",
        projection: model.projectionName(),
        // as: 'shape',
        ...shapeDef && isFieldDef(shapeDef) && shapeDef.type === GEOJSON ? { field: vgField(shapeDef, { expr: "datum" }) } : {}
      };
      return [transform4];
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/image.js
  var image2 = {
    vgMark: "image",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "ignore",
          orient: "ignore",
          size: "ignore",
          theta: "ignore"
        }),
        ...rectPosition(model, "x"),
        ...rectPosition(model, "y"),
        ...text2(model, "url")
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/line.js
  var line3 = {
    vgMark: "line",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          size: "ignore",
          orient: "ignore",
          theta: "ignore"
        }),
        ...pointPosition("x", model, { defaultPos: "mid" }),
        ...pointPosition("y", model, { defaultPos: "mid" }),
        ...nonPosition("size", model, {
          vgChannel: "strokeWidth"
          // VL's line size is strokeWidth
        }),
        ...defined(model)
      };
    }
  };
  var trail2 = {
    vgMark: "trail",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          size: "include",
          orient: "ignore",
          theta: "ignore"
        }),
        ...pointPosition("x", model, { defaultPos: "mid" }),
        ...pointPosition("y", model, { defaultPos: "mid" }),
        ...nonPosition("size", model),
        ...defined(model)
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/point.js
  function encodeEntry(model, fixedShape) {
    const { config } = model;
    return {
      ...baseEncodeEntry(model, {
        align: "ignore",
        baseline: "ignore",
        color: "include",
        size: "include",
        orient: "ignore",
        theta: "ignore"
      }),
      ...pointPosition("x", model, { defaultPos: "mid" }),
      ...pointPosition("y", model, { defaultPos: "mid" }),
      ...nonPosition("size", model),
      ...nonPosition("angle", model),
      ...shapeMixins(model, config, fixedShape)
    };
  }
  function shapeMixins(model, config, fixedShape) {
    if (fixedShape) {
      return { shape: { value: fixedShape } };
    }
    return nonPosition("shape", model);
  }
  var point8 = {
    vgMark: "symbol",
    encodeEntry: (model) => {
      return encodeEntry(model);
    }
  };
  var circle = {
    vgMark: "symbol",
    encodeEntry: (model) => {
      return encodeEntry(model, "circle");
    }
  };
  var square = {
    vgMark: "symbol",
    encodeEntry: (model) => {
      return encodeEntry(model, "square");
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/rect.js
  var rect2 = {
    vgMark: "rect",
    encodeEntry: (model) => {
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          orient: "ignore",
          size: "ignore",
          theta: "ignore"
        }),
        ...rectPosition(model, "x"),
        ...rectPosition(model, "y")
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/rule.js
  var rule3 = {
    vgMark: "rule",
    encodeEntry: (model) => {
      const { markDef } = model;
      const orient2 = markDef.orient;
      if (!model.encoding.x && !model.encoding.y && !model.encoding.latitude && !model.encoding.longitude) {
        return {};
      }
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          orient: "ignore",
          size: "ignore",
          theta: "ignore"
        }),
        ...pointOrRangePosition("x", model, {
          defaultPos: orient2 === "horizontal" ? "zeroOrMax" : "mid",
          defaultPos2: "zeroOrMin",
          range: orient2 !== "vertical"
          // include x2 for horizontal or line segment rule
        }),
        ...pointOrRangePosition("y", model, {
          defaultPos: orient2 === "vertical" ? "zeroOrMax" : "mid",
          defaultPos2: "zeroOrMin",
          range: orient2 !== "horizontal"
          // include y2 for vertical or line segment rule
        }),
        ...nonPosition("size", model, {
          vgChannel: "strokeWidth"
          // VL's rule size is strokeWidth
        })
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/text.js
  var text3 = {
    vgMark: "text",
    encodeEntry: (model) => {
      const { config, encoding } = model;
      return {
        ...baseEncodeEntry(model, {
          align: "include",
          baseline: "include",
          color: "include",
          size: "ignore",
          orient: "ignore",
          theta: "include"
        }),
        ...pointPosition("x", model, { defaultPos: "mid" }),
        ...pointPosition("y", model, { defaultPos: "mid" }),
        ...text2(model),
        ...nonPosition("size", model, {
          vgChannel: "fontSize"
          // VL's text size is fontSize
        }),
        ...nonPosition("angle", model),
        ...valueIfDefined("align", align(model.markDef, encoding, config)),
        ...valueIfDefined("baseline", baseline2(model.markDef, encoding, config)),
        ...pointPosition("radius", model, { defaultPos: null }),
        ...pointPosition("theta", model, { defaultPos: null })
      };
    }
  };
  function align(markDef, encoding, config) {
    const a4 = getMarkPropOrConfig("align", markDef, config);
    if (a4 === void 0) {
      return "center";
    }
    return void 0;
  }
  function baseline2(markDef, encoding, config) {
    const b3 = getMarkPropOrConfig("baseline", markDef, config);
    if (b3 === void 0) {
      return "middle";
    }
    return void 0;
  }

  // node_modules/vega-lite/build/src/compile/mark/tick.js
  var tick = {
    vgMark: "rect",
    encodeEntry: (model) => {
      const { config, markDef } = model;
      const orient2 = markDef.orient;
      const vgSizeAxisChannel = orient2 === "horizontal" ? "x" : "y";
      const vgThicknessAxisChannel = orient2 === "horizontal" ? "y" : "x";
      const vgThicknessChannel = orient2 === "horizontal" ? "height" : "width";
      return {
        ...baseEncodeEntry(model, {
          align: "ignore",
          baseline: "ignore",
          color: "include",
          orient: "ignore",
          size: "ignore",
          theta: "ignore"
        }),
        ...rectPosition(model, vgSizeAxisChannel),
        ...pointPosition(vgThicknessAxisChannel, model, {
          defaultPos: "mid",
          vgChannel: vgThicknessAxisChannel === "y" ? "yc" : "xc"
        }),
        [vgThicknessChannel]: signalOrValueRef(getMarkPropOrConfig("thickness", markDef, config))
      };
    }
  };

  // node_modules/vega-lite/build/src/compile/mark/mark.js
  var markCompiler = {
    arc: arc3,
    area: area3,
    bar,
    circle,
    geoshape,
    image: image2,
    line: line3,
    point: point8,
    rect: rect2,
    rule: rule3,
    square,
    text: text3,
    tick,
    trail: trail2
  };
  function parseMarkGroups(model) {
    if (contains2([LINE, AREA, TRAIL], model.mark)) {
      const details = pathGroupingFields(model.mark, model.encoding);
      if (details.length > 0) {
        return getPathGroups(model, details);
      }
    } else if (model.mark === BAR) {
      const hasCornerRadius2 = VG_CORNERRADIUS_CHANNELS.some((prop) => getMarkPropOrConfig(prop, model.markDef, model.config));
      if (model.stack && !model.fieldDef("size") && hasCornerRadius2) {
        return getGroupsForStackedBarWithCornerRadius(model);
      }
    }
    return getMarkGroup(model);
  }
  var FACETED_PATH_PREFIX = "faceted_path_";
  function getPathGroups(model, details) {
    return [
      {
        name: model.getName("pathgroup"),
        type: "group",
        from: {
          facet: {
            name: FACETED_PATH_PREFIX + model.requestDataName(DataSourceType.Main),
            data: model.requestDataName(DataSourceType.Main),
            groupby: details
          }
        },
        encode: {
          update: {
            width: { field: { group: "width" } },
            height: { field: { group: "height" } }
          }
        },
        // With subfacet for line/area group, need to use faceted data from above.
        marks: getMarkGroup(model, { fromPrefix: FACETED_PATH_PREFIX })
      }
    ];
  }
  var STACK_GROUP_PREFIX = "stack_group_";
  function getGroupsForStackedBarWithCornerRadius(model) {
    const [mark] = getMarkGroup(model, { fromPrefix: STACK_GROUP_PREFIX });
    const fieldScale = model.scaleName(model.stack.fieldChannel);
    const stackField = (opt = {}) => model.vgField(model.stack.fieldChannel, opt);
    const stackFieldGroup = (func, expr2) => {
      const vgFieldMinMax = [
        stackField({ prefix: "min", suffix: "start", expr: expr2 }),
        stackField({ prefix: "max", suffix: "start", expr: expr2 }),
        stackField({ prefix: "min", suffix: "end", expr: expr2 }),
        stackField({ prefix: "max", suffix: "end", expr: expr2 })
      ];
      return `${func}(${vgFieldMinMax.map((field3) => `scale('${fieldScale}',${field3})`).join(",")})`;
    };
    let groupUpdate;
    let innerGroupUpdate;
    if (model.stack.fieldChannel === "x") {
      groupUpdate = {
        ...pick2(mark.encode.update, ["y", "yc", "y2", "height", ...VG_CORNERRADIUS_CHANNELS]),
        x: { signal: stackFieldGroup("min", "datum") },
        x2: { signal: stackFieldGroup("max", "datum") },
        clip: { value: true }
      };
      innerGroupUpdate = {
        x: { field: { group: "x" }, mult: -1 },
        height: { field: { group: "height" } }
      };
      mark.encode.update = {
        ...omit(mark.encode.update, ["y", "yc", "y2"]),
        height: { field: { group: "height" } }
      };
    } else {
      groupUpdate = {
        ...pick2(mark.encode.update, ["x", "xc", "x2", "width"]),
        y: { signal: stackFieldGroup("min", "datum") },
        y2: { signal: stackFieldGroup("max", "datum") },
        clip: { value: true }
      };
      innerGroupUpdate = {
        y: { field: { group: "y" }, mult: -1 },
        width: { field: { group: "width" } }
      };
      mark.encode.update = {
        ...omit(mark.encode.update, ["x", "xc", "x2"]),
        width: { field: { group: "width" } }
      };
    }
    for (const key2 of VG_CORNERRADIUS_CHANNELS) {
      const configValue = getMarkConfig(key2, model.markDef, model.config);
      if (mark.encode.update[key2]) {
        groupUpdate[key2] = mark.encode.update[key2];
        delete mark.encode.update[key2];
      } else if (configValue) {
        groupUpdate[key2] = signalOrValueRef(configValue);
      }
      if (configValue) {
        mark.encode.update[key2] = { value: 0 };
      }
    }
    const groupby = [];
    if (model.stack.groupbyChannels?.length > 0) {
      for (const groupbyChannel of model.stack.groupbyChannels) {
        const groupByField = model.fieldDef(groupbyChannel);
        const field3 = vgField(groupByField);
        if (field3) {
          groupby.push(field3);
        }
        if (groupByField?.bin || groupByField?.timeUnit) {
          groupby.push(vgField(groupByField, { binSuffix: "end" }));
        }
      }
    }
    const strokeProperties = [
      "stroke",
      "strokeWidth",
      "strokeJoin",
      "strokeCap",
      "strokeDash",
      "strokeDashOffset",
      "strokeMiterLimit",
      "strokeOpacity"
    ];
    groupUpdate = strokeProperties.reduce((encode2, prop) => {
      if (mark.encode.update[prop]) {
        return { ...encode2, [prop]: mark.encode.update[prop] };
      } else {
        const configValue = getMarkConfig(prop, model.markDef, model.config);
        if (configValue !== void 0) {
          return { ...encode2, [prop]: signalOrValueRef(configValue) };
        } else {
          return encode2;
        }
      }
    }, groupUpdate);
    if (groupUpdate.stroke) {
      groupUpdate.strokeForeground = { value: true };
      groupUpdate.strokeOffset = { value: 0 };
    }
    return [
      {
        type: "group",
        from: {
          facet: {
            data: model.requestDataName(DataSourceType.Main),
            name: STACK_GROUP_PREFIX + model.requestDataName(DataSourceType.Main),
            groupby,
            aggregate: {
              fields: [
                stackField({ suffix: "start" }),
                stackField({ suffix: "start" }),
                stackField({ suffix: "end" }),
                stackField({ suffix: "end" })
              ],
              ops: ["min", "max", "min", "max"]
            }
          }
        },
        encode: {
          update: groupUpdate
        },
        marks: [
          {
            type: "group",
            encode: { update: innerGroupUpdate },
            marks: [mark]
          }
        ]
      }
    ];
  }
  function getSort2(model) {
    const { encoding, stack: stack2, mark, markDef, config } = model;
    const order = encoding.order;
    if (!isArray(order) && isValueDef(order) && isNullOrFalse(order.value) || !order && isNullOrFalse(getMarkPropOrConfig("order", markDef, config))) {
      return void 0;
    } else if ((isArray(order) || isFieldDef(order)) && !stack2) {
      return sortParams(order, { expr: "datum" });
    } else if (isPathMark(mark)) {
      const dimensionChannel = markDef.orient === "horizontal" ? "y" : "x";
      const dimensionChannelDef = encoding[dimensionChannel];
      if (isFieldDef(dimensionChannelDef)) {
        return { field: dimensionChannel };
      }
    }
    return void 0;
  }
  function getMarkGroup(model, opt = { fromPrefix: "" }) {
    const { mark, markDef, encoding, config } = model;
    const clip3 = getFirstDefined(markDef.clip, scaleClip(model), projectionClip(model));
    const style2 = getStyles(markDef);
    const key2 = encoding.key;
    const sort3 = getSort2(model);
    const interactive2 = interactiveFlag(model);
    const aria2 = getMarkPropOrConfig("aria", markDef, config);
    const postEncodingTransform = markCompiler[mark].postEncodingTransform ? markCompiler[mark].postEncodingTransform(model) : null;
    return [
      {
        name: model.getName("marks"),
        type: markCompiler[mark].vgMark,
        ...clip3 ? { clip: clip3 } : {},
        ...style2 ? { style: style2 } : {},
        ...key2 ? { key: key2.field } : {},
        ...sort3 ? { sort: sort3 } : {},
        ...interactive2 ? interactive2 : {},
        ...aria2 === false ? { aria: aria2 } : {},
        from: { data: opt.fromPrefix + model.requestDataName(DataSourceType.Main) },
        encode: {
          update: markCompiler[mark].encodeEntry(model)
        },
        ...postEncodingTransform ? {
          transform: postEncodingTransform
        } : {}
      }
    ];
  }
  function scaleClip(model) {
    const xScale = model.getScaleComponent("x");
    const yScale = model.getScaleComponent("y");
    return xScale?.get("selectionExtent") || yScale?.get("selectionExtent") ? true : void 0;
  }
  function projectionClip(model) {
    const projection3 = model.component.projection;
    return projection3 && !projection3.isFit ? true : void 0;
  }
  function interactiveFlag(model) {
    if (!model.component.selection)
      return null;
    const unitCount = keys3(model.component.selection).length;
    let parentCount = unitCount;
    let parent = model.parent;
    while (parent && parentCount === 0) {
      parentCount = keys3(parent.component.selection).length;
      parent = parent.parent;
    }
    return parentCount ? {
      interactive: unitCount > 0 || model.mark === "geoshape" || !!model.encoding.tooltip || !!model.markDef.tooltip
    } : null;
  }

  // node_modules/vega-lite/build/src/compile/unit.js
  var UnitModel = class extends ModelWithField {
    constructor(spec, parent, parentGivenName, parentGivenSize = {}, config) {
      super(spec, "unit", parent, parentGivenName, config, void 0, isFrameMixins(spec) ? spec.view : void 0);
      this.specifiedScales = {};
      this.specifiedAxes = {};
      this.specifiedLegends = {};
      this.specifiedProjection = {};
      this.selection = [];
      this.children = [];
      this.correctDataNames = (mark2) => {
        if (mark2.from?.data) {
          mark2.from.data = this.lookupDataSource(mark2.from.data);
          if ("time" in this.encoding) {
            mark2.from.data = mark2.from.data + CURR;
          }
        }
        if (mark2.from?.facet?.data) {
          mark2.from.facet.data = this.lookupDataSource(mark2.from.facet.data);
        }
        return mark2;
      };
      const markDef = isMarkDef(spec.mark) ? { ...spec.mark } : { type: spec.mark };
      const mark = markDef.type;
      if (markDef.filled === void 0) {
        markDef.filled = defaultFilled(markDef, config, {
          graticule: spec.data && isGraticuleGenerator(spec.data)
        });
      }
      const encoding = this.encoding = initEncoding(spec.encoding || {}, mark, markDef.filled, config);
      this.markDef = initMarkdef(markDef, encoding, config);
      this.size = initLayoutSize({
        encoding,
        size: isFrameMixins(spec) ? {
          ...parentGivenSize,
          ...spec.width ? { width: spec.width } : {},
          ...spec.height ? { height: spec.height } : {}
        } : parentGivenSize
      });
      this.stack = stack(this.markDef, encoding);
      this.specifiedScales = this.initScales(mark, encoding);
      this.specifiedAxes = this.initAxes(encoding);
      this.specifiedLegends = this.initLegends(encoding);
      this.specifiedProjection = spec.projection;
      this.selection = (spec.params ?? []).filter((p2) => isSelectionParameter(p2));
    }
    get hasProjection() {
      const { encoding } = this;
      const isGeoShapeMark = this.mark === GEOSHAPE;
      const hasGeoPosition = encoding && GEOPOSITION_CHANNELS.some((channel) => isFieldOrDatumDef(encoding[channel]));
      return isGeoShapeMark || hasGeoPosition;
    }
    /**
     * Return specified Vega-Lite scale domain for a particular channel
     * @param channel
     */
    scaleDomain(channel) {
      const scale7 = this.specifiedScales[channel];
      return scale7 ? scale7.domain : void 0;
    }
    axis(channel) {
      return this.specifiedAxes[channel];
    }
    legend(channel) {
      return this.specifiedLegends[channel];
    }
    initScales(mark, encoding) {
      return SCALE_CHANNELS.reduce((scales2, channel) => {
        const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
        if (fieldOrDatumDef) {
          scales2[channel] = this.initScale(fieldOrDatumDef.scale ?? {});
        }
        return scales2;
      }, {});
    }
    initScale(scale7) {
      const { domain: domain4, range: range7 } = scale7;
      const scaleInternal = replaceExprRef(scale7);
      if (isArray(domain4)) {
        scaleInternal.domain = domain4.map(signalRefOrValue);
      }
      if (isArray(range7)) {
        scaleInternal.range = range7.map(signalRefOrValue);
      }
      return scaleInternal;
    }
    initAxes(encoding) {
      return POSITION_SCALE_CHANNELS.reduce((_axis, channel) => {
        const channelDef = encoding[channel];
        if (isFieldOrDatumDef(channelDef) || channel === X3 && isFieldOrDatumDef(encoding.x2) || channel === Y3 && isFieldOrDatumDef(encoding.y2)) {
          const axisSpec = isFieldOrDatumDef(channelDef) ? channelDef.axis : void 0;
          _axis[channel] = axisSpec ? this.initAxis({ ...axisSpec }) : axisSpec;
        }
        return _axis;
      }, {});
    }
    initAxis(axis) {
      const props = keys3(axis);
      const axisInternal = {};
      for (const prop of props) {
        const val = axis[prop];
        axisInternal[prop] = isConditionalAxisValue(val) ? signalOrValueRefWithCondition(val) : signalRefOrValue(val);
      }
      return axisInternal;
    }
    initLegends(encoding) {
      return NONPOSITION_SCALE_CHANNELS.reduce((_legend, channel) => {
        const fieldOrDatumDef = getFieldOrDatumDef(encoding[channel]);
        if (fieldOrDatumDef && supportLegend(channel)) {
          const legend = fieldOrDatumDef.legend;
          _legend[channel] = legend ? replaceExprRef(legend) : legend;
        }
        return _legend;
      }, {});
    }
    parseData() {
      this.component.data = parseData2(this);
    }
    parseLayoutSize() {
      parseUnitLayoutSize(this);
    }
    parseSelections() {
      this.component.selection = parseUnitSelection(this, this.selection);
    }
    parseMarkGroup() {
      this.component.mark = parseMarkGroups(this);
    }
    parseAxesAndHeaders() {
      this.component.axes = parseUnitAxes(this);
    }
    assembleSelectionTopLevelSignals(signals) {
      return assembleTopLevelSignals(this, signals);
    }
    assembleSignals() {
      return [...assembleAxisSignals(this), ...assembleUnitSelectionSignals(this, [])];
    }
    assembleSelectionData(data3) {
      return assembleUnitSelectionData(this, data3);
    }
    assembleLayout() {
      return null;
    }
    assembleLayoutSignals() {
      return assembleLayoutSignals(this);
    }
    assembleMarks() {
      let marks = this.component.mark ?? [];
      if (!this.parent || !isLayerModel(this.parent)) {
        marks = assembleUnitSelectionMarks(this, marks);
      }
      return marks.map(this.correctDataNames);
    }
    assembleGroupStyle() {
      const { style: style2 } = this.view || {};
      if (style2 !== void 0) {
        return style2;
      }
      if (this.encoding.x || this.encoding.y) {
        return "cell";
      } else {
        return "view";
      }
    }
    getMapping() {
      return this.encoding;
    }
    get mark() {
      return this.markDef.type;
    }
    channelHasField(channel) {
      return channelHasField(this.encoding, channel);
    }
    fieldDef(channel) {
      const channelDef = this.encoding[channel];
      return getFieldDef(channelDef);
    }
    typedFieldDef(channel) {
      const fieldDef = this.fieldDef(channel);
      if (isTypedFieldDef(fieldDef)) {
        return fieldDef;
      }
      return null;
    }
  };

  // node_modules/vega-lite/build/src/compile/layer.js
  var LayerModel = class _LayerModel extends Model {
    constructor(spec, parent, parentGivenName, parentGivenSize, config) {
      super(spec, "layer", parent, parentGivenName, config, spec.resolve, spec.view);
      const layoutSize = {
        ...parentGivenSize,
        ...spec.width ? { width: spec.width } : {},
        ...spec.height ? { height: spec.height } : {}
      };
      this.children = spec.layer.map((layer, i2) => {
        if (isLayerSpec(layer)) {
          return new _LayerModel(layer, this, this.getName(`layer_${i2}`), layoutSize, config);
        } else if (isUnitSpec(layer)) {
          return new UnitModel(layer, this, this.getName(`layer_${i2}`), layoutSize, config);
        }
        throw new Error(message_exports.invalidSpec(layer));
      });
    }
    parseData() {
      this.component.data = parseData2(this);
      for (const child of this.children) {
        child.parseData();
      }
    }
    parseLayoutSize() {
      parseLayerLayoutSize(this);
    }
    parseSelections() {
      this.component.selection = {};
      for (const child of this.children) {
        child.parseSelections();
        for (const key2 of keys3(child.component.selection)) {
          this.component.selection[key2] = child.component.selection[key2];
        }
      }
      if (Object.values(this.component.selection).some((selCmpt) => isTimerSelection(selCmpt))) {
        error2(MULTI_VIEW_ANIMATION_UNSUPPORTED);
      }
    }
    parseMarkGroup() {
      for (const child of this.children) {
        child.parseMarkGroup();
      }
    }
    parseAxesAndHeaders() {
      parseLayerAxes(this);
    }
    assembleSelectionTopLevelSignals(signals) {
      return this.children.reduce((sg, child) => child.assembleSelectionTopLevelSignals(sg), signals);
    }
    // TODO: Support same named selections across children.
    assembleSignals() {
      return this.children.reduce((signals, child) => {
        return signals.concat(child.assembleSignals());
      }, assembleAxisSignals(this));
    }
    assembleLayoutSignals() {
      return this.children.reduce((signals, child) => {
        return signals.concat(child.assembleLayoutSignals());
      }, assembleLayoutSignals(this));
    }
    assembleSelectionData(data3) {
      return this.children.reduce((db, child) => child.assembleSelectionData(db), data3);
    }
    assembleGroupStyle() {
      const uniqueStyles = /* @__PURE__ */ new Set();
      for (const child of this.children) {
        for (const style2 of array(child.assembleGroupStyle())) {
          uniqueStyles.add(style2);
        }
      }
      const styles = Array.from(uniqueStyles);
      return styles.length > 1 ? styles : styles.length === 1 ? styles[0] : void 0;
    }
    assembleTitle() {
      let title2 = super.assembleTitle();
      if (title2) {
        return title2;
      }
      for (const child of this.children) {
        title2 = child.assembleTitle();
        if (title2) {
          return title2;
        }
      }
      return void 0;
    }
    assembleLayout() {
      return null;
    }
    assembleMarks() {
      return assembleLayerSelectionMarks(this, this.children.flatMap((child) => {
        return child.assembleMarks();
      }));
    }
    assembleLegends() {
      return this.children.reduce((legends, child) => {
        return legends.concat(child.assembleLegends());
      }, assembleLegends(this));
    }
  };

  // node_modules/vega-lite/build/src/compile/buildmodel.js
  function buildModel(spec, parent, parentGivenName, unitSize, config) {
    if (isFacetSpec(spec)) {
      return new FacetModel(spec, parent, parentGivenName, config);
    } else if (isLayerSpec(spec)) {
      return new LayerModel(spec, parent, parentGivenName, unitSize, config);
    } else if (isUnitSpec(spec)) {
      return new UnitModel(spec, parent, parentGivenName, unitSize, config);
    } else if (isAnyConcatSpec(spec)) {
      return new ConcatModel(spec, parent, parentGivenName, config);
    }
    throw new Error(message_exports.invalidSpec(spec));
  }

  // node_modules/vega-lite/build/src/compile/compile.js
  function compile(inputSpec, opt = {}) {
    if (opt.logger) {
      set6(opt.logger);
    }
    if (opt.fieldTitle) {
      setTitleFormatter(opt.fieldTitle);
    }
    try {
      const config = initConfig(mergeConfig(opt.config, inputSpec.config));
      const spec = normalize3(inputSpec, config);
      const model = buildModel(spec, null, "", void 0, config);
      model.parse();
      optimizeDataflow(model.component.data, model);
      const vgSpec = assembleTopLevelModel(model, getTopLevelProperties(inputSpec, spec.autosize, config, model), inputSpec.datasets, inputSpec.usermeta);
      return {
        spec: vgSpec,
        normalized: spec
      };
    } finally {
      if (opt.logger) {
        reset2();
      }
      if (opt.fieldTitle) {
        resetTitleFormatter();
      }
    }
  }
  function getTopLevelProperties(inputSpec, autosize, config, model) {
    const width2 = model.component.layoutSize.get("width");
    const height2 = model.component.layoutSize.get("height");
    if (autosize === void 0) {
      autosize = { type: "pad" };
      if (model.hasAxisOrientSignalRef()) {
        autosize.resize = true;
      }
    } else if (isString(autosize)) {
      autosize = { type: autosize };
    }
    if (width2 && height2 && isFitType(autosize.type)) {
      if (width2 === "step" && height2 === "step") {
        warn2(message_exports.droppingFit());
        autosize.type = "pad";
      } else if (width2 === "step" || height2 === "step") {
        const sizeType = width2 === "step" ? "width" : "height";
        warn2(message_exports.droppingFit(getPositionScaleChannel(sizeType)));
        const inverseSizeType = sizeType === "width" ? "height" : "width";
        autosize.type = getFitType(inverseSizeType);
      }
    }
    return {
      ...keys3(autosize).length === 1 && autosize.type ? autosize.type === "pad" ? {} : { autosize: autosize.type } : { autosize },
      ...extractTopLevelProperties(config, false),
      ...extractTopLevelProperties(inputSpec, true)
    };
  }
  function assembleTopLevelModel(model, topLevelProperties, datasets = {}, usermeta) {
    const vgConfig = model.config ? stripAndRedirectConfig(model.config) : void 0;
    const rootData = assembleRootData(model.component.data, datasets);
    const data3 = model.assembleSelectionData(rootData);
    const projections2 = model.assembleProjections();
    const title2 = model.assembleTitle();
    const style2 = model.assembleGroupStyle();
    const encodeEntry2 = model.assembleGroupEncodeEntry(true);
    let layoutSignals = model.assembleLayoutSignals();
    layoutSignals = layoutSignals.filter((signal) => {
      if ((signal.name === "width" || signal.name === "height") && signal.value !== void 0) {
        topLevelProperties[signal.name] = +signal.value;
        return false;
      }
      return true;
    });
    const { params: params2, ...otherTopLevelProps } = topLevelProperties;
    return {
      $schema: "https://vega.github.io/schema/vega/v5.json",
      ...model.description ? { description: model.description } : {},
      ...otherTopLevelProps,
      ...title2 ? { title: title2 } : {},
      ...style2 ? { style: style2 } : {},
      ...encodeEntry2 ? { encode: { update: encodeEntry2 } } : {},
      data: data3,
      ...projections2.length > 0 ? { projections: projections2 } : {},
      ...model.assembleGroup([
        ...layoutSignals,
        ...model.assembleSelectionTopLevelSignals([]),
        ...assembleParameterSignals(params2)
      ]),
      ...vgConfig ? { config: vgConfig } : {},
      ...usermeta ? { usermeta } : {}
    };
  }

  // node_modules/vega-lite/build/src/index.js
  var version2 = package_default.version;

  // node_modules/vega-schema-url-parser/dist/parser.module.js
  function e(e4) {
    const [n2, r2] = /schema\/([\w-]+)\/([\w\.\-]+)\.json$/g.exec(e4).slice(1, 3);
    return { library: n2, version: r2 };
  }
  var parser_module_default = e;

  // node_modules/vega-themes/build/vega-themes.module.js
  var vega_themes_module_exports = {};
  __export(vega_themes_module_exports, {
    carbong10: () => carbong10,
    carbong100: () => carbong100,
    carbong90: () => carbong90,
    carbonwhite: () => carbonwhite,
    dark: () => darkTheme,
    excel: () => excelTheme,
    fivethirtyeight: () => fiveThirtyEightTheme,
    ggplot2: () => ggplot2Theme,
    googlecharts: () => googlechartsTheme,
    latimes: () => latimesTheme,
    powerbi: () => powerbiTheme,
    quartz: () => quartzTheme,
    urbaninstitute: () => urbanInstituteTheme,
    version: () => version3,
    vox: () => voxTheme
  });
  var name = "vega-themes";
  var version$1 = "2.15.0";
  var description2 = "Themes for stylized Vega and Vega-Lite visualizations.";
  var keywords3 = ["vega", "vega-lite", "themes", "style"];
  var license = "BSD-3-Clause";
  var author = {
    name: "UW Interactive Data Lab",
    url: "https://idl.cs.washington.edu"
  };
  var contributors = [{
    name: "Emily Gu",
    url: "https://github.com/emilygu"
  }, {
    name: "Arvind Satyanarayan",
    url: "http://arvindsatya.com"
  }, {
    name: "Jeffrey Heer",
    url: "https://idl.cs.washington.edu"
  }, {
    name: "Dominik Moritz",
    url: "https://www.domoritz.de"
  }];
  var main2 = "build/vega-themes.js";
  var module2 = "build/vega-themes.module.js";
  var unpkg = "build/vega-themes.min.js";
  var jsdelivr = "build/vega-themes.min.js";
  var types = "build/vega-themes.module.d.ts";
  var repository = {
    type: "git",
    url: "https://github.com/vega/vega-themes.git"
  };
  var files = ["src", "build"];
  var scripts = {
    prebuild: "yarn clean",
    build: "rollup -c",
    clean: "rimraf build && rimraf examples/build",
    "copy:data": "rsync -r node_modules/vega-datasets/data/* examples/data",
    "copy:build": "rsync -r build/* examples/build",
    "deploy:gh": "yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples",
    preversion: "yarn lint",
    serve: "browser-sync start -s -f build examples --serveStatic examples",
    start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'",
    format: "eslint . --fix",
    lint: "eslint .",
    release: "release-it"
  };
  var devDependencies = {
    "@babel/core": "^7.24.6",
    "@babel/plugin-transform-runtime": "^7.24.6",
    "@babel/preset-env": "^7.24.6",
    "@babel/preset-typescript": "^7.24.6",
    "@release-it/conventional-changelog": "^8.0.1",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-terser": "^0.4.4",
    "@typescript-eslint/eslint-plugin": "^7.11.0",
    "@typescript-eslint/parser": "^7.11.0",
    "browser-sync": "^3.0.2",
    concurrently: "^8.2.2",
    eslint: "^8.45.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.1.3",
    "gh-pages": "^6.1.1",
    prettier: "^3.2.5",
    "release-it": "^17.3.0",
    rollup: "^4.18.0",
    "rollup-plugin-bundle-size": "^1.0.3",
    "rollup-plugin-ts": "^3.4.5",
    typescript: "^5.4.5",
    vega: "^5.25.0",
    "vega-lite": "^5.9.3"
  };
  var peerDependencies = {
    vega: "*",
    "vega-lite": "*"
  };
  var dependencies = {};
  var pkg = {
    name,
    version: version$1,
    description: description2,
    keywords: keywords3,
    license,
    author,
    contributors,
    main: main2,
    module: module2,
    unpkg,
    jsdelivr,
    types,
    repository,
    files,
    scripts,
    devDependencies,
    peerDependencies,
    dependencies
  };
  var lightColor = "#fff";
  var medColor = "#888";
  var darkTheme = {
    background: "#333",
    view: {
      stroke: medColor
    },
    title: {
      color: lightColor,
      subtitleColor: lightColor
    },
    style: {
      "guide-label": {
        fill: lightColor
      },
      "guide-title": {
        fill: lightColor
      }
    },
    axis: {
      domainColor: lightColor,
      gridColor: medColor,
      tickColor: lightColor
    }
  };
  var markColor$7 = "#4572a7";
  var excelTheme = {
    background: "#fff",
    arc: {
      fill: markColor$7
    },
    area: {
      fill: markColor$7
    },
    line: {
      stroke: markColor$7,
      strokeWidth: 2
    },
    path: {
      stroke: markColor$7
    },
    rect: {
      fill: markColor$7
    },
    shape: {
      stroke: markColor$7
    },
    symbol: {
      fill: markColor$7,
      strokeWidth: 1.5,
      size: 50
    },
    axis: {
      bandPosition: 0.5,
      grid: true,
      gridColor: "#000000",
      gridOpacity: 1,
      gridWidth: 0.5,
      labelPadding: 10,
      tickSize: 5,
      tickWidth: 0.5
    },
    axisBand: {
      grid: false,
      tickExtra: true
    },
    legend: {
      labelBaseline: "middle",
      labelFontSize: 11,
      symbolSize: 50,
      symbolType: "square"
    },
    range: {
      category: ["#4572a7", "#aa4643", "#8aa453", "#71598e", "#4598ae", "#d98445", "#94aace", "#d09393", "#b9cc98", "#a99cbc"]
    }
  };
  var markColor$6 = "#30a2da";
  var axisColor$2 = "#cbcbcb";
  var guideLabelColor = "#999";
  var guideTitleColor = "#333";
  var backgroundColor$2 = "#f0f0f0";
  var blackTitle = "#333";
  var fiveThirtyEightTheme = {
    arc: {
      fill: markColor$6
    },
    area: {
      fill: markColor$6
    },
    axis: {
      domainColor: axisColor$2,
      grid: true,
      gridColor: axisColor$2,
      gridWidth: 1,
      labelColor: guideLabelColor,
      labelFontSize: 10,
      titleColor: guideTitleColor,
      tickColor: axisColor$2,
      tickSize: 10,
      titleFontSize: 14,
      titlePadding: 10,
      labelPadding: 4
    },
    axisBand: {
      grid: false
    },
    background: backgroundColor$2,
    group: {
      fill: backgroundColor$2
    },
    legend: {
      labelColor: blackTitle,
      labelFontSize: 11,
      padding: 1,
      symbolSize: 30,
      symbolType: "square",
      titleColor: blackTitle,
      titleFontSize: 14,
      titlePadding: 10
    },
    line: {
      stroke: markColor$6,
      strokeWidth: 2
    },
    path: {
      stroke: markColor$6,
      strokeWidth: 0.5
    },
    rect: {
      fill: markColor$6
    },
    range: {
      category: ["#30a2da", "#fc4f30", "#e5ae38", "#6d904f", "#8b8b8b", "#b96db8", "#ff9e27", "#56cc60", "#52d2ca", "#52689e", "#545454", "#9fe4f8"],
      diverging: ["#cc0020", "#e77866", "#f6e7e1", "#d6e8ed", "#91bfd9", "#1d78b5"],
      heatmap: ["#d6e8ed", "#cee0e5", "#91bfd9", "#549cc6", "#1d78b5"]
    },
    point: {
      filled: true,
      shape: "circle"
    },
    shape: {
      stroke: markColor$6
    },
    bar: {
      binSpacing: 2,
      fill: markColor$6,
      stroke: null
    },
    title: {
      anchor: "start",
      fontSize: 24,
      fontWeight: 600,
      offset: 20
    }
  };
  var markColor$5 = "#000";
  var ggplot2Theme = {
    group: {
      fill: "#e5e5e5"
    },
    arc: {
      fill: markColor$5
    },
    area: {
      fill: markColor$5
    },
    line: {
      stroke: markColor$5
    },
    path: {
      stroke: markColor$5
    },
    rect: {
      fill: markColor$5
    },
    shape: {
      stroke: markColor$5
    },
    symbol: {
      fill: markColor$5,
      size: 40
    },
    axis: {
      domain: false,
      grid: true,
      gridColor: "#FFFFFF",
      gridOpacity: 1,
      labelColor: "#7F7F7F",
      labelPadding: 4,
      tickColor: "#7F7F7F",
      tickSize: 5.67,
      titleFontSize: 16,
      titleFontWeight: "normal"
    },
    legend: {
      labelBaseline: "middle",
      labelFontSize: 11,
      symbolSize: 40
    },
    range: {
      category: ["#000000", "#7F7F7F", "#1A1A1A", "#999999", "#333333", "#B0B0B0", "#4D4D4D", "#C9C9C9", "#666666", "#DCDCDC"]
    }
  };
  var headlineFontSize = 22;
  var headlineFontWeight = "normal";
  var labelFont$1 = "Benton Gothic, sans-serif";
  var labelFontSize = 11.5;
  var labelFontWeight = "normal";
  var markColor$4 = "#82c6df";
  var titleFont = "Benton Gothic Bold, sans-serif";
  var titleFontWeight = "normal";
  var titleFontSize$1 = 13;
  var colorSchemes$1 = {
    "category-6": ["#ec8431", "#829eb1", "#c89d29", "#3580b1", "#adc839", "#ab7fb4"],
    "fire-7": ["#fbf2c7", "#f9e39c", "#f8d36e", "#f4bb6a", "#e68a4f", "#d15a40", "#ab4232"],
    "fireandice-6": ["#e68a4f", "#f4bb6a", "#f9e39c", "#dadfe2", "#a6b7c6", "#849eae"],
    "ice-7": ["#edefee", "#dadfe2", "#c4ccd2", "#a6b7c6", "#849eae", "#607785", "#47525d"]
  };
  var latimesTheme = {
    background: "#ffffff",
    title: {
      anchor: "start",
      color: "#000000",
      font: titleFont,
      fontSize: headlineFontSize,
      fontWeight: headlineFontWeight
    },
    arc: {
      fill: markColor$4
    },
    area: {
      fill: markColor$4
    },
    line: {
      stroke: markColor$4,
      strokeWidth: 2
    },
    path: {
      stroke: markColor$4
    },
    rect: {
      fill: markColor$4
    },
    shape: {
      stroke: markColor$4
    },
    symbol: {
      fill: markColor$4,
      size: 30
    },
    axis: {
      labelFont: labelFont$1,
      labelFontSize,
      labelFontWeight,
      titleFont,
      titleFontSize: titleFontSize$1,
      titleFontWeight
    },
    axisX: {
      labelAngle: 0,
      labelPadding: 4,
      tickSize: 3
    },
    axisY: {
      labelBaseline: "middle",
      maxExtent: 45,
      minExtent: 45,
      tickSize: 2,
      titleAlign: "left",
      titleAngle: 0,
      titleX: -45,
      titleY: -11
    },
    legend: {
      labelFont: labelFont$1,
      labelFontSize,
      symbolType: "square",
      titleFont,
      titleFontSize: titleFontSize$1,
      titleFontWeight
    },
    range: {
      category: colorSchemes$1["category-6"],
      diverging: colorSchemes$1["fireandice-6"],
      heatmap: colorSchemes$1["fire-7"],
      ordinal: colorSchemes$1["fire-7"],
      ramp: colorSchemes$1["fire-7"]
    }
  };
  var markColor$3 = "#ab5787";
  var axisColor$1 = "#979797";
  var quartzTheme = {
    background: "#f9f9f9",
    arc: {
      fill: markColor$3
    },
    area: {
      fill: markColor$3
    },
    line: {
      stroke: markColor$3
    },
    path: {
      stroke: markColor$3
    },
    rect: {
      fill: markColor$3
    },
    shape: {
      stroke: markColor$3
    },
    symbol: {
      fill: markColor$3,
      size: 30
    },
    axis: {
      domainColor: axisColor$1,
      domainWidth: 0.5,
      gridWidth: 0.2,
      labelColor: axisColor$1,
      tickColor: axisColor$1,
      tickWidth: 0.2,
      titleColor: axisColor$1
    },
    axisBand: {
      grid: false
    },
    axisX: {
      grid: true,
      tickSize: 10
    },
    axisY: {
      domain: false,
      grid: true,
      tickSize: 0
    },
    legend: {
      labelFontSize: 11,
      padding: 1,
      symbolSize: 30,
      symbolType: "square"
    },
    range: {
      category: ["#ab5787", "#51b2e5", "#703c5c", "#168dd9", "#d190b6", "#00609f", "#d365ba", "#154866", "#666666", "#c4c4c4"]
    }
  };
  var markColor$2 = "#3e5c69";
  var voxTheme = {
    background: "#fff",
    arc: {
      fill: markColor$2
    },
    area: {
      fill: markColor$2
    },
    line: {
      stroke: markColor$2
    },
    path: {
      stroke: markColor$2
    },
    rect: {
      fill: markColor$2
    },
    shape: {
      stroke: markColor$2
    },
    symbol: {
      fill: markColor$2
    },
    axis: {
      domainWidth: 0.5,
      grid: true,
      labelPadding: 2,
      tickSize: 5,
      tickWidth: 0.5,
      titleFontWeight: "normal"
    },
    axisBand: {
      grid: false
    },
    axisX: {
      gridWidth: 0.2
    },
    axisY: {
      gridDash: [3],
      gridWidth: 0.4
    },
    legend: {
      labelFontSize: 11,
      padding: 1,
      symbolType: "square"
    },
    range: {
      category: ["#3e5c69", "#6793a6", "#182429", "#0570b0", "#3690c0", "#74a9cf", "#a6bddb", "#e2ddf2"]
    }
  };
  var markColor$1 = "#1696d2";
  var axisColor = "#000000";
  var backgroundColor$1 = "#FFFFFF";
  var font2 = "Lato";
  var labelFont = "Lato";
  var sourceFont = "Lato";
  var gridColor$1 = "#DEDDDD";
  var titleFontSize = 18;
  var colorSchemes = {
    "main-colors": ["#1696d2", "#d2d2d2", "#000000", "#fdbf11", "#ec008b", "#55b748", "#5c5859", "#db2b27"],
    "shades-blue": ["#CFE8F3", "#A2D4EC", "#73BFE2", "#46ABDB", "#1696D2", "#12719E", "#0A4C6A", "#062635"],
    "shades-gray": ["#F5F5F5", "#ECECEC", "#E3E3E3", "#DCDBDB", "#D2D2D2", "#9D9D9D", "#696969", "#353535"],
    "shades-yellow": ["#FFF2CF", "#FCE39E", "#FDD870", "#FCCB41", "#FDBF11", "#E88E2D", "#CA5800", "#843215"],
    "shades-magenta": ["#F5CBDF", "#EB99C2", "#E46AA7", "#E54096", "#EC008B", "#AF1F6B", "#761548", "#351123"],
    "shades-green": ["#DCEDD9", "#BCDEB4", "#98CF90", "#78C26D", "#55B748", "#408941", "#2C5C2D", "#1A2E19"],
    "shades-black": ["#D5D5D4", "#ADABAC", "#848081", "#5C5859", "#332D2F", "#262223", "#1A1717", "#0E0C0D"],
    "shades-red": ["#F8D5D4", "#F1AAA9", "#E9807D", "#E25552", "#DB2B27", "#A4201D", "#6E1614", "#370B0A"],
    "one-group": ["#1696d2", "#000000"],
    "two-groups-cat-1": ["#1696d2", "#000000"],
    "two-groups-cat-2": ["#1696d2", "#fdbf11"],
    "two-groups-cat-3": ["#1696d2", "#db2b27"],
    "two-groups-seq": ["#a2d4ec", "#1696d2"],
    "three-groups-cat": ["#1696d2", "#fdbf11", "#000000"],
    "three-groups-seq": ["#a2d4ec", "#1696d2", "#0a4c6a"],
    "four-groups-cat-1": ["#000000", "#d2d2d2", "#fdbf11", "#1696d2"],
    "four-groups-cat-2": ["#1696d2", "#ec0008b", "#fdbf11", "#5c5859"],
    "four-groups-seq": ["#cfe8f3", "#73bf42", "#1696d2", "#0a4c6a"],
    "five-groups-cat-1": ["#1696d2", "#fdbf11", "#d2d2d2", "#ec008b", "#000000"],
    "five-groups-cat-2": ["#1696d2", "#0a4c6a", "#d2d2d2", "#fdbf11", "#332d2f"],
    "five-groups-seq": ["#cfe8f3", "#73bf42", "#1696d2", "#0a4c6a", "#000000"],
    "six-groups-cat-1": ["#1696d2", "#ec008b", "#fdbf11", "#000000", "#d2d2d2", "#55b748"],
    "six-groups-cat-2": ["#1696d2", "#d2d2d2", "#ec008b", "#fdbf11", "#332d2f", "#0a4c6a"],
    "six-groups-seq": ["#cfe8f3", "#a2d4ec", "#73bfe2", "#46abdb", "#1696d2", "#12719e"],
    "diverging-colors": ["#ca5800", "#fdbf11", "#fdd870", "#fff2cf", "#cfe8f3", "#73bfe2", "#1696d2", "#0a4c6a"]
  };
  var urbanInstituteTheme = {
    background: backgroundColor$1,
    title: {
      anchor: "start",
      fontSize: titleFontSize,
      font: font2
    },
    axisX: {
      domain: true,
      domainColor: axisColor,
      domainWidth: 1,
      grid: false,
      labelFontSize: 12,
      labelFont,
      labelAngle: 0,
      tickColor: axisColor,
      tickSize: 5,
      titleFontSize: 12,
      titlePadding: 10,
      titleFont: font2
    },
    axisY: {
      domain: false,
      domainWidth: 1,
      grid: true,
      gridColor: gridColor$1,
      gridWidth: 1,
      labelFontSize: 12,
      labelFont,
      labelPadding: 8,
      ticks: false,
      titleFontSize: 12,
      titlePadding: 10,
      titleFont: font2,
      titleAngle: 0,
      titleY: -10,
      titleX: 18
    },
    legend: {
      labelFontSize: 12,
      labelFont,
      symbolSize: 100,
      titleFontSize: 12,
      titlePadding: 10,
      titleFont: font2,
      orient: "right",
      offset: 10
    },
    view: {
      stroke: "transparent"
    },
    range: {
      category: colorSchemes["six-groups-cat-1"],
      diverging: colorSchemes["diverging-colors"],
      heatmap: colorSchemes["diverging-colors"],
      ordinal: colorSchemes["six-groups-seq"],
      ramp: colorSchemes["shades-blue"]
    },
    area: {
      fill: markColor$1
    },
    rect: {
      fill: markColor$1
    },
    line: {
      color: markColor$1,
      stroke: markColor$1,
      strokeWidth: 5
    },
    trail: {
      color: markColor$1,
      stroke: markColor$1,
      strokeWidth: 0,
      size: 1
    },
    path: {
      stroke: markColor$1,
      strokeWidth: 0.5
    },
    point: {
      filled: true
    },
    text: {
      font: sourceFont,
      color: markColor$1,
      fontSize: 11,
      align: "center",
      fontWeight: 400,
      size: 11
    },
    style: {
      bar: {
        fill: markColor$1,
        stroke: null
      }
    },
    arc: {
      fill: markColor$1
    },
    shape: {
      stroke: markColor$1
    },
    symbol: {
      fill: markColor$1,
      size: 30
    }
  };
  var markColor = "#3366CC";
  var gridColor = "#ccc";
  var defaultFont$1 = "Arial, sans-serif";
  var googlechartsTheme = {
    arc: {
      fill: markColor
    },
    area: {
      fill: markColor
    },
    path: {
      stroke: markColor
    },
    rect: {
      fill: markColor
    },
    shape: {
      stroke: markColor
    },
    symbol: {
      stroke: markColor
    },
    circle: {
      fill: markColor
    },
    background: "#fff",
    padding: {
      top: 10,
      right: 10,
      bottom: 10,
      left: 10
    },
    style: {
      "guide-label": {
        font: defaultFont$1,
        fontSize: 12
      },
      "guide-title": {
        font: defaultFont$1,
        fontSize: 12
      },
      "group-title": {
        font: defaultFont$1,
        fontSize: 12
      }
    },
    title: {
      font: defaultFont$1,
      fontSize: 14,
      fontWeight: "bold",
      dy: -3,
      anchor: "start"
    },
    axis: {
      gridColor,
      tickColor: gridColor,
      domain: false,
      grid: true
    },
    range: {
      category: ["#4285F4", "#DB4437", "#F4B400", "#0F9D58", "#AB47BC", "#00ACC1", "#FF7043", "#9E9D24", "#5C6BC0", "#F06292", "#00796B", "#C2185B"],
      heatmap: ["#c6dafc", "#5e97f6", "#2a56c6"]
    }
  };
  var ptToPx = (value3) => value3 * (1 / 3 + 1);
  var fontSmallPx = ptToPx(9);
  var legendFontPx = ptToPx(10);
  var fontLargePx = ptToPx(12);
  var fontStandard = "Segoe UI";
  var fontTitle = "wf_standard-font, helvetica, arial, sans-serif";
  var firstLevelElementColor = "#252423";
  var secondLevelElementColor = "#605E5C";
  var backgroundColor = "transparent";
  var backgroundSecondaryColor = "#C8C6C4";
  var paletteColor1 = "#118DFF";
  var paletteColor2 = "#12239E";
  var paletteColor3 = "#E66C37";
  var paletteColor4 = "#6B007B";
  var paletteColor5 = "#E044A7";
  var paletteColor6 = "#744EC2";
  var paletteColor7 = "#D9B300";
  var paletteColor8 = "#D64550";
  var divergentColorMax = paletteColor1;
  var divergentColorMin = "#DEEFFF";
  var divergentPalette = [divergentColorMin, divergentColorMax];
  var ordinalPalette = [divergentColorMin, "#c7e4ff", "#b0d9ff", "#9aceff", "#83c3ff", "#6cb9ff", "#55aeff", "#3fa3ff", "#2898ff", divergentColorMax];
  var powerbiTheme = {
    view: {
      stroke: backgroundColor
    },
    background: backgroundColor,
    font: fontStandard,
    header: {
      titleFont: fontTitle,
      titleFontSize: fontLargePx,
      titleColor: firstLevelElementColor,
      labelFont: fontStandard,
      labelFontSize: legendFontPx,
      labelColor: secondLevelElementColor
    },
    axis: {
      ticks: false,
      grid: false,
      domain: false,
      labelColor: secondLevelElementColor,
      labelFontSize: fontSmallPx,
      titleFont: fontTitle,
      titleColor: firstLevelElementColor,
      titleFontSize: fontLargePx,
      titleFontWeight: "normal"
    },
    axisQuantitative: {
      tickCount: 3,
      grid: true,
      gridColor: backgroundSecondaryColor,
      gridDash: [1, 5],
      labelFlush: false
    },
    axisBand: {
      tickExtra: true
    },
    axisX: {
      labelPadding: 5
    },
    axisY: {
      labelPadding: 10
    },
    bar: {
      fill: paletteColor1
    },
    line: {
      stroke: paletteColor1,
      strokeWidth: 3,
      strokeCap: "round",
      strokeJoin: "round"
    },
    text: {
      font: fontStandard,
      fontSize: fontSmallPx,
      fill: secondLevelElementColor
    },
    arc: {
      fill: paletteColor1
    },
    area: {
      fill: paletteColor1,
      line: true,
      opacity: 0.6
    },
    path: {
      stroke: paletteColor1
    },
    rect: {
      fill: paletteColor1
    },
    point: {
      fill: paletteColor1,
      filled: true,
      size: 75
    },
    shape: {
      stroke: paletteColor1
    },
    symbol: {
      fill: paletteColor1,
      strokeWidth: 1.5,
      size: 50
    },
    legend: {
      titleFont: fontStandard,
      titleFontWeight: "bold",
      titleColor: secondLevelElementColor,
      labelFont: fontStandard,
      labelFontSize: legendFontPx,
      labelColor: secondLevelElementColor,
      symbolType: "circle",
      symbolSize: 75
    },
    range: {
      category: [paletteColor1, paletteColor2, paletteColor3, paletteColor4, paletteColor5, paletteColor6, paletteColor7, paletteColor8],
      diverging: divergentPalette,
      heatmap: divergentPalette,
      ordinal: ordinalPalette
    }
  };
  var defaultFont = 'IBM Plex Sans,system-ui,-apple-system,BlinkMacSystemFont,".sfnstext-regular",sans-serif';
  var condensedFont = 'IBM Plex Sans Condensed, system-ui, -apple-system, BlinkMacSystemFont, ".SFNSText-Regular", sans-serif';
  var fontWeight = 400;
  var TOKENS = {
    textPrimary: {
      g90: "#f4f4f4",
      g100: "#f4f4f4",
      white: "#161616",
      g10: "#161616"
    },
    textSecondary: {
      g90: "#c6c6c6",
      g100: "#c6c6c6",
      white: "#525252",
      g10: "#525252"
    },
    // layer
    layerAccent01: {
      white: "#e0e0e0",
      g10: "#e0e0e0",
      g90: "#525252",
      g100: "#393939"
    },
    // grid
    gridBg: {
      white: "#ffffff",
      g10: "#ffffff",
      g90: "#161616",
      g100: "#161616"
    }
  };
  var darkCategories = ["#8a3ffc", "#33b1ff", "#007d79", "#ff7eb6", "#fa4d56", "#fff1f1", "#6fdc8c", "#4589ff", "#d12771", "#d2a106", "#08bdba", "#bae6ff", "#ba4e00", "#d4bbff"];
  var lightCategories = ["#6929c4", "#1192e8", "#005d5d", "#9f1853", "#fa4d56", "#570408", "#198038", "#002d9c", "#ee538b", "#b28600", "#009d9a", "#012749", "#8a3800", "#a56eff"];
  function genCarbonConfig({
    theme,
    background: background3
  }) {
    const type3 = ["white", "g10"].includes(theme) ? "light" : "dark";
    const viewbg = TOKENS.gridBg[theme];
    const titleColor = TOKENS.textPrimary[theme];
    const textColor = TOKENS.textSecondary[theme];
    const category = type3 === "dark" ? darkCategories : lightCategories;
    const markColor2 = type3 === "dark" ? "#d4bbff" : "#6929c4";
    return {
      background: background3,
      arc: {
        fill: markColor2
      },
      area: {
        fill: markColor2
      },
      path: {
        stroke: markColor2
      },
      rect: {
        fill: markColor2
      },
      shape: {
        stroke: markColor2
      },
      symbol: {
        stroke: markColor2
      },
      circle: {
        fill: markColor2
      },
      view: {
        fill: viewbg,
        stroke: viewbg
      },
      group: {
        fill: viewbg
      },
      title: {
        color: titleColor,
        anchor: "start",
        dy: -15,
        fontSize: 16,
        font: defaultFont,
        fontWeight: 600
      },
      axis: {
        // Axis labels
        labelColor: textColor,
        labelFontSize: 12,
        labelFont: condensedFont,
        labelFontWeight: fontWeight,
        // Axis titles
        titleColor,
        titleFontWeight: 600,
        titleFontSize: 12,
        // MISC
        grid: true,
        gridColor: TOKENS.layerAccent01[theme],
        labelAngle: 0
      },
      axisX: {
        titlePadding: 10
      },
      axisY: {
        titlePadding: 2.5
      },
      style: {
        "guide-label": {
          font: defaultFont,
          fill: textColor,
          fontWeight
        },
        "guide-title": {
          font: defaultFont,
          fill: textColor,
          fontWeight
        }
      },
      range: {
        category,
        diverging: ["#750e13", "#a2191f", "#da1e28", "#fa4d56", "#ff8389", "#ffb3b8", "#ffd7d9", "#fff1f1", "#e5f6ff", "#bae6ff", "#82cfff", "#33b1ff", "#1192e8", "#0072c3", "#00539a", "#003a6d"],
        heatmap: ["#f6f2ff", "#e8daff", "#d4bbff", "#be95ff", "#a56eff", "#8a3ffc", "#6929c4", "#491d8b", "#31135e", "#1c0f30"]
      }
    };
  }
  var carbonwhite = genCarbonConfig({
    theme: "white",
    background: "#ffffff"
  });
  var carbong10 = genCarbonConfig({
    theme: "g10",
    background: "#f4f4f4"
  });
  var carbong90 = genCarbonConfig({
    theme: "g90",
    background: "#262626"
  });
  var carbong100 = genCarbonConfig({
    theme: "g100",
    background: "#161616"
  });
  var version3 = pkg.version;

  // node_modules/vega-tooltip/build/vega-tooltip.module.js
  var name2 = "vega-tooltip";
  var version$12 = "0.35.2";
  var description3 = "A tooltip plugin for Vega-Lite and Vega visualizations.";
  var keywords4 = [
    "vega-lite",
    "vega",
    "tooltip"
  ];
  var repository2 = {
    type: "git",
    url: "https://github.com/vega/vega-tooltip.git"
  };
  var author2 = {
    name: "UW Interactive Data Lab",
    url: "https://idl.cs.washington.edu"
  };
  var collaborators = [
    "Dominik Moritz",
    "Sira Horradarn",
    "Zening Qu",
    "Kanit Wongsuphasawat",
    "Yuri Astrakhan",
    "Jeffrey Heer"
  ];
  var license2 = "BSD-3-Clause";
  var bugs = {
    url: "https://github.com/vega/vega-tooltip/issues"
  };
  var homepage = "https://github.com/vega/vega-tooltip#readme";
  var main3 = "build/vega-tooltip.js";
  var module3 = "build/vega-tooltip.module.js";
  var unpkg2 = "build/vega-tooltip.min.js";
  var jsdelivr2 = "build/vega-tooltip.min.js";
  var types2 = "build/src/index.d.ts";
  var files2 = [
    "src",
    "build",
    "types"
  ];
  var scripts2 = {
    prebuild: "npm run clean && npm run build:style",
    build: "rollup -c",
    "build:style": "./build-style.sh",
    clean: "rimraf build && rimraf src/style.ts",
    "copy:data": "cp -R node_modules/vega-datasets/data examples",
    "copy:build": "cp -R build examples",
    "deploy:gh": "npm run build && npm run copy:build && gh-pages -d examples && npm run clean",
    prepublishOnly: "npm run clean && npm run build",
    preversion: "npm run lint && npm run test",
    serve: "browser-sync start -s -f build examples --serveStatic examples",
    start: "npm run build && concurrently --kill-others -n Server,Rollup 'npm run serve' 'rollup -c -w'",
    pretest: "npm run build:style",
    test: "jest",
    "test:inspect": "node --inspect-brk ./node_modules/.bin/jest --runInBand",
    prepare: "npm run copy:data",
    prettierbase: "prettier '*.{css,scss,html}'",
    format: "eslint . --fix && npm run prettierbase -- --write",
    lint: "eslint . && npm run prettierbase -- --check",
    release: "release-it"
  };
  var devDependencies2 = {
    "@babel/core": "^7.26.0",
    "@babel/plugin-proposal-async-generator-functions": "^7.20.7",
    "@babel/plugin-proposal-json-strings": "^7.18.6",
    "@babel/plugin-proposal-object-rest-spread": "^7.20.7",
    "@babel/plugin-proposal-optional-catch-binding": "^7.18.6",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.25.9",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-typescript": "^7.26.0",
    "@release-it/conventional-changelog": "^9.0.2",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.3.0",
    "@rollup/plugin-terser": "^0.4.4",
    "@rollup/plugin-typescript": "^12.1.1",
    "@types/jest": "^29.5.14",
    "@typescript-eslint/eslint-plugin": "^8.13.0",
    "@typescript-eslint/parser": "^8.13.0",
    "browser-sync": "^3.0.3",
    concurrently: "^9.1.0",
    eslint: "^8.46.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-jest": "^28.8.3",
    "eslint-plugin-prettier": "^5.2.1",
    "gh-pages": "^6.2.0",
    jest: "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    path: "^0.12.7",
    prettier: "^3.3.3",
    "release-it": "^17.10.0",
    rollup: "^4.24.4",
    "rollup-plugin-bundle-size": "^1.0.3",
    sass: "^1.80.6",
    typescript: "~5.6.3",
    "vega-datasets": "^2.9.0",
    "vega-typings": "^1.3.1"
  };
  var dependencies2 = {
    "vega-util": "^1.17.2"
  };
  var optionalDependencies = {
    "@rollup/rollup-linux-x64-gnu": "^4.24.4"
  };
  var pkg2 = {
    name: name2,
    version: version$12,
    description: description3,
    keywords: keywords4,
    repository: repository2,
    author: author2,
    collaborators,
    license: license2,
    bugs,
    homepage,
    main: main3,
    module: module3,
    unpkg: unpkg2,
    jsdelivr: jsdelivr2,
    types: types2,
    files: files2,
    scripts: scripts2,
    devDependencies: devDependencies2,
    dependencies: dependencies2,
    optionalDependencies
  };
  function formatValue3(value3, valueToHtml, maxDepth2, baseURL) {
    if (isArray(value3)) {
      return `[${value3.map((v3) => valueToHtml(isString(v3) ? v3 : stringify3(v3, maxDepth2))).join(", ")}]`;
    }
    if (isObject(value3)) {
      let content2 = "";
      const { title: title2, image: image3, ...rest } = value3;
      if (title2) {
        content2 += `<h2>${valueToHtml(title2)}</h2>`;
      }
      if (image3) {
        content2 += `<img src="${new URL(valueToHtml(image3), baseURL || location.href).href}">`;
      }
      const keys4 = Object.keys(rest);
      if (keys4.length > 0) {
        content2 += "<table>";
        for (const key2 of keys4) {
          let val = rest[key2];
          if (val === void 0) {
            continue;
          }
          if (isObject(val)) {
            val = stringify3(val, maxDepth2);
          }
          content2 += `<tr><td class="key">${valueToHtml(key2)}</td><td class="value">${valueToHtml(val)}</td></tr>`;
        }
        content2 += `</table>`;
      }
      return content2 || "{}";
    }
    return valueToHtml(value3);
  }
  function replacer(maxDepth2) {
    const stack2 = [];
    return function(key2, value3) {
      if (typeof value3 !== "object" || value3 === null) {
        return value3;
      }
      const pos = stack2.indexOf(this) + 1;
      stack2.length = pos;
      if (stack2.length > maxDepth2) {
        return "[Object]";
      }
      if (stack2.indexOf(value3) >= 0) {
        return "[Circular]";
      }
      stack2.push(value3);
      return value3;
    };
  }
  function stringify3(obj, maxDepth2) {
    return JSON.stringify(obj, replacer(maxDepth2));
  }
  var defaultStyle = `#vg-tooltip-element {
  visibility: hidden;
  padding: 8px;
  position: fixed;
  z-index: 1000;
  font-family: sans-serif;
  font-size: 11px;
  border-radius: 3px;
  box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  /* The default theme is the light theme. */
  background-color: rgba(255, 255, 255, 0.95);
  border: 1px solid #d9d9d9;
  color: black;
}
#vg-tooltip-element.visible {
  visibility: visible;
}
#vg-tooltip-element h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 13px;
}
#vg-tooltip-element table {
  border-spacing: 0;
}
#vg-tooltip-element table tr {
  border: none;
}
#vg-tooltip-element table tr td {
  overflow: hidden;
  text-overflow: ellipsis;
  padding-top: 2px;
  padding-bottom: 2px;
}
#vg-tooltip-element table tr td.key {
  color: #808080;
  max-width: 150px;
  text-align: right;
  padding-right: 4px;
}
#vg-tooltip-element table tr td.value {
  display: block;
  max-width: 300px;
  max-height: 7em;
  text-align: left;
}
#vg-tooltip-element.dark-theme {
  background-color: rgba(32, 32, 32, 0.9);
  border: 1px solid #f5f5f5;
  color: white;
}
#vg-tooltip-element.dark-theme td.key {
  color: #bfbfbf;
}
`;
  var EL_ID = "vg-tooltip-element";
  var DEFAULT_OPTIONS = {
    offsetX: 10,
    offsetY: 10,
    id: EL_ID,
    styleId: "vega-tooltip-style",
    theme: "light",
    disableDefaultStyle: false,
    sanitize: escapeHTML,
    maxDepth: 2,
    formatTooltip: formatValue3,
    baseURL: "",
    anchor: "cursor",
    position: ["top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"]
  };
  function escapeHTML(value3) {
    return String(value3).replace(/&/g, "&amp;").replace(/</g, "&lt;");
  }
  function createDefaultStyle(id2) {
    if (!/^[A-Za-z]+[-:.\w]*$/.test(id2)) {
      throw new Error("Invalid HTML ID");
    }
    return defaultStyle.toString().replace(EL_ID, id2);
  }
  function calculatePositionRelativeToCursor(event2, tooltipBox, { offsetX, offsetY }) {
    const positions = getPositions({ x1: event2.clientX, x2: event2.clientX, y1: event2.clientY, y2: event2.clientY }, tooltipBox, offsetX, offsetY);
    const postionArr = ["bottom-right", "bottom-left", "top-right", "top-left"];
    for (const p2 of postionArr) {
      if (tooltipIsInViewport(positions[p2], tooltipBox)) {
        return positions[p2];
      }
    }
    return positions["top-left"];
  }
  function calculatePositionRelativeToMark(handler, event2, item, tooltipBox, options) {
    const { position: position2, offsetX, offsetY } = options;
    const containerBox = handler._el.getBoundingClientRect();
    const origin = handler._origin;
    const markBounds = getMarkBounds(containerBox, origin, item);
    const positions = getPositions(markBounds, tooltipBox, offsetX, offsetY);
    const positionArr = Array.isArray(position2) ? position2 : [position2];
    for (const p2 of positionArr) {
      if (tooltipIsInViewport(positions[p2], tooltipBox) && !mouseIsOnTooltip(event2, positions[p2], tooltipBox)) {
        return positions[p2];
      }
    }
    return calculatePositionRelativeToCursor(event2, tooltipBox, options);
  }
  function getMarkBounds(containerBox, origin, item) {
    const markBounds = item.isVoronoi ? item.datum.bounds : item.bounds;
    let left = containerBox.left + origin[0] + markBounds.x1;
    let top = containerBox.top + origin[1] + markBounds.y1;
    let parentItem = item;
    while (parentItem.mark.group) {
      parentItem = parentItem.mark.group;
      left += parentItem.x ?? 0;
      top += parentItem.y ?? 0;
    }
    const markWidth = markBounds.x2 - markBounds.x1;
    const markHeight = markBounds.y2 - markBounds.y1;
    return {
      x1: left,
      x2: left + markWidth,
      y1: top,
      y2: top + markHeight
    };
  }
  function getPositions(markBounds, tooltipBox, offsetX, offsetY) {
    const xc = (markBounds.x1 + markBounds.x2) / 2;
    const yc = (markBounds.y1 + markBounds.y2) / 2;
    const left = markBounds.x1 - tooltipBox.width - offsetX;
    const center = xc - tooltipBox.width / 2;
    const right = markBounds.x2 + offsetX;
    const top = markBounds.y1 - tooltipBox.height - offsetY;
    const middle = yc - tooltipBox.height / 2;
    const bottom = markBounds.y2 + offsetY;
    const positions = {
      top: { x: center, y: top },
      bottom: { x: center, y: bottom },
      left: { x: left, y: middle },
      right: { x: right, y: middle },
      "top-left": { x: left, y: top },
      "top-right": { x: right, y: top },
      "bottom-left": { x: left, y: bottom },
      "bottom-right": { x: right, y: bottom }
    };
    return positions;
  }
  function tooltipIsInViewport(position2, tooltipBox) {
    return position2.x >= 0 && position2.y >= 0 && position2.x + tooltipBox.width <= window.innerWidth && position2.y + tooltipBox.height <= window.innerHeight;
  }
  function mouseIsOnTooltip(event2, position2, tooltipBox) {
    return event2.clientX >= position2.x && event2.clientX <= position2.x + tooltipBox.width && event2.clientY >= position2.y && event2.clientY <= position2.y + tooltipBox.height;
  }
  var Handler2 = class {
    /**
     * Create the tooltip handler and initialize the element and style.
     *
     * @param options Tooltip Options
     */
    constructor(options) {
      this.options = { ...DEFAULT_OPTIONS, ...options };
      const elementId = this.options.id;
      this.el = null;
      this.call = this.tooltipHandler.bind(this);
      if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {
        const style2 = document.createElement("style");
        style2.setAttribute("id", this.options.styleId);
        style2.innerHTML = createDefaultStyle(elementId);
        const head = document.head;
        if (head.childNodes.length > 0) {
          head.insertBefore(style2, head.childNodes[0]);
        } else {
          head.appendChild(style2);
        }
      }
    }
    /**
     * The tooltip handler function.
     */
    tooltipHandler(handler, event2, item, value3) {
      this.el = document.getElementById(this.options.id);
      if (!this.el) {
        this.el = document.createElement("div");
        this.el.setAttribute("id", this.options.id);
        this.el.classList.add("vg-tooltip");
        const tooltipContainer = document.fullscreenElement ?? document.body;
        tooltipContainer.appendChild(this.el);
      }
      if (value3 == null || value3 === "") {
        this.el.classList.remove("visible", `${this.options.theme}-theme`);
        return;
      }
      this.el.innerHTML = this.options.formatTooltip(value3, this.options.sanitize, this.options.maxDepth, this.options.baseURL);
      this.el.classList.add("visible", `${this.options.theme}-theme`);
      const { x: x5, y: y5 } = this.options.anchor === "mark" ? calculatePositionRelativeToMark(handler, event2, item, this.el.getBoundingClientRect(), this.options) : calculatePositionRelativeToCursor(event2, this.el.getBoundingClientRect(), this.options);
      this.el.style.top = `${y5}px`;
      this.el.style.left = `${x5}px`;
    }
  };
  var version4 = pkg2.version;

  // node_modules/vega-embed/build/vega-embed.module.js
  var __extends = /* @__PURE__ */ function() {
    var extendStatics = function(d2, b3) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b4) {
        d3.__proto__ = b4;
      } || function(d3, b4) {
        for (var p2 in b4) if (b4.hasOwnProperty(p2)) d3[p2] = b4[p2];
      };
      return extendStatics(d2, b3);
    };
    return function(d2, b3) {
      extendStatics(d2, b3);
      function __() {
        this.constructor = d2;
      }
      d2.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __());
    };
  }();
  var _hasOwnProperty = Object.prototype.hasOwnProperty;
  function hasOwnProperty(obj, key2) {
    return _hasOwnProperty.call(obj, key2);
  }
  function _objectKeys(obj) {
    if (Array.isArray(obj)) {
      var keys_1 = new Array(obj.length);
      for (var k2 = 0; k2 < keys_1.length; k2++) {
        keys_1[k2] = "" + k2;
      }
      return keys_1;
    }
    if (Object.keys) {
      return Object.keys(obj);
    }
    var keys4 = [];
    for (var i2 in obj) {
      if (hasOwnProperty(obj, i2)) {
        keys4.push(i2);
      }
    }
    return keys4;
  }
  function _deepClone(obj) {
    switch (typeof obj) {
      case "object":
        return JSON.parse(JSON.stringify(obj));
      //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
      case "undefined":
        return null;
      //this is how JSON.stringify behaves for array items
      default:
        return obj;
    }
  }
  function isInteger2(str) {
    var i2 = 0;
    var len = str.length;
    var charCode;
    while (i2 < len) {
      charCode = str.charCodeAt(i2);
      if (charCode >= 48 && charCode <= 57) {
        i2++;
        continue;
      }
      return false;
    }
    return true;
  }
  function escapePathComponent(path3) {
    if (path3.indexOf("/") === -1 && path3.indexOf("~") === -1)
      return path3;
    return path3.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  function unescapePathComponent(path3) {
    return path3.replace(/~1/g, "/").replace(/~0/g, "~");
  }
  function hasUndefined(obj) {
    if (obj === void 0) {
      return true;
    }
    if (obj) {
      if (Array.isArray(obj)) {
        for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {
          if (hasUndefined(obj[i_1])) {
            return true;
          }
        }
      } else if (typeof obj === "object") {
        var objKeys = _objectKeys(obj);
        var objKeysLength = objKeys.length;
        for (var i2 = 0; i2 < objKeysLength; i2++) {
          if (hasUndefined(obj[objKeys[i2]])) {
            return true;
          }
        }
      }
    }
    return false;
  }
  function patchErrorMessageFormatter(message, args) {
    var messageParts = [message];
    for (var key2 in args) {
      var value3 = typeof args[key2] === "object" ? JSON.stringify(args[key2], null, 2) : args[key2];
      if (typeof value3 !== "undefined") {
        messageParts.push(key2 + ": " + value3);
      }
    }
    return messageParts.join("\n");
  }
  var PatchError = (
    /** @class */
    function(_super) {
      __extends(PatchError2, _super);
      function PatchError2(message, name4, index4, operation, tree) {
        var _newTarget = this.constructor;
        var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name4, index: index4, operation, tree })) || this;
        _this.name = name4;
        _this.index = index4;
        _this.operation = operation;
        _this.tree = tree;
        Object.setPrototypeOf(_this, _newTarget.prototype);
        _this.message = patchErrorMessageFormatter(message, { name: name4, index: index4, operation, tree });
        return _this;
      }
      return PatchError2;
    }(Error)
  );
  var JsonPatchError = PatchError;
  var deepClone = _deepClone;
  var objOps = {
    add: function(obj, key2, document2) {
      obj[key2] = this.value;
      return { newDocument: document2 };
    },
    remove: function(obj, key2, document2) {
      var removed = obj[key2];
      delete obj[key2];
      return { newDocument: document2, removed };
    },
    replace: function(obj, key2, document2) {
      var removed = obj[key2];
      obj[key2] = this.value;
      return { newDocument: document2, removed };
    },
    move: function(obj, key2, document2) {
      var removed = getValueByPointer(document2, this.path);
      if (removed) {
        removed = _deepClone(removed);
      }
      var originalValue = applyOperation(document2, { op: "remove", path: this.from }).removed;
      applyOperation(document2, { op: "add", path: this.path, value: originalValue });
      return { newDocument: document2, removed };
    },
    copy: function(obj, key2, document2) {
      var valueToCopy = getValueByPointer(document2, this.from);
      applyOperation(document2, { op: "add", path: this.path, value: _deepClone(valueToCopy) });
      return { newDocument: document2 };
    },
    test: function(obj, key2, document2) {
      return { newDocument: document2, test: _areEquals(obj[key2], this.value) };
    },
    _get: function(obj, key2, document2) {
      this.value = obj[key2];
      return { newDocument: document2 };
    }
  };
  var arrOps = {
    add: function(arr, i2, document2) {
      if (isInteger2(i2)) {
        arr.splice(i2, 0, this.value);
      } else {
        arr[i2] = this.value;
      }
      return { newDocument: document2, index: i2 };
    },
    remove: function(arr, i2, document2) {
      var removedList = arr.splice(i2, 1);
      return { newDocument: document2, removed: removedList[0] };
    },
    replace: function(arr, i2, document2) {
      var removed = arr[i2];
      arr[i2] = this.value;
      return { newDocument: document2, removed };
    },
    move: objOps.move,
    copy: objOps.copy,
    test: objOps.test,
    _get: objOps._get
  };
  function getValueByPointer(document2, pointer) {
    if (pointer == "") {
      return document2;
    }
    var getOriginalDestination = { op: "_get", path: pointer };
    applyOperation(document2, getOriginalDestination);
    return getOriginalDestination.value;
  }
  function applyOperation(document2, operation, validateOperation, mutateDocument, banPrototypeModifications, index4) {
    if (validateOperation === void 0) {
      validateOperation = false;
    }
    if (mutateDocument === void 0) {
      mutateDocument = true;
    }
    if (banPrototypeModifications === void 0) {
      banPrototypeModifications = true;
    }
    if (index4 === void 0) {
      index4 = 0;
    }
    if (validateOperation) {
      if (typeof validateOperation == "function") {
        validateOperation(operation, 0, document2, operation.path);
      } else {
        validator(operation, 0);
      }
    }
    if (operation.path === "") {
      var returnValue = { newDocument: document2 };
      if (operation.op === "add") {
        returnValue.newDocument = operation.value;
        return returnValue;
      } else if (operation.op === "replace") {
        returnValue.newDocument = operation.value;
        returnValue.removed = document2;
        return returnValue;
      } else if (operation.op === "move" || operation.op === "copy") {
        returnValue.newDocument = getValueByPointer(document2, operation.from);
        if (operation.op === "move") {
          returnValue.removed = document2;
        }
        return returnValue;
      } else if (operation.op === "test") {
        returnValue.test = _areEquals(document2, operation.value);
        if (returnValue.test === false) {
          throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index4, operation, document2);
        }
        returnValue.newDocument = document2;
        return returnValue;
      } else if (operation.op === "remove") {
        returnValue.removed = document2;
        returnValue.newDocument = null;
        return returnValue;
      } else if (operation.op === "_get") {
        operation.value = document2;
        return returnValue;
      } else {
        if (validateOperation) {
          throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index4, operation, document2);
        } else {
          return returnValue;
        }
      }
    } else {
      if (!mutateDocument) {
        document2 = _deepClone(document2);
      }
      var path3 = operation.path || "";
      var keys4 = path3.split("/");
      var obj = document2;
      var t4 = 1;
      var len = keys4.length;
      var existingPathFragment = void 0;
      var key2 = void 0;
      var validateFunction = void 0;
      if (typeof validateOperation == "function") {
        validateFunction = validateOperation;
      } else {
        validateFunction = validator;
      }
      while (true) {
        key2 = keys4[t4];
        if (key2 && key2.indexOf("~") != -1) {
          key2 = unescapePathComponent(key2);
        }
        if (banPrototypeModifications && (key2 == "__proto__" || key2 == "prototype" && t4 > 0 && keys4[t4 - 1] == "constructor")) {
          throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");
        }
        if (validateOperation) {
          if (existingPathFragment === void 0) {
            if (obj[key2] === void 0) {
              existingPathFragment = keys4.slice(0, t4).join("/");
            } else if (t4 == len - 1) {
              existingPathFragment = operation.path;
            }
            if (existingPathFragment !== void 0) {
              validateFunction(operation, 0, document2, existingPathFragment);
            }
          }
        }
        t4++;
        if (Array.isArray(obj)) {
          if (key2 === "-") {
            key2 = obj.length;
          } else {
            if (validateOperation && !isInteger2(key2)) {
              throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index4, operation, document2);
            } else if (isInteger2(key2)) {
              key2 = ~~key2;
            }
          }
          if (t4 >= len) {
            if (validateOperation && operation.op === "add" && key2 > obj.length) {
              throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index4, operation, document2);
            }
            var returnValue = arrOps[operation.op].call(operation, obj, key2, document2);
            if (returnValue.test === false) {
              throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index4, operation, document2);
            }
            return returnValue;
          }
        } else {
          if (t4 >= len) {
            var returnValue = objOps[operation.op].call(operation, obj, key2, document2);
            if (returnValue.test === false) {
              throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index4, operation, document2);
            }
            return returnValue;
          }
        }
        obj = obj[key2];
        if (validateOperation && t4 < len && (!obj || typeof obj !== "object")) {
          throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index4, operation, document2);
        }
      }
    }
  }
  function applyPatch(document2, patch2, validateOperation, mutateDocument, banPrototypeModifications) {
    if (mutateDocument === void 0) {
      mutateDocument = true;
    }
    if (banPrototypeModifications === void 0) {
      banPrototypeModifications = true;
    }
    if (validateOperation) {
      if (!Array.isArray(patch2)) {
        throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
      }
    }
    if (!mutateDocument) {
      document2 = _deepClone(document2);
    }
    var results = new Array(patch2.length);
    for (var i2 = 0, length_1 = patch2.length; i2 < length_1; i2++) {
      results[i2] = applyOperation(document2, patch2[i2], validateOperation, true, banPrototypeModifications, i2);
      document2 = results[i2].newDocument;
    }
    results.newDocument = document2;
    return results;
  }
  function applyReducer(document2, operation, index4) {
    var operationResult = applyOperation(document2, operation);
    if (operationResult.test === false) {
      throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index4, operation, document2);
    }
    return operationResult.newDocument;
  }
  function validator(operation, index4, document2, existingPathFragment) {
    if (typeof operation !== "object" || operation === null || Array.isArray(operation)) {
      throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index4, operation, document2);
    } else if (!objOps[operation.op]) {
      throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index4, operation, document2);
    } else if (typeof operation.path !== "string") {
      throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index4, operation, document2);
    } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) {
      throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index4, operation, document2);
    } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") {
      throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index4, operation, document2);
    } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) {
      throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index4, operation, document2);
    } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) {
      throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index4, operation, document2);
    } else if (document2) {
      if (operation.op == "add") {
        var pathLen = operation.path.split("/").length;
        var existingPathLen = existingPathFragment.split("/").length;
        if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
          throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index4, operation, document2);
        }
      } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") {
        if (operation.path !== existingPathFragment) {
          throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index4, operation, document2);
        }
      } else if (operation.op === "move" || operation.op === "copy") {
        var existingValue = { op: "_get", path: operation.from, value: void 0 };
        var error3 = validate([existingValue], document2);
        if (error3 && error3.name === "OPERATION_PATH_UNRESOLVABLE") {
          throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index4, operation, document2);
        }
      }
    }
  }
  function validate(sequence3, document2, externalValidator) {
    try {
      if (!Array.isArray(sequence3)) {
        throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY");
      }
      if (document2) {
        applyPatch(_deepClone(document2), _deepClone(sequence3), externalValidator || true);
      } else {
        externalValidator = externalValidator || validator;
        for (var i2 = 0; i2 < sequence3.length; i2++) {
          externalValidator(sequence3[i2], i2, document2, void 0);
        }
      }
    } catch (e4) {
      if (e4 instanceof JsonPatchError) {
        return e4;
      } else {
        throw e4;
      }
    }
  }
  function _areEquals(a4, b3) {
    if (a4 === b3)
      return true;
    if (a4 && b3 && typeof a4 == "object" && typeof b3 == "object") {
      var arrA = Array.isArray(a4), arrB = Array.isArray(b3), i2, length3, key2;
      if (arrA && arrB) {
        length3 = a4.length;
        if (length3 != b3.length)
          return false;
        for (i2 = length3; i2-- !== 0; )
          if (!_areEquals(a4[i2], b3[i2]))
            return false;
        return true;
      }
      if (arrA != arrB)
        return false;
      var keys4 = Object.keys(a4);
      length3 = keys4.length;
      if (length3 !== Object.keys(b3).length)
        return false;
      for (i2 = length3; i2-- !== 0; )
        if (!b3.hasOwnProperty(keys4[i2]))
          return false;
      for (i2 = length3; i2-- !== 0; ) {
        key2 = keys4[i2];
        if (!_areEquals(a4[key2], b3[key2]))
          return false;
      }
      return true;
    }
    return a4 !== a4 && b3 !== b3;
  }
  var core = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    JsonPatchError,
    _areEquals,
    applyOperation,
    applyPatch,
    applyReducer,
    deepClone,
    getValueByPointer,
    validate,
    validator
  });
  var beforeDict = /* @__PURE__ */ new WeakMap();
  var Mirror = (
    /** @class */
    /* @__PURE__ */ function() {
      function Mirror2(obj) {
        this.observers = /* @__PURE__ */ new Map();
        this.obj = obj;
      }
      return Mirror2;
    }()
  );
  var ObserverInfo = (
    /** @class */
    /* @__PURE__ */ function() {
      function ObserverInfo2(callback, observer) {
        this.callback = callback;
        this.observer = observer;
      }
      return ObserverInfo2;
    }()
  );
  function getMirror(obj) {
    return beforeDict.get(obj);
  }
  function getObserverFromMirror(mirror, callback) {
    return mirror.observers.get(callback);
  }
  function removeObserverFromMirror(mirror, observer) {
    mirror.observers.delete(observer.callback);
  }
  function unobserve(root, observer) {
    observer.unobserve();
  }
  function observe(obj, callback) {
    var patches = [];
    var observer;
    var mirror = getMirror(obj);
    if (!mirror) {
      mirror = new Mirror(obj);
      beforeDict.set(obj, mirror);
    } else {
      var observerInfo = getObserverFromMirror(mirror, callback);
      observer = observerInfo && observerInfo.observer;
    }
    if (observer) {
      return observer;
    }
    observer = {};
    mirror.value = _deepClone(obj);
    if (callback) {
      observer.callback = callback;
      observer.next = null;
      var dirtyCheck = function() {
        generate2(observer);
      };
      var fastCheck = function() {
        clearTimeout(observer.next);
        observer.next = setTimeout(dirtyCheck);
      };
      if (typeof window !== "undefined") {
        window.addEventListener("mouseup", fastCheck);
        window.addEventListener("keyup", fastCheck);
        window.addEventListener("mousedown", fastCheck);
        window.addEventListener("keydown", fastCheck);
        window.addEventListener("change", fastCheck);
      }
    }
    observer.patches = patches;
    observer.object = obj;
    observer.unobserve = function() {
      generate2(observer);
      clearTimeout(observer.next);
      removeObserverFromMirror(mirror, observer);
      if (typeof window !== "undefined") {
        window.removeEventListener("mouseup", fastCheck);
        window.removeEventListener("keyup", fastCheck);
        window.removeEventListener("mousedown", fastCheck);
        window.removeEventListener("keydown", fastCheck);
        window.removeEventListener("change", fastCheck);
      }
    };
    mirror.observers.set(callback, new ObserverInfo(callback, observer));
    return observer;
  }
  function generate2(observer, invertible) {
    if (invertible === void 0) {
      invertible = false;
    }
    var mirror = beforeDict.get(observer.object);
    _generate(mirror.value, observer.object, observer.patches, "", invertible);
    if (observer.patches.length) {
      applyPatch(mirror.value, observer.patches);
    }
    var temp2 = observer.patches;
    if (temp2.length > 0) {
      observer.patches = [];
      if (observer.callback) {
        observer.callback(temp2);
      }
    }
    return temp2;
  }
  function _generate(mirror, obj, patches, path3, invertible) {
    if (obj === mirror) {
      return;
    }
    if (typeof obj.toJSON === "function") {
      obj = obj.toJSON();
    }
    var newKeys = _objectKeys(obj);
    var oldKeys = _objectKeys(mirror);
    var deleted = false;
    for (var t4 = oldKeys.length - 1; t4 >= 0; t4--) {
      var key2 = oldKeys[t4];
      var oldVal = mirror[key2];
      if (hasOwnProperty(obj, key2) && !(obj[key2] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) {
        var newVal = obj[key2];
        if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
          _generate(oldVal, newVal, patches, path3 + "/" + escapePathComponent(key2), invertible);
        } else {
          if (oldVal !== newVal) {
            if (invertible) {
              patches.push({ op: "test", path: path3 + "/" + escapePathComponent(key2), value: _deepClone(oldVal) });
            }
            patches.push({ op: "replace", path: path3 + "/" + escapePathComponent(key2), value: _deepClone(newVal) });
          }
        }
      } else if (Array.isArray(mirror) === Array.isArray(obj)) {
        if (invertible) {
          patches.push({ op: "test", path: path3 + "/" + escapePathComponent(key2), value: _deepClone(oldVal) });
        }
        patches.push({ op: "remove", path: path3 + "/" + escapePathComponent(key2) });
        deleted = true;
      } else {
        if (invertible) {
          patches.push({ op: "test", path: path3, value: mirror });
        }
        patches.push({ op: "replace", path: path3, value: obj });
      }
    }
    if (!deleted && newKeys.length == oldKeys.length) {
      return;
    }
    for (var t4 = 0; t4 < newKeys.length; t4++) {
      var key2 = newKeys[t4];
      if (!hasOwnProperty(mirror, key2) && obj[key2] !== void 0) {
        patches.push({ op: "add", path: path3 + "/" + escapePathComponent(key2), value: _deepClone(obj[key2]) });
      }
    }
  }
  function compare3(tree1, tree2, invertible) {
    if (invertible === void 0) {
      invertible = false;
    }
    var patches = [];
    _generate(tree1, tree2, patches, "", invertible);
    return patches;
  }
  var duplex = /* @__PURE__ */ Object.freeze({
    __proto__: null,
    compare: compare3,
    generate: generate2,
    observe,
    unobserve
  });
  Object.assign({}, core, duplex, {
    JsonPatchError: PatchError,
    deepClone: _deepClone,
    escapePathComponent,
    unescapePathComponent
  });
  function getDefaultExportFromCjs(x5) {
    return x5 && x5.__esModule && Object.prototype.hasOwnProperty.call(x5, "default") ? x5["default"] : x5;
  }
  var lrucache;
  var hasRequiredLrucache;
  function requireLrucache() {
    if (hasRequiredLrucache) return lrucache;
    hasRequiredLrucache = 1;
    class LRUCache {
      constructor() {
        this.max = 1e3;
        this.map = /* @__PURE__ */ new Map();
      }
      get(key2) {
        const value3 = this.map.get(key2);
        if (value3 === void 0) {
          return void 0;
        } else {
          this.map.delete(key2);
          this.map.set(key2, value3);
          return value3;
        }
      }
      delete(key2) {
        return this.map.delete(key2);
      }
      set(key2, value3) {
        const deleted = this.delete(key2);
        if (!deleted && value3 !== void 0) {
          if (this.map.size >= this.max) {
            const firstKey = this.map.keys().next().value;
            this.delete(firstKey);
          }
          this.map.set(key2, value3);
        }
        return this;
      }
    }
    lrucache = LRUCache;
    return lrucache;
  }
  var parseOptions_1;
  var hasRequiredParseOptions;
  function requireParseOptions() {
    if (hasRequiredParseOptions) return parseOptions_1;
    hasRequiredParseOptions = 1;
    const looseOption = Object.freeze({ loose: true });
    const emptyOpts = Object.freeze({});
    const parseOptions = (options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    };
    parseOptions_1 = parseOptions;
    return parseOptions_1;
  }
  var re2 = { exports: {} };
  var constants2;
  var hasRequiredConstants;
  function requireConstants() {
    if (hasRequiredConstants) return constants2;
    hasRequiredConstants = 1;
    const SEMVER_SPEC_VERSION = "2.0.0";
    const MAX_LENGTH = 256;
    const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    const MAX_SAFE_COMPONENT_LENGTH = 16;
    const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    const RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    constants2 = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
    return constants2;
  }
  var debug_1;
  var hasRequiredDebug;
  function requireDebug() {
    if (hasRequiredDebug) return debug_1;
    hasRequiredDebug = 1;
    const debug3 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    debug_1 = debug3;
    return debug_1;
  }
  var hasRequiredRe;
  function requireRe() {
    if (hasRequiredRe) return re2.exports;
    hasRequiredRe = 1;
    (function(module5, exports2) {
      const {
        MAX_SAFE_COMPONENT_LENGTH,
        MAX_SAFE_BUILD_LENGTH,
        MAX_LENGTH
      } = requireConstants();
      const debug3 = requireDebug();
      exports2 = module5.exports = {};
      const re3 = exports2.re = [];
      const safeRe = exports2.safeRe = [];
      const src = exports2.src = [];
      const t4 = exports2.t = {};
      let R = 0;
      const LETTERDASHNUMBER = "[a-zA-Z0-9-]";
      const safeRegexReplacements = [
        ["\\s", 1],
        ["\\d", MAX_LENGTH],
        [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
      ];
      const makeSafeRegex = (value3) => {
        for (const [token, max4] of safeRegexReplacements) {
          value3 = value3.split(`${token}*`).join(`${token}{0,${max4}}`).split(`${token}+`).join(`${token}{1,${max4}}`);
        }
        return value3;
      };
      const createToken = (name4, value3, isGlobal) => {
        const safe = makeSafeRegex(value3);
        const index4 = R++;
        debug3(name4, index4, value3);
        t4[name4] = index4;
        src[index4] = value3;
        re3[index4] = new RegExp(value3, isGlobal ? "g" : void 0);
        safeRe[index4] = new RegExp(safe, isGlobal ? "g" : void 0);
      };
      createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
      createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
      createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
      createToken("MAINVERSION", `(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})\\.(${src[t4.NUMERICIDENTIFIER]})`);
      createToken("MAINVERSIONLOOSE", `(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})\\.(${src[t4.NUMERICIDENTIFIERLOOSE]})`);
      createToken("PRERELEASEIDENTIFIER", `(?:${src[t4.NUMERICIDENTIFIER]}|${src[t4.NONNUMERICIDENTIFIER]})`);
      createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t4.NUMERICIDENTIFIERLOOSE]}|${src[t4.NONNUMERICIDENTIFIER]})`);
      createToken("PRERELEASE", `(?:-(${src[t4.PRERELEASEIDENTIFIER]}(?:\\.${src[t4.PRERELEASEIDENTIFIER]})*))`);
      createToken("PRERELEASELOOSE", `(?:-?(${src[t4.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t4.PRERELEASEIDENTIFIERLOOSE]})*))`);
      createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
      createToken("BUILD", `(?:\\+(${src[t4.BUILDIDENTIFIER]}(?:\\.${src[t4.BUILDIDENTIFIER]})*))`);
      createToken("FULLPLAIN", `v?${src[t4.MAINVERSION]}${src[t4.PRERELEASE]}?${src[t4.BUILD]}?`);
      createToken("FULL", `^${src[t4.FULLPLAIN]}$`);
      createToken("LOOSEPLAIN", `[v=\\s]*${src[t4.MAINVERSIONLOOSE]}${src[t4.PRERELEASELOOSE]}?${src[t4.BUILD]}?`);
      createToken("LOOSE", `^${src[t4.LOOSEPLAIN]}$`);
      createToken("GTLT", "((?:<|>)?=?)");
      createToken("XRANGEIDENTIFIERLOOSE", `${src[t4.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
      createToken("XRANGEIDENTIFIER", `${src[t4.NUMERICIDENTIFIER]}|x|X|\\*`);
      createToken("XRANGEPLAIN", `[v=\\s]*(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:\\.(${src[t4.XRANGEIDENTIFIER]})(?:${src[t4.PRERELEASE]})?${src[t4.BUILD]}?)?)?`);
      createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t4.XRANGEIDENTIFIERLOOSE]})(?:${src[t4.PRERELEASELOOSE]})?${src[t4.BUILD]}?)?)?`);
      createToken("XRANGE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAIN]}$`);
      createToken("XRANGELOOSE", `^${src[t4.GTLT]}\\s*${src[t4.XRANGEPLAINLOOSE]}$`);
      createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
      createToken("COERCE", `${src[t4.COERCEPLAIN]}(?:$|[^\\d])`);
      createToken("COERCEFULL", src[t4.COERCEPLAIN] + `(?:${src[t4.PRERELEASE]})?(?:${src[t4.BUILD]})?(?:$|[^\\d])`);
      createToken("COERCERTL", src[t4.COERCE], true);
      createToken("COERCERTLFULL", src[t4.COERCEFULL], true);
      createToken("LONETILDE", "(?:~>?)");
      createToken("TILDETRIM", `(\\s*)${src[t4.LONETILDE]}\\s+`, true);
      exports2.tildeTrimReplace = "$1~";
      createToken("TILDE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAIN]}$`);
      createToken("TILDELOOSE", `^${src[t4.LONETILDE]}${src[t4.XRANGEPLAINLOOSE]}$`);
      createToken("LONECARET", "(?:\\^)");
      createToken("CARETTRIM", `(\\s*)${src[t4.LONECARET]}\\s+`, true);
      exports2.caretTrimReplace = "$1^";
      createToken("CARET", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAIN]}$`);
      createToken("CARETLOOSE", `^${src[t4.LONECARET]}${src[t4.XRANGEPLAINLOOSE]}$`);
      createToken("COMPARATORLOOSE", `^${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]})$|^$`);
      createToken("COMPARATOR", `^${src[t4.GTLT]}\\s*(${src[t4.FULLPLAIN]})$|^$`);
      createToken("COMPARATORTRIM", `(\\s*)${src[t4.GTLT]}\\s*(${src[t4.LOOSEPLAIN]}|${src[t4.XRANGEPLAIN]})`, true);
      exports2.comparatorTrimReplace = "$1$2$3";
      createToken("HYPHENRANGE", `^\\s*(${src[t4.XRANGEPLAIN]})\\s+-\\s+(${src[t4.XRANGEPLAIN]})\\s*$`);
      createToken("HYPHENRANGELOOSE", `^\\s*(${src[t4.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t4.XRANGEPLAINLOOSE]})\\s*$`);
      createToken("STAR", "(<|>)?=?\\s*\\*");
      createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
      createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
    })(re2, re2.exports);
    return re2.exports;
  }
  var identifiers;
  var hasRequiredIdentifiers;
  function requireIdentifiers() {
    if (hasRequiredIdentifiers) return identifiers;
    hasRequiredIdentifiers = 1;
    const numeric = /^[0-9]+$/;
    const compareIdentifiers = (a4, b3) => {
      const anum = numeric.test(a4);
      const bnum = numeric.test(b3);
      if (anum && bnum) {
        a4 = +a4;
        b3 = +b3;
      }
      return a4 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a4 < b3 ? -1 : 1;
    };
    const rcompareIdentifiers = (a4, b3) => compareIdentifiers(b3, a4);
    identifiers = {
      compareIdentifiers,
      rcompareIdentifiers
    };
    return identifiers;
  }
  var semver;
  var hasRequiredSemver;
  function requireSemver() {
    if (hasRequiredSemver) return semver;
    hasRequiredSemver = 1;
    const debug3 = requireDebug();
    const { MAX_LENGTH, MAX_SAFE_INTEGER } = requireConstants();
    const { safeRe: re3, t: t4 } = requireRe();
    const parseOptions = requireParseOptions();
    const { compareIdentifiers } = requireIdentifiers();
    class SemVer {
      constructor(version6, options) {
        options = parseOptions(options);
        if (version6 instanceof SemVer) {
          if (version6.loose === !!options.loose && version6.includePrerelease === !!options.includePrerelease) {
            return version6;
          } else {
            version6 = version6.version;
          }
        } else if (typeof version6 !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version6}".`);
        }
        if (version6.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug3("SemVer", version6, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m4 = version6.trim().match(options.loose ? re3[t4.LOOSE] : re3[t4.FULL]);
        if (!m4) {
          throw new TypeError(`Invalid Version: ${version6}`);
        }
        this.raw = version6;
        this.major = +m4[1];
        this.minor = +m4[2];
        this.patch = +m4[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m4[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m4[4].split(".").map((id2) => {
            if (/^[0-9]+$/.test(id2)) {
              const num = +id2;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id2;
          });
        }
        this.build = m4[5] ? m4[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug3("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
      }
      comparePre(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i2 = 0;
        do {
          const a4 = this.prerelease[i2];
          const b3 = other.prerelease[i2];
          debug3("prerelease compare", i2, a4, b3);
          if (a4 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a4 === void 0) {
            return -1;
          } else if (a4 === b3) {
            continue;
          } else {
            return compareIdentifiers(a4, b3);
          }
        } while (++i2);
      }
      compareBuild(other) {
        if (!(other instanceof SemVer)) {
          other = new SemVer(other, this.options);
        }
        let i2 = 0;
        do {
          const a4 = this.build[i2];
          const b3 = other.build[i2];
          debug3("build compare", i2, a4, b3);
          if (a4 === void 0 && b3 === void 0) {
            return 0;
          } else if (b3 === void 0) {
            return 1;
          } else if (a4 === void 0) {
            return -1;
          } else if (a4 === b3) {
            continue;
          } else {
            return compareIdentifiers(a4, b3);
          }
        } while (++i2);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (!identifier && identifierBase === false) {
              throw new Error("invalid increment argument: identifier is empty");
            }
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i2 = this.prerelease.length;
              while (--i2 >= 0) {
                if (typeof this.prerelease[i2] === "number") {
                  this.prerelease[i2]++;
                  i2 = -2;
                }
              }
              if (i2 === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    }
    semver = SemVer;
    return semver;
  }
  var compare_1;
  var hasRequiredCompare;
  function requireCompare() {
    if (hasRequiredCompare) return compare_1;
    hasRequiredCompare = 1;
    const SemVer = requireSemver();
    const compare4 = (a4, b3, loose) => new SemVer(a4, loose).compare(new SemVer(b3, loose));
    compare_1 = compare4;
    return compare_1;
  }
  var eq_1;
  var hasRequiredEq;
  function requireEq() {
    if (hasRequiredEq) return eq_1;
    hasRequiredEq = 1;
    const compare4 = requireCompare();
    const eq = (a4, b3, loose) => compare4(a4, b3, loose) === 0;
    eq_1 = eq;
    return eq_1;
  }
  var neq_1;
  var hasRequiredNeq;
  function requireNeq() {
    if (hasRequiredNeq) return neq_1;
    hasRequiredNeq = 1;
    const compare4 = requireCompare();
    const neq = (a4, b3, loose) => compare4(a4, b3, loose) !== 0;
    neq_1 = neq;
    return neq_1;
  }
  var gt_1;
  var hasRequiredGt;
  function requireGt() {
    if (hasRequiredGt) return gt_1;
    hasRequiredGt = 1;
    const compare4 = requireCompare();
    const gt = (a4, b3, loose) => compare4(a4, b3, loose) > 0;
    gt_1 = gt;
    return gt_1;
  }
  var gte_1;
  var hasRequiredGte;
  function requireGte() {
    if (hasRequiredGte) return gte_1;
    hasRequiredGte = 1;
    const compare4 = requireCompare();
    const gte = (a4, b3, loose) => compare4(a4, b3, loose) >= 0;
    gte_1 = gte;
    return gte_1;
  }
  var lt_1;
  var hasRequiredLt;
  function requireLt() {
    if (hasRequiredLt) return lt_1;
    hasRequiredLt = 1;
    const compare4 = requireCompare();
    const lt = (a4, b3, loose) => compare4(a4, b3, loose) < 0;
    lt_1 = lt;
    return lt_1;
  }
  var lte_1;
  var hasRequiredLte;
  function requireLte() {
    if (hasRequiredLte) return lte_1;
    hasRequiredLte = 1;
    const compare4 = requireCompare();
    const lte = (a4, b3, loose) => compare4(a4, b3, loose) <= 0;
    lte_1 = lte;
    return lte_1;
  }
  var cmp_1;
  var hasRequiredCmp;
  function requireCmp() {
    if (hasRequiredCmp) return cmp_1;
    hasRequiredCmp = 1;
    const eq = requireEq();
    const neq = requireNeq();
    const gt = requireGt();
    const gte = requireGte();
    const lt = requireLt();
    const lte = requireLte();
    const cmp = (a4, op, b3, loose) => {
      switch (op) {
        case "===":
          if (typeof a4 === "object") {
            a4 = a4.version;
          }
          if (typeof b3 === "object") {
            b3 = b3.version;
          }
          return a4 === b3;
        case "!==":
          if (typeof a4 === "object") {
            a4 = a4.version;
          }
          if (typeof b3 === "object") {
            b3 = b3.version;
          }
          return a4 !== b3;
        case "":
        case "=":
        case "==":
          return eq(a4, b3, loose);
        case "!=":
          return neq(a4, b3, loose);
        case ">":
          return gt(a4, b3, loose);
        case ">=":
          return gte(a4, b3, loose);
        case "<":
          return lt(a4, b3, loose);
        case "<=":
          return lte(a4, b3, loose);
        default:
          throw new TypeError(`Invalid operator: ${op}`);
      }
    };
    cmp_1 = cmp;
    return cmp_1;
  }
  var comparator2;
  var hasRequiredComparator;
  function requireComparator() {
    if (hasRequiredComparator) return comparator2;
    hasRequiredComparator = 1;
    const ANY = Symbol("SemVer ANY");
    class Comparator {
      static get ANY() {
        return ANY;
      }
      constructor(comp, options) {
        options = parseOptions(options);
        if (comp instanceof Comparator) {
          if (comp.loose === !!options.loose) {
            return comp;
          } else {
            comp = comp.value;
          }
        }
        comp = comp.trim().split(/\s+/).join(" ");
        debug3("comparator", comp, options);
        this.options = options;
        this.loose = !!options.loose;
        this.parse(comp);
        if (this.semver === ANY) {
          this.value = "";
        } else {
          this.value = this.operator + this.semver.version;
        }
        debug3("comp", this);
      }
      parse(comp) {
        const r2 = this.options.loose ? re3[t4.COMPARATORLOOSE] : re3[t4.COMPARATOR];
        const m4 = comp.match(r2);
        if (!m4) {
          throw new TypeError(`Invalid comparator: ${comp}`);
        }
        this.operator = m4[1] !== void 0 ? m4[1] : "";
        if (this.operator === "=") {
          this.operator = "";
        }
        if (!m4[2]) {
          this.semver = ANY;
        } else {
          this.semver = new SemVer(m4[2], this.options.loose);
        }
      }
      toString() {
        return this.value;
      }
      test(version6) {
        debug3("Comparator.test", version6, this.options.loose);
        if (this.semver === ANY || version6 === ANY) {
          return true;
        }
        if (typeof version6 === "string") {
          try {
            version6 = new SemVer(version6, this.options);
          } catch (er) {
            return false;
          }
        }
        return cmp(version6, this.operator, this.semver, this.options);
      }
      intersects(comp, options) {
        if (!(comp instanceof Comparator)) {
          throw new TypeError("a Comparator is required");
        }
        if (this.operator === "") {
          if (this.value === "") {
            return true;
          }
          return new Range(comp.value, options).test(this.value);
        } else if (comp.operator === "") {
          if (comp.value === "") {
            return true;
          }
          return new Range(this.value, options).test(comp.semver);
        }
        options = parseOptions(options);
        if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) {
          return false;
        }
        if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) {
          return false;
        }
        if (this.operator.startsWith(">") && comp.operator.startsWith(">")) {
          return true;
        }
        if (this.operator.startsWith("<") && comp.operator.startsWith("<")) {
          return true;
        }
        if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
          return true;
        }
        if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
          return true;
        }
        if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
          return true;
        }
        return false;
      }
    }
    comparator2 = Comparator;
    const parseOptions = requireParseOptions();
    const { safeRe: re3, t: t4 } = requireRe();
    const cmp = requireCmp();
    const debug3 = requireDebug();
    const SemVer = requireSemver();
    const Range = requireRange();
    return comparator2;
  }
  var range6;
  var hasRequiredRange;
  function requireRange() {
    if (hasRequiredRange) return range6;
    hasRequiredRange = 1;
    const SPACE_CHARACTERS = /\s+/g;
    class Range {
      constructor(range7, options) {
        options = parseOptions(options);
        if (range7 instanceof Range) {
          if (range7.loose === !!options.loose && range7.includePrerelease === !!options.includePrerelease) {
            return range7;
          } else {
            return new Range(range7.raw, options);
          }
        }
        if (range7 instanceof Comparator) {
          this.raw = range7.value;
          this.set = [[range7]];
          this.formatted = void 0;
          return this;
        }
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        this.raw = range7.trim().replace(SPACE_CHARACTERS, " ");
        this.set = this.raw.split("||").map((r2) => this.parseRange(r2.trim())).filter((c4) => c4.length);
        if (!this.set.length) {
          throw new TypeError(`Invalid SemVer Range: ${this.raw}`);
        }
        if (this.set.length > 1) {
          const first = this.set[0];
          this.set = this.set.filter((c4) => !isNullSet(c4[0]));
          if (this.set.length === 0) {
            this.set = [first];
          } else if (this.set.length > 1) {
            for (const c4 of this.set) {
              if (c4.length === 1 && isAny(c4[0])) {
                this.set = [c4];
                break;
              }
            }
          }
        }
        this.formatted = void 0;
      }
      get range() {
        if (this.formatted === void 0) {
          this.formatted = "";
          for (let i2 = 0; i2 < this.set.length; i2++) {
            if (i2 > 0) {
              this.formatted += "||";
            }
            const comps = this.set[i2];
            for (let k2 = 0; k2 < comps.length; k2++) {
              if (k2 > 0) {
                this.formatted += " ";
              }
              this.formatted += comps[k2].toString().trim();
            }
          }
        }
        return this.formatted;
      }
      format() {
        return this.range;
      }
      toString() {
        return this.range;
      }
      parseRange(range7) {
        const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
        const memoKey = memoOpts + ":" + range7;
        const cached = cache3.get(memoKey);
        if (cached) {
          return cached;
        }
        const loose = this.options.loose;
        const hr = loose ? re3[t4.HYPHENRANGELOOSE] : re3[t4.HYPHENRANGE];
        range7 = range7.replace(hr, hyphenReplace(this.options.includePrerelease));
        debug3("hyphen replace", range7);
        range7 = range7.replace(re3[t4.COMPARATORTRIM], comparatorTrimReplace);
        debug3("comparator trim", range7);
        range7 = range7.replace(re3[t4.TILDETRIM], tildeTrimReplace);
        debug3("tilde trim", range7);
        range7 = range7.replace(re3[t4.CARETTRIM], caretTrimReplace);
        debug3("caret trim", range7);
        let rangeList = range7.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options));
        if (loose) {
          rangeList = rangeList.filter((comp) => {
            debug3("loose invalid filter", comp, this.options);
            return !!comp.match(re3[t4.COMPARATORLOOSE]);
          });
        }
        debug3("range list", rangeList);
        const rangeMap = /* @__PURE__ */ new Map();
        const comparators = rangeList.map((comp) => new Comparator(comp, this.options));
        for (const comp of comparators) {
          if (isNullSet(comp)) {
            return [comp];
          }
          rangeMap.set(comp.value, comp);
        }
        if (rangeMap.size > 1 && rangeMap.has("")) {
          rangeMap.delete("");
        }
        const result = [...rangeMap.values()];
        cache3.set(memoKey, result);
        return result;
      }
      intersects(range7, options) {
        if (!(range7 instanceof Range)) {
          throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators) => {
          return isSatisfiable(thisComparators, options) && range7.set.some((rangeComparators) => {
            return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options);
              });
            });
          });
        });
      }
      // if ANY of the sets match ALL of its comparators, then pass
      test(version6) {
        if (!version6) {
          return false;
        }
        if (typeof version6 === "string") {
          try {
            version6 = new SemVer(version6, this.options);
          } catch (er) {
            return false;
          }
        }
        for (let i2 = 0; i2 < this.set.length; i2++) {
          if (testSet(this.set[i2], version6, this.options)) {
            return true;
          }
        }
        return false;
      }
    }
    range6 = Range;
    const LRU = requireLrucache();
    const cache3 = new LRU();
    const parseOptions = requireParseOptions();
    const Comparator = requireComparator();
    const debug3 = requireDebug();
    const SemVer = requireSemver();
    const {
      safeRe: re3,
      t: t4,
      comparatorTrimReplace,
      tildeTrimReplace,
      caretTrimReplace
    } = requireRe();
    const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = requireConstants();
    const isNullSet = (c4) => c4.value === "<0.0.0-0";
    const isAny = (c4) => c4.value === "";
    const isSatisfiable = (comparators, options) => {
      let result = true;
      const remainingComparators = comparators.slice();
      let testComparator = remainingComparators.pop();
      while (result && remainingComparators.length) {
        result = remainingComparators.every((otherComparator) => {
          return testComparator.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
      }
      return result;
    };
    const parseComparator = (comp, options) => {
      debug3("comp", comp, options);
      comp = replaceCarets(comp, options);
      debug3("caret", comp);
      comp = replaceTildes(comp, options);
      debug3("tildes", comp);
      comp = replaceXRanges(comp, options);
      debug3("xrange", comp);
      comp = replaceStars(comp, options);
      debug3("stars", comp);
      return comp;
    };
    const isX2 = (id2) => !id2 || id2.toLowerCase() === "x" || id2 === "*";
    const replaceTildes = (comp, options) => {
      return comp.trim().split(/\s+/).map((c4) => replaceTilde(c4, options)).join(" ");
    };
    const replaceTilde = (comp, options) => {
      const r2 = options.loose ? re3[t4.TILDELOOSE] : re3[t4.TILDE];
      return comp.replace(r2, (_, M2, m4, p2, pr) => {
        debug3("tilde", comp, _, M2, m4, p2, pr);
        let ret;
        if (isX2(M2)) {
          ret = "";
        } else if (isX2(m4)) {
          ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`;
        } else if (isX2(p2)) {
          ret = `>=${M2}.${m4}.0 <${M2}.${+m4 + 1}.0-0`;
        } else if (pr) {
          debug3("replaceTilde pr", pr);
          ret = `>=${M2}.${m4}.${p2}-${pr} <${M2}.${+m4 + 1}.0-0`;
        } else {
          ret = `>=${M2}.${m4}.${p2} <${M2}.${+m4 + 1}.0-0`;
        }
        debug3("tilde return", ret);
        return ret;
      });
    };
    const replaceCarets = (comp, options) => {
      return comp.trim().split(/\s+/).map((c4) => replaceCaret(c4, options)).join(" ");
    };
    const replaceCaret = (comp, options) => {
      debug3("caret", comp, options);
      const r2 = options.loose ? re3[t4.CARETLOOSE] : re3[t4.CARET];
      const z = options.includePrerelease ? "-0" : "";
      return comp.replace(r2, (_, M2, m4, p2, pr) => {
        debug3("caret", comp, _, M2, m4, p2, pr);
        let ret;
        if (isX2(M2)) {
          ret = "";
        } else if (isX2(m4)) {
          ret = `>=${M2}.0.0${z} <${+M2 + 1}.0.0-0`;
        } else if (isX2(p2)) {
          if (M2 === "0") {
            ret = `>=${M2}.${m4}.0${z} <${M2}.${+m4 + 1}.0-0`;
          } else {
            ret = `>=${M2}.${m4}.0${z} <${+M2 + 1}.0.0-0`;
          }
        } else if (pr) {
          debug3("replaceCaret pr", pr);
          if (M2 === "0") {
            if (m4 === "0") {
              ret = `>=${M2}.${m4}.${p2}-${pr} <${M2}.${m4}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m4}.${p2}-${pr} <${M2}.${+m4 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m4}.${p2}-${pr} <${+M2 + 1}.0.0-0`;
          }
        } else {
          debug3("no pr");
          if (M2 === "0") {
            if (m4 === "0") {
              ret = `>=${M2}.${m4}.${p2}${z} <${M2}.${m4}.${+p2 + 1}-0`;
            } else {
              ret = `>=${M2}.${m4}.${p2}${z} <${M2}.${+m4 + 1}.0-0`;
            }
          } else {
            ret = `>=${M2}.${m4}.${p2} <${+M2 + 1}.0.0-0`;
          }
        }
        debug3("caret return", ret);
        return ret;
      });
    };
    const replaceXRanges = (comp, options) => {
      debug3("replaceXRanges", comp, options);
      return comp.split(/\s+/).map((c4) => replaceXRange(c4, options)).join(" ");
    };
    const replaceXRange = (comp, options) => {
      comp = comp.trim();
      const r2 = options.loose ? re3[t4.XRANGELOOSE] : re3[t4.XRANGE];
      return comp.replace(r2, (ret, gtlt, M2, m4, p2, pr) => {
        debug3("xRange", comp, ret, gtlt, M2, m4, p2, pr);
        const xM = isX2(M2);
        const xm = xM || isX2(m4);
        const xp = xm || isX2(p2);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
          gtlt = "";
        }
        pr = options.includePrerelease ? "-0" : "";
        if (xM) {
          if (gtlt === ">" || gtlt === "<") {
            ret = "<0.0.0-0";
          } else {
            ret = "*";
          }
        } else if (gtlt && anyX) {
          if (xm) {
            m4 = 0;
          }
          p2 = 0;
          if (gtlt === ">") {
            gtlt = ">=";
            if (xm) {
              M2 = +M2 + 1;
              m4 = 0;
              p2 = 0;
            } else {
              m4 = +m4 + 1;
              p2 = 0;
            }
          } else if (gtlt === "<=") {
            gtlt = "<";
            if (xm) {
              M2 = +M2 + 1;
            } else {
              m4 = +m4 + 1;
            }
          }
          if (gtlt === "<") {
            pr = "-0";
          }
          ret = `${gtlt + M2}.${m4}.${p2}${pr}`;
        } else if (xm) {
          ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`;
        } else if (xp) {
          ret = `>=${M2}.${m4}.0${pr} <${M2}.${+m4 + 1}.0-0`;
        }
        debug3("xRange return", ret);
        return ret;
      });
    };
    const replaceStars = (comp, options) => {
      debug3("replaceStars", comp, options);
      return comp.trim().replace(re3[t4.STAR], "");
    };
    const replaceGTE0 = (comp, options) => {
      debug3("replaceGTE0", comp, options);
      return comp.trim().replace(re3[options.includePrerelease ? t4.GTE0PRE : t4.GTE0], "");
    };
    const hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
      if (isX2(fM)) {
        from = "";
      } else if (isX2(fm)) {
        from = `>=${fM}.0.0${incPr ? "-0" : ""}`;
      } else if (isX2(fp)) {
        from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`;
      } else if (fpr) {
        from = `>=${from}`;
      } else {
        from = `>=${from}${incPr ? "-0" : ""}`;
      }
      if (isX2(tM)) {
        to = "";
      } else if (isX2(tm)) {
        to = `<${+tM + 1}.0.0-0`;
      } else if (isX2(tp)) {
        to = `<${tM}.${+tm + 1}.0-0`;
      } else if (tpr) {
        to = `<=${tM}.${tm}.${tp}-${tpr}`;
      } else if (incPr) {
        to = `<${tM}.${tm}.${+tp + 1}-0`;
      } else {
        to = `<=${to}`;
      }
      return `${from} ${to}`.trim();
    };
    const testSet = (set7, version6, options) => {
      for (let i2 = 0; i2 < set7.length; i2++) {
        if (!set7[i2].test(version6)) {
          return false;
        }
      }
      if (version6.prerelease.length && !options.includePrerelease) {
        for (let i2 = 0; i2 < set7.length; i2++) {
          debug3(set7[i2].semver);
          if (set7[i2].semver === Comparator.ANY) {
            continue;
          }
          if (set7[i2].semver.prerelease.length > 0) {
            const allowed = set7[i2].semver;
            if (allowed.major === version6.major && allowed.minor === version6.minor && allowed.patch === version6.patch) {
              return true;
            }
          }
        }
        return false;
      }
      return true;
    };
    return range6;
  }
  var satisfies_1;
  var hasRequiredSatisfies;
  function requireSatisfies() {
    if (hasRequiredSatisfies) return satisfies_1;
    hasRequiredSatisfies = 1;
    const Range = requireRange();
    const satisfies2 = (version6, range7, options) => {
      try {
        range7 = new Range(range7, options);
      } catch (er) {
        return false;
      }
      return range7.test(version6);
    };
    satisfies_1 = satisfies2;
    return satisfies_1;
  }
  var satisfiesExports = requireSatisfies();
  var satisfies = /* @__PURE__ */ getDefaultExportFromCjs(satisfiesExports);
  function post(window2, url, data3) {
    const editor = window2.open(url);
    const wait = 1e4;
    const step = 250;
    const { origin } = new URL(url);
    let count2 = ~~(wait / step);
    function listen(evt) {
      if (evt.source === editor) {
        count2 = 0;
        window2.removeEventListener("message", listen, false);
      }
    }
    window2.addEventListener("message", listen, false);
    function send() {
      if (count2 <= 0) {
        return;
      }
      editor.postMessage(data3, origin);
      setTimeout(send, step);
      count2 -= 1;
    }
    setTimeout(send, step);
  }
  var embedStyle = `.vega-embed {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
}
.vega-embed.has-actions {
  padding-right: 38px;
}
.vega-embed details:not([open]) > :not(summary) {
  display: none !important;
}
.vega-embed summary {
  list-style: none;
  position: absolute;
  top: 0;
  right: 0;
  padding: 6px;
  z-index: 1000;
  background: white;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
  color: #1b1e23;
  border: 1px solid #aaa;
  border-radius: 999px;
  opacity: 0.2;
  transition: opacity 0.4s ease-in;
  cursor: pointer;
  line-height: 0px;
}
.vega-embed summary::-webkit-details-marker {
  display: none;
}
.vega-embed summary:active {
  box-shadow: #aaa 0px 0px 0px 1px inset;
}
.vega-embed summary svg {
  width: 14px;
  height: 14px;
}
.vega-embed details[open] summary {
  opacity: 0.7;
}
.vega-embed:hover summary, .vega-embed:focus-within summary {
  opacity: 1 !important;
  transition: opacity 0.2s ease;
}
.vega-embed .vega-actions {
  position: absolute;
  z-index: 1001;
  top: 35px;
  right: -9px;
  display: flex;
  flex-direction: column;
  padding-bottom: 8px;
  padding-top: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
  border: 1px solid #d9d9d9;
  background: white;
  animation-duration: 0.15s;
  animation-name: scale-in;
  animation-timing-function: cubic-bezier(0.2, 0, 0.13, 1.5);
  text-align: left;
}
.vega-embed .vega-actions a {
  padding: 8px 16px;
  font-family: sans-serif;
  font-size: 14px;
  font-weight: 600;
  white-space: nowrap;
  color: #434a56;
  text-decoration: none;
}
.vega-embed .vega-actions a:hover, .vega-embed .vega-actions a:focus {
  background-color: #f7f7f9;
  color: black;
}
.vega-embed .vega-actions::before, .vega-embed .vega-actions::after {
  content: "";
  display: inline-block;
  position: absolute;
}
.vega-embed .vega-actions::before {
  left: auto;
  right: 14px;
  top: -16px;
  border: 8px solid rgba(0, 0, 0, 0);
  border-bottom-color: #d9d9d9;
}
.vega-embed .vega-actions::after {
  left: auto;
  right: 15px;
  top: -14px;
  border: 7px solid rgba(0, 0, 0, 0);
  border-bottom-color: #fff;
}
.vega-embed .chart-wrapper.fit-x {
  width: 100%;
}
.vega-embed .chart-wrapper.fit-y {
  height: 100%;
}

.vega-embed-wrapper {
  max-width: 100%;
  overflow: auto;
  padding-right: 14px;
}

@keyframes scale-in {
  from {
    opacity: 0;
    transform: scale(0.6);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
`;
  function mergeDeep2(dest, ...src) {
    for (const s2 of src) {
      deepMerge_2(dest, s2);
    }
    return dest;
  }
  function deepMerge_2(dest, src) {
    for (const property2 of Object.keys(src)) {
      writeConfig(dest, property2, src[property2], true);
    }
  }
  var name3 = "vega-embed";
  var version$13 = "6.29.0";
  var description4 = "Publish Vega visualizations as embedded web components.";
  var keywords5 = [
    "vega",
    "data",
    "visualization",
    "component",
    "embed"
  ];
  var repository3 = {
    type: "git",
    url: "http://github.com/vega/vega-embed.git"
  };
  var author3 = {
    name: "UW Interactive Data Lab",
    url: "http://idl.cs.washington.edu"
  };
  var contributors2 = [
    {
      name: "Dominik Moritz",
      url: "https://www.domoritz.de"
    }
  ];
  var bugs2 = {
    url: "https://github.com/vega/vega-embed/issues"
  };
  var homepage2 = "https://github.com/vega/vega-embed#readme";
  var license3 = "BSD-3-Clause";
  var main4 = "build/vega-embed.js";
  var module4 = "build/vega-embed.module.js";
  var unpkg3 = "build/vega-embed.min.js";
  var jsdelivr3 = "build/vega-embed.min.js";
  var types3 = "build/src/embed.d.ts";
  var files3 = [
    "src",
    "build"
  ];
  var exports = {
    ".": {
      "import": {
        types: "./build/src/embed.d.ts",
        "default": "./build/vega-embed.module.js"
      },
      require: {
        "default": "./build/vega-embed.js"
      }
    }
  };
  var devDependencies3 = {
    "@babel/core": "^7.26.0",
    "@babel/eslint-parser": "^7.25.9",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.25.9",
    "@babel/preset-env": "^7.26.0",
    "@babel/preset-typescript": "^7.26.0",
    "@release-it/conventional-changelog": "^9.0.3",
    "@rollup/plugin-commonjs": "28.0.1",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.3.0",
    "@rollup/plugin-terser": "^0.4.4",
    "@rollup/plugin-typescript": "^12.1.1",
    "@types/semver": "^7.5.8",
    "@typescript-eslint/parser": "^8.15.0",
    "@vitest/coverage-istanbul": "^2.1.5",
    "browser-sync": "^3.0.3",
    concurrently: "^9.1.0",
    "del-cli": "^6.0.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.2.1",
    "eslint-plugin-vitest": "^0.5.4",
    eslint: "^9.15.0",
    jsdom: "^25.0.1",
    "postinstall-postinstall": "^2.1.0",
    prettier: "^3.3.3",
    "release-it": "^17.10.0",
    "rollup-plugin-bundle-size": "^1.0.3",
    rollup: "4.27.3",
    sass: "^1.81.0",
    "typescript-eslint": "^8.15.0",
    typescript: "^5.6.3",
    "vega-lite": "^5.21.0",
    vega: "^5.30.0",
    "vitest-canvas-mock": "^0.3.3",
    vitest: "^2.1.5"
  };
  var peerDependencies2 = {
    vega: "^5.21.0",
    "vega-lite": "*"
  };
  var dependencies3 = {
    "fast-json-patch": "^3.1.1",
    "json-stringify-pretty-compact": "^4.0.0",
    semver: "^7.6.3",
    tslib: "^2.8.1",
    "vega-interpreter": "^1.0.5",
    "vega-schema-url-parser": "^2.2.0",
    "vega-themes": "^2.15.0",
    "vega-tooltip": "^0.35.2"
  };
  var scripts3 = {
    prebuild: "npm run clean && npm run build:style",
    build: "rollup -c",
    "build:style": "./build-style.sh",
    clean: "del-cli build src/style.ts",
    prepublishOnly: "npm run clean && npm run build",
    preversion: "npm run lint && npm run test",
    serve: "browser-sync start --directory -s -f build *.html",
    start: "npm run build && concurrently --kill-others -n Server,Rollup 'npm run serve' 'rollup -c -w'",
    pretest: "npm run build:style",
    test: "vitest run",
    prettierbase: "prettier '*.{css,scss,html}'",
    format: "eslint . --fix && npm run prettierbase -- --write",
    lint: "eslint . && npm run prettierbase -- --check",
    release: "release-it"
  };
  var pkg3 = {
    name: name3,
    version: version$13,
    description: description4,
    keywords: keywords5,
    repository: repository3,
    author: author3,
    contributors: contributors2,
    bugs: bugs2,
    homepage: homepage2,
    license: license3,
    main: main4,
    module: module4,
    unpkg: unpkg3,
    jsdelivr: jsdelivr3,
    types: types3,
    files: files3,
    exports,
    devDependencies: devDependencies3,
    peerDependencies: peerDependencies2,
    dependencies: dependencies3,
    scripts: scripts3
  };
  var version5 = pkg3.version;
  var vega = vega_module_exports;
  var vegaLite = src_exports3;
  var w2 = typeof window !== "undefined" ? window : void 0;
  if (vegaLite === void 0 && w2?.vl?.compile) {
    vegaLite = w2.vl;
  }
  var DEFAULT_ACTIONS = { export: { svg: true, png: true }, source: true, compiled: true, editor: true };
  var I18N = {
    CLICK_TO_VIEW_ACTIONS: "Click to view actions",
    COMPILED_ACTION: "View Compiled Vega",
    EDITOR_ACTION: "Open in Vega Editor",
    PNG_ACTION: "Save as PNG",
    SOURCE_ACTION: "View Source",
    SVG_ACTION: "Save as SVG"
  };
  var NAMES = {
    vega: "Vega",
    "vega-lite": "Vega-Lite"
  };
  var VERSION = {
    vega: vega.version,
    "vega-lite": vegaLite ? vegaLite.version : "not available"
  };
  var PREPROCESSOR = {
    vega: (vgSpec) => vgSpec,
    "vega-lite": (vlSpec, config) => vegaLite.compile(vlSpec, { config }).spec
  };
  var SVG_CIRCLES = `
<svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
  <circle r="2" cy="8" cx="2"></circle>
  <circle r="2" cy="8" cx="8"></circle>
  <circle r="2" cy="8" cx="14"></circle>
</svg>`;
  var CHART_WRAPPER_CLASS = "chart-wrapper";
  function isTooltipHandler(h3) {
    return typeof h3 === "function";
  }
  function viewSource(source4, sourceHeader, sourceFooter, mode) {
    const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`;
    const footer = `</code></pre>${sourceFooter}</body></html>`;
    const win = window.open("");
    win.document.write(header + source4 + footer);
    win.document.title = `${NAMES[mode]} JSON Source`;
  }
  function guessMode(spec, providedMode) {
    if (spec.$schema) {
      const parsed = parser_module_default(spec.$schema);
      if (providedMode && providedMode !== parsed.library) {
        console.warn(`The given visualization spec is written in ${NAMES[parsed.library]}, but mode argument sets ${NAMES[providedMode] ?? providedMode}.`);
      }
      const mode = parsed.library;
      if (!satisfies(VERSION[mode], `^${parsed.version.slice(1)}`)) {
        console.warn(`The input spec uses ${NAMES[mode]} ${parsed.version}, but the current version of ${NAMES[mode]} is v${VERSION[mode]}.`);
      }
      return mode;
    }
    if ("mark" in spec || "encoding" in spec || "layer" in spec || "hconcat" in spec || "vconcat" in spec || "facet" in spec || "repeat" in spec) {
      return "vega-lite";
    }
    if ("marks" in spec || "signals" in spec || "scales" in spec || "axes" in spec) {
      return "vega";
    }
    return providedMode ?? "vega";
  }
  function isLoader(o2) {
    return !!(o2 && "load" in o2);
  }
  function createLoader(opts) {
    return isLoader(opts) ? opts : vega.loader(opts);
  }
  function embedOptionsFromUsermeta(parsedSpec) {
    const opts = parsedSpec.usermeta?.embedOptions ?? {};
    if (isString(opts.defaultStyle)) {
      opts.defaultStyle = false;
    }
    return opts;
  }
  async function embed(el, spec, opts = {}) {
    let parsedSpec;
    let loader2;
    if (isString(spec)) {
      loader2 = createLoader(opts.loader);
      parsedSpec = JSON.parse(await loader2.load(spec));
    } else {
      parsedSpec = spec;
    }
    const loadedEmbedOptions = embedOptionsFromUsermeta(parsedSpec);
    const usermetaLoader = loadedEmbedOptions.loader;
    if (!loader2 || usermetaLoader) {
      loader2 = createLoader(opts.loader ?? usermetaLoader);
    }
    const usermetaOpts = await loadOpts(loadedEmbedOptions, loader2);
    const parsedOpts = await loadOpts(opts, loader2);
    const mergedOpts = {
      ...mergeDeep2(parsedOpts, usermetaOpts),
      config: mergeConfig(parsedOpts.config ?? {}, usermetaOpts.config ?? {})
    };
    return await _embed(el, parsedSpec, mergedOpts, loader2);
  }
  async function loadOpts(opt, loader2) {
    const config = isString(opt.config) ? JSON.parse(await loader2.load(opt.config)) : opt.config ?? {};
    const patch2 = isString(opt.patch) ? JSON.parse(await loader2.load(opt.patch)) : opt.patch;
    return {
      ...opt,
      ...patch2 ? { patch: patch2 } : {},
      ...config ? { config } : {}
    };
  }
  function getRoot(el) {
    const possibleRoot = el.getRootNode ? el.getRootNode() : document;
    return possibleRoot instanceof ShadowRoot ? { root: possibleRoot, rootContainer: possibleRoot } : { root: document, rootContainer: document.head ?? document.body };
  }
  async function _embed(el, spec, opts = {}, loader2) {
    const config = opts.theme ? mergeConfig(vega_themes_module_exports[opts.theme], opts.config ?? {}) : opts.config;
    const actions = isBoolean(opts.actions) ? opts.actions : mergeDeep2({}, DEFAULT_ACTIONS, opts.actions ?? {});
    const i18n = { ...I18N, ...opts.i18n };
    const renderer = opts.renderer ?? "canvas";
    const logLevel = opts.logLevel ?? vega.Warn;
    const downloadFileName = opts.downloadFileName ?? "visualization";
    const element3 = typeof el === "string" ? document.querySelector(el) : el;
    if (!element3) {
      throw new Error(`${el} does not exist`);
    }
    if (opts.defaultStyle !== false) {
      const ID = "vega-embed-style";
      const { root, rootContainer } = getRoot(element3);
      if (!root.getElementById(ID)) {
        const style2 = document.createElement("style");
        style2.id = ID;
        style2.innerHTML = opts.defaultStyle === void 0 || opts.defaultStyle === true ? embedStyle.toString() : opts.defaultStyle;
        rootContainer.appendChild(style2);
      }
    }
    const mode = guessMode(spec, opts.mode);
    let vgSpec = PREPROCESSOR[mode](spec, config);
    if (mode === "vega-lite") {
      if (vgSpec.$schema) {
        const parsed = parser_module_default(vgSpec.$schema);
        if (!satisfies(VERSION.vega, `^${parsed.version.slice(1)}`)) {
          console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${VERSION.vega}.`);
        }
      }
    }
    element3.classList.add("vega-embed");
    if (actions) {
      element3.classList.add("has-actions");
    }
    element3.innerHTML = "";
    let container = element3;
    if (actions) {
      const chartWrapper = document.createElement("div");
      chartWrapper.classList.add(CHART_WRAPPER_CLASS);
      element3.appendChild(chartWrapper);
      container = chartWrapper;
    }
    const patch2 = opts.patch;
    if (patch2) {
      vgSpec = patch2 instanceof Function ? patch2(vgSpec) : applyPatch(vgSpec, patch2, true, false).newDocument;
    }
    if (opts.formatLocale) {
      vega.formatLocale(opts.formatLocale);
    }
    if (opts.timeFormatLocale) {
      vega.timeFormatLocale(opts.timeFormatLocale);
    }
    if (opts.expressionFunctions) {
      for (const name4 in opts.expressionFunctions) {
        const expressionFunction2 = opts.expressionFunctions[name4];
        if ("fn" in expressionFunction2) {
          vega.expressionFunction(name4, expressionFunction2.fn, expressionFunction2["visitor"]);
        } else if (expressionFunction2 instanceof Function) {
          vega.expressionFunction(name4, expressionFunction2);
        }
      }
    }
    const { ast } = opts;
    const runtime2 = vega.parse(vgSpec, mode === "vega-lite" ? {} : config, { ast });
    const view = new (opts.viewClass || vega.View)(runtime2, {
      loader: loader2,
      logLevel,
      renderer,
      ...ast ? { expr: vega.expressionInterpreter ?? opts.expr ?? expression2 } : {}
    });
    view.addSignalListener("autosize", (_, autosize) => {
      const { type: type3 } = autosize;
      if (type3 == "fit-x") {
        container.classList.add("fit-x");
        container.classList.remove("fit-y");
      } else if (type3 == "fit-y") {
        container.classList.remove("fit-x");
        container.classList.add("fit-y");
      } else if (type3 == "fit") {
        container.classList.add("fit-x", "fit-y");
      } else {
        container.classList.remove("fit-x", "fit-y");
      }
    });
    if (opts.tooltip !== false) {
      const { loader: loader_, tooltip: tooltip2 } = opts;
      const baseURL = loader_ && !isLoader(loader_) ? loader_?.baseURL : void 0;
      const handler = isTooltipHandler(tooltip2) ? tooltip2 : (
        // user provided boolean true or tooltip options
        new Handler2({ baseURL, ...tooltip2 === true ? {} : tooltip2 }).call
      );
      view.tooltip(handler);
    }
    let { hover: hover2 } = opts;
    if (hover2 === void 0) {
      hover2 = mode === "vega";
    }
    if (hover2) {
      const { hoverSet, updateSet } = typeof hover2 === "boolean" ? {} : hover2;
      view.hover(hoverSet, updateSet);
    }
    if (opts) {
      if (opts.width != null) {
        view.width(opts.width);
      }
      if (opts.height != null) {
        view.height(opts.height);
      }
      if (opts.padding != null) {
        view.padding(opts.padding);
      }
    }
    await view.initialize(container, opts.bind).runAsync();
    let documentClickHandler;
    if (actions !== false) {
      let wrapper = element3;
      if (opts.defaultStyle !== false || opts.forceActionsMenu) {
        const details = document.createElement("details");
        details.title = i18n.CLICK_TO_VIEW_ACTIONS;
        element3.append(details);
        wrapper = details;
        const summary = document.createElement("summary");
        summary.innerHTML = SVG_CIRCLES;
        details.append(summary);
        documentClickHandler = (ev) => {
          if (!details.contains(ev.target)) {
            details.removeAttribute("open");
          }
        };
        document.addEventListener("click", documentClickHandler);
      }
      const ctrl = document.createElement("div");
      wrapper.append(ctrl);
      ctrl.classList.add("vega-actions");
      if (actions === true || actions.export !== false) {
        for (const ext of ["svg", "png"]) {
          if (actions === true || actions.export === true || actions.export[ext]) {
            const i18nExportAction = i18n[`${ext.toUpperCase()}_ACTION`];
            const exportLink = document.createElement("a");
            const scaleFactor = isObject(opts.scaleFactor) ? opts.scaleFactor[ext] : opts.scaleFactor;
            exportLink.text = i18nExportAction;
            exportLink.href = "#";
            exportLink.target = "_blank";
            exportLink.download = `${downloadFileName}.${ext}`;
            exportLink.addEventListener("mousedown", async function(e4) {
              e4.preventDefault();
              const url = await view.toImageURL(ext, scaleFactor);
              this.href = url;
            });
            ctrl.append(exportLink);
          }
        }
      }
      if (actions === true || actions.source !== false) {
        const viewSourceLink = document.createElement("a");
        viewSourceLink.text = i18n.SOURCE_ACTION;
        viewSourceLink.href = "#";
        viewSourceLink.addEventListener("click", function(e4) {
          viewSource(stringify(spec), opts.sourceHeader ?? "", opts.sourceFooter ?? "", mode);
          e4.preventDefault();
        });
        ctrl.append(viewSourceLink);
      }
      if (mode === "vega-lite" && (actions === true || actions.compiled !== false)) {
        const compileLink = document.createElement("a");
        compileLink.text = i18n.COMPILED_ACTION;
        compileLink.href = "#";
        compileLink.addEventListener("click", function(e4) {
          viewSource(stringify(vgSpec), opts.sourceHeader ?? "", opts.sourceFooter ?? "", "vega");
          e4.preventDefault();
        });
        ctrl.append(compileLink);
      }
      if (actions === true || actions.editor !== false) {
        const editorUrl = opts.editorUrl ?? "https://vega.github.io/editor/";
        const editorLink = document.createElement("a");
        editorLink.text = i18n.EDITOR_ACTION;
        editorLink.href = "#";
        editorLink.addEventListener("click", function(e4) {
          post(window, editorUrl, {
            config,
            mode: patch2 ? "vega" : mode,
            renderer,
            spec: stringify(patch2 ? vgSpec : spec)
          });
          e4.preventDefault();
        });
        ctrl.append(editorLink);
      }
    }
    function finalize2() {
      if (documentClickHandler) {
        document.removeEventListener("click", documentClickHandler);
      }
      view.finalize();
    }
    return { view, spec, vgSpec, finalize: finalize2, embedOptions: opts };
  }

  // prism.js
  var _self = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope ? self : {};
  var Prism2 = function(_self2) {
    var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
    var uniqueId2 = 0;
    var plainTextGrammar = {};
    var _ = {
      /**
       * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
       * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
       * additional languages or plugins yourself.
       *
       * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
       *
       * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.manual = true;
       * // add a new <script> to load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      manual: _self2.Prism && _self2.Prism.manual,
      /**
       * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
       * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
       * own worker, you don't want it to do this.
       *
       * By setting this value to `true`, Prism will not add its own listeners to the worker.
       *
       * You obviously have to change this value before Prism executes. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.disableWorkerMessageHandler = true;
       * // Load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      disableWorkerMessageHandler: _self2.Prism && _self2.Prism.disableWorkerMessageHandler,
      /**
       * A namespace for utility methods.
       *
       * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
       * change or disappear at any time.
       *
       * @namespace
       * @memberof Prism
       */
      util: {
        encode: function encode2(tokens) {
          if (tokens instanceof Token) {
            return new Token(tokens.type, encode2(tokens.content), tokens.alias);
          } else if (Array.isArray(tokens)) {
            return tokens.map(encode2);
          } else {
            return tokens.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ");
          }
        },
        /**
         * Returns the name of the type of the given value.
         *
         * @param {any} o
         * @returns {string}
         * @example
         * type(null)      === 'Null'
         * type(undefined) === 'Undefined'
         * type(123)       === 'Number'
         * type('foo')     === 'String'
         * type(true)      === 'Boolean'
         * type([1, 2])    === 'Array'
         * type({})        === 'Object'
         * type(String)    === 'Function'
         * type(/abc+/)    === 'RegExp'
         */
        type: function(o2) {
          return Object.prototype.toString.call(o2).slice(8, -1);
        },
        /**
         * Returns a unique number for the given object. Later calls will still return the same number.
         *
         * @param {Object} obj
         * @returns {number}
         */
        objId: function(obj) {
          if (!obj["__id"]) {
            Object.defineProperty(obj, "__id", { value: ++uniqueId2 });
          }
          return obj["__id"];
        },
        /**
         * Creates a deep clone of the given object.
         *
         * The main intended use of this function is to clone language definitions.
         *
         * @param {T} o
         * @param {Record<number, any>} [visited]
         * @returns {T}
         * @template T
         */
        clone: function deepClone2(o2, visited) {
          visited = visited || {};
          var clone;
          var id2;
          switch (_.util.type(o2)) {
            case "Object":
              id2 = _.util.objId(o2);
              if (visited[id2]) {
                return visited[id2];
              }
              clone = /** @type {Record<string, any>} */
              {};
              visited[id2] = clone;
              for (var key2 in o2) {
                if (o2.hasOwnProperty(key2)) {
                  clone[key2] = deepClone2(o2[key2], visited);
                }
              }
              return (
                /** @type {any} */
                clone
              );
            case "Array":
              id2 = _.util.objId(o2);
              if (visited[id2]) {
                return visited[id2];
              }
              clone = [];
              visited[id2] = clone;
              /** @type {any} */
              o2.forEach(
                function(v3, i2) {
                  clone[i2] = deepClone2(v3, visited);
                }
              );
              return (
                /** @type {any} */
                clone
              );
            default:
              return o2;
          }
        },
        /**
         * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
         *
         * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
         *
         * @param {Element} element
         * @returns {string}
         */
        getLanguage: function(element3) {
          while (element3) {
            var m4 = lang.exec(element3.className);
            if (m4) {
              return m4[1].toLowerCase();
            }
            element3 = element3.parentElement;
          }
          return "none";
        },
        /**
         * Sets the Prism `language-xxxx` class of the given element.
         *
         * @param {Element} element
         * @param {string} language
         * @returns {void}
         */
        setLanguage: function(element3, language) {
          element3.className = element3.className.replace(RegExp(lang, "gi"), "");
          element3.classList.add("language-" + language);
        },
        /**
         * Returns the script element that is currently executing.
         *
         * This does __not__ work for line script element.
         *
         * @returns {HTMLScriptElement | null}
         */
        currentScript: function() {
          if (typeof document === "undefined") {
            return null;
          }
          if ("currentScript" in document && 1 < 2) {
            return (
              /** @type {any} */
              document.currentScript
            );
          }
          try {
            throw new Error();
          } catch (err) {
            var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
            if (src) {
              var scripts4 = document.getElementsByTagName("script");
              for (var i2 in scripts4) {
                if (scripts4[i2].src == src) {
                  return scripts4[i2];
                }
              }
            }
            return null;
          }
        },
        /**
         * Returns whether a given class is active for `element`.
         *
         * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
         * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
         * given class is just the given class with a `no-` prefix.
         *
         * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
         * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
         * ancestors have the given class or the negated version of it, then the default activation will be returned.
         *
         * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
         * version of it, the class is considered active.
         *
         * @param {Element} element
         * @param {string} className
         * @param {boolean} [defaultActivation=false]
         * @returns {boolean}
         */
        isActive: function(element3, className, defaultActivation) {
          var no = "no-" + className;
          while (element3) {
            var classList = element3.classList;
            if (classList.contains(className)) {
              return true;
            }
            if (classList.contains(no)) {
              return false;
            }
            element3 = element3.parentElement;
          }
          return !!defaultActivation;
        }
      },
      /**
       * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
       *
       * @namespace
       * @memberof Prism
       * @public
       */
      languages: {
        /**
         * The grammar for plain, unformatted text.
         */
        plain: plainTextGrammar,
        plaintext: plainTextGrammar,
        text: plainTextGrammar,
        txt: plainTextGrammar,
        /**
         * Creates a deep copy of the language with the given id and appends the given tokens.
         *
         * If a token in `redef` also appears in the copied language, then the existing token in the copied language
         * will be overwritten at its original position.
         *
         * ## Best practices
         *
         * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
         * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
         * understand the language definition because, normally, the order of tokens matters in Prism grammars.
         *
         * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
         * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
         *
         * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
         * @param {Grammar} redef The new tokens to append.
         * @returns {Grammar} The new language created.
         * @public
         * @example
         * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
         *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
         *     // at its original position
         *     'comment': { ... },
         *     // CSS doesn't have a 'color' token, so this token will be appended
         *     'color': /\b(?:red|green|blue)\b/
         * });
         */
        extend: function(id2, redef) {
          var lang2 = _.util.clone(_.languages[id2]);
          for (var key2 in redef) {
            lang2[key2] = redef[key2];
          }
          return lang2;
        },
        /**
         * Inserts tokens _before_ another token in a language definition or any other grammar.
         *
         * ## Usage
         *
         * This helper method makes it easy to modify existing languages. For example, the CSS language definition
         * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
         * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
         * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
         * this:
         *
         * ```js
         * Prism.languages.markup.style = {
         *     // token
         * };
         * ```
         *
         * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
         * before existing tokens. For the CSS example above, you would use it like this:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'cdata', {
         *     'style': {
         *         // token
         *     }
         * });
         * ```
         *
         * ## Special cases
         *
         * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
         * will be ignored.
         *
         * This behavior can be used to insert tokens after `before`:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'comment', {
         *     'comment': Prism.languages.markup.comment,
         *     // tokens after 'comment'
         * });
         * ```
         *
         * ## Limitations
         *
         * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
         * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
         * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
         * deleting properties which is necessary to insert at arbitrary positions.
         *
         * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
         * Instead, it will create a new object and replace all references to the target object with the new one. This
         * can be done without temporarily deleting properties, so the iteration order is well-defined.
         *
         * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
         * you hold the target object in a variable, then the value of the variable will not change.
         *
         * ```js
         * var oldMarkup = Prism.languages.markup;
         * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
         *
         * assert(oldMarkup !== Prism.languages.markup);
         * assert(newMarkup === Prism.languages.markup);
         * ```
         *
         * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
         * object to be modified.
         * @param {string} before The key to insert before.
         * @param {Grammar} insert An object containing the key-value pairs to be inserted.
         * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
         * object to be modified.
         *
         * Defaults to `Prism.languages`.
         * @returns {Grammar} The new grammar object.
         * @public
         */
        insertBefore: function(inside, before, insert2, root) {
          root = root || /** @type {any} */
          _.languages;
          var grammar = root[inside];
          var ret = {};
          for (var token in grammar) {
            if (grammar.hasOwnProperty(token)) {
              if (token == before) {
                for (var newToken in insert2) {
                  if (insert2.hasOwnProperty(newToken)) {
                    ret[newToken] = insert2[newToken];
                  }
                }
              }
              if (!insert2.hasOwnProperty(token)) {
                ret[token] = grammar[token];
              }
            }
          }
          var old = root[inside];
          root[inside] = ret;
          _.languages.DFS(_.languages, function(key2, value3) {
            if (value3 === old && key2 != inside) {
              this[key2] = ret;
            }
          });
          return ret;
        },
        // Traverse a language definition with Depth First Search
        DFS: function DFS(o2, callback, type3, visited) {
          visited = visited || {};
          var objId = _.util.objId;
          for (var i2 in o2) {
            if (o2.hasOwnProperty(i2)) {
              callback.call(o2, i2, o2[i2], type3 || i2);
              var property2 = o2[i2];
              var propertyType = _.util.type(property2);
              if (propertyType === "Object" && !visited[objId(property2)]) {
                visited[objId(property2)] = true;
                DFS(property2, callback, null, visited);
              } else if (propertyType === "Array" && !visited[objId(property2)]) {
                visited[objId(property2)] = true;
                DFS(property2, callback, i2, visited);
              }
            }
          }
        }
      },
      plugins: {},
      /**
       * This is the most high-level function in Prism’s API.
       * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
       * each one of them.
       *
       * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
       *
       * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
       * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
       * @memberof Prism
       * @public
       */
      highlightAll: function(async, callback) {
        _.highlightAllUnder(document, async, callback);
      },
      /**
       * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
       * {@link Prism.highlightElement} on each one of them.
       *
       * The following hooks will be run:
       * 1. `before-highlightall`
       * 2. `before-all-elements-highlight`
       * 3. All hooks of {@link Prism.highlightElement} for each element.
       *
       * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
       * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
       * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
       * @memberof Prism
       * @public
       */
      highlightAllUnder: function(container, async, callback) {
        var env = {
          callback,
          container,
          selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
        };
        _.hooks.run("before-highlightall", env);
        env.elements = Array.prototype.slice.apply(
          env.container.querySelectorAll(env.selector)
        );
        _.hooks.run("before-all-elements-highlight", env);
        for (var i2 = 0, element3; element3 = env.elements[i2++]; ) {
          _.highlightElement(element3, async === true, env.callback);
        }
      },
      /**
       * Highlights the code inside a single element.
       *
       * The following hooks will be run:
       * 1. `before-sanity-check`
       * 2. `before-highlight`
       * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
       * 4. `before-insert`
       * 5. `after-highlight`
       * 6. `complete`
       *
       * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
       * the element's language.
       *
       * @param {Element} element The element containing the code.
       * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
       * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
       * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
       * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
       *
       * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
       * asynchronous highlighting to work. You can build your own bundle on the
       * [Download page](https://prismjs.com/download.html).
       * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
       * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
       * @memberof Prism
       * @public
       */
      highlightElement: function(element3, async, callback) {
        var language = _.util.getLanguage(element3);
        var grammar = _.languages[language];
        _.util.setLanguage(element3, language);
        var parent = element3.parentElement;
        if (parent && parent.nodeName.toLowerCase() === "pre") {
          _.util.setLanguage(parent, language);
        }
        var code = element3.textContent;
        var env = {
          element: element3,
          language,
          grammar,
          code
        };
        function insertHighlightedCode(highlightedCode) {
          env.highlightedCode = highlightedCode;
          _.hooks.run("before-insert", env);
          env.element.innerHTML = env.highlightedCode;
          _.hooks.run("after-highlight", env);
          _.hooks.run("complete", env);
          callback && callback.call(env.element);
        }
        _.hooks.run("before-sanity-check", env);
        parent = env.element.parentElement;
        if (parent && parent.nodeName.toLowerCase() === "pre" && !parent.hasAttribute("tabindex")) {
          parent.setAttribute("tabindex", "0");
        }
        if (!env.code) {
          _.hooks.run("complete", env);
          callback && callback.call(env.element);
          return;
        }
        _.hooks.run("before-highlight", env);
        if (!env.grammar) {
          insertHighlightedCode(_.util.encode(env.code));
          return;
        }
        if (async && _self2.Worker) {
          var worker = new Worker(_.filename);
          worker.onmessage = function(evt) {
            insertHighlightedCode(evt.data);
          };
          worker.postMessage(
            JSON.stringify({
              language: env.language,
              code: env.code,
              immediateClose: true
            })
          );
        } else {
          insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
        }
      },
      /**
       * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
       * and the language definitions to use, and returns a string with the HTML produced.
       *
       * The following hooks will be run:
       * 1. `before-tokenize`
       * 2. `after-tokenize`
       * 3. `wrap`: On each {@link Token}.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @param {string} language The name of the language definition passed to `grammar`.
       * @returns {string} The highlighted HTML.
       * @memberof Prism
       * @public
       * @example
       * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
       */
      highlight: function(text4, grammar, language) {
        var env = {
          code: text4,
          grammar,
          language
        };
        _.hooks.run("before-tokenize", env);
        env.tokens = _.tokenize(env.code, env.grammar);
        _.hooks.run("after-tokenize", env);
        return Token.stringify(_.util.encode(env.tokens), env.language);
      },
      /**
       * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
       * and the language definitions to use, and returns an array with the tokenized code.
       *
       * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
       *
       * This method could be useful in other contexts as well, as a very crude parser.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @returns {TokenStream} An array of strings and tokens, a token stream.
       * @memberof Prism
       * @public
       * @example
       * let code = `var foo = 0;`;
       * let tokens = Prism.tokenize(code, Prism.languages.javascript);
       * tokens.forEach(token => {
       *     if (token instanceof Prism.Token && token.type === 'number') {
       *         console.log(`Found numeric literal: ${token.content}`);
       *     }
       * });
       */
      tokenize: function(text4, grammar) {
        var rest = grammar.rest;
        if (rest) {
          for (var token in rest) {
            grammar[token] = rest[token];
          }
          delete grammar.rest;
        }
        var tokenList = new LinkedList();
        addAfter(tokenList, tokenList.head, text4);
        matchGrammar(text4, tokenList, grammar, tokenList.head, 0);
        return toArray(tokenList);
      },
      /**
       * @namespace
       * @memberof Prism
       * @public
       */
      hooks: {
        all: {},
        /**
         * Adds the given callback to the list of callbacks for the given hook.
         *
         * The callback will be invoked when the hook it is registered for is run.
         * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
         *
         * One callback function can be registered to multiple hooks and the same hook multiple times.
         *
         * @param {string} name The name of the hook.
         * @param {HookCallback} callback The callback function which is given environment variables.
         * @public
         */
        add: function(name4, callback) {
          var hooks = _.hooks.all;
          hooks[name4] = hooks[name4] || [];
          hooks[name4].push(callback);
        },
        /**
         * Runs a hook invoking all registered callbacks with the given environment variables.
         *
         * Callbacks will be invoked synchronously and in the order in which they were registered.
         *
         * @param {string} name The name of the hook.
         * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
         * @public
         */
        run: function(name4, env) {
          var callbacks = _.hooks.all[name4];
          if (!callbacks || !callbacks.length) {
            return;
          }
          for (var i2 = 0, callback; callback = callbacks[i2++]; ) {
            callback(env);
          }
        }
      },
      Token
    };
    _self2.Prism = _;
    function Token(type3, content2, alias, matchedStr) {
      this.type = type3;
      this.content = content2;
      this.alias = alias;
      this.length = (matchedStr || "").length | 0;
    }
    Token.stringify = function stringify4(o2, language) {
      if (typeof o2 == "string") {
        return o2;
      }
      if (Array.isArray(o2)) {
        var s2 = "";
        o2.forEach(function(e4) {
          s2 += stringify4(e4, language);
        });
        return s2;
      }
      var env = {
        type: o2.type,
        content: stringify4(o2.content, language),
        tag: "span",
        classes: ["token", o2.type],
        attributes: {},
        language
      };
      var aliases = o2.alias;
      if (aliases) {
        if (Array.isArray(aliases)) {
          Array.prototype.push.apply(env.classes, aliases);
        } else {
          env.classes.push(aliases);
        }
      }
      _.hooks.run("wrap", env);
      var attributes = "";
      for (var name4 in env.attributes) {
        attributes += " " + name4 + '="' + (env.attributes[name4] || "").replace(/"/g, "&quot;") + '"';
      }
      return "<" + env.tag + ' class="' + env.classes.join(" ") + '"' + attributes + ">" + env.content + "</" + env.tag + ">";
    };
    function matchPattern(pattern, pos, text4, lookbehind) {
      pattern.lastIndex = pos;
      var match3 = pattern.exec(text4);
      if (match3 && lookbehind && match3[1]) {
        var lookbehindLength = match3[1].length;
        match3.index += lookbehindLength;
        match3[0] = match3[0].slice(lookbehindLength);
      }
      return match3;
    }
    function matchGrammar(text4, tokenList, grammar, startNode, startPos, rematch) {
      for (var token in grammar) {
        if (!grammar.hasOwnProperty(token) || !grammar[token]) {
          continue;
        }
        var patterns = grammar[token];
        patterns = Array.isArray(patterns) ? patterns : [patterns];
        for (var j2 = 0; j2 < patterns.length; ++j2) {
          if (rematch && rematch.cause == token + "," + j2) {
            return;
          }
          var patternObj = patterns[j2];
          var inside = patternObj.inside;
          var lookbehind = !!patternObj.lookbehind;
          var greedy = !!patternObj.greedy;
          var alias = patternObj.alias;
          if (greedy && !patternObj.pattern.global) {
            var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
            patternObj.pattern = RegExp(patternObj.pattern.source, flags + "g");
          }
          var pattern = patternObj.pattern || patternObj;
          for (var currentNode = startNode.next, pos = startPos; currentNode !== tokenList.tail; pos += currentNode.value.length, currentNode = currentNode.next) {
            if (rematch && pos >= rematch.reach) {
              break;
            }
            var str = currentNode.value;
            if (tokenList.length > text4.length) {
              return;
            }
            if (str instanceof Token) {
              continue;
            }
            var removeCount = 1;
            var match3;
            if (greedy) {
              match3 = matchPattern(pattern, pos, text4, lookbehind);
              if (!match3 || match3.index >= text4.length) {
                break;
              }
              var from = match3.index;
              var to = match3.index + match3[0].length;
              var p2 = pos;
              p2 += currentNode.value.length;
              while (from >= p2) {
                currentNode = currentNode.next;
                p2 += currentNode.value.length;
              }
              p2 -= currentNode.value.length;
              pos = p2;
              if (currentNode.value instanceof Token) {
                continue;
              }
              for (var k2 = currentNode; k2 !== tokenList.tail && (p2 < to || typeof k2.value === "string"); k2 = k2.next) {
                removeCount++;
                p2 += k2.value.length;
              }
              removeCount--;
              str = text4.slice(pos, p2);
              match3.index -= pos;
            } else {
              match3 = matchPattern(pattern, 0, str, lookbehind);
              if (!match3) {
                continue;
              }
            }
            var from = match3.index;
            var matchStr = match3[0];
            var before = str.slice(0, from);
            var after = str.slice(from + matchStr.length);
            var reach = pos + str.length;
            if (rematch && reach > rematch.reach) {
              rematch.reach = reach;
            }
            var removeFrom = currentNode.prev;
            if (before) {
              removeFrom = addAfter(tokenList, removeFrom, before);
              pos += before.length;
            }
            removeRange(tokenList, removeFrom, removeCount);
            var wrapped = new Token(
              token,
              inside ? _.tokenize(matchStr, inside) : matchStr,
              alias,
              matchStr
            );
            currentNode = addAfter(tokenList, removeFrom, wrapped);
            if (after) {
              addAfter(tokenList, currentNode, after);
            }
            if (removeCount > 1) {
              var nestedRematch = {
                cause: token + "," + j2,
                reach
              };
              matchGrammar(
                text4,
                tokenList,
                grammar,
                currentNode.prev,
                pos,
                nestedRematch
              );
              if (rematch && nestedRematch.reach > rematch.reach) {
                rematch.reach = nestedRematch.reach;
              }
            }
          }
        }
      }
    }
    function LinkedList() {
      var head = { value: null, prev: null, next: null };
      var tail = { value: null, prev: head, next: null };
      head.next = tail;
      this.head = head;
      this.tail = tail;
      this.length = 0;
    }
    function addAfter(list, node, value3) {
      var next = node.next;
      var newNode = { value: value3, prev: node, next };
      node.next = newNode;
      next.prev = newNode;
      list.length++;
      return newNode;
    }
    function removeRange(list, node, count2) {
      var next = node.next;
      for (var i2 = 0; i2 < count2 && next !== list.tail; i2++) {
        next = next.next;
      }
      node.next = next;
      next.prev = node;
      list.length -= i2;
    }
    function toArray(list) {
      var array4 = [];
      var node = list.head.next;
      while (node !== list.tail) {
        array4.push(node.value);
        node = node.next;
      }
      return array4;
    }
    if (!_self2.document) {
      if (!_self2.addEventListener) {
        return _;
      }
      if (!_.disableWorkerMessageHandler) {
        _self2.addEventListener(
          "message",
          function(evt) {
            var message = JSON.parse(evt.data);
            var lang2 = message.language;
            var code = message.code;
            var immediateClose = message.immediateClose;
            _self2.postMessage(_.highlight(code, _.languages[lang2], lang2));
            if (immediateClose) {
              _self2.close();
            }
          },
          false
        );
      }
      return _;
    }
    var script = _.util.currentScript();
    if (script) {
      _.filename = script.src;
      if (script.hasAttribute("data-manual")) {
        _.manual = true;
      }
    }
    function highlightAutomaticallyCallback() {
      if (!_.manual) {
        _.highlightAll();
      }
    }
    if (!_.manual) {
      var readyState = document.readyState;
      if (readyState === "loading" || readyState === "interactive" && script && script.defer) {
        document.addEventListener(
          "DOMContentLoaded",
          highlightAutomaticallyCallback
        );
      } else {
        if (window.requestAnimationFrame) {
          window.requestAnimationFrame(highlightAutomaticallyCallback);
        } else {
          window.setTimeout(highlightAutomaticallyCallback, 16);
        }
      }
    }
    return _;
  }(_self);
  if (typeof module !== "undefined" && module.exports) {
    module.exports = Prism2;
  }
  if (typeof global !== "undefined") {
    global.Prism = Prism2;
  }
  Prism2.languages.markup = {
    comment: {
      pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
      greedy: true
    },
    prolog: {
      pattern: /<\?[\s\S]+?\?>/,
      greedy: true
    },
    doctype: {
      // https://www.w3.org/TR/xml/#NT-doctypedecl
      pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
      greedy: true,
      inside: {
        "internal-subset": {
          pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
          lookbehind: true,
          greedy: true,
          inside: null
          // see below
        },
        string: {
          pattern: /"[^"]*"|'[^']*'/,
          greedy: true
        },
        punctuation: /^<!|>$|[[\]]/,
        "doctype-tag": /^DOCTYPE/i,
        name: /[^\s<>'"]+/
      }
    },
    cdata: {
      pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
      greedy: true
    },
    tag: {
      pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
      greedy: true,
      inside: {
        tag: {
          pattern: /^<\/?[^\s>\/]+/,
          inside: {
            punctuation: /^<\/?/,
            namespace: /^[^\s>\/:]+:/
          }
        },
        "special-attr": [],
        "attr-value": {
          pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
          inside: {
            punctuation: [
              {
                pattern: /^=/,
                alias: "attr-equals"
              },
              /"|'/
            ]
          }
        },
        punctuation: /\/?>/,
        "attr-name": {
          pattern: /[^\s>\/]+/,
          inside: {
            namespace: /^[^\s>\/:]+:/
          }
        }
      }
    },
    entity: [
      {
        pattern: /&[\da-z]{1,8};/i,
        alias: "named-entity"
      },
      /&#x?[\da-f]{1,8};/i
    ]
  };
  Prism2.languages.markup["tag"].inside["attr-value"].inside["entity"] = Prism2.languages.markup["entity"];
  Prism2.languages.markup["doctype"].inside["internal-subset"].inside = Prism2.languages.markup;
  Prism2.hooks.add("wrap", function(env) {
    if (env.type === "entity") {
      env.attributes["title"] = env.content.replace(/&amp;/, "&");
    }
  });
  Object.defineProperty(Prism2.languages.markup.tag, "addInlined", {
    /**
     * Adds an inlined language to markup.
     *
     * An example of an inlined language is CSS with `<style>` tags.
     *
     * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addInlined('style', 'css');
     */
    value: function addInlined(tagName, lang) {
      var includedCdataInside = {};
      includedCdataInside["language-" + lang] = {
        pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
        lookbehind: true,
        inside: Prism2.languages[lang]
      };
      includedCdataInside["cdata"] = /^<!\[CDATA\[|\]\]>$/i;
      var inside = {
        "included-cdata": {
          pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
          inside: includedCdataInside
        }
      };
      inside["language-" + lang] = {
        pattern: /[\s\S]+/,
        inside: Prism2.languages[lang]
      };
      var def2 = {};
      def2[tagName] = {
        pattern: RegExp(
          /(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(
            /__/g,
            function() {
              return tagName;
            }
          ),
          "i"
        ),
        lookbehind: true,
        greedy: true,
        inside
      };
      Prism2.languages.insertBefore("markup", "cdata", def2);
    }
  });
  Object.defineProperty(Prism2.languages.markup.tag, "addAttribute", {
    /**
     * Adds an pattern to highlight languages embedded in HTML attributes.
     *
     * An example of an inlined language is CSS with `style` attributes.
     *
     * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addAttribute('style', 'css');
     */
    value: function(attrName, lang) {
      Prism2.languages.markup.tag.inside["special-attr"].push({
        pattern: RegExp(
          /(^|["'\s])/.source + "(?:" + attrName + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
          "i"
        ),
        lookbehind: true,
        inside: {
          "attr-name": /^[^\s=]+/,
          "attr-value": {
            pattern: /=[\s\S]+/,
            inside: {
              value: {
                pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                lookbehind: true,
                alias: [lang, "language-" + lang],
                inside: Prism2.languages[lang]
              },
              punctuation: [
                {
                  pattern: /^=/,
                  alias: "attr-equals"
                },
                /"|'/
              ]
            }
          }
        }
      });
    }
  });
  Prism2.languages.html = Prism2.languages.markup;
  Prism2.languages.mathml = Prism2.languages.markup;
  Prism2.languages.svg = Prism2.languages.markup;
  Prism2.languages.xml = Prism2.languages.extend("markup", {});
  Prism2.languages.ssml = Prism2.languages.xml;
  Prism2.languages.atom = Prism2.languages.xml;
  Prism2.languages.rss = Prism2.languages.xml;
  (function(Prism3) {
    var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
    Prism3.languages.css = {
      comment: /\/\*[\s\S]*?\*\//,
      atrule: {
        pattern: /@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,
        inside: {
          rule: /^@[\w-]+/,
          "selector-function-argument": {
            pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
            lookbehind: true,
            alias: "selector"
          },
          keyword: {
            pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
            lookbehind: true
          }
          // See rest below
        }
      },
      url: {
        // https://drafts.csswg.org/css-values-3/#urls
        pattern: RegExp(
          "\\burl\\((?:" + string.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)",
          "i"
        ),
        greedy: true,
        inside: {
          function: /^url/i,
          punctuation: /^\(|\)$/,
          string: {
            pattern: RegExp("^" + string.source + "$"),
            alias: "url"
          }
        }
      },
      selector: {
        pattern: RegExp(
          `(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + string.source + ")*(?=\\s*\\{)"
        ),
        lookbehind: true
      },
      string: {
        pattern: string,
        greedy: true
      },
      property: {
        pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
        lookbehind: true
      },
      important: /!important\b/i,
      function: {
        pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
        lookbehind: true
      },
      punctuation: /[(){};:,]/
    };
    Prism3.languages.css["atrule"].inside.rest = Prism3.languages.css;
    var markup2 = Prism3.languages.markup;
    if (markup2) {
      markup2.tag.addInlined("style", "css");
      markup2.tag.addAttribute("style", "css");
    }
  })(Prism2);
  Prism2.languages.clike = {
    comment: [
      {
        pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
        lookbehind: true,
        greedy: true
      },
      {
        pattern: /(^|[^\\:])\/\/.*/,
        lookbehind: true,
        greedy: true
      }
    ],
    string: {
      pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
      greedy: true
    },
    "class-name": {
      pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
      lookbehind: true,
      inside: {
        punctuation: /[.\\]/
      }
    },
    keyword: /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
    boolean: /\b(?:false|true)\b/,
    function: /\b\w+(?=\()/,
    number: /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
    operator: /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
    punctuation: /[{}[\];(),.:]/
  };
  Prism2.languages.javascript = Prism2.languages.extend("clike", {
    "class-name": [
      Prism2.languages.clike["class-name"],
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
        lookbehind: true
      }
    ],
    keyword: [
      {
        pattern: /((?:^|\})\s*)catch\b/,
        lookbehind: true
      },
      {
        pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
        lookbehind: true
      }
    ],
    // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
    function: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
    number: {
      pattern: RegExp(
        /(^|[^\w$])/.source + "(?:" + // constant
        (/NaN|Infinity/.source + "|" + // binary integer
        /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
        /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
        /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
        /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
        /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
      ),
      lookbehind: true
    },
    operator: /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
  });
  Prism2.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
  Prism2.languages.insertBefore("javascript", "keyword", {
    regex: {
      // eslint-disable-next-line regexp/no-dupe-characters-character-class
      pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,
      lookbehind: true,
      greedy: true,
      inside: {
        "regex-source": {
          pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
          lookbehind: true,
          alias: "language-regex",
          inside: Prism2.languages.regex
        },
        "regex-delimiter": /^\/|\/$/,
        "regex-flags": /^[a-z]+$/
      }
    },
    // This must be declared before keyword because we use "function" inside the look-forward
    "function-variable": {
      pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
      alias: "function"
    },
    parameter: [
      {
        pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      }
    ],
    constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/
  });
  Prism2.languages.insertBefore("javascript", "string", {
    hashbang: {
      pattern: /^#!.*/,
      greedy: true,
      alias: "comment"
    },
    "template-string": {
      pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
      greedy: true,
      inside: {
        "template-punctuation": {
          pattern: /^`|`$/,
          alias: "string"
        },
        interpolation: {
          pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
          lookbehind: true,
          inside: {
            "interpolation-punctuation": {
              pattern: /^\$\{|\}$/,
              alias: "punctuation"
            },
            rest: Prism2.languages.javascript
          }
        },
        string: /[\s\S]+/
      }
    },
    "string-property": {
      pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
      lookbehind: true,
      greedy: true,
      alias: "property"
    }
  });
  Prism2.languages.insertBefore("javascript", "operator", {
    "literal-property": {
      pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
      lookbehind: true,
      alias: "property"
    }
  });
  if (Prism2.languages.markup) {
    Prism2.languages.markup.tag.addInlined("script", "javascript");
    Prism2.languages.markup.tag.addAttribute(
      /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
      "javascript"
    );
  }
  Prism2.languages.js = Prism2.languages.javascript;
  Prism2.languages.python = {
    comment: {
      pattern: /(^|[^\\])#.*/,
      lookbehind: true,
      greedy: true
    },
    "string-interpolation": {
      pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
      greedy: true,
      inside: {
        interpolation: {
          // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
          pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
          lookbehind: true,
          inside: {
            "format-spec": {
              pattern: /(:)[^:(){}]+(?=\}$)/,
              lookbehind: true
            },
            "conversion-option": {
              pattern: /![sra](?=[:}]$)/,
              alias: "punctuation"
            },
            rest: null
          }
        },
        string: /[\s\S]+/
      }
    },
    "triple-quoted-string": {
      pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
      greedy: true,
      alias: "string"
    },
    string: {
      pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
      greedy: true
    },
    function: {
      pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
      lookbehind: true
    },
    "class-name": {
      pattern: /(\bclass\s+)\w+/i,
      lookbehind: true
    },
    decorator: {
      pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
      lookbehind: true,
      alias: ["annotation", "punctuation"],
      inside: {
        punctuation: /\./
      }
    },
    keyword: /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
    builtin: /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
    boolean: /\b(?:False|None|True)\b/,
    number: /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
    operator: /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
    punctuation: /[{}[\];(),.:]/
  };
  Prism2.languages.python["string-interpolation"].inside["interpolation"].inside.rest = Prism2.languages.python;
  Prism2.languages.py = Prism2.languages.python;
  (function() {
    if (typeof Prism2 === "undefined") {
      return;
    }
    var assign = Object.assign || function(obj1, obj2) {
      for (var name4 in obj2) {
        if (obj2.hasOwnProperty(name4)) {
          obj1[name4] = obj2[name4];
        }
      }
      return obj1;
    };
    function NormalizeWhitespace(defaults2) {
      this.defaults = assign({}, defaults2);
    }
    function toCamelCase(value3) {
      return value3.replace(/-(\w)/g, function(match3, firstChar) {
        return firstChar.toUpperCase();
      });
    }
    function tabLen(str) {
      var res = 0;
      for (var i2 = 0; i2 < str.length; ++i2) {
        if (str.charCodeAt(i2) == "	".charCodeAt(0)) {
          res += 3;
        }
      }
      return str.length + res;
    }
    NormalizeWhitespace.prototype = {
      setDefaults: function(defaults2) {
        this.defaults = assign(this.defaults, defaults2);
      },
      normalize: function(input, settings) {
        settings = assign(this.defaults, settings);
        for (var name4 in settings) {
          var methodName = toCamelCase(name4);
          if (name4 !== "normalize" && methodName !== "setDefaults" && settings[name4] && this[methodName]) {
            input = this[methodName].call(this, input, settings[name4]);
          }
        }
        return input;
      },
      /*
       * Normalization methods
       */
      leftTrim: function(input) {
        return input.replace(/^\s+/, "");
      },
      rightTrim: function(input) {
        return input.replace(/\s+$/, "");
      },
      tabsToSpaces: function(input, spaces) {
        spaces = spaces | 0 || 4;
        return input.replace(/\t/g, new Array(++spaces).join(" "));
      },
      spacesToTabs: function(input, spaces) {
        spaces = spaces | 0 || 4;
        return input.replace(RegExp(" {" + spaces + "}", "g"), "	");
      },
      removeTrailing: function(input) {
        return input.replace(/\s*?$/gm, "");
      },
      // Support for deprecated plugin remove-initial-line-feed
      removeInitialLineFeed: function(input) {
        return input.replace(/^(?:\r?\n|\r)/, "");
      },
      removeIndent: function(input) {
        var indents = input.match(/^[^\S\n\r]*(?=\S)/gm);
        if (!indents || !indents[0].length) {
          return input;
        }
        indents.sort(function(a4, b3) {
          return a4.length - b3.length;
        });
        if (!indents[0].length) {
          return input;
        }
        return input.replace(RegExp("^" + indents[0], "gm"), "");
      },
      indent: function(input, tabs) {
        return input.replace(
          /^[^\S\n\r]*(?=\S)/gm,
          new Array(++tabs).join("	") + "$&"
        );
      },
      breakLines: function(input, characters) {
        characters = characters === true ? 80 : characters | 0 || 80;
        var lines = input.split("\n");
        for (var i2 = 0; i2 < lines.length; ++i2) {
          if (tabLen(lines[i2]) <= characters) {
            continue;
          }
          var line4 = lines[i2].split(/(\s+)/g);
          var len = 0;
          for (var j2 = 0; j2 < line4.length; ++j2) {
            var tl2 = tabLen(line4[j2]);
            len += tl2;
            if (len > characters) {
              line4[j2] = "\n" + line4[j2];
              len = tl2;
            }
          }
          lines[i2] = line4.join("");
        }
        return lines.join("\n");
      }
    };
    if (typeof module !== "undefined" && module.exports) {
      module.exports = NormalizeWhitespace;
    }
    Prism2.plugins.NormalizeWhitespace = new NormalizeWhitespace({
      "remove-trailing": true,
      "remove-indent": false,
      "left-trim": false,
      "right-trim": true
      /*'break-lines': 80,
      'indent': 2,
      'remove-initial-line-feed': false,
      'tabs-to-spaces': 4,
      'spaces-to-tabs': 4*/
    });
    Prism2.hooks.add("before-sanity-check", function(env) {
      var Normalizer = Prism2.plugins.NormalizeWhitespace;
      if (env.settings && env.settings["whitespace-normalization"] === false) {
        return;
      }
      if (!Prism2.util.isActive(env.element, "whitespace-normalization", true)) {
        return;
      }
      if ((!env.element || !env.element.parentNode) && env.code) {
        env.code = Normalizer.normalize(env.code, env.settings);
        return;
      }
      var pre = env.element.parentNode;
      if (!env.code || !pre || pre.nodeName.toLowerCase() !== "pre") {
        return;
      }
      var children4 = pre.childNodes;
      var before = "";
      var after = "";
      var codeFound = false;
      for (var i2 = 0; i2 < children4.length; ++i2) {
        var node = children4[i2];
        if (node == env.element) {
          codeFound = true;
        } else if (node.nodeName === "#text") {
          if (codeFound) {
            after += node.nodeValue;
          } else {
            before += node.nodeValue;
          }
          pre.removeChild(node);
          --i2;
        }
      }
      if (!env.element.children.length || !Prism2.plugins.KeepMarkup) {
        env.code = before + env.code + after;
        env.code = Normalizer.normalize(env.code, env.settings);
      } else {
        var html = before + env.element.innerHTML + after;
        env.element.innerHTML = Normalizer.normalize(html, env.settings);
        env.code = env.element.textContent;
      }
    });
  })();

  // tablesort.js
  var createEvent = (name4) => {
    let evt;
    if (!window.CustomEvent || typeof window.CustomEvent !== "function") {
      evt = document.createEvent("CustomEvent");
      evt.initCustomEvent(name4, false, false, void 0);
    } else {
      evt = new CustomEvent(name4);
    }
    return evt;
  };
  var getInnerText = (el, options) => {
    return el.getAttribute(options.sortAttribute || "data-sort") || el.textContent || el.innerText || "";
  };
  var caseInsensitiveSort = (a4, b3) => {
    a4 = a4.trim().toLowerCase();
    b3 = b3.trim().toLowerCase();
    if (a4 === b3) return 0;
    return a4 < b3 ? 1 : -1;
  };
  var getCellByKey = (cells, key2) => {
    return Array.from(cells).find(
      (cell2) => cell2.getAttribute("data-sort-column-key") === key2
    );
  };
  var stabilize = (sort3, antiStabilize) => (a4, b3) => {
    const unstableResult = sort3(a4.td, b3.td);
    if (unstableResult === 0) {
      return antiStabilize ? b3.index - a4.index : a4.index - b3.index;
    }
    return unstableResult;
  };
  var sortOptions = [];
  var Tablesort = class {
    constructor(el, options = {}) {
      if (!(el instanceof HTMLTableElement)) {
        throw new Error("Element must be a table");
      }
      this.init(el, options);
    }
    static extend(name4, pattern, sort3) {
      if (typeof pattern !== "function" || typeof sort3 !== "function") {
        throw new Error("Pattern and sort must be a function");
      }
      sortOptions.push({ name: name4, pattern, sort: sort3 });
    }
    init(el, options) {
      this.table = el;
      this.thead = false;
      this.options = options;
      let firstRow;
      if (el.tHead && el.tHead.rows.length > 0) {
        firstRow = Array.from(el.tHead.rows).find(
          (row) => row.getAttribute("data-sort-method") === "thead"
        ) || el.tHead.rows[el.tHead.rows.length - 1];
        this.thead = true;
      } else {
        firstRow = el.rows[0];
      }
      if (!firstRow) return;
      const onClick = (event2) => {
        if (this.current && this.current !== event2.currentTarget) {
          this.current.removeAttribute("aria-sort");
        }
        this.current = event2.currentTarget;
        this.sortTable(event2.currentTarget);
      };
      for (const cell2 of firstRow.cells) {
        cell2.setAttribute("role", "columnheader");
        if (cell2.getAttribute("data-sort-method") !== "none") {
          cell2.tabIndex = 0;
          cell2.addEventListener("click", onClick, false);
          if (cell2.getAttribute("data-sort-default") !== null) {
            this.current = cell2;
            this.sortTable(cell2);
          }
        }
      }
    }
    sortTable(header, update3 = false) {
      const columnKey = header.getAttribute("data-sort-column-key");
      const column = header.cellIndex;
      let sortFunction = caseInsensitiveSort;
      let items = [];
      let i2 = this.thead ? 0 : 1;
      const sortMethod = header.getAttribute("data-sort-method");
      let sortOrder = header.getAttribute("aria-sort");
      this.table.dispatchEvent(createEvent("beforeSort"));
      if (!update3) {
        sortOrder = sortOrder === "ascending" ? "descending" : sortOrder === "descending" ? "ascending" : this.options.descending ? "descending" : "ascending";
        header.setAttribute("aria-sort", sortOrder);
      }
      if (this.table.rows.length < 2) return;
      while (items.length < 3 && i2 < this.table.tBodies[0].rows.length) {
        const cell2 = columnKey ? getCellByKey(this.table.tBodies[0].rows[i2].cells, columnKey) : this.table.tBodies[0].rows[i2].cells[column];
        const item = cell2 ? getInnerText(cell2, this.options).trim() : "";
        if (item.length > 0) items.push(item);
        i2++;
      }
      for (const option of sortOptions) {
        if (sortMethod && option.name === sortMethod) {
          sortFunction = option.sort;
          break;
        } else if (items.every(option.pattern)) {
          sortFunction = option.sort;
          break;
        }
      }
      this.col = column;
      for (const tbody of this.table.tBodies) {
        const newRows = [];
        const noSorts = {};
        let totalRows = 0;
        let noSortsSoFar = 0;
        for (const row of tbody.rows) {
          if (row.getAttribute("data-sort-method") === "none") {
            noSorts[totalRows] = row;
          } else {
            const cell2 = columnKey ? getCellByKey(row.cells, columnKey) : row.cells[this.col];
            newRows.push({
              tr: row,
              td: cell2 ? getInnerText(cell2, this.options) : "",
              index: totalRows
            });
          }
          totalRows++;
        }
        if (sortOrder === "descending") {
          newRows.sort(stabilize(sortFunction, true));
        } else {
          newRows.sort(stabilize(sortFunction, false)).reverse();
        }
        for (let j2 = 0; j2 < totalRows; j2++) {
          const row = noSorts[j2] || newRows[j2 - noSortsSoFar].tr;
          tbody.appendChild(row);
        }
      }
      this.table.dispatchEvent(createEvent("afterSort"));
    }
    refresh() {
      if (this.current) {
        this.sortTable(this.current, true);
      }
    }
  };
  var cleanNumber = (i2) => i2.replace(/[^\-?0-9.]/g, "");
  var compareNumber = (a4, b3) => (parseFloat(b3) || 0) - (parseFloat(a4) || 0);
  Tablesort.extend(
    "number",
    (item) => item.match(/^[-+]?[£\x24Û¢´€]?\d+\s*([,\.]\d{0,2})/) || item.match(/^[-+]?\d+\s*([,\.]\d{0,2})?[£\x24Û¢´€]/) || item.match(/^[-+]?(\d)*-?([,\.]){0,1}-?(\d)+([E,e][\-+][\d]+)?%?$/),
    (a4, b3) => compareNumber(cleanNumber(a4), cleanNumber(b3))
  );
  var tablesort_default = Tablesort;

  // openai.ts
  async function tryApi(apiKey) {
    const response = await fetch("https://api.openai.com/v1/completions", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`
      }
    });
    return response;
  }
  async function isValidApiKey(apiKey) {
    const response = await tryApi(apiKey);
    const data3 = await response.json();
    if (data3.error && data3.error.code && data3.error.code in {
      invalid_api_key: true,
      invalid_request_error: true,
      model_not_found: true,
      insufficient_quota: true
    }) {
      return false;
    } else {
      return true;
    }
  }
  async function fetchOpenAIModels(apiKey) {
    if (!apiKey) return [];
    const customUrlElement = document.getElementById("openai-custom-url");
    const customUrl = customUrlElement?.value?.trim() || "";
    const baseUrl = customUrl || "https://api.openai.com/v1";
    const endpoint = `${baseUrl}/models`;
    try {
      const response = await fetch(endpoint, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${apiKey}`
        }
      });
      const data3 = await response.json();
      if (data3.error || !data3.data) {
        console.error("Failed to fetch OpenAI models:", data3.error);
        return [];
      }
      const chatModels = data3.data.map((m4) => m4.id).filter(
        (id2) => id2.includes("gpt") || id2.includes("o1") || id2.includes("o3") || id2.includes("o4")
      ).filter((id2) => !id2.includes("instruct") && !id2.includes("realtime") && !id2.includes("audio")).sort();
      return chatModels;
    } catch (error3) {
      console.error("Error fetching OpenAI models:", error3);
      return [];
    }
  }
  function checkApiKey(apiKey) {
    (async () => {
      try {
        window.localStorage.setItem("scalene-api-key", apiKey);
      } catch {
      }
      if (apiKey.length === 0) {
        const validKeyElement2 = document.getElementById("valid-api-key");
        if (validKeyElement2) {
          validKeyElement2.innerHTML = "";
        }
        return;
      }
      const customUrlElement = document.getElementById("openai-custom-url");
      const customUrl = customUrlElement?.value?.trim() || "";
      if (customUrl) {
        const validKeyElement2 = document.getElementById("valid-api-key");
        if (validKeyElement2) {
          validKeyElement2.innerHTML = "";
        }
        return;
      }
      const isValid2 = await isValidApiKey(apiKey);
      const validKeyElement = document.getElementById("valid-api-key");
      if (validKeyElement) {
        if (!isValid2) {
          validKeyElement.innerHTML = "&#10005;";
        } else {
          validKeyElement.innerHTML = "&check;";
        }
      }
    })();
  }
  async function sendPromptToOpenAI(prompt, apiKey) {
    const customUrlElement = document.getElementById("openai-custom-url");
    const customUrl = customUrlElement?.value?.trim() || "";
    const endpoint = customUrl || "https://api.openai.com/v1/chat/completions";
    const customModelElement = document.getElementById("openai-custom-model");
    const customModel = customModelElement?.value?.trim() || "";
    const modelElement = document.getElementById("language-model-openai");
    const model = customModel || modelElement?.value || "gpt-4";
    const body = JSON.stringify({
      model,
      messages: [
        {
          role: "system",
          content: "You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      user: "scalene-user"
    });
    console.log(body);
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`
      },
      body
    });
    const data3 = await response.json();
    if (data3.error) {
      if (data3.error.code && data3.error.code in {
        invalid_request_error: true,
        model_not_found: true,
        insufficient_quota: true
      }) {
        if (data3.error.code === "model_not_found" && model === "gpt-4") {
          alert(
            "You either need to add funds to your OpenAI account to use this feature, or you need to switch to GPT-3.5 if you are using free credits."
          );
        } else {
          alert(
            "You need to add funds to your OpenAI account to use this feature."
          );
        }
        return "";
      }
    }
    try {
      if (data3.choices && data3.choices[0]) {
        console.log(
          `Debugging info: Retrieved ${JSON.stringify(data3.choices[0], null, 4)}`
        );
      }
    } catch {
      console.log(
        `Debugging info: Failed to retrieve data.choices from the server. data = ${JSON.stringify(data3)}`
      );
    }
    try {
      if (data3.choices && data3.choices[0]) {
        return data3.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
      }
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    } catch {
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    }
  }

  // anthropic.ts
  async function sendPromptToAnthropic(prompt, apiKey) {
    const customUrlElement = document.getElementById("anthropic-custom-url");
    const customUrl = customUrlElement?.value?.trim() || "";
    const endpoint = customUrl || "https://api.anthropic.com/v1/messages";
    const customModelElement = document.getElementById("anthropic-custom-model");
    const customModel = customModelElement?.value?.trim() || "";
    const modelElement = document.getElementById("language-model-anthropic");
    const model = customModel || modelElement?.value || "claude-sonnet-4-5-20250929";
    const body = JSON.stringify({
      model,
      max_tokens: 4096,
      messages: [
        {
          role: "user",
          content: prompt
        }
      ],
      system: "You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```."
    });
    console.log(body);
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": apiKey,
        "anthropic-version": "2023-06-01",
        "anthropic-dangerous-direct-browser-access": "true"
      },
      body
    });
    const data3 = await response.json();
    if (data3.error) {
      console.error("Anthropic API error:", data3.error);
      if (data3.error.type === "authentication_error") {
        alert("Invalid Anthropic API key. Please check your API key and try again.");
      } else if (data3.error.type === "rate_limit_error") {
        alert("Rate limit exceeded. Please wait a moment and try again.");
      } else {
        alert(`Anthropic API error: ${data3.error.message || "Unknown error"}`);
      }
      return "";
    }
    try {
      if (data3.content && data3.content[0]) {
        console.log(
          `Debugging info: Retrieved ${JSON.stringify(data3.content[0], null, 4)}`
        );
        return data3.content[0].text.replace(/^\s*[\r\n]/gm, "");
      }
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    } catch {
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    }
  }

  // gemini.ts
  async function sendPromptToGemini(prompt, apiKey) {
    const customUrlElement = document.getElementById("gemini-custom-url");
    const customUrl = customUrlElement?.value?.trim() || "";
    const customModelElement = document.getElementById("gemini-custom-model");
    const customModel = customModelElement?.value?.trim() || "";
    const modelElement = document.getElementById("language-model-gemini");
    const model = customModel || modelElement?.value || "gemini-2.0-flash";
    const baseUrl = customUrl || "https://generativelanguage.googleapis.com/v1beta";
    const endpoint = `${baseUrl}/models/${model}:generateContent?key=${apiKey}`;
    const body = JSON.stringify({
      contents: [
        {
          parts: [
            {
              text: prompt
            }
          ]
        }
      ],
      systemInstruction: {
        parts: [
          {
            text: "You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```."
          }
        ]
      },
      generationConfig: {
        temperature: 0.3,
        maxOutputTokens: 4096
      }
    });
    console.log(body);
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body
    });
    const data3 = await response.json();
    if (data3.error) {
      console.error("Gemini API error:", data3.error);
      if (data3.error.status === "INVALID_ARGUMENT" || data3.error.code === 400) {
        alert(`Gemini API error: ${data3.error.message || "Invalid request"}`);
      } else if (data3.error.status === "UNAUTHENTICATED" || data3.error.code === 401) {
        alert("Invalid Gemini API key. Please check your API key and try again.");
      } else if (data3.error.status === "RESOURCE_EXHAUSTED" || data3.error.code === 429) {
        alert("Rate limit exceeded. Please wait a moment and try again.");
      } else {
        alert(`Gemini API error: ${data3.error.message || "Unknown error"}`);
      }
      return "";
    }
    try {
      if (data3.candidates && data3.candidates[0] && data3.candidates[0].content) {
        const text4 = data3.candidates[0].content.parts.map((part) => part.text).join("");
        console.log(
          `Debugging info: Retrieved ${JSON.stringify(data3.candidates[0], null, 4)}`
        );
        return text4.replace(/^\s*[\r\n]/gm, "");
      }
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    } catch {
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    }
  }
  async function fetchGeminiModels(apiKey) {
    if (!apiKey) return [];
    const customUrlElement = document.getElementById("gemini-custom-url");
    const customUrl = customUrlElement?.value?.trim() || "";
    const baseUrl = customUrl || "https://generativelanguage.googleapis.com/v1beta";
    const endpoint = `${baseUrl}/models?key=${apiKey}`;
    try {
      const response = await fetch(endpoint, {
        method: "GET",
        headers: {
          "Content-Type": "application/json"
        }
      });
      const data3 = await response.json();
      if (data3.error || !data3.models) {
        console.error("Failed to fetch Gemini models:", data3.error);
        return [];
      }
      const chatModels = data3.models.filter((m4) => m4.supportedGenerationMethods?.includes("generateContent")).map((m4) => m4.name.replace("models/", "")).filter((id2) => id2.includes("gemini")).sort();
      return chatModels;
    } catch (error3) {
      console.error("Error fetching Gemini models:", error3);
      return [];
    }
  }

  // ollama.ts
  async function fetchModelNames(local_ip, local_port, revealInstallMessage2) {
    try {
      const response = await fetch(`http://${local_ip}:${local_port}/api/tags`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data3 = await response.json();
      const modelNames = data3.models.map((model) => model.name);
      if (modelNames.length === 0) {
        revealInstallMessage2();
      }
      return modelNames;
    } catch (error3) {
      console.error("Error fetching model names:", error3);
      revealInstallMessage2();
      return [];
    }
  }
  async function sendPromptToOllama(prompt, model, ipAddr, portNum) {
    const url = `http://${ipAddr}:${portNum}/api/chat`;
    const headers = { "Content-Type": "application/json" };
    const body = JSON.stringify({
      model,
      messages: [
        {
          role: "system",
          content: "You are an expert code assistant who only responds in Python code."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      stream: false,
      temperature: 0.3,
      frequency_penalty: 0,
      presence_penalty: 0,
      user: "scalene-user"
    });
    console.log(body);
    let done = false;
    let responseAggregated = "";
    let retried = 0;
    const retries = 3;
    while (!done) {
      if (retried >= retries) {
        return "";
      }
      try {
        const response = await fetch(url, {
          method: "POST",
          headers,
          body
        });
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const text4 = await response.text();
        const responses = text4.split("\n");
        for (const resp of responses) {
          if (!resp.trim()) continue;
          const responseJson = JSON.parse(resp);
          if (responseJson.message && responseJson.message.content) {
            responseAggregated += responseJson.message.content;
          }
          if (responseJson.done) {
            done = true;
            break;
          }
        }
      } catch (error3) {
        console.log(`Error: ${error3}`);
        retried++;
      }
    }
    console.log(responseAggregated);
    try {
      return responseAggregated;
    } catch {
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    }
  }

  // node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamConfiguration.js
  function resolveEventStreamConfig(input) {
    const eventSigner = input.signer;
    const messageSigner = input.signer;
    const newInput = Object.assign(input, {
      eventSigner,
      messageSigner
    });
    const eventStreamPayloadHandler = newInput.eventStreamPayloadHandlerProvider(newInput);
    return Object.assign(newInput, {
      eventStreamPayloadHandler
    });
  }

  // node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js
  var getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
    return {
      setHttpHandler(handler) {
        runtimeConfig.httpHandler = handler;
      },
      httpHandler() {
        return runtimeConfig.httpHandler;
      },
      updateHttpClientConfig(key2, value3) {
        runtimeConfig.httpHandler?.updateHttpClientConfig(key2, value3);
      },
      httpHandlerConfigs() {
        return runtimeConfig.httpHandler.httpHandlerConfigs();
      }
    };
  };
  var resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
    return {
      httpHandler: httpHandlerExtensionConfiguration.httpHandler()
    };
  };

  // node_modules/@smithy/types/dist-es/auth/auth.js
  var HttpAuthLocation;
  (function(HttpAuthLocation2) {
    HttpAuthLocation2["HEADER"] = "header";
    HttpAuthLocation2["QUERY"] = "query";
  })(HttpAuthLocation || (HttpAuthLocation = {}));

  // node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js
  var HttpApiKeyAuthLocation;
  (function(HttpApiKeyAuthLocation2) {
    HttpApiKeyAuthLocation2["HEADER"] = "header";
    HttpApiKeyAuthLocation2["QUERY"] = "query";
  })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {}));

  // node_modules/@smithy/types/dist-es/endpoint.js
  var EndpointURLScheme;
  (function(EndpointURLScheme2) {
    EndpointURLScheme2["HTTP"] = "http";
    EndpointURLScheme2["HTTPS"] = "https";
  })(EndpointURLScheme || (EndpointURLScheme = {}));

  // node_modules/@smithy/types/dist-es/extensions/checksum.js
  var AlgorithmId;
  (function(AlgorithmId2) {
    AlgorithmId2["MD5"] = "md5";
    AlgorithmId2["CRC32"] = "crc32";
    AlgorithmId2["CRC32C"] = "crc32c";
    AlgorithmId2["SHA1"] = "sha1";
    AlgorithmId2["SHA256"] = "sha256";
  })(AlgorithmId || (AlgorithmId = {}));

  // node_modules/@smithy/types/dist-es/http.js
  var FieldPosition;
  (function(FieldPosition2) {
    FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER";
    FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER";
  })(FieldPosition || (FieldPosition = {}));

  // node_modules/@smithy/types/dist-es/middleware.js
  var SMITHY_CONTEXT_KEY = "__smithy_context";

  // node_modules/@smithy/types/dist-es/profile.js
  var IniSectionType;
  (function(IniSectionType2) {
    IniSectionType2["PROFILE"] = "profile";
    IniSectionType2["SSO_SESSION"] = "sso-session";
    IniSectionType2["SERVICES"] = "services";
  })(IniSectionType || (IniSectionType = {}));

  // node_modules/@smithy/types/dist-es/transfer.js
  var RequestHandlerProtocol;
  (function(RequestHandlerProtocol2) {
    RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9";
    RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0";
    RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0";
  })(RequestHandlerProtocol || (RequestHandlerProtocol = {}));

  // node_modules/@smithy/protocol-http/dist-es/httpRequest.js
  var HttpRequest = class _HttpRequest {
    constructor(options) {
      this.method = options.method || "GET";
      this.hostname = options.hostname || "localhost";
      this.port = options.port;
      this.query = options.query || {};
      this.headers = options.headers || {};
      this.body = options.body;
      this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:";
      this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/";
      this.username = options.username;
      this.password = options.password;
      this.fragment = options.fragment;
    }
    static clone(request2) {
      const cloned = new _HttpRequest({
        ...request2,
        headers: { ...request2.headers }
      });
      if (cloned.query) {
        cloned.query = cloneQuery(cloned.query);
      }
      return cloned;
    }
    static isInstance(request2) {
      if (!request2) {
        return false;
      }
      const req = request2;
      return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object";
    }
    clone() {
      return _HttpRequest.clone(this);
    }
  };
  function cloneQuery(query) {
    return Object.keys(query).reduce((carry, paramName) => {
      const param2 = query[paramName];
      return {
        ...carry,
        [paramName]: Array.isArray(param2) ? [...param2] : param2
      };
    }, {});
  }

  // node_modules/@smithy/protocol-http/dist-es/httpResponse.js
  var HttpResponse = class {
    constructor(options) {
      this.statusCode = options.statusCode;
      this.reason = options.reason;
      this.headers = options.headers || {};
      this.body = options.body;
    }
    static isInstance(response) {
      if (!response)
        return false;
      const resp = response;
      return typeof resp.statusCode === "number" && typeof resp.headers === "object";
    }
  };

  // node_modules/@aws-sdk/middleware-host-header/dist-es/index.js
  function resolveHostHeaderConfig(input) {
    return input;
  }
  var hostHeaderMiddleware = (options) => (next) => async (args) => {
    if (!HttpRequest.isInstance(args.request))
      return next(args);
    const { request: request2 } = args;
    const { handlerProtocol = "" } = options.requestHandler.metadata || {};
    if (handlerProtocol.indexOf("h2") >= 0 && !request2.headers[":authority"]) {
      delete request2.headers["host"];
      request2.headers[":authority"] = request2.hostname + (request2.port ? ":" + request2.port : "");
    } else if (!request2.headers["host"]) {
      let host = request2.hostname;
      if (request2.port != null)
        host += `:${request2.port}`;
      request2.headers["host"] = host;
    }
    return next(args);
  };
  var hostHeaderMiddlewareOptions = {
    name: "hostHeaderMiddleware",
    step: "build",
    priority: "low",
    tags: ["HOST"],
    override: true
  };
  var getHostHeaderPlugin = (options) => ({
    applyToStack: (clientStack) => {
      clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions);
    }
  });

  // node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js
  var loggerMiddleware = () => (next, context3) => async (args) => {
    try {
      const response = await next(args);
      const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context3;
      const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
      const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context3.inputFilterSensitiveLog;
      const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context3.outputFilterSensitiveLog;
      const { $metadata, ...outputWithoutMetadata } = response.output;
      logger3?.info?.({
        clientName,
        commandName,
        input: inputFilterSensitiveLog(args.input),
        output: outputFilterSensitiveLog(outputWithoutMetadata),
        metadata: $metadata
      });
      return response;
    } catch (error3) {
      const { clientName, commandName, logger: logger3, dynamoDbDocumentClientOptions = {} } = context3;
      const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions;
      const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context3.inputFilterSensitiveLog;
      logger3?.error?.({
        clientName,
        commandName,
        input: inputFilterSensitiveLog(args.input),
        error: error3,
        metadata: error3.$metadata
      });
      throw error3;
    }
  };
  var loggerMiddlewareOptions = {
    name: "loggerMiddleware",
    tags: ["LOGGER"],
    step: "initialize",
    override: true
  };
  var getLoggerPlugin = (options) => ({
    applyToStack: (clientStack) => {
      clientStack.add(loggerMiddleware(), loggerMiddlewareOptions);
    }
  });

  // node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js
  var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
  var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
  var ENV_TRACE_ID = "_X_AMZN_TRACE_ID";
  var recursionDetectionMiddleware = (options) => (next) => async (args) => {
    const { request: request2 } = args;
    if (!HttpRequest.isInstance(request2) || options.runtime !== "node") {
      return next(args);
    }
    const traceIdHeader = Object.keys(request2.headers ?? {}).find((h3) => h3.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? TRACE_ID_HEADER_NAME;
    if (request2.headers.hasOwnProperty(traceIdHeader)) {
      return next(args);
    }
    const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME];
    const traceId = process.env[ENV_TRACE_ID];
    const nonEmptyString = (str) => typeof str === "string" && str.length > 0;
    if (nonEmptyString(functionName) && nonEmptyString(traceId)) {
      request2.headers[TRACE_ID_HEADER_NAME] = traceId;
    }
    return next({
      ...args,
      request: request2
    });
  };
  var addRecursionDetectionMiddlewareOptions = {
    step: "build",
    tags: ["RECURSION_DETECTION"],
    name: "recursionDetectionMiddleware",
    override: true,
    priority: "low"
  };
  var getRecursionDetectionPlugin = (options) => ({
    applyToStack: (clientStack) => {
      clientStack.add(recursionDetectionMiddleware(options), addRecursionDetectionMiddlewareOptions);
    }
  });

  // node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js
  var getSmithyContext = (context3) => context3[SMITHY_CONTEXT_KEY] || (context3[SMITHY_CONTEXT_KEY] = {});

  // node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js
  var normalizeProvider = (input) => {
    if (typeof input === "function")
      return input;
    const promisified = Promise.resolve(input);
    return () => promisified;
  };

  // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js
  var resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => {
    if (!authSchemePreference || authSchemePreference.length === 0) {
      return candidateAuthOptions;
    }
    const preferredAuthOptions = [];
    for (const preferredSchemeName of authSchemePreference) {
      for (const candidateAuthOption of candidateAuthOptions) {
        const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1];
        if (candidateAuthSchemeName === preferredSchemeName) {
          preferredAuthOptions.push(candidateAuthOption);
        }
      }
    }
    for (const candidateAuthOption of candidateAuthOptions) {
      if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) {
        preferredAuthOptions.push(candidateAuthOption);
      }
    }
    return preferredAuthOptions;
  };

  // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js
  function convertHttpAuthSchemesToMap(httpAuthSchemes) {
    const map4 = /* @__PURE__ */ new Map();
    for (const scheme3 of httpAuthSchemes) {
      map4.set(scheme3.schemeId, scheme3);
    }
    return map4;
  }
  var httpAuthSchemeMiddleware = (config, mwOptions) => (next, context3) => async (args) => {
    const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context3, args.input));
    const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : [];
    const resolvedOptions = resolveAuthOptions(options, authSchemePreference);
    const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes);
    const smithyContext = getSmithyContext(context3);
    const failureReasons = [];
    for (const option of resolvedOptions) {
      const scheme3 = authSchemes.get(option.schemeId);
      if (!scheme3) {
        failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);
        continue;
      }
      const identityProvider = scheme3.identityProvider(await mwOptions.identityProviderConfigProvider(config));
      if (!identityProvider) {
        failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);
        continue;
      }
      const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context3) || {};
      option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties);
      option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties);
      smithyContext.selectedHttpAuthScheme = {
        httpAuthOption: option,
        identity: await identityProvider(option.identityProperties),
        signer: scheme3.signer
      };
      break;
    }
    if (!smithyContext.selectedHttpAuthScheme) {
      throw new Error(failureReasons.join("\n"));
    }
    return next(args);
  };

  // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js
  var httpAuthSchemeEndpointRuleSetMiddlewareOptions = {
    step: "serialize",
    tags: ["HTTP_AUTH_SCHEME"],
    name: "httpAuthSchemeMiddleware",
    override: true,
    relation: "before",
    toMiddleware: "endpointV2Middleware"
  };
  var getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({
    applyToStack: (clientStack) => {
      clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, {
        httpAuthSchemeParametersProvider,
        identityProviderConfigProvider
      }), httpAuthSchemeEndpointRuleSetMiddlewareOptions);
    }
  });

  // node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js
  var deserializerMiddleware = (options, deserializer) => (next, context3) => async (args) => {
    const { response } = await next(args);
    try {
      const parsed = await deserializer(response, options);
      return {
        response,
        output: parsed
      };
    } catch (error3) {
      Object.defineProperty(error3, "$response", {
        value: response
      });
      if (!("$metadata" in error3)) {
        const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
        try {
          error3.message += "\n  " + hint;
        } catch (e4) {
          if (!context3.logger || context3.logger?.constructor?.name === "NoOpLogger") {
            console.warn(hint);
          } else {
            context3.logger?.warn?.(hint);
          }
        }
        if (typeof error3.$responseBodyText !== "undefined") {
          if (error3.$response) {
            error3.$response.body = error3.$responseBodyText;
          }
        }
        try {
          if (HttpResponse.isInstance(response)) {
            const { headers = {} } = response;
            const headerEntries = Object.entries(headers);
            error3.$metadata = {
              httpStatusCode: response.statusCode,
              requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
              extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
              cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
            };
          }
        } catch (e4) {
        }
      }
      throw error3;
    }
  };
  var findHeader = (pattern, headers) => {
    return (headers.find(([k2]) => {
      return k2.match(pattern);
    }) || [void 0, void 0])[1];
  };

  // node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js
  var serializerMiddleware = (options, serializer) => (next, context3) => async (args) => {
    const endpointConfig = options;
    const endpoint = context3.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context3.endpointV2.url) : endpointConfig.endpoint;
    if (!endpoint) {
      throw new Error("No valid endpoint provider available.");
    }
    const request2 = await serializer(args.input, { ...options, endpoint });
    return next({
      ...args,
      request: request2
    });
  };

  // node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js
  var deserializerMiddlewareOption = {
    name: "deserializerMiddleware",
    step: "deserialize",
    tags: ["DESERIALIZER"],
    override: true
  };
  var serializerMiddlewareOption = {
    name: "serializerMiddleware",
    step: "serialize",
    tags: ["SERIALIZER"],
    override: true
  };
  function getSerdePlugin(config, serializer, deserializer) {
    return {
      applyToStack: (commandStack) => {
        commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption);
        commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption);
      }
    };
  }

  // node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js
  var defaultErrorHandler = (signingProperties) => (error3) => {
    throw error3;
  };
  var defaultSuccessHandler = (httpResponse, signingProperties) => {
  };
  var httpSigningMiddleware = (config) => (next, context3) => async (args) => {
    if (!HttpRequest.isInstance(args.request)) {
      return next(args);
    }
    const smithyContext = getSmithyContext(context3);
    const scheme3 = smithyContext.selectedHttpAuthScheme;
    if (!scheme3) {
      throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
    }
    const { httpAuthOption: { signingProperties = {} }, identity: identity5, signer } = scheme3;
    const output3 = await next({
      ...args,
      request: await signer.sign(args.request, identity5, signingProperties)
    }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
    (signer.successHandler || defaultSuccessHandler)(output3.response, signingProperties);
    return output3;
  };

  // node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js
  var httpSigningMiddlewareOptions = {
    step: "finalizeRequest",
    tags: ["HTTP_SIGNING"],
    name: "httpSigningMiddleware",
    aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"],
    override: true,
    relation: "after",
    toMiddleware: "retryMiddleware"
  };
  var getHttpSigningPlugin = (config) => ({
    applyToStack: (clientStack) => {
      clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions);
    }
  });

  // node_modules/@smithy/core/dist-es/normalizeProvider.js
  var normalizeProvider2 = (input) => {
    if (typeof input === "function")
      return input;
    const promisified = Promise.resolve(input);
    return () => promisified;
  };

  // node_modules/@smithy/util-base64/dist-es/constants.browser.js
  var alphabetByEncoding = {};
  var alphabetByValue = new Array(64);
  for (let i2 = 0, start = "A".charCodeAt(0), limit = "Z".charCodeAt(0); i2 + start <= limit; i2++) {
    const char = String.fromCharCode(i2 + start);
    alphabetByEncoding[char] = i2;
    alphabetByValue[i2] = char;
  }
  for (let i2 = 0, start = "a".charCodeAt(0), limit = "z".charCodeAt(0); i2 + start <= limit; i2++) {
    const char = String.fromCharCode(i2 + start);
    const index4 = i2 + 26;
    alphabetByEncoding[char] = index4;
    alphabetByValue[index4] = char;
  }
  for (let i2 = 0; i2 < 10; i2++) {
    alphabetByEncoding[i2.toString(10)] = i2 + 52;
    const char = i2.toString(10);
    const index4 = i2 + 52;
    alphabetByEncoding[char] = index4;
    alphabetByValue[index4] = char;
  }
  alphabetByEncoding["+"] = 62;
  alphabetByValue[62] = "+";
  alphabetByEncoding["/"] = 63;
  alphabetByValue[63] = "/";
  var bitsPerLetter = 6;
  var bitsPerByte = 8;
  var maxLetterValue = 63;

  // node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js
  var fromBase64 = (input) => {
    let totalByteLength = input.length / 4 * 3;
    if (input.slice(-2) === "==") {
      totalByteLength -= 2;
    } else if (input.slice(-1) === "=") {
      totalByteLength--;
    }
    const out = new ArrayBuffer(totalByteLength);
    const dataView = new DataView(out);
    for (let i2 = 0; i2 < input.length; i2 += 4) {
      let bits = 0;
      let bitLength = 0;
      for (let j2 = i2, limit = i2 + 3; j2 <= limit; j2++) {
        if (input[j2] !== "=") {
          if (!(input[j2] in alphabetByEncoding)) {
            throw new TypeError(`Invalid character ${input[j2]} in base64 string.`);
          }
          bits |= alphabetByEncoding[input[j2]] << (limit - j2) * bitsPerLetter;
          bitLength += bitsPerLetter;
        } else {
          bits >>= bitsPerLetter;
        }
      }
      const chunkOffset = i2 / 4 * 3;
      bits >>= bitLength % bitsPerByte;
      const byteLength = Math.floor(bitLength / bitsPerByte);
      for (let k2 = 0; k2 < byteLength; k2++) {
        const offset4 = (byteLength - k2 - 1) * bitsPerByte;
        dataView.setUint8(chunkOffset + k2, (bits & 255 << offset4) >> offset4);
      }
    }
    return new Uint8Array(out);
  };

  // node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
  var fromUtf8 = (input) => new TextEncoder().encode(input);

  // node_modules/@smithy/util-utf8/dist-es/toUint8Array.js
  var toUint8Array = (data3) => {
    if (typeof data3 === "string") {
      return fromUtf8(data3);
    }
    if (ArrayBuffer.isView(data3)) {
      return new Uint8Array(data3.buffer, data3.byteOffset, data3.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    }
    return new Uint8Array(data3);
  };

  // node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js
  var toUtf8 = (input) => {
    if (typeof input === "string") {
      return input;
    }
    if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
      throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");
    }
    return new TextDecoder("utf-8").decode(input);
  };

  // node_modules/@smithy/util-base64/dist-es/toBase64.browser.js
  function toBase64(_input) {
    let input;
    if (typeof _input === "string") {
      input = fromUtf8(_input);
    } else {
      input = _input;
    }
    const isArrayLike = typeof input === "object" && typeof input.length === "number";
    const isUint8Array = typeof input === "object" && typeof input.byteOffset === "number" && typeof input.byteLength === "number";
    if (!isArrayLike && !isUint8Array) {
      throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
    }
    let str = "";
    for (let i2 = 0; i2 < input.length; i2 += 3) {
      let bits = 0;
      let bitLength = 0;
      for (let j2 = i2, limit = Math.min(i2 + 3, input.length); j2 < limit; j2++) {
        bits |= input[j2] << (limit - j2 - 1) * bitsPerByte;
        bitLength += bitsPerByte;
      }
      const bitClusterCount = Math.ceil(bitLength / bitsPerLetter);
      bits <<= bitClusterCount * bitsPerLetter - bitLength;
      for (let k2 = 1; k2 <= bitClusterCount; k2++) {
        const offset4 = (bitClusterCount - k2) * bitsPerLetter;
        str += alphabetByValue[(bits & maxLetterValue << offset4) >> offset4];
      }
      str += "==".slice(0, 4 - bitClusterCount);
    }
    return str;
  }

  // node_modules/@smithy/util-stream/dist-es/blob/transforms.js
  function transformToString(payload, encoding = "utf-8") {
    if (encoding === "base64") {
      return toBase64(payload);
    }
    return toUtf8(payload);
  }
  function transformFromString(str, encoding) {
    if (encoding === "base64") {
      return Uint8ArrayBlobAdapter.mutate(fromBase64(str));
    }
    return Uint8ArrayBlobAdapter.mutate(fromUtf8(str));
  }

  // node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js
  var Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array {
    static fromString(source4, encoding = "utf-8") {
      switch (typeof source4) {
        case "string":
          return transformFromString(source4, encoding);
        default:
          throw new Error(`Unsupported conversion from ${typeof source4} to Uint8ArrayBlobAdapter.`);
      }
    }
    static mutate(source4) {
      Object.setPrototypeOf(source4, _Uint8ArrayBlobAdapter.prototype);
      return source4;
    }
    transformToString(encoding = "utf-8") {
      return transformToString(this, encoding);
    }
  };

  // node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js
  var escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);
  var hexEncode = (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}`;

  // node_modules/@smithy/querystring-builder/dist-es/index.js
  function buildQueryString(query) {
    const parts = [];
    for (let key2 of Object.keys(query).sort()) {
      const value3 = query[key2];
      key2 = escapeUri(key2);
      if (Array.isArray(value3)) {
        for (let i2 = 0, iLen = value3.length; i2 < iLen; i2++) {
          parts.push(`${key2}=${escapeUri(value3[i2])}`);
        }
      } else {
        let qsEntry = key2;
        if (value3 || typeof value3 === "string") {
          qsEntry += `=${escapeUri(value3)}`;
        }
        parts.push(qsEntry);
      }
    }
    return parts.join("&");
  }

  // node_modules/@smithy/fetch-http-handler/dist-es/create-request.js
  function createRequest(url, requestOptions) {
    return new Request(url, requestOptions);
  }

  // node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js
  function requestTimeout(timeoutInMs = 0) {
    return new Promise((resolve2, reject) => {
      if (timeoutInMs) {
        setTimeout(() => {
          const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
          timeoutError.name = "TimeoutError";
          reject(timeoutError);
        }, timeoutInMs);
      }
    });
  }

  // node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js
  var keepAliveSupport = {
    supported: void 0
  };
  var FetchHttpHandler = class _FetchHttpHandler {
    static create(instanceOrOptions) {
      if (typeof instanceOrOptions?.handle === "function") {
        return instanceOrOptions;
      }
      return new _FetchHttpHandler(instanceOrOptions);
    }
    constructor(options) {
      if (typeof options === "function") {
        this.configProvider = options().then((opts) => opts || {});
      } else {
        this.config = options ?? {};
        this.configProvider = Promise.resolve(this.config);
      }
      if (keepAliveSupport.supported === void 0) {
        keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]"));
      }
    }
    destroy() {
    }
    async handle(request2, { abortSignal, requestTimeout: requestTimeout2 } = {}) {
      if (!this.config) {
        this.config = await this.configProvider;
      }
      const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout;
      const keepAlive = this.config.keepAlive === true;
      const credentials = this.config.credentials;
      if (abortSignal?.aborted) {
        const abortError = new Error("Request aborted");
        abortError.name = "AbortError";
        return Promise.reject(abortError);
      }
      let path3 = request2.path;
      const queryString = buildQueryString(request2.query || {});
      if (queryString) {
        path3 += `?${queryString}`;
      }
      if (request2.fragment) {
        path3 += `#${request2.fragment}`;
      }
      let auth = "";
      if (request2.username != null || request2.password != null) {
        const username = request2.username ?? "";
        const password = request2.password ?? "";
        auth = `${username}:${password}@`;
      }
      const { port, method: method2 } = request2;
      const url = `${request2.protocol}//${auth}${request2.hostname}${port ? `:${port}` : ""}${path3}`;
      const body = method2 === "GET" || method2 === "HEAD" ? void 0 : request2.body;
      const requestOptions = {
        body,
        headers: new Headers(request2.headers),
        method: method2,
        credentials
      };
      if (this.config?.cache) {
        requestOptions.cache = this.config.cache;
      }
      if (body) {
        requestOptions.duplex = "half";
      }
      if (typeof AbortController !== "undefined") {
        requestOptions.signal = abortSignal;
      }
      if (keepAliveSupport.supported) {
        requestOptions.keepalive = keepAlive;
      }
      if (typeof this.config.requestInit === "function") {
        Object.assign(requestOptions, this.config.requestInit(request2));
      }
      let removeSignalEventListener = () => {
      };
      const fetchRequest = createRequest(url, requestOptions);
      const raceOfPromises = [
        fetch(fetchRequest).then((response) => {
          const fetchHeaders = response.headers;
          const transformedHeaders = {};
          for (const pair of fetchHeaders.entries()) {
            transformedHeaders[pair[0]] = pair[1];
          }
          const hasReadableStream = response.body != void 0;
          if (!hasReadableStream) {
            return response.blob().then((body2) => ({
              response: new HttpResponse({
                headers: transformedHeaders,
                reason: response.statusText,
                statusCode: response.status,
                body: body2
              })
            }));
          }
          return {
            response: new HttpResponse({
              headers: transformedHeaders,
              reason: response.statusText,
              statusCode: response.status,
              body: response.body
            })
          };
        }),
        requestTimeout(requestTimeoutInMs)
      ];
      if (abortSignal) {
        raceOfPromises.push(new Promise((resolve2, reject) => {
          const onAbort = () => {
            const abortError = new Error("Request aborted");
            abortError.name = "AbortError";
            reject(abortError);
          };
          if (typeof abortSignal.addEventListener === "function") {
            const signal = abortSignal;
            signal.addEventListener("abort", onAbort, { once: true });
            removeSignalEventListener = () => signal.removeEventListener("abort", onAbort);
          } else {
            abortSignal.onabort = onAbort;
          }
        }));
      }
      return Promise.race(raceOfPromises).finally(removeSignalEventListener);
    }
    updateHttpClientConfig(key2, value3) {
      this.config = void 0;
      this.configProvider = this.configProvider.then((config) => {
        config[key2] = value3;
        return config;
      });
    }
    httpHandlerConfigs() {
      return this.config ?? {};
    }
  };

  // node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js
  var streamCollector = async (stream2) => {
    if (typeof Blob === "function" && stream2 instanceof Blob || stream2.constructor?.name === "Blob") {
      if (Blob.prototype.arrayBuffer !== void 0) {
        return new Uint8Array(await stream2.arrayBuffer());
      }
      return collectBlob(stream2);
    }
    return collectStream(stream2);
  };
  async function collectBlob(blob) {
    const base64 = await readToBase64(blob);
    const arrayBuffer = fromBase64(base64);
    return new Uint8Array(arrayBuffer);
  }
  async function collectStream(stream2) {
    const chunks = [];
    const reader = stream2.getReader();
    let isDone = false;
    let length3 = 0;
    while (!isDone) {
      const { done, value: value3 } = await reader.read();
      if (value3) {
        chunks.push(value3);
        length3 += value3.length;
      }
      isDone = done;
    }
    const collected = new Uint8Array(length3);
    let offset4 = 0;
    for (const chunk of chunks) {
      collected.set(chunk, offset4);
      offset4 += chunk.length;
    }
    return collected;
  }
  function readToBase64(blob) {
    return new Promise((resolve2, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        if (reader.readyState !== 2) {
          return reject(new Error("Reader aborted too early"));
        }
        const result = reader.result ?? "";
        const commaIndex = result.indexOf(",");
        const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
        resolve2(result.substring(dataOffset));
      };
      reader.onabort = () => reject(new Error("Read aborted"));
      reader.onerror = () => reject(reader.error);
      reader.readAsDataURL(blob);
    });
  }

  // node_modules/@smithy/util-hex-encoding/dist-es/index.js
  var SHORT_TO_HEX = {};
  var HEX_TO_SHORT = {};
  for (let i2 = 0; i2 < 256; i2++) {
    let encodedByte = i2.toString(16).toLowerCase();
    if (encodedByte.length === 1) {
      encodedByte = `0${encodedByte}`;
    }
    SHORT_TO_HEX[i2] = encodedByte;
    HEX_TO_SHORT[encodedByte] = i2;
  }
  function fromHex(encoded) {
    if (encoded.length % 2 !== 0) {
      throw new Error("Hex encoded strings must have an even number length");
    }
    const out = new Uint8Array(encoded.length / 2);
    for (let i2 = 0; i2 < encoded.length; i2 += 2) {
      const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase();
      if (encodedByte in HEX_TO_SHORT) {
        out[i2 / 2] = HEX_TO_SHORT[encodedByte];
      } else {
        throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);
      }
    }
    return out;
  }
  function toHex(bytes) {
    let out = "";
    for (let i2 = 0; i2 < bytes.byteLength; i2++) {
      out += SHORT_TO_HEX[bytes[i2]];
    }
    return out;
  }

  // node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js
  var collectBody = async (streamBody = new Uint8Array(), context3) => {
    if (streamBody instanceof Uint8Array) {
      return Uint8ArrayBlobAdapter.mutate(streamBody);
    }
    if (!streamBody) {
      return Uint8ArrayBlobAdapter.mutate(new Uint8Array());
    }
    const fromContext = context3.streamCollector(streamBody);
    return Uint8ArrayBlobAdapter.mutate(await fromContext);
  };

  // node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js
  function extendedEncodeURIComponent(str) {
    return encodeURIComponent(str).replace(/[!'()*]/g, function(c4) {
      return "%" + c4.charCodeAt(0).toString(16).toUpperCase();
    });
  }

  // node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js
  var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23));
  var expectLong = (value3) => {
    if (value3 === null || value3 === void 0) {
      return void 0;
    }
    if (Number.isInteger(value3) && !Number.isNaN(value3)) {
      return value3;
    }
    throw new TypeError(`Expected integer, got ${typeof value3}: ${value3}`);
  };
  var expectInt32 = (value3) => expectSizedInt(value3, 32);
  var expectSizedInt = (value3, size) => {
    const expected = expectLong(value3);
    if (expected !== void 0 && castInt(expected, size) !== expected) {
      throw new TypeError(`Expected ${size}-bit integer, got ${value3}`);
    }
    return expected;
  };
  var castInt = (value3, size) => {
    switch (size) {
      case 32:
        return Int32Array.of(value3)[0];
      case 16:
        return Int16Array.of(value3)[0];
      case 8:
        return Int8Array.of(value3)[0];
    }
  };
  var expectString = (value3) => {
    if (value3 === null || value3 === void 0) {
      return void 0;
    }
    if (typeof value3 === "string") {
      return value3;
    }
    if (["boolean", "number", "bigint"].includes(typeof value3)) {
      logger2.warn(stackTraceWarning(`Expected string, got ${typeof value3}: ${value3}`));
      return String(value3);
    }
    throw new TypeError(`Expected string, got ${typeof value3}: ${value3}`);
  };
  var stackTraceWarning = (message) => {
    return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s2) => !s2.includes("stackTraceWarning")).join("\n");
  };
  var logger2 = {
    warn: console.warn
  };

  // node_modules/uuid/dist/esm-browser/rng.js
  var getRandomValues;
  var rnds8 = new Uint8Array(16);
  function rng() {
    if (!getRandomValues) {
      getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
      if (!getRandomValues) {
        throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
      }
    }
    return getRandomValues(rnds8);
  }

  // node_modules/uuid/dist/esm-browser/stringify.js
  var byteToHex = [];
  for (let i2 = 0; i2 < 256; ++i2) {
    byteToHex.push((i2 + 256).toString(16).slice(1));
  }
  function unsafeStringify(arr, offset4 = 0) {
    return byteToHex[arr[offset4 + 0]] + byteToHex[arr[offset4 + 1]] + byteToHex[arr[offset4 + 2]] + byteToHex[arr[offset4 + 3]] + "-" + byteToHex[arr[offset4 + 4]] + byteToHex[arr[offset4 + 5]] + "-" + byteToHex[arr[offset4 + 6]] + byteToHex[arr[offset4 + 7]] + "-" + byteToHex[arr[offset4 + 8]] + byteToHex[arr[offset4 + 9]] + "-" + byteToHex[arr[offset4 + 10]] + byteToHex[arr[offset4 + 11]] + byteToHex[arr[offset4 + 12]] + byteToHex[arr[offset4 + 13]] + byteToHex[arr[offset4 + 14]] + byteToHex[arr[offset4 + 15]];
  }

  // node_modules/uuid/dist/esm-browser/native.js
  var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
  var native_default = {
    randomUUID
  };

  // node_modules/uuid/dist/esm-browser/v4.js
  function v4(options, buf, offset4) {
    if (native_default.randomUUID && !buf && !options) {
      return native_default.randomUUID();
    }
    options = options || {};
    const rnds = options.random || (options.rng || rng)();
    rnds[6] = rnds[6] & 15 | 64;
    rnds[8] = rnds[8] & 63 | 128;
    if (buf) {
      offset4 = offset4 || 0;
      for (let i2 = 0; i2 < 16; ++i2) {
        buf[offset4 + i2] = rnds[i2];
      }
      return buf;
    }
    return unsafeStringify(rnds);
  }
  var v4_default = v4;

  // node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js
  var resolvedPath = (resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => {
    if (input != null && input[memberName] !== void 0) {
      const labelValue = labelValueProvider();
      if (labelValue.length <= 0) {
        throw new Error("Empty value provided for input HTTP label: " + memberName + ".");
      }
      resolvedPath2 = resolvedPath2.replace(uriLabel, isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue));
    } else {
      throw new Error("No value provided for input HTTP label: " + memberName + ".");
    }
    return resolvedPath2;
  };

  // node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js
  function requestBuilder(input, context3) {
    return new RequestBuilder(input, context3);
  }
  var RequestBuilder = class {
    constructor(input, context3) {
      this.input = input;
      this.context = context3;
      this.query = {};
      this.method = "";
      this.headers = {};
      this.path = "";
      this.body = null;
      this.hostname = "";
      this.resolvePathStack = [];
    }
    async build() {
      const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint();
      this.path = basePath;
      for (const resolvePath of this.resolvePathStack) {
        resolvePath(this.path);
      }
      return new HttpRequest({
        protocol,
        hostname: this.hostname || hostname,
        port,
        method: this.method,
        path: this.path,
        query: this.query,
        body: this.body,
        headers: this.headers
      });
    }
    hn(hostname) {
      this.hostname = hostname;
      return this;
    }
    bp(uriLabel) {
      this.resolvePathStack.push((basePath) => {
        this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel;
      });
      return this;
    }
    p(memberName, labelValueProvider, uriLabel, isGreedyLabel) {
      this.resolvePathStack.push((path3) => {
        this.path = resolvedPath(path3, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel);
      });
      return this;
    }
    h(headers) {
      this.headers = headers;
      return this;
    }
    q(query) {
      this.query = query;
      return this;
    }
    b(body) {
      this.body = body;
      return this;
    }
    m(method2) {
      this.method = method2;
      return this;
    }
  };

  // node_modules/@smithy/core/dist-es/setFeature.js
  function setFeature(context3, feature2, value3) {
    if (!context3.__smithy_context) {
      context3.__smithy_context = {
        features: {}
      };
    } else if (!context3.__smithy_context.features) {
      context3.__smithy_context.features = {};
    }
    context3.__smithy_context.features[feature2] = value3;
  }

  // node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js
  var DefaultIdentityProviderConfig = class {
    constructor(config) {
      this.authSchemes = /* @__PURE__ */ new Map();
      for (const [key2, value3] of Object.entries(config)) {
        if (value3 !== void 0) {
          this.authSchemes.set(key2, value3);
        }
      }
    }
    getIdentityProvider(schemeId) {
      return this.authSchemes.get(schemeId);
    }
  };

  // node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js
  var HttpBearerAuthSigner = class {
    async sign(httpRequest, identity5, signingProperties) {
      const clonedRequest = HttpRequest.clone(httpRequest);
      if (!identity5.token) {
        throw new Error("request could not be signed with `token` since the `token` is not defined");
      }
      clonedRequest.headers["Authorization"] = `Bearer ${identity5.token}`;
      return clonedRequest;
    }
  };

  // node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js
  var createIsIdentityExpiredFunction = (expirationMs) => (identity5) => doesIdentityRequireRefresh(identity5) && identity5.expiration.getTime() - Date.now() < expirationMs;
  var EXPIRATION_MS = 3e5;
  var isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS);
  var doesIdentityRequireRefresh = (identity5) => identity5.expiration !== void 0;
  var memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => {
    if (provider === void 0) {
      return void 0;
    }
    const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider;
    let resolved;
    let pending;
    let hasResult;
    let isConstant = false;
    const coalesceProvider = async (options) => {
      if (!pending) {
        pending = normalizedProvider(options);
      }
      try {
        resolved = await pending;
        hasResult = true;
        isConstant = false;
      } finally {
        pending = void 0;
      }
      return resolved;
    };
    if (isExpired === void 0) {
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider(options);
        }
        return resolved;
      };
    }
    return async (options) => {
      if (!hasResult || options?.forceRefresh) {
        resolved = await coalesceProvider(options);
      }
      if (isConstant) {
        return resolved;
      }
      if (!requiresRefresh(resolved)) {
        isConstant = true;
        return resolved;
      }
      if (isExpired(resolved)) {
        await coalesceProvider(options);
        return resolved;
      }
      return resolved;
    };
  };

  // node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js
  var DEFAULT_UA_APP_ID = void 0;
  function isValidUserAgentAppId(appId) {
    if (appId === void 0) {
      return true;
    }
    return typeof appId === "string" && appId.length <= 50;
  }
  function resolveUserAgentConfig(input) {
    const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID);
    const { customUserAgent } = input;
    return Object.assign(input, {
      customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent,
      userAgentAppId: async () => {
        const appId = await normalizedAppIdProvider();
        if (!isValidUserAgentAppId(appId)) {
          const logger3 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger;
          if (typeof appId !== "string") {
            logger3?.warn("userAgentAppId must be a string or undefined.");
          } else if (appId.length > 50) {
            logger3?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.");
          }
        }
        return appId;
      }
    });
  }

  // node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js
  var EndpointCache = class {
    constructor({ size, params: params2 }) {
      this.data = /* @__PURE__ */ new Map();
      this.parameters = [];
      this.capacity = size ?? 50;
      if (params2) {
        this.parameters = params2;
      }
    }
    get(endpointParams, resolver) {
      const key2 = this.hash(endpointParams);
      if (key2 === false) {
        return resolver();
      }
      if (!this.data.has(key2)) {
        if (this.data.size > this.capacity + 10) {
          const keys4 = this.data.keys();
          let i2 = 0;
          while (true) {
            const { value: value3, done } = keys4.next();
            this.data.delete(value3);
            if (done || ++i2 > 10) {
              break;
            }
          }
        }
        this.data.set(key2, resolver());
      }
      return this.data.get(key2);
    }
    size() {
      return this.data.size;
    }
    hash(endpointParams) {
      let buffer = "";
      const { parameters } = this;
      if (parameters.length === 0) {
        return false;
      }
      for (const param2 of parameters) {
        const val = String(endpointParams[param2] ?? "");
        if (val.includes("|;")) {
          return false;
        }
        buffer += val + "|;";
      }
      return buffer;
    }
  };

  // node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js
  var IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`);
  var isIpAddress = (value3) => IP_V4_REGEX.test(value3) || value3.startsWith("[") && value3.endsWith("]");

  // node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js
  var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`);
  var isValidHostLabel = (value3, allowSubDomains = false) => {
    if (!allowSubDomains) {
      return VALID_HOST_LABEL_REGEX.test(value3);
    }
    const labels3 = value3.split(".");
    for (const label of labels3) {
      if (!isValidHostLabel(label)) {
        return false;
      }
    }
    return true;
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js
  var customEndpointFunctions = {};

  // node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js
  var debugId = "endpoints";

  // node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js
  function toDebugString(input) {
    if (typeof input !== "object" || input == null) {
      return input;
    }
    if ("ref" in input) {
      return `$${toDebugString(input.ref)}`;
    }
    if ("fn" in input) {
      return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`;
    }
    return JSON.stringify(input, null, 2);
  }

  // node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js
  var EndpointError = class extends Error {
    constructor(message) {
      super(message);
      this.name = "EndpointError";
    }
  };

  // node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js
  var booleanEquals = (value1, value22) => value1 === value22;

  // node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js
  var getAttrPathList = (path3) => {
    const parts = path3.split(".");
    const pathList = [];
    for (const part of parts) {
      const squareBracketIndex = part.indexOf("[");
      if (squareBracketIndex !== -1) {
        if (part.indexOf("]") !== part.length - 1) {
          throw new EndpointError(`Path: '${path3}' does not end with ']'`);
        }
        const arrayIndex = part.slice(squareBracketIndex + 1, -1);
        if (Number.isNaN(parseInt(arrayIndex))) {
          throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path3}'`);
        }
        if (squareBracketIndex !== 0) {
          pathList.push(part.slice(0, squareBracketIndex));
        }
        pathList.push(arrayIndex);
      } else {
        pathList.push(part);
      }
    }
    return pathList;
  };

  // node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js
  var getAttr = (value3, path3) => getAttrPathList(path3).reduce((acc, index4) => {
    if (typeof acc !== "object") {
      throw new EndpointError(`Index '${index4}' in '${path3}' not found in '${JSON.stringify(value3)}'`);
    } else if (Array.isArray(acc)) {
      return acc[parseInt(index4)];
    }
    return acc[index4];
  }, value3);

  // node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js
  var isSet = (value3) => value3 != null;

  // node_modules/@smithy/util-endpoints/dist-es/lib/not.js
  var not = (value3) => !value3;

  // node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js
  var DEFAULT_PORTS = {
    [EndpointURLScheme.HTTP]: 80,
    [EndpointURLScheme.HTTPS]: 443
  };
  var parseURL = (value3) => {
    const whatwgURL = (() => {
      try {
        if (value3 instanceof URL) {
          return value3;
        }
        if (typeof value3 === "object" && "hostname" in value3) {
          const { hostname: hostname2, port, protocol: protocol2 = "", path: path3 = "", query = {} } = value3;
          const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path3}`);
          url.search = Object.entries(query).map(([k2, v3]) => `${k2}=${v3}`).join("&");
          return url;
        }
        return new URL(value3);
      } catch (error3) {
        return null;
      }
    })();
    if (!whatwgURL) {
      console.error(`Unable to parse ${JSON.stringify(value3)} as a whatwg URL.`);
      return null;
    }
    const urlString = whatwgURL.href;
    const { host, hostname, pathname, protocol, search } = whatwgURL;
    if (search) {
      return null;
    }
    const scheme3 = protocol.slice(0, -1);
    if (!Object.values(EndpointURLScheme).includes(scheme3)) {
      return null;
    }
    const isIp = isIpAddress(hostname);
    const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme3]}`) || typeof value3 === "string" && value3.includes(`${host}:${DEFAULT_PORTS[scheme3]}`);
    const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme3]}` : ``}`;
    return {
      scheme: scheme3,
      authority,
      path: pathname,
      normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`,
      isIp
    };
  };

  // node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js
  var stringEquals = (value1, value22) => value1 === value22;

  // node_modules/@smithy/util-endpoints/dist-es/lib/substring.js
  var substring = (input, start, stop2, reverse3) => {
    if (start >= stop2 || input.length < stop2) {
      return null;
    }
    if (!reverse3) {
      return input.substring(start, stop2);
    }
    return input.substring(input.length - stop2, input.length - start);
  };

  // node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js
  var uriEncode = (value3) => encodeURIComponent(value3).replace(/[!*'()]/g, (c4) => `%${c4.charCodeAt(0).toString(16).toUpperCase()}`);

  // node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js
  var endpointFunctions = {
    booleanEquals,
    getAttr,
    isSet,
    isValidHostLabel,
    not,
    parseURL,
    stringEquals,
    substring,
    uriEncode
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js
  var evaluateTemplate = (template, options) => {
    const evaluatedTemplateArr = [];
    const templateContext = {
      ...options.endpointParams,
      ...options.referenceRecord
    };
    let currentIndex = 0;
    while (currentIndex < template.length) {
      const openingBraceIndex = template.indexOf("{", currentIndex);
      if (openingBraceIndex === -1) {
        evaluatedTemplateArr.push(template.slice(currentIndex));
        break;
      }
      evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex));
      const closingBraceIndex = template.indexOf("}", openingBraceIndex);
      if (closingBraceIndex === -1) {
        evaluatedTemplateArr.push(template.slice(openingBraceIndex));
        break;
      }
      if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") {
        evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex));
        currentIndex = closingBraceIndex + 2;
      }
      const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex);
      if (parameterName.includes("#")) {
        const [refName, attrName] = parameterName.split("#");
        evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName));
      } else {
        evaluatedTemplateArr.push(templateContext[parameterName]);
      }
      currentIndex = closingBraceIndex + 1;
    }
    return evaluatedTemplateArr.join("");
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js
  var getReferenceValue = ({ ref: ref2 }, options) => {
    const referenceRecord = {
      ...options.endpointParams,
      ...options.referenceRecord
    };
    return referenceRecord[ref2];
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js
  var evaluateExpression = (obj, keyName, options) => {
    if (typeof obj === "string") {
      return evaluateTemplate(obj, options);
    } else if (obj["fn"]) {
      return callFunction(obj, options);
    } else if (obj["ref"]) {
      return getReferenceValue(obj, options);
    }
    throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`);
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js
  var callFunction = ({ fn, argv }, options) => {
    const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options));
    const fnSegments = fn.split(".");
    if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) {
      return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs);
    }
    return endpointFunctions[fn](...evaluatedArgs);
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js
  var evaluateCondition = ({ assign, ...fnArgs }, options) => {
    if (assign && assign in options.referenceRecord) {
      throw new EndpointError(`'${assign}' is already defined in Reference Record.`);
    }
    const value3 = callFunction(fnArgs, options);
    options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value3)}`);
    return {
      result: value3 === "" ? true : !!value3,
      ...assign != null && { toAssign: { name: assign, value: value3 } }
    };
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js
  var evaluateConditions = (conditions = [], options) => {
    const conditionsReferenceRecord = {};
    for (const condition of conditions) {
      const { result, toAssign } = evaluateCondition(condition, {
        ...options,
        referenceRecord: {
          ...options.referenceRecord,
          ...conditionsReferenceRecord
        }
      });
      if (!result) {
        return { result };
      }
      if (toAssign) {
        conditionsReferenceRecord[toAssign.name] = toAssign.value;
        options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`);
      }
    }
    return { result: true, referenceRecord: conditionsReferenceRecord };
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js
  var getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({
    ...acc,
    [headerKey]: headerVal.map((headerValEntry) => {
      const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options);
      if (typeof processedExpr !== "string") {
        throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);
      }
      return processedExpr;
    })
  }), {});

  // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js
  var getEndpointProperty = (property2, options) => {
    if (Array.isArray(property2)) {
      return property2.map((propertyEntry) => getEndpointProperty(propertyEntry, options));
    }
    switch (typeof property2) {
      case "string":
        return evaluateTemplate(property2, options);
      case "object":
        if (property2 === null) {
          throw new EndpointError(`Unexpected endpoint property: ${property2}`);
        }
        return getEndpointProperties(property2, options);
      case "boolean":
        return property2;
      default:
        throw new EndpointError(`Unexpected endpoint property type: ${typeof property2}`);
    }
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js
  var getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({
    ...acc,
    [propertyKey]: getEndpointProperty(propertyVal, options)
  }), {});

  // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js
  var getEndpointUrl = (endpointUrl, options) => {
    const expression4 = evaluateExpression(endpointUrl, "Endpoint URL", options);
    if (typeof expression4 === "string") {
      try {
        return new URL(expression4);
      } catch (error3) {
        console.error(`Failed to construct URL with ${expression4}`, error3);
        throw error3;
      }
    }
    throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression4}`);
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js
  var evaluateEndpointRule = (endpointRule, options) => {
    const { conditions, endpoint } = endpointRule;
    const { result, referenceRecord } = evaluateConditions(conditions, options);
    if (!result) {
      return;
    }
    const endpointRuleOptions = {
      ...options,
      referenceRecord: { ...options.referenceRecord, ...referenceRecord }
    };
    const { url, properties, headers } = endpoint;
    options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);
    return {
      ...headers != void 0 && {
        headers: getEndpointHeaders(headers, endpointRuleOptions)
      },
      ...properties != void 0 && {
        properties: getEndpointProperties(properties, endpointRuleOptions)
      },
      url: getEndpointUrl(url, endpointRuleOptions)
    };
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js
  var evaluateErrorRule = (errorRule, options) => {
    const { conditions, error: error3 } = errorRule;
    const { result, referenceRecord } = evaluateConditions(conditions, options);
    if (!result) {
      return;
    }
    throw new EndpointError(evaluateExpression(error3, "Error", {
      ...options,
      referenceRecord: { ...options.referenceRecord, ...referenceRecord }
    }));
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js
  var evaluateTreeRule = (treeRule, options) => {
    const { conditions, rules } = treeRule;
    const { result, referenceRecord } = evaluateConditions(conditions, options);
    if (!result) {
      return;
    }
    return evaluateRules(rules, {
      ...options,
      referenceRecord: { ...options.referenceRecord, ...referenceRecord }
    });
  };

  // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js
  var evaluateRules = (rules, options) => {
    for (const rule4 of rules) {
      if (rule4.type === "endpoint") {
        const endpointOrUndefined = evaluateEndpointRule(rule4, options);
        if (endpointOrUndefined) {
          return endpointOrUndefined;
        }
      } else if (rule4.type === "error") {
        evaluateErrorRule(rule4, options);
      } else if (rule4.type === "tree") {
        const endpointOrUndefined = evaluateTreeRule(rule4, options);
        if (endpointOrUndefined) {
          return endpointOrUndefined;
        }
      } else {
        throw new EndpointError(`Unknown endpoint rule: ${rule4}`);
      }
    }
    throw new EndpointError(`Rules evaluation failed`);
  };

  // node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js
  var resolveEndpoint = (ruleSetObject, options) => {
    const { endpointParams, logger: logger3 } = options;
    const { parameters, rules } = ruleSetObject;
    options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);
    const paramsWithDefault = Object.entries(parameters).filter(([, v3]) => v3.default != null).map(([k2, v3]) => [k2, v3.default]);
    if (paramsWithDefault.length > 0) {
      for (const [paramKey, paramDefaultValue] of paramsWithDefault) {
        endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue;
      }
    }
    const requiredParams = Object.entries(parameters).filter(([, v3]) => v3.required).map(([k2]) => k2);
    for (const requiredParam of requiredParams) {
      if (endpointParams[requiredParam] == null) {
        throw new EndpointError(`Missing required parameter: '${requiredParam}'`);
      }
    }
    const endpoint = evaluateRules(rules, { endpointParams, logger: logger3, referenceRecord: {} });
    options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);
    return endpoint;
  };

  // node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js
  var isVirtualHostableS3Bucket = (value3, allowSubDomains = false) => {
    if (allowSubDomains) {
      for (const label of value3.split(".")) {
        if (!isVirtualHostableS3Bucket(label)) {
          return false;
        }
      }
      return true;
    }
    if (!isValidHostLabel(value3)) {
      return false;
    }
    if (value3.length < 3 || value3.length > 63) {
      return false;
    }
    if (value3 !== value3.toLowerCase()) {
      return false;
    }
    if (isIpAddress(value3)) {
      return false;
    }
    return true;
  };

  // node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js
  var ARN_DELIMITER = ":";
  var RESOURCE_DELIMITER = "/";
  var parseArn = (value3) => {
    const segments2 = value3.split(ARN_DELIMITER);
    if (segments2.length < 6)
      return null;
    const [arn, partition6, service, region, accountId, ...resourcePath] = segments2;
    if (arn !== "arn" || partition6 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "")
      return null;
    const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat();
    return {
      partition: partition6,
      service,
      region,
      accountId,
      resourceId
    };
  };

  // node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json
  var partitions_default = {
    partitions: [{
      id: "aws",
      outputs: {
        dnsSuffix: "amazonaws.com",
        dualStackDnsSuffix: "api.aws",
        implicitGlobalRegion: "us-east-1",
        name: "aws",
        supportsDualStack: true,
        supportsFIPS: true
      },
      regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",
      regions: {
        "af-south-1": {
          description: "Africa (Cape Town)"
        },
        "ap-east-1": {
          description: "Asia Pacific (Hong Kong)"
        },
        "ap-east-2": {
          description: "Asia Pacific (Taipei)"
        },
        "ap-northeast-1": {
          description: "Asia Pacific (Tokyo)"
        },
        "ap-northeast-2": {
          description: "Asia Pacific (Seoul)"
        },
        "ap-northeast-3": {
          description: "Asia Pacific (Osaka)"
        },
        "ap-south-1": {
          description: "Asia Pacific (Mumbai)"
        },
        "ap-south-2": {
          description: "Asia Pacific (Hyderabad)"
        },
        "ap-southeast-1": {
          description: "Asia Pacific (Singapore)"
        },
        "ap-southeast-2": {
          description: "Asia Pacific (Sydney)"
        },
        "ap-southeast-3": {
          description: "Asia Pacific (Jakarta)"
        },
        "ap-southeast-4": {
          description: "Asia Pacific (Melbourne)"
        },
        "ap-southeast-5": {
          description: "Asia Pacific (Malaysia)"
        },
        "ap-southeast-7": {
          description: "Asia Pacific (Thailand)"
        },
        "aws-global": {
          description: "AWS Standard global region"
        },
        "ca-central-1": {
          description: "Canada (Central)"
        },
        "ca-west-1": {
          description: "Canada West (Calgary)"
        },
        "eu-central-1": {
          description: "Europe (Frankfurt)"
        },
        "eu-central-2": {
          description: "Europe (Zurich)"
        },
        "eu-north-1": {
          description: "Europe (Stockholm)"
        },
        "eu-south-1": {
          description: "Europe (Milan)"
        },
        "eu-south-2": {
          description: "Europe (Spain)"
        },
        "eu-west-1": {
          description: "Europe (Ireland)"
        },
        "eu-west-2": {
          description: "Europe (London)"
        },
        "eu-west-3": {
          description: "Europe (Paris)"
        },
        "il-central-1": {
          description: "Israel (Tel Aviv)"
        },
        "me-central-1": {
          description: "Middle East (UAE)"
        },
        "me-south-1": {
          description: "Middle East (Bahrain)"
        },
        "mx-central-1": {
          description: "Mexico (Central)"
        },
        "sa-east-1": {
          description: "South America (Sao Paulo)"
        },
        "us-east-1": {
          description: "US East (N. Virginia)"
        },
        "us-east-2": {
          description: "US East (Ohio)"
        },
        "us-west-1": {
          description: "US West (N. California)"
        },
        "us-west-2": {
          description: "US West (Oregon)"
        }
      }
    }, {
      id: "aws-cn",
      outputs: {
        dnsSuffix: "amazonaws.com.cn",
        dualStackDnsSuffix: "api.amazonwebservices.com.cn",
        implicitGlobalRegion: "cn-northwest-1",
        name: "aws-cn",
        supportsDualStack: true,
        supportsFIPS: true
      },
      regionRegex: "^cn\\-\\w+\\-\\d+$",
      regions: {
        "aws-cn-global": {
          description: "AWS China global region"
        },
        "cn-north-1": {
          description: "China (Beijing)"
        },
        "cn-northwest-1": {
          description: "China (Ningxia)"
        }
      }
    }, {
      id: "aws-us-gov",
      outputs: {
        dnsSuffix: "amazonaws.com",
        dualStackDnsSuffix: "api.aws",
        implicitGlobalRegion: "us-gov-west-1",
        name: "aws-us-gov",
        supportsDualStack: true,
        supportsFIPS: true
      },
      regionRegex: "^us\\-gov\\-\\w+\\-\\d+$",
      regions: {
        "aws-us-gov-global": {
          description: "AWS GovCloud (US) global region"
        },
        "us-gov-east-1": {
          description: "AWS GovCloud (US-East)"
        },
        "us-gov-west-1": {
          description: "AWS GovCloud (US-West)"
        }
      }
    }, {
      id: "aws-iso",
      outputs: {
        dnsSuffix: "c2s.ic.gov",
        dualStackDnsSuffix: "c2s.ic.gov",
        implicitGlobalRegion: "us-iso-east-1",
        name: "aws-iso",
        supportsDualStack: false,
        supportsFIPS: true
      },
      regionRegex: "^us\\-iso\\-\\w+\\-\\d+$",
      regions: {
        "aws-iso-global": {
          description: "AWS ISO (US) global region"
        },
        "us-iso-east-1": {
          description: "US ISO East"
        },
        "us-iso-west-1": {
          description: "US ISO WEST"
        }
      }
    }, {
      id: "aws-iso-b",
      outputs: {
        dnsSuffix: "sc2s.sgov.gov",
        dualStackDnsSuffix: "sc2s.sgov.gov",
        implicitGlobalRegion: "us-isob-east-1",
        name: "aws-iso-b",
        supportsDualStack: false,
        supportsFIPS: true
      },
      regionRegex: "^us\\-isob\\-\\w+\\-\\d+$",
      regions: {
        "aws-iso-b-global": {
          description: "AWS ISOB (US) global region"
        },
        "us-isob-east-1": {
          description: "US ISOB East (Ohio)"
        }
      }
    }, {
      id: "aws-iso-e",
      outputs: {
        dnsSuffix: "cloud.adc-e.uk",
        dualStackDnsSuffix: "cloud.adc-e.uk",
        implicitGlobalRegion: "eu-isoe-west-1",
        name: "aws-iso-e",
        supportsDualStack: false,
        supportsFIPS: true
      },
      regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$",
      regions: {
        "aws-iso-e-global": {
          description: "AWS ISOE (Europe) global region"
        },
        "eu-isoe-west-1": {
          description: "EU ISOE West"
        }
      }
    }, {
      id: "aws-iso-f",
      outputs: {
        dnsSuffix: "csp.hci.ic.gov",
        dualStackDnsSuffix: "csp.hci.ic.gov",
        implicitGlobalRegion: "us-isof-south-1",
        name: "aws-iso-f",
        supportsDualStack: false,
        supportsFIPS: true
      },
      regionRegex: "^us\\-isof\\-\\w+\\-\\d+$",
      regions: {
        "aws-iso-f-global": {
          description: "AWS ISOF global region"
        },
        "us-isof-east-1": {
          description: "US ISOF EAST"
        },
        "us-isof-south-1": {
          description: "US ISOF SOUTH"
        }
      }
    }, {
      id: "aws-eusc",
      outputs: {
        dnsSuffix: "amazonaws.eu",
        dualStackDnsSuffix: "amazonaws.eu",
        implicitGlobalRegion: "eusc-de-east-1",
        name: "aws-eusc",
        supportsDualStack: false,
        supportsFIPS: true
      },
      regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$",
      regions: {
        "eusc-de-east-1": {
          description: "EU (Germany)"
        }
      }
    }],
    version: "1.1"
  };

  // node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js
  var selectedPartitionsInfo = partitions_default;
  var selectedUserAgentPrefix = "";
  var partition5 = (value3) => {
    const { partitions } = selectedPartitionsInfo;
    for (const partition6 of partitions) {
      const { regions, outputs } = partition6;
      for (const [region, regionData] of Object.entries(regions)) {
        if (region === value3) {
          return {
            ...outputs,
            ...regionData
          };
        }
      }
    }
    for (const partition6 of partitions) {
      const { regionRegex, outputs } = partition6;
      if (new RegExp(regionRegex).test(value3)) {
        return {
          ...outputs
        };
      }
    }
    const DEFAULT_PARTITION = partitions.find((partition6) => partition6.id === "aws");
    if (!DEFAULT_PARTITION) {
      throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");
    }
    return {
      ...DEFAULT_PARTITION.outputs
    };
  };
  var getUserAgentPrefix = () => selectedUserAgentPrefix;

  // node_modules/@aws-sdk/util-endpoints/dist-es/aws.js
  var awsEndpointFunctions = {
    isVirtualHostableS3Bucket,
    parseArn,
    partition: partition5
  };
  customEndpointFunctions.aws = awsEndpointFunctions;

  // node_modules/@smithy/querystring-parser/dist-es/index.js
  function parseQueryString(querystring) {
    const query = {};
    querystring = querystring.replace(/^\?/, "");
    if (querystring) {
      for (const pair of querystring.split("&")) {
        let [key2, value3 = null] = pair.split("=");
        key2 = decodeURIComponent(key2);
        if (value3) {
          value3 = decodeURIComponent(value3);
        }
        if (!(key2 in query)) {
          query[key2] = value3;
        } else if (Array.isArray(query[key2])) {
          query[key2].push(value3);
        } else {
          query[key2] = [query[key2], value3];
        }
      }
    }
    return query;
  }

  // node_modules/@smithy/url-parser/dist-es/index.js
  var parseUrl = (url) => {
    if (typeof url === "string") {
      return parseUrl(new URL(url));
    }
    const { hostname, pathname, port, protocol, search } = url;
    let query;
    if (search) {
      query = parseQueryString(search);
    }
    return {
      hostname,
      port: port ? parseInt(port) : void 0,
      protocol,
      path: pathname,
      query
    };
  };

  // node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js
  function setCredentialFeature(credentials, feature2, value3) {
    if (!credentials.$source) {
      credentials.$source = {};
    }
    credentials.$source[feature2] = value3;
    return credentials;
  }

  // node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js
  function setFeature2(context3, feature2, value3) {
    if (!context3.__aws_sdk_context) {
      context3.__aws_sdk_context = {
        features: {}
      };
    } else if (!context3.__aws_sdk_context.features) {
      context3.__aws_sdk_context.features = {};
    }
    context3.__aws_sdk_context.features[feature2] = value3;
  }

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js
  var getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0;

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js
  var getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js
  var isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5;

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js
  var getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => {
    const clockTimeInMs = Date.parse(clockTime);
    if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) {
      return clockTimeInMs - Date.now();
    }
    return currentSystemClockOffset;
  };

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js
  var throwSigningPropertyError = (name4, property2) => {
    if (!property2) {
      throw new Error(`Property \`${name4}\` is not resolved for AWS SDK SigV4Auth`);
    }
    return property2;
  };
  var validateSigningProperties = async (signingProperties) => {
    const context3 = throwSigningPropertyError("context", signingProperties.context);
    const config = throwSigningPropertyError("config", signingProperties.config);
    const authScheme = context3.endpointV2?.properties?.authSchemes?.[0];
    const signerFunction = throwSigningPropertyError("signer", config.signer);
    const signer = await signerFunction(authScheme);
    const signingRegion = signingProperties?.signingRegion;
    const signingRegionSet = signingProperties?.signingRegionSet;
    const signingName = signingProperties?.signingName;
    return {
      config,
      signer,
      signingRegion,
      signingRegionSet,
      signingName
    };
  };
  var AwsSdkSigV4Signer = class {
    async sign(httpRequest, identity5, signingProperties) {
      if (!HttpRequest.isInstance(httpRequest)) {
        throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");
      }
      const validatedProps = await validateSigningProperties(signingProperties);
      const { config, signer } = validatedProps;
      let { signingRegion, signingName } = validatedProps;
      const handlerExecutionContext = signingProperties.context;
      if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) {
        const [first, second2] = handlerExecutionContext.authSchemes;
        if (first?.name === "sigv4a" && second2?.name === "sigv4") {
          signingRegion = second2?.signingRegion ?? signingRegion;
          signingName = second2?.signingName ?? signingName;
        }
      }
      const signedRequest = await signer.sign(httpRequest, {
        signingDate: getSkewCorrectedDate(config.systemClockOffset),
        signingRegion,
        signingService: signingName
      });
      return signedRequest;
    }
    errorHandler(signingProperties) {
      return (error3) => {
        const serverTime = error3.ServerTime ?? getDateHeader(error3.$response);
        if (serverTime) {
          const config = throwSigningPropertyError("config", signingProperties.config);
          const initialSystemClockOffset = config.systemClockOffset;
          config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset);
          const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset;
          if (clockSkewCorrected && error3.$metadata) {
            error3.$metadata.clockSkewCorrected = true;
          }
        }
        throw error3;
      };
    }
    successHandler(httpResponse, signingProperties) {
      const dateHeader = getDateHeader(httpResponse);
      if (dateHeader) {
        const config = throwSigningPropertyError("config", signingProperties.config);
        config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset);
      }
    }
  };

  // node_modules/@smithy/property-provider/dist-es/memoize.js
  var memoize2 = (provider, isExpired, requiresRefresh) => {
    let resolved;
    let pending;
    let hasResult;
    let isConstant = false;
    const coalesceProvider = async () => {
      if (!pending) {
        pending = provider();
      }
      try {
        resolved = await pending;
        hasResult = true;
        isConstant = false;
      } finally {
        pending = void 0;
      }
      return resolved;
    };
    if (isExpired === void 0) {
      return async (options) => {
        if (!hasResult || options?.forceRefresh) {
          resolved = await coalesceProvider();
        }
        return resolved;
      };
    }
    return async (options) => {
      if (!hasResult || options?.forceRefresh) {
        resolved = await coalesceProvider();
      }
      if (isConstant) {
        return resolved;
      }
      if (requiresRefresh && !requiresRefresh(resolved)) {
        isConstant = true;
        return resolved;
      }
      if (isExpired(resolved)) {
        await coalesceProvider();
        return resolved;
      }
      return resolved;
    };
  };

  // node_modules/@smithy/signature-v4/dist-es/constants.js
  var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm";
  var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential";
  var AMZ_DATE_QUERY_PARAM = "X-Amz-Date";
  var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders";
  var EXPIRES_QUERY_PARAM = "X-Amz-Expires";
  var SIGNATURE_QUERY_PARAM = "X-Amz-Signature";
  var TOKEN_QUERY_PARAM = "X-Amz-Security-Token";
  var AUTH_HEADER = "authorization";
  var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();
  var DATE_HEADER = "date";
  var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER];
  var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase();
  var SHA256_HEADER = "x-amz-content-sha256";
  var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();
  var ALWAYS_UNSIGNABLE_HEADERS = {
    authorization: true,
    "cache-control": true,
    connection: true,
    expect: true,
    from: true,
    "keep-alive": true,
    "max-forwards": true,
    pragma: true,
    referer: true,
    te: true,
    trailer: true,
    "transfer-encoding": true,
    upgrade: true,
    "user-agent": true,
    "x-amzn-trace-id": true
  };
  var PROXY_HEADER_PATTERN = /^proxy-/;
  var SEC_HEADER_PATTERN = /^sec-/;
  var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256";
  var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD";
  var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
  var MAX_CACHE_SIZE = 50;
  var KEY_TYPE_IDENTIFIER = "aws4_request";
  var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7;

  // node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js
  var signingKeyCache = {};
  var cacheQueue = [];
  var createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;
  var getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => {
    const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId);
    const cacheKey = `${shortDate}:${region}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`;
    if (cacheKey in signingKeyCache) {
      return signingKeyCache[cacheKey];
    }
    cacheQueue.push(cacheKey);
    while (cacheQueue.length > MAX_CACHE_SIZE) {
      delete signingKeyCache[cacheQueue.shift()];
    }
    let key2 = `AWS4${credentials.secretAccessKey}`;
    for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) {
      key2 = await hmac(sha256Constructor, key2, signable);
    }
    return signingKeyCache[cacheKey] = key2;
  };
  var hmac = (ctor, secret, data3) => {
    const hash2 = new ctor(secret);
    hash2.update(toUint8Array(data3));
    return hash2.digest();
  };

  // node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js
  var getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => {
    const canonical = {};
    for (const headerName of Object.keys(headers).sort()) {
      if (headers[headerName] == void 0) {
        continue;
      }
      const canonicalHeaderName = headerName.toLowerCase();
      if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) {
        if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) {
          continue;
        }
      }
      canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " ");
    }
    return canonical;
  };

  // node_modules/@smithy/is-array-buffer/dist-es/index.js
  var isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]";

  // node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js
  var getPayloadHash = async ({ headers, body }, hashConstructor) => {
    for (const headerName of Object.keys(headers)) {
      if (headerName.toLowerCase() === SHA256_HEADER) {
        return headers[headerName];
      }
    }
    if (body == void 0) {
      return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) {
      const hashCtor = new hashConstructor();
      hashCtor.update(toUint8Array(body));
      return toHex(await hashCtor.digest());
    }
    return UNSIGNED_PAYLOAD;
  };

  // node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js
  var HeaderFormatter = class {
    format(headers) {
      const chunks = [];
      for (const headerName of Object.keys(headers)) {
        const bytes = fromUtf8(headerName);
        chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
      }
      const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
      let position2 = 0;
      for (const chunk of chunks) {
        out.set(chunk, position2);
        position2 += chunk.byteLength;
      }
      return out;
    }
    formatHeaderValue(header) {
      switch (header.type) {
        case "boolean":
          return Uint8Array.from([header.value ? 0 : 1]);
        case "byte":
          return Uint8Array.from([2, header.value]);
        case "short":
          const shortView = new DataView(new ArrayBuffer(3));
          shortView.setUint8(0, 3);
          shortView.setInt16(1, header.value, false);
          return new Uint8Array(shortView.buffer);
        case "integer":
          const intView = new DataView(new ArrayBuffer(5));
          intView.setUint8(0, 4);
          intView.setInt32(1, header.value, false);
          return new Uint8Array(intView.buffer);
        case "long":
          const longBytes = new Uint8Array(9);
          longBytes[0] = 5;
          longBytes.set(header.value.bytes, 1);
          return longBytes;
        case "binary":
          const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
          binView.setUint8(0, 6);
          binView.setUint16(1, header.value.byteLength, false);
          const binBytes = new Uint8Array(binView.buffer);
          binBytes.set(header.value, 3);
          return binBytes;
        case "string":
          const utf8Bytes = fromUtf8(header.value);
          const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
          strView.setUint8(0, 7);
          strView.setUint16(1, utf8Bytes.byteLength, false);
          const strBytes = new Uint8Array(strView.buffer);
          strBytes.set(utf8Bytes, 3);
          return strBytes;
        case "timestamp":
          const tsBytes = new Uint8Array(9);
          tsBytes[0] = 8;
          tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1);
          return tsBytes;
        case "uuid":
          if (!UUID_PATTERN.test(header.value)) {
            throw new Error(`Invalid UUID received: ${header.value}`);
          }
          const uuidBytes = new Uint8Array(17);
          uuidBytes[0] = 9;
          uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
          return uuidBytes;
      }
    }
  };
  var HEADER_VALUE_TYPE;
  (function(HEADER_VALUE_TYPE3) {
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
  })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {}));
  var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
  var Int64 = class _Int64 {
    constructor(bytes) {
      this.bytes = bytes;
      if (bytes.byteLength !== 8) {
        throw new Error("Int64 buffers must be exactly 8 bytes");
      }
    }
    static fromNumber(number8) {
      if (number8 > 9223372036854776e3 || number8 < -9223372036854776e3) {
        throw new Error(`${number8} is too large (or, if negative, too small) to represent as an Int64`);
      }
      const bytes = new Uint8Array(8);
      for (let i2 = 7, remaining = Math.abs(Math.round(number8)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
        bytes[i2] = remaining;
      }
      if (number8 < 0) {
        negate2(bytes);
      }
      return new _Int64(bytes);
    }
    valueOf() {
      const bytes = this.bytes.slice(0);
      const negative = bytes[0] & 128;
      if (negative) {
        negate2(bytes);
      }
      return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
    }
    toString() {
      return String(this.valueOf());
    }
  };
  function negate2(bytes) {
    for (let i2 = 0; i2 < 8; i2++) {
      bytes[i2] ^= 255;
    }
    for (let i2 = 7; i2 > -1; i2--) {
      bytes[i2]++;
      if (bytes[i2] !== 0)
        break;
    }
  }

  // node_modules/@smithy/signature-v4/dist-es/headerUtil.js
  var hasHeader = (soughtHeader, headers) => {
    soughtHeader = soughtHeader.toLowerCase();
    for (const headerName of Object.keys(headers)) {
      if (soughtHeader === headerName.toLowerCase()) {
        return true;
      }
    }
    return false;
  };

  // node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js
  var moveHeadersToQuery = (request2, options = {}) => {
    const { headers, query = {} } = HttpRequest.clone(request2);
    for (const name4 of Object.keys(headers)) {
      const lname = name4.toLowerCase();
      if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) {
        query[name4] = headers[name4];
        delete headers[name4];
      }
    }
    return {
      ...request2,
      headers,
      query
    };
  };

  // node_modules/@smithy/signature-v4/dist-es/prepareRequest.js
  var prepareRequest = (request2) => {
    request2 = HttpRequest.clone(request2);
    for (const headerName of Object.keys(request2.headers)) {
      if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) {
        delete request2.headers[headerName];
      }
    }
    return request2;
  };

  // node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js
  var getCanonicalQuery = ({ query = {} }) => {
    const keys4 = [];
    const serialized = {};
    for (const key2 of Object.keys(query)) {
      if (key2.toLowerCase() === SIGNATURE_HEADER) {
        continue;
      }
      const encodedKey = escapeUri(key2);
      keys4.push(encodedKey);
      const value3 = query[key2];
      if (typeof value3 === "string") {
        serialized[encodedKey] = `${encodedKey}=${escapeUri(value3)}`;
      } else if (Array.isArray(value3)) {
        serialized[encodedKey] = value3.slice(0).reduce((encoded, value4) => encoded.concat([`${encodedKey}=${escapeUri(value4)}`]), []).sort().join("&");
      }
    }
    return keys4.sort().map((key2) => serialized[key2]).filter((serialized2) => serialized2).join("&");
  };

  // node_modules/@smithy/signature-v4/dist-es/utilDate.js
  var iso8601 = (time3) => toDate2(time3).toISOString().replace(/\.\d{3}Z$/, "Z");
  var toDate2 = (time3) => {
    if (typeof time3 === "number") {
      return new Date(time3 * 1e3);
    }
    if (typeof time3 === "string") {
      if (Number(time3)) {
        return new Date(Number(time3) * 1e3);
      }
      return new Date(time3);
    }
    return time3;
  };

  // node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js
  var SignatureV4Base = class {
    constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
      this.service = service;
      this.sha256 = sha256;
      this.uriEscapePath = uriEscapePath;
      this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true;
      this.regionProvider = normalizeProvider(region);
      this.credentialProvider = normalizeProvider(credentials);
    }
    createCanonicalRequest(request2, canonicalHeaders, payloadHash) {
      const sortedHeaders = Object.keys(canonicalHeaders).sort();
      return `${request2.method}
${this.getCanonicalPath(request2)}
${getCanonicalQuery(request2)}
${sortedHeaders.map((name4) => `${name4}:${canonicalHeaders[name4]}`).join("\n")}

${sortedHeaders.join(";")}
${payloadHash}`;
    }
    async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) {
      const hash2 = new this.sha256();
      hash2.update(toUint8Array(canonicalRequest));
      const hashedRequest = await hash2.digest();
      return `${algorithmIdentifier}
${longDate}
${credentialScope}
${toHex(hashedRequest)}`;
    }
    getCanonicalPath({ path: path3 }) {
      if (this.uriEscapePath) {
        const normalizedPathSegments = [];
        for (const pathSegment of path3.split("/")) {
          if (pathSegment?.length === 0)
            continue;
          if (pathSegment === ".")
            continue;
          if (pathSegment === "..") {
            normalizedPathSegments.pop();
          } else {
            normalizedPathSegments.push(pathSegment);
          }
        }
        const normalizedPath = `${path3?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path3?.endsWith("/") ? "/" : ""}`;
        const doubleEncoded = escapeUri(normalizedPath);
        return doubleEncoded.replace(/%2F/g, "/");
      }
      return path3;
    }
    validateResolvedCredentials(credentials) {
      if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") {
        throw new Error("Resolved credential object is not valid");
      }
    }
    formatDate(now2) {
      const longDate = iso8601(now2).replace(/[\-:]/g, "");
      return {
        longDate,
        shortDate: longDate.slice(0, 8)
      };
    }
    getCanonicalHeaderList(headers) {
      return Object.keys(headers).sort().join(";");
    }
  };

  // node_modules/@smithy/signature-v4/dist-es/SignatureV4.js
  var SignatureV4 = class extends SignatureV4Base {
    constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true }) {
      super({
        applyChecksum,
        credentials,
        region,
        service,
        sha256,
        uriEscapePath
      });
      this.headerFormatter = new HeaderFormatter();
    }
    async presign(originalRequest, options = {}) {
      const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options;
      const credentials = await this.credentialProvider();
      this.validateResolvedCredentials(credentials);
      const region = signingRegion ?? await this.regionProvider();
      const { longDate, shortDate } = this.formatDate(signingDate);
      if (expiresIn > MAX_PRESIGNED_TTL) {
        return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");
      }
      const scope = createScope(shortDate, region, signingService ?? this.service);
      const request2 = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders });
      if (credentials.sessionToken) {
        request2.query[TOKEN_QUERY_PARAM] = credentials.sessionToken;
      }
      request2.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER;
      request2.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`;
      request2.query[AMZ_DATE_QUERY_PARAM] = longDate;
      request2.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10);
      const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
      request2.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders);
      request2.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)));
      return request2;
    }
    async sign(toSign, options) {
      if (typeof toSign === "string") {
        return this.signString(toSign, options);
      } else if (toSign.headers && toSign.payload) {
        return this.signEvent(toSign, options);
      } else if (toSign.message) {
        return this.signMessage(toSign, options);
      } else {
        return this.signRequest(toSign, options);
      }
    }
    async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) {
      const region = signingRegion ?? await this.regionProvider();
      const { shortDate, longDate } = this.formatDate(signingDate);
      const scope = createScope(shortDate, region, signingService ?? this.service);
      const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256);
      const hash2 = new this.sha256();
      hash2.update(headers);
      const hashedHeaders = toHex(await hash2.digest());
      const stringToSign = [
        EVENT_ALGORITHM_IDENTIFIER,
        longDate,
        scope,
        priorSignature,
        hashedHeaders,
        hashedPayload
      ].join("\n");
      return this.signString(stringToSign, { signingDate, signingRegion: region, signingService });
    }
    async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) {
      const promise = this.signEvent({
        headers: this.headerFormatter.format(signableMessage.message.headers),
        payload: signableMessage.message.body
      }, {
        signingDate,
        signingRegion,
        signingService,
        priorSignature: signableMessage.priorSignature
      });
      return promise.then((signature) => {
        return { message: signableMessage.message, signature };
      });
    }
    async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) {
      const credentials = await this.credentialProvider();
      this.validateResolvedCredentials(credentials);
      const region = signingRegion ?? await this.regionProvider();
      const { shortDate } = this.formatDate(signingDate);
      const hash2 = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService));
      hash2.update(toUint8Array(stringToSign));
      return toHex(await hash2.digest());
    }
    async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) {
      const credentials = await this.credentialProvider();
      this.validateResolvedCredentials(credentials);
      const region = signingRegion ?? await this.regionProvider();
      const request2 = prepareRequest(requestToSign);
      const { longDate, shortDate } = this.formatDate(signingDate);
      const scope = createScope(shortDate, region, signingService ?? this.service);
      request2.headers[AMZ_DATE_HEADER] = longDate;
      if (credentials.sessionToken) {
        request2.headers[TOKEN_HEADER] = credentials.sessionToken;
      }
      const payloadHash = await getPayloadHash(request2, this.sha256);
      if (!hasHeader(SHA256_HEADER, request2.headers) && this.applyChecksum) {
        request2.headers[SHA256_HEADER] = payloadHash;
      }
      const canonicalHeaders = getCanonicalHeaders(request2, unsignableHeaders, signableHeaders);
      const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request2, canonicalHeaders, payloadHash));
      request2.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;
      return request2;
    }
    async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) {
      const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER);
      const hash2 = new this.sha256(await keyPromise);
      hash2.update(toUint8Array(stringToSign));
      return toHex(await hash2.digest());
    }
    getSigningKey(credentials, region, shortDate, service) {
      return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service);
    }
  };

  // node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js
  var resolveAwsSdkSigV4Config = (config) => {
    let inputCredentials = config.credentials;
    let isUserSupplied = !!config.credentials;
    let resolvedCredentials = void 0;
    Object.defineProperty(config, "credentials", {
      set(credentials) {
        if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) {
          isUserSupplied = true;
        }
        inputCredentials = credentials;
        const memoizedProvider = normalizeCredentialProvider(config, {
          credentials: inputCredentials,
          credentialDefaultProvider: config.credentialDefaultProvider
        });
        const boundProvider = bindCallerConfig(config, memoizedProvider);
        if (isUserSupplied && !boundProvider.attributed) {
          resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e"));
          resolvedCredentials.memoized = boundProvider.memoized;
          resolvedCredentials.configBound = boundProvider.configBound;
          resolvedCredentials.attributed = true;
        } else {
          resolvedCredentials = boundProvider;
        }
      },
      get() {
        return resolvedCredentials;
      },
      enumerable: true,
      configurable: true
    });
    config.credentials = inputCredentials;
    const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256 } = config;
    let signer;
    if (config.signer) {
      signer = normalizeProvider2(config.signer);
    } else if (config.regionInfoProvider) {
      signer = () => normalizeProvider2(config.region)().then(async (region) => [
        await config.regionInfoProvider(region, {
          useFipsEndpoint: await config.useFipsEndpoint(),
          useDualstackEndpoint: await config.useDualstackEndpoint()
        }) || {},
        region
      ]).then(([regionInfo, region]) => {
        const { signingRegion, signingService } = regionInfo;
        config.signingRegion = config.signingRegion || signingRegion || region;
        config.signingName = config.signingName || signingService || config.serviceId;
        const params2 = {
          ...config,
          credentials: config.credentials,
          region: config.signingRegion,
          service: config.signingName,
          sha256,
          uriEscapePath: signingEscapePath
        };
        const SignerCtor = config.signerConstructor || SignatureV4;
        return new SignerCtor(params2);
      });
    } else {
      signer = async (authScheme) => {
        authScheme = Object.assign({}, {
          name: "sigv4",
          signingName: config.signingName || config.defaultSigningName,
          signingRegion: await normalizeProvider2(config.region)(),
          properties: {}
        }, authScheme);
        const signingRegion = authScheme.signingRegion;
        const signingService = authScheme.signingName;
        config.signingRegion = config.signingRegion || signingRegion;
        config.signingName = config.signingName || signingService || config.serviceId;
        const params2 = {
          ...config,
          credentials: config.credentials,
          region: config.signingRegion,
          service: config.signingName,
          sha256,
          uriEscapePath: signingEscapePath
        };
        const SignerCtor = config.signerConstructor || SignatureV4;
        return new SignerCtor(params2);
      };
    }
    const resolvedConfig = Object.assign(config, {
      systemClockOffset,
      signingEscapePath,
      signer
    });
    return resolvedConfig;
  };
  function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider }) {
    let credentialsProvider;
    if (credentials) {
      if (!credentials?.memoized) {
        credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh);
      } else {
        credentialsProvider = credentials;
      }
    } else {
      if (credentialDefaultProvider) {
        credentialsProvider = normalizeProvider2(credentialDefaultProvider(Object.assign({}, config, {
          parentClientConfig: config
        })));
      } else {
        credentialsProvider = async () => {
          throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.");
        };
      }
    }
    credentialsProvider.memoized = true;
    return credentialsProvider;
  }
  function bindCallerConfig(config, credentialsProvider) {
    if (credentialsProvider.configBound) {
      return credentialsProvider;
    }
    const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config });
    fn.memoized = credentialsProvider.memoized;
    fn.configBound = true;
    return fn;
  }

  // node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js
  var TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null;
  var calculateBodyLength = (body) => {
    if (typeof body === "string") {
      if (TEXT_ENCODER) {
        return TEXT_ENCODER.encode(body).byteLength;
      }
      let len = body.length;
      for (let i2 = len - 1; i2 >= 0; i2--) {
        const code = body.charCodeAt(i2);
        if (code > 127 && code <= 2047)
          len++;
        else if (code > 2047 && code <= 65535)
          len += 2;
        if (code >= 56320 && code <= 57343)
          i2--;
      }
      return len;
    } else if (typeof body.byteLength === "number") {
      return body.byteLength;
    } else if (typeof body.size === "number") {
      return body.size;
    }
    throw new Error(`Body Length computation failed for ${body}`);
  };

  // node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js
  var getAllAliases = (name4, aliases) => {
    const _aliases = [];
    if (name4) {
      _aliases.push(name4);
    }
    if (aliases) {
      for (const alias of aliases) {
        _aliases.push(alias);
      }
    }
    return _aliases;
  };
  var getMiddlewareNameWithAliases = (name4, aliases) => {
    return `${name4 || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`;
  };
  var constructStack = () => {
    let absoluteEntries = [];
    let relativeEntries = [];
    let identifyOnResolve = false;
    const entriesNameSet = /* @__PURE__ */ new Set();
    const sort3 = (entries3) => entries3.sort((a4, b3) => stepWeights[b3.step] - stepWeights[a4.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a4.priority || "normal"]);
    const removeByName = (toRemove) => {
      let isRemoved = false;
      const filterCb = (entry2) => {
        const aliases = getAllAliases(entry2.name, entry2.aliases);
        if (aliases.includes(toRemove)) {
          isRemoved = true;
          for (const alias of aliases) {
            entriesNameSet.delete(alias);
          }
          return false;
        }
        return true;
      };
      absoluteEntries = absoluteEntries.filter(filterCb);
      relativeEntries = relativeEntries.filter(filterCb);
      return isRemoved;
    };
    const removeByReference = (toRemove) => {
      let isRemoved = false;
      const filterCb = (entry2) => {
        if (entry2.middleware === toRemove) {
          isRemoved = true;
          for (const alias of getAllAliases(entry2.name, entry2.aliases)) {
            entriesNameSet.delete(alias);
          }
          return false;
        }
        return true;
      };
      absoluteEntries = absoluteEntries.filter(filterCb);
      relativeEntries = relativeEntries.filter(filterCb);
      return isRemoved;
    };
    const cloneTo = (toStack) => {
      absoluteEntries.forEach((entry2) => {
        toStack.add(entry2.middleware, { ...entry2 });
      });
      relativeEntries.forEach((entry2) => {
        toStack.addRelativeTo(entry2.middleware, { ...entry2 });
      });
      toStack.identifyOnResolve?.(stack2.identifyOnResolve());
      return toStack;
    };
    const expandRelativeMiddlewareList = (from) => {
      const expandedMiddlewareList = [];
      from.before.forEach((entry2) => {
        if (entry2.before.length === 0 && entry2.after.length === 0) {
          expandedMiddlewareList.push(entry2);
        } else {
          expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry2));
        }
      });
      expandedMiddlewareList.push(from);
      from.after.reverse().forEach((entry2) => {
        if (entry2.before.length === 0 && entry2.after.length === 0) {
          expandedMiddlewareList.push(entry2);
        } else {
          expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry2));
        }
      });
      return expandedMiddlewareList;
    };
    const getMiddlewareList = (debug3 = false) => {
      const normalizedAbsoluteEntries = [];
      const normalizedRelativeEntries = [];
      const normalizedEntriesNameMap = {};
      absoluteEntries.forEach((entry2) => {
        const normalizedEntry = {
          ...entry2,
          before: [],
          after: []
        };
        for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
          normalizedEntriesNameMap[alias] = normalizedEntry;
        }
        normalizedAbsoluteEntries.push(normalizedEntry);
      });
      relativeEntries.forEach((entry2) => {
        const normalizedEntry = {
          ...entry2,
          before: [],
          after: []
        };
        for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) {
          normalizedEntriesNameMap[alias] = normalizedEntry;
        }
        normalizedRelativeEntries.push(normalizedEntry);
      });
      normalizedRelativeEntries.forEach((entry2) => {
        if (entry2.toMiddleware) {
          const toMiddleware = normalizedEntriesNameMap[entry2.toMiddleware];
          if (toMiddleware === void 0) {
            if (debug3) {
              return;
            }
            throw new Error(`${entry2.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry2.name, entry2.aliases)} middleware ${entry2.relation} ${entry2.toMiddleware}`);
          }
          if (entry2.relation === "after") {
            toMiddleware.after.push(entry2);
          }
          if (entry2.relation === "before") {
            toMiddleware.before.push(entry2);
          }
        }
      });
      const mainChain = sort3(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => {
        wholeList.push(...expandedMiddlewareList);
        return wholeList;
      }, []);
      return mainChain;
    };
    const stack2 = {
      add: (middleware, options = {}) => {
        const { name: name4, override, aliases: _aliases } = options;
        const entry2 = {
          step: "initialize",
          priority: "normal",
          middleware,
          ...options
        };
        const aliases = getAllAliases(name4, _aliases);
        if (aliases.length > 0) {
          if (aliases.some((alias) => entriesNameSet.has(alias))) {
            if (!override)
              throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name4, _aliases)}'`);
            for (const alias of aliases) {
              const toOverrideIndex = absoluteEntries.findIndex((entry3) => entry3.name === alias || entry3.aliases?.some((a4) => a4 === alias));
              if (toOverrideIndex === -1) {
                continue;
              }
              const toOverride = absoluteEntries[toOverrideIndex];
              if (toOverride.step !== entry2.step || entry2.priority !== toOverride.priority) {
                throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name4, _aliases)}" middleware with ${entry2.priority} priority in ${entry2.step} step.`);
              }
              absoluteEntries.splice(toOverrideIndex, 1);
            }
          }
          for (const alias of aliases) {
            entriesNameSet.add(alias);
          }
        }
        absoluteEntries.push(entry2);
      },
      addRelativeTo: (middleware, options) => {
        const { name: name4, override, aliases: _aliases } = options;
        const entry2 = {
          middleware,
          ...options
        };
        const aliases = getAllAliases(name4, _aliases);
        if (aliases.length > 0) {
          if (aliases.some((alias) => entriesNameSet.has(alias))) {
            if (!override)
              throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name4, _aliases)}'`);
            for (const alias of aliases) {
              const toOverrideIndex = relativeEntries.findIndex((entry3) => entry3.name === alias || entry3.aliases?.some((a4) => a4 === alias));
              if (toOverrideIndex === -1) {
                continue;
              }
              const toOverride = relativeEntries[toOverrideIndex];
              if (toOverride.toMiddleware !== entry2.toMiddleware || toOverride.relation !== entry2.relation) {
                throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name4, _aliases)}" middleware ${entry2.relation} "${entry2.toMiddleware}" middleware.`);
              }
              relativeEntries.splice(toOverrideIndex, 1);
            }
          }
          for (const alias of aliases) {
            entriesNameSet.add(alias);
          }
        }
        relativeEntries.push(entry2);
      },
      clone: () => cloneTo(constructStack()),
      use: (plugin) => {
        plugin.applyToStack(stack2);
      },
      remove: (toRemove) => {
        if (typeof toRemove === "string")
          return removeByName(toRemove);
        else
          return removeByReference(toRemove);
      },
      removeByTag: (toRemove) => {
        let isRemoved = false;
        const filterCb = (entry2) => {
          const { tags, name: name4, aliases: _aliases } = entry2;
          if (tags && tags.includes(toRemove)) {
            const aliases = getAllAliases(name4, _aliases);
            for (const alias of aliases) {
              entriesNameSet.delete(alias);
            }
            isRemoved = true;
            return false;
          }
          return true;
        };
        absoluteEntries = absoluteEntries.filter(filterCb);
        relativeEntries = relativeEntries.filter(filterCb);
        return isRemoved;
      },
      concat: (from) => {
        const cloned = cloneTo(constructStack());
        cloned.use(from);
        cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false));
        return cloned;
      },
      applyToStack: cloneTo,
      identify: () => {
        return getMiddlewareList(true).map((mw) => {
          const step = mw.step ?? mw.relation + " " + mw.toMiddleware;
          return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step;
        });
      },
      identifyOnResolve(toggle2) {
        if (typeof toggle2 === "boolean")
          identifyOnResolve = toggle2;
        return identifyOnResolve;
      },
      resolve: (handler, context3) => {
        for (const middleware of getMiddlewareList().map((entry2) => entry2.middleware).reverse()) {
          handler = middleware(handler, context3);
        }
        if (identifyOnResolve) {
          console.log(stack2.identify());
        }
        return handler;
      }
    };
    return stack2;
  };
  var stepWeights = {
    initialize: 5,
    serialize: 4,
    build: 3,
    finalizeRequest: 2,
    deserialize: 1
  };
  var priorityWeights = {
    high: 3,
    normal: 2,
    low: 1
  };

  // node_modules/@smithy/smithy-client/dist-es/client.js
  var Client = class {
    constructor(config) {
      this.config = config;
      this.middlewareStack = constructStack();
    }
    send(command, optionsOrCb, cb) {
      const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0;
      const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
      const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true;
      let handler;
      if (useHandlerCache) {
        if (!this.handlers) {
          this.handlers = /* @__PURE__ */ new WeakMap();
        }
        const handlers = this.handlers;
        if (handlers.has(command.constructor)) {
          handler = handlers.get(command.constructor);
        } else {
          handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
          handlers.set(command.constructor, handler);
        }
      } else {
        delete this.handlers;
        handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
      }
      if (callback) {
        handler(command).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => {
        });
      } else {
        return handler(command).then((result) => result.output);
      }
    }
    destroy() {
      this.config?.requestHandler?.destroy?.();
      delete this.handlers;
    }
  };

  // node_modules/@smithy/smithy-client/dist-es/command.js
  var Command = class {
    constructor() {
      this.middlewareStack = constructStack();
    }
    static classBuilder() {
      return new ClassBuilder();
    }
    resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) {
      for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
        this.middlewareStack.use(mw);
      }
      const stack2 = clientStack.concat(this.middlewareStack);
      const { logger: logger3 } = configuration;
      const handlerExecutionContext = {
        logger: logger3,
        clientName,
        commandName,
        inputFilterSensitiveLog,
        outputFilterSensitiveLog,
        [SMITHY_CONTEXT_KEY]: {
          commandInstance: this,
          ...smithyContext
        },
        ...additionalContext
      };
      const { requestHandler } = configuration;
      return stack2.resolve((request2) => requestHandler.handle(request2.request, options || {}), handlerExecutionContext);
    }
  };
  var ClassBuilder = class {
    constructor() {
      this._init = () => {
      };
      this._ep = {};
      this._middlewareFn = () => [];
      this._commandName = "";
      this._clientName = "";
      this._additionalContext = {};
      this._smithyContext = {};
      this._inputFilterSensitiveLog = (_) => _;
      this._outputFilterSensitiveLog = (_) => _;
      this._serializer = null;
      this._deserializer = null;
    }
    init(cb) {
      this._init = cb;
    }
    ep(endpointParameterInstructions) {
      this._ep = endpointParameterInstructions;
      return this;
    }
    m(middlewareSupplier) {
      this._middlewareFn = middlewareSupplier;
      return this;
    }
    s(service, operation, smithyContext = {}) {
      this._smithyContext = {
        service,
        operation,
        ...smithyContext
      };
      return this;
    }
    c(additionalContext = {}) {
      this._additionalContext = additionalContext;
      return this;
    }
    n(clientName, commandName) {
      this._clientName = clientName;
      this._commandName = commandName;
      return this;
    }
    f(inputFilter = (_) => _, outputFilter = (_) => _) {
      this._inputFilterSensitiveLog = inputFilter;
      this._outputFilterSensitiveLog = outputFilter;
      return this;
    }
    ser(serializer) {
      this._serializer = serializer;
      return this;
    }
    de(deserializer) {
      this._deserializer = deserializer;
      return this;
    }
    sc(operation) {
      this._operationSchema = operation;
      this._smithyContext.operationSchema = operation;
      return this;
    }
    build() {
      const closure = this;
      let CommandRef;
      return CommandRef = class extends Command {
        static getEndpointParameterInstructions() {
          return closure._ep;
        }
        constructor(...[input]) {
          super();
          this.serialize = closure._serializer;
          this.deserialize = closure._deserializer;
          this.input = input ?? {};
          closure._init(this);
          this.schema = closure._operationSchema;
        }
        resolveMiddleware(stack2, configuration, options) {
          return this.resolveMiddlewareWithContext(stack2, configuration, options, {
            CommandCtor: CommandRef,
            middlewareFn: closure._middlewareFn,
            clientName: closure._clientName,
            commandName: closure._commandName,
            inputFilterSensitiveLog: closure._inputFilterSensitiveLog,
            outputFilterSensitiveLog: closure._outputFilterSensitiveLog,
            smithyContext: closure._smithyContext,
            additionalContext: closure._additionalContext
          });
        }
      };
    }
  };

  // node_modules/@smithy/smithy-client/dist-es/constants.js
  var SENSITIVE_STRING = "***SensitiveInformation***";

  // node_modules/@smithy/smithy-client/dist-es/exceptions.js
  var ServiceException = class _ServiceException extends Error {
    constructor(options) {
      super(options.message);
      Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
      this.name = options.name;
      this.$fault = options.$fault;
      this.$metadata = options.$metadata;
    }
    static isInstance(value3) {
      if (!value3)
        return false;
      const candidate = value3;
      return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
    }
    static [Symbol.hasInstance](instance) {
      if (!instance)
        return false;
      const candidate = instance;
      if (this === _ServiceException) {
        return _ServiceException.isInstance(instance);
      }
      if (_ServiceException.isInstance(instance)) {
        if (candidate.name && this.name) {
          return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
        }
        return this.prototype.isPrototypeOf(instance);
      }
      return false;
    }
  };
  var decorateServiceException = (exception, additions = {}) => {
    Object.entries(additions).filter(([, v3]) => v3 !== void 0).forEach(([k2, v3]) => {
      if (exception[k2] == void 0 || exception[k2] === "") {
        exception[k2] = v3;
      }
    });
    const message = exception.message || exception.Message || "UnknownError";
    exception.message = message;
    delete exception.Message;
    return exception;
  };

  // node_modules/@smithy/smithy-client/dist-es/default-error-handler.js
  var throwDefaultError = ({ output: output3, parsedBody, exceptionCtor, errorCode }) => {
    const $metadata = deserializeMetadata(output3);
    const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0;
    const response = new exceptionCtor({
      name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
      $fault: "client",
      $metadata
    });
    throw decorateServiceException(response, parsedBody);
  };
  var withBaseException = (ExceptionCtor) => {
    return ({ output: output3, parsedBody, errorCode }) => {
      throwDefaultError({ output: output3, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
    };
  };
  var deserializeMetadata = (output3) => ({
    httpStatusCode: output3.statusCode,
    requestId: output3.headers["x-amzn-requestid"] ?? output3.headers["x-amzn-request-id"] ?? output3.headers["x-amz-request-id"],
    extendedRequestId: output3.headers["x-amz-id-2"],
    cfId: output3.headers["x-amz-cf-id"]
  });

  // node_modules/@smithy/smithy-client/dist-es/defaults-mode.js
  var loadConfigsForDefaultMode = (mode) => {
    switch (mode) {
      case "standard":
        return {
          retryMode: "standard",
          connectionTimeout: 3100
        };
      case "in-region":
        return {
          retryMode: "standard",
          connectionTimeout: 1100
        };
      case "cross-region":
        return {
          retryMode: "standard",
          connectionTimeout: 3100
        };
      case "mobile":
        return {
          retryMode: "standard",
          connectionTimeout: 3e4
        };
      default:
        return {};
    }
  };

  // node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js
  var getChecksumConfiguration2 = (runtimeConfig) => {
    const checksumAlgorithms = [];
    for (const id2 in AlgorithmId) {
      const algorithmId = AlgorithmId[id2];
      if (runtimeConfig[algorithmId] === void 0) {
        continue;
      }
      checksumAlgorithms.push({
        algorithmId: () => algorithmId,
        checksumConstructor: () => runtimeConfig[algorithmId]
      });
    }
    return {
      addChecksumAlgorithm(algo) {
        checksumAlgorithms.push(algo);
      },
      checksumAlgorithms() {
        return checksumAlgorithms;
      }
    };
  };
  var resolveChecksumRuntimeConfig2 = (clientConfig) => {
    const runtimeConfig = {};
    clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
      runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
    });
    return runtimeConfig;
  };

  // node_modules/@smithy/smithy-client/dist-es/extensions/retry.js
  var getRetryConfiguration = (runtimeConfig) => {
    return {
      setRetryStrategy(retryStrategy) {
        runtimeConfig.retryStrategy = retryStrategy;
      },
      retryStrategy() {
        return runtimeConfig.retryStrategy;
      }
    };
  };
  var resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
    const runtimeConfig = {};
    runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
    return runtimeConfig;
  };

  // node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js
  var getDefaultExtensionConfiguration = (runtimeConfig) => {
    return Object.assign(getChecksumConfiguration2(runtimeConfig), getRetryConfiguration(runtimeConfig));
  };
  var resolveDefaultRuntimeConfig = (config) => {
    return Object.assign(resolveChecksumRuntimeConfig2(config), resolveRetryRuntimeConfig(config));
  };

  // node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js
  var isSerializableHeaderValue = (value3) => {
    return value3 != null;
  };

  // node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js
  var NoOpLogger = class {
    trace() {
    }
    debug() {
    }
    info() {
    }
    warn() {
    }
    error() {
    }
  };

  // node_modules/@smithy/smithy-client/dist-es/object-mapping.js
  function map3(arg0, arg1, arg2) {
    let target2;
    let filter3;
    let instructions;
    if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
      target2 = {};
      instructions = arg0;
    } else {
      target2 = arg0;
      if (typeof arg1 === "function") {
        filter3 = arg1;
        instructions = arg2;
        return mapWithFilter(target2, filter3, instructions);
      } else {
        instructions = arg1;
      }
    }
    for (const key2 of Object.keys(instructions)) {
      if (!Array.isArray(instructions[key2])) {
        target2[key2] = instructions[key2];
        continue;
      }
      applyInstruction(target2, null, instructions, key2);
    }
    return target2;
  }
  var take = (source4, instructions) => {
    const out = {};
    for (const key2 in instructions) {
      applyInstruction(out, source4, instructions, key2);
    }
    return out;
  };
  var mapWithFilter = (target2, filter3, instructions) => {
    return map3(target2, Object.entries(instructions).reduce((_instructions, [key2, value3]) => {
      if (Array.isArray(value3)) {
        _instructions[key2] = value3;
      } else {
        if (typeof value3 === "function") {
          _instructions[key2] = [filter3, value3()];
        } else {
          _instructions[key2] = [filter3, value3];
        }
      }
      return _instructions;
    }, {}));
  };
  var applyInstruction = (target2, source4, instructions, targetKey) => {
    if (source4 !== null) {
      let instruction = instructions[targetKey];
      if (typeof instruction === "function") {
        instruction = [, instruction];
      }
      const [filter4 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
      if (typeof filter4 === "function" && filter4(source4[sourceKey]) || typeof filter4 !== "function" && !!filter4) {
        target2[targetKey] = valueFn(source4[sourceKey]);
      }
      return;
    }
    let [filter3, value3] = instructions[targetKey];
    if (typeof value3 === "function") {
      let _value;
      const defaultFilterPassed = filter3 === void 0 && (_value = value3()) != null;
      const customFilterPassed = typeof filter3 === "function" && !!filter3(void 0) || typeof filter3 !== "function" && !!filter3;
      if (defaultFilterPassed) {
        target2[targetKey] = _value;
      } else if (customFilterPassed) {
        target2[targetKey] = value3();
      }
    } else {
      const defaultFilterPassed = filter3 === void 0 && value3 != null;
      const customFilterPassed = typeof filter3 === "function" && !!filter3(value3) || typeof filter3 !== "function" && !!filter3;
      if (defaultFilterPassed || customFilterPassed) {
        target2[targetKey] = value3;
      }
    }
  };
  var nonNullish = (_) => _ != null;
  var pass = (_) => _;

  // node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js
  var collectBodyString = (streamBody, context3) => collectBody(streamBody, context3).then((body) => context3.utf8Encoder(body));

  // node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js
  var parseJsonBody = (streamBody, context3) => collectBodyString(streamBody, context3).then((encoded) => {
    if (encoded.length) {
      try {
        return JSON.parse(encoded);
      } catch (e4) {
        if (e4?.name === "SyntaxError") {
          Object.defineProperty(e4, "$responseBodyText", {
            value: encoded
          });
        }
        throw e4;
      }
    }
    return {};
  });
  var parseJsonErrorBody = async (errorBody, context3) => {
    const value3 = await parseJsonBody(errorBody, context3);
    value3.message = value3.message ?? value3.Message;
    return value3;
  };
  var loadRestJsonErrorCode = (output3, data3) => {
    const findKey = (object2, key2) => Object.keys(object2).find((k2) => k2.toLowerCase() === key2.toLowerCase());
    const sanitizeErrorCode = (rawValue) => {
      let cleanValue = rawValue;
      if (typeof cleanValue === "number") {
        cleanValue = cleanValue.toString();
      }
      if (cleanValue.indexOf(",") >= 0) {
        cleanValue = cleanValue.split(",")[0];
      }
      if (cleanValue.indexOf(":") >= 0) {
        cleanValue = cleanValue.split(":")[0];
      }
      if (cleanValue.indexOf("#") >= 0) {
        cleanValue = cleanValue.split("#")[1];
      }
      return cleanValue;
    };
    const headerKey = findKey(output3.headers, "x-amzn-errortype");
    if (headerKey !== void 0) {
      return sanitizeErrorCode(output3.headers[headerKey]);
    }
    if (data3 && typeof data3 === "object") {
      const codeKey = findKey(data3, "code");
      if (codeKey && data3[codeKey] !== void 0) {
        return sanitizeErrorCode(data3[codeKey]);
      }
      if (data3["__type"] !== void 0) {
        return sanitizeErrorCode(data3["__type"]);
      }
    }
  };

  // node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js
  var ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/;
  async function checkFeatures(context3, config, args) {
    const request2 = args.request;
    if (request2?.headers?.["smithy-protocol"] === "rpc-v2-cbor") {
      setFeature2(context3, "PROTOCOL_RPC_V2_CBOR", "M");
    }
    if (typeof config.retryStrategy === "function") {
      const retryStrategy = await config.retryStrategy();
      if (typeof retryStrategy.acquireInitialRetryToken === "function") {
        if (retryStrategy.constructor?.name?.includes("Adaptive")) {
          setFeature2(context3, "RETRY_MODE_ADAPTIVE", "F");
        } else {
          setFeature2(context3, "RETRY_MODE_STANDARD", "E");
        }
      } else {
        setFeature2(context3, "RETRY_MODE_LEGACY", "D");
      }
    }
    if (typeof config.accountIdEndpointMode === "function") {
      const endpointV2 = context3.endpointV2;
      if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) {
        setFeature2(context3, "ACCOUNT_ID_ENDPOINT", "O");
      }
      switch (await config.accountIdEndpointMode?.()) {
        case "disabled":
          setFeature2(context3, "ACCOUNT_ID_MODE_DISABLED", "Q");
          break;
        case "preferred":
          setFeature2(context3, "ACCOUNT_ID_MODE_PREFERRED", "P");
          break;
        case "required":
          setFeature2(context3, "ACCOUNT_ID_MODE_REQUIRED", "R");
          break;
      }
    }
    const identity5 = context3.__smithy_context?.selectedHttpAuthScheme?.identity;
    if (identity5?.$source) {
      const credentials = identity5;
      if (credentials.accountId) {
        setFeature2(context3, "RESOLVED_ACCOUNT_ID", "T");
      }
      for (const [key2, value3] of Object.entries(credentials.$source ?? {})) {
        setFeature2(context3, key2, value3);
      }
    }
  }

  // node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js
  var USER_AGENT = "user-agent";
  var X_AMZ_USER_AGENT = "x-amz-user-agent";
  var SPACE = " ";
  var UA_NAME_SEPARATOR = "/";
  var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
  var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
  var UA_ESCAPE_CHAR = "-";

  // node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js
  var BYTE_LIMIT = 1024;
  function encodeFeatures(features) {
    let buffer = "";
    for (const key2 in features) {
      const val = features[key2];
      if (buffer.length + val.length + 1 <= BYTE_LIMIT) {
        if (buffer.length) {
          buffer += "," + val;
        } else {
          buffer += val;
        }
        continue;
      }
      break;
    }
    return buffer;
  }

  // node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js
  var userAgentMiddleware = (options) => (next, context3) => async (args) => {
    const { request: request2 } = args;
    if (!HttpRequest.isInstance(request2)) {
      return next(args);
    }
    const { headers } = request2;
    const userAgent = context3?.userAgent?.map(escapeUserAgent) || [];
    const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent);
    await checkFeatures(context3, options, args);
    const awsContext = context3;
    defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context3.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`);
    const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
    const appId = await options.userAgentAppId();
    if (appId) {
      defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
    }
    const prefix = getUserAgentPrefix();
    const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE);
    const normalUAValue = [
      ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")),
      ...customUserAgent
    ].join(SPACE);
    if (options.runtime !== "browser") {
      if (normalUAValue) {
        headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue;
      }
      headers[USER_AGENT] = sdkUserAgentValue;
    } else {
      headers[X_AMZ_USER_AGENT] = sdkUserAgentValue;
    }
    return next({
      ...args,
      request: request2
    });
  };
  var escapeUserAgent = (userAgentPair) => {
    const name4 = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR);
    const version6 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR);
    const prefixSeparatorIndex = name4.indexOf(UA_NAME_SEPARATOR);
    const prefix = name4.substring(0, prefixSeparatorIndex);
    let uaName = name4.substring(prefixSeparatorIndex + 1);
    if (prefix === "api") {
      uaName = uaName.toLowerCase();
    }
    return [prefix, uaName, version6].filter((item) => item && item.length > 0).reduce((acc, item, index4) => {
      switch (index4) {
        case 0:
          return item;
        case 1:
          return `${acc}/${item}`;
        default:
          return `${acc}#${item}`;
      }
    }, "");
  };
  var getUserAgentMiddlewareOptions = {
    name: "getUserAgentMiddleware",
    step: "build",
    priority: "low",
    tags: ["SET_USER_AGENT", "USER_AGENT"],
    override: true
  };
  var getUserAgentPlugin = (config) => ({
    applyToStack: (clientStack) => {
      clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions);
    }
  });

  // node_modules/tslib/tslib.es6.mjs
  function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value3) {
      return value3 instanceof P ? value3 : new P(function(resolve2) {
        resolve2(value3);
      });
    }
    return new (P || (P = Promise))(function(resolve2, reject) {
      function fulfilled(value3) {
        try {
          step(generator.next(value3));
        } catch (e4) {
          reject(e4);
        }
      }
      function rejected(value3) {
        try {
          step(generator["throw"](value3));
        } catch (e4) {
          reject(e4);
        }
      }
      function step(result) {
        result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
      }
      step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
  }
  function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() {
      if (t4[0] & 1) throw t4[1];
      return t4[1];
    }, trys: [], ops: [] }, f2, y5, t4, g2 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g2.next = verb(0), g2["throw"] = verb(1), g2["return"] = verb(2), typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
      return this;
    }), g2;
    function verb(n2) {
      return function(v3) {
        return step([n2, v3]);
      };
    }
    function step(op) {
      if (f2) throw new TypeError("Generator is already executing.");
      while (g2 && (g2 = 0, op[0] && (_ = 0)), _) try {
        if (f2 = 1, y5 && (t4 = op[0] & 2 ? y5["return"] : op[0] ? y5["throw"] || ((t4 = y5["return"]) && t4.call(y5), 0) : y5.next) && !(t4 = t4.call(y5, op[1])).done) return t4;
        if (y5 = 0, t4) op = [op[0] & 2, t4.value];
        switch (op[0]) {
          case 0:
          case 1:
            t4 = op;
            break;
          case 4:
            _.label++;
            return { value: op[1], done: false };
          case 5:
            _.label++;
            y5 = op[1];
            op = [0];
            continue;
          case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;
          default:
            if (!(t4 = _.trys, t4 = t4.length > 0 && t4[t4.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _ = 0;
              continue;
            }
            if (op[0] === 3 && (!t4 || op[1] > t4[0] && op[1] < t4[3])) {
              _.label = op[1];
              break;
            }
            if (op[0] === 6 && _.label < t4[1]) {
              _.label = t4[1];
              t4 = op;
              break;
            }
            if (t4 && _.label < t4[2]) {
              _.label = t4[2];
              _.ops.push(op);
              break;
            }
            if (t4[2]) _.ops.pop();
            _.trys.pop();
            continue;
        }
        op = body.call(thisArg, _);
      } catch (e4) {
        op = [6, e4];
        y5 = 0;
      } finally {
        f2 = t4 = 0;
      }
      if (op[0] & 5) throw op[1];
      return { value: op[0] ? op[1] : void 0, done: true };
    }
  }
  function __values(o2) {
    var s2 = typeof Symbol === "function" && Symbol.iterator, m4 = s2 && o2[s2], i2 = 0;
    if (m4) return m4.call(o2);
    if (o2 && typeof o2.length === "number") return {
      next: function() {
        if (o2 && i2 >= o2.length) o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
    throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
  }

  // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js
  var fromUtf82 = (input) => new TextEncoder().encode(input);

  // node_modules/@aws-crypto/util/build/module/convertToBuffer.js
  var fromUtf83 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
    return Buffer.from(input, "utf8");
  } : fromUtf82;
  function convertToBuffer(data3) {
    if (data3 instanceof Uint8Array)
      return data3;
    if (typeof data3 === "string") {
      return fromUtf83(data3);
    }
    if (ArrayBuffer.isView(data3)) {
      return new Uint8Array(data3.buffer, data3.byteOffset, data3.byteLength / Uint8Array.BYTES_PER_ELEMENT);
    }
    return new Uint8Array(data3);
  }

  // node_modules/@aws-crypto/util/build/module/isEmptyData.js
  function isEmptyData(data3) {
    if (typeof data3 === "string") {
      return data3.length === 0;
    }
    return data3.byteLength === 0;
  }

  // node_modules/@aws-crypto/util/build/module/numToUint8.js
  function numToUint8(num) {
    return new Uint8Array([
      (num & 4278190080) >> 24,
      (num & 16711680) >> 16,
      (num & 65280) >> 8,
      num & 255
    ]);
  }

  // node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js
  function uint32ArrayFrom(a_lookUpTable2) {
    if (!Uint32Array.from) {
      var return_array = new Uint32Array(a_lookUpTable2.length);
      var a_index = 0;
      while (a_index < a_lookUpTable2.length) {
        return_array[a_index] = a_lookUpTable2[a_index];
        a_index += 1;
      }
      return return_array;
    }
    return Uint32Array.from(a_lookUpTable2);
  }

  // node_modules/@aws-crypto/crc32/build/module/aws_crc32.js
  var AwsCrc32 = (
    /** @class */
    function() {
      function AwsCrc322() {
        this.crc32 = new Crc32();
      }
      AwsCrc322.prototype.update = function(toHash) {
        if (isEmptyData(toHash))
          return;
        this.crc32.update(convertToBuffer(toHash));
      };
      AwsCrc322.prototype.digest = function() {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            return [2, numToUint8(this.crc32.digest())];
          });
        });
      };
      AwsCrc322.prototype.reset = function() {
        this.crc32 = new Crc32();
      };
      return AwsCrc322;
    }()
  );

  // node_modules/@aws-crypto/crc32/build/module/index.js
  var Crc32 = (
    /** @class */
    function() {
      function Crc322() {
        this.checksum = 4294967295;
      }
      Crc322.prototype.update = function(data3) {
        var e_1, _a2;
        try {
          for (var data_1 = __values(data3), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) {
            var byte = data_1_1.value;
            this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255];
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (data_1_1 && !data_1_1.done && (_a2 = data_1.return)) _a2.call(data_1);
          } finally {
            if (e_1) throw e_1.error;
          }
        }
        return this;
      };
      Crc322.prototype.digest = function() {
        return (this.checksum ^ 4294967295) >>> 0;
      };
      return Crc322;
    }()
  );
  var a_lookUpTable = [
    0,
    1996959894,
    3993919788,
    2567524794,
    124634137,
    1886057615,
    3915621685,
    2657392035,
    249268274,
    2044508324,
    3772115230,
    2547177864,
    162941995,
    2125561021,
    3887607047,
    2428444049,
    498536548,
    1789927666,
    4089016648,
    2227061214,
    450548861,
    1843258603,
    4107580753,
    2211677639,
    325883990,
    1684777152,
    4251122042,
    2321926636,
    335633487,
    1661365465,
    4195302755,
    2366115317,
    997073096,
    1281953886,
    3579855332,
    2724688242,
    1006888145,
    1258607687,
    3524101629,
    2768942443,
    901097722,
    1119000684,
    3686517206,
    2898065728,
    853044451,
    1172266101,
    3705015759,
    2882616665,
    651767980,
    1373503546,
    3369554304,
    3218104598,
    565507253,
    1454621731,
    3485111705,
    3099436303,
    671266974,
    1594198024,
    3322730930,
    2970347812,
    795835527,
    1483230225,
    3244367275,
    3060149565,
    1994146192,
    31158534,
    2563907772,
    4023717930,
    1907459465,
    112637215,
    2680153253,
    3904427059,
    2013776290,
    251722036,
    2517215374,
    3775830040,
    2137656763,
    141376813,
    2439277719,
    3865271297,
    1802195444,
    476864866,
    2238001368,
    4066508878,
    1812370925,
    453092731,
    2181625025,
    4111451223,
    1706088902,
    314042704,
    2344532202,
    4240017532,
    1658658271,
    366619977,
    2362670323,
    4224994405,
    1303535960,
    984961486,
    2747007092,
    3569037538,
    1256170817,
    1037604311,
    2765210733,
    3554079995,
    1131014506,
    879679996,
    2909243462,
    3663771856,
    1141124467,
    855842277,
    2852801631,
    3708648649,
    1342533948,
    654459306,
    3188396048,
    3373015174,
    1466479909,
    544179635,
    3110523913,
    3462522015,
    1591671054,
    702138776,
    2966460450,
    3352799412,
    1504918807,
    783551873,
    3082640443,
    3233442989,
    3988292384,
    2596254646,
    62317068,
    1957810842,
    3939845945,
    2647816111,
    81470997,
    1943803523,
    3814918930,
    2489596804,
    225274430,
    2053790376,
    3826175755,
    2466906013,
    167816743,
    2097651377,
    4027552580,
    2265490386,
    503444072,
    1762050814,
    4150417245,
    2154129355,
    426522225,
    1852507879,
    4275313526,
    2312317920,
    282753626,
    1742555852,
    4189708143,
    2394877945,
    397917763,
    1622183637,
    3604390888,
    2714866558,
    953729732,
    1340076626,
    3518719985,
    2797360999,
    1068828381,
    1219638859,
    3624741850,
    2936675148,
    906185462,
    1090812512,
    3747672003,
    2825379669,
    829329135,
    1181335161,
    3412177804,
    3160834842,
    628085408,
    1382605366,
    3423369109,
    3138078467,
    570562233,
    1426400815,
    3317316542,
    2998733608,
    733239954,
    1555261956,
    3268935591,
    3050360625,
    752459403,
    1541320221,
    2607071920,
    3965973030,
    1969922972,
    40735498,
    2617837225,
    3943577151,
    1913087877,
    83908371,
    2512341634,
    3803740692,
    2075208622,
    213261112,
    2463272603,
    3855990285,
    2094854071,
    198958881,
    2262029012,
    4057260610,
    1759359992,
    534414190,
    2176718541,
    4139329115,
    1873836001,
    414664567,
    2282248934,
    4279200368,
    1711684554,
    285281116,
    2405801727,
    4167216745,
    1634467795,
    376229701,
    2685067896,
    3608007406,
    1308918612,
    956543938,
    2808555105,
    3495958263,
    1231636301,
    1047427035,
    2932959818,
    3654703836,
    1088359270,
    936918e3,
    2847714899,
    3736837829,
    1202900863,
    817233897,
    3183342108,
    3401237130,
    1404277552,
    615818150,
    3134207493,
    3453421203,
    1423857449,
    601450431,
    3009837614,
    3294710456,
    1567103746,
    711928724,
    3020668471,
    3272380065,
    1510334235,
    755167117
  ];
  var lookupTable = uint32ArrayFrom(a_lookUpTable);

  // node_modules/@smithy/eventstream-codec/dist-es/Int64.js
  var Int642 = class _Int64 {
    constructor(bytes) {
      this.bytes = bytes;
      if (bytes.byteLength !== 8) {
        throw new Error("Int64 buffers must be exactly 8 bytes");
      }
    }
    static fromNumber(number8) {
      if (number8 > 9223372036854776e3 || number8 < -9223372036854776e3) {
        throw new Error(`${number8} is too large (or, if negative, too small) to represent as an Int64`);
      }
      const bytes = new Uint8Array(8);
      for (let i2 = 7, remaining = Math.abs(Math.round(number8)); i2 > -1 && remaining > 0; i2--, remaining /= 256) {
        bytes[i2] = remaining;
      }
      if (number8 < 0) {
        negate3(bytes);
      }
      return new _Int64(bytes);
    }
    valueOf() {
      const bytes = this.bytes.slice(0);
      const negative = bytes[0] & 128;
      if (negative) {
        negate3(bytes);
      }
      return parseInt(toHex(bytes), 16) * (negative ? -1 : 1);
    }
    toString() {
      return String(this.valueOf());
    }
  };
  function negate3(bytes) {
    for (let i2 = 0; i2 < 8; i2++) {
      bytes[i2] ^= 255;
    }
    for (let i2 = 7; i2 > -1; i2--) {
      bytes[i2]++;
      if (bytes[i2] !== 0)
        break;
    }
  }

  // node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js
  var HeaderMarshaller = class {
    constructor(toUtf82, fromUtf84) {
      this.toUtf8 = toUtf82;
      this.fromUtf8 = fromUtf84;
    }
    format(headers) {
      const chunks = [];
      for (const headerName of Object.keys(headers)) {
        const bytes = this.fromUtf8(headerName);
        chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName]));
      }
      const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0));
      let position2 = 0;
      for (const chunk of chunks) {
        out.set(chunk, position2);
        position2 += chunk.byteLength;
      }
      return out;
    }
    formatHeaderValue(header) {
      switch (header.type) {
        case "boolean":
          return Uint8Array.from([header.value ? 0 : 1]);
        case "byte":
          return Uint8Array.from([2, header.value]);
        case "short":
          const shortView = new DataView(new ArrayBuffer(3));
          shortView.setUint8(0, 3);
          shortView.setInt16(1, header.value, false);
          return new Uint8Array(shortView.buffer);
        case "integer":
          const intView = new DataView(new ArrayBuffer(5));
          intView.setUint8(0, 4);
          intView.setInt32(1, header.value, false);
          return new Uint8Array(intView.buffer);
        case "long":
          const longBytes = new Uint8Array(9);
          longBytes[0] = 5;
          longBytes.set(header.value.bytes, 1);
          return longBytes;
        case "binary":
          const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength));
          binView.setUint8(0, 6);
          binView.setUint16(1, header.value.byteLength, false);
          const binBytes = new Uint8Array(binView.buffer);
          binBytes.set(header.value, 3);
          return binBytes;
        case "string":
          const utf8Bytes = this.fromUtf8(header.value);
          const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength));
          strView.setUint8(0, 7);
          strView.setUint16(1, utf8Bytes.byteLength, false);
          const strBytes = new Uint8Array(strView.buffer);
          strBytes.set(utf8Bytes, 3);
          return strBytes;
        case "timestamp":
          const tsBytes = new Uint8Array(9);
          tsBytes[0] = 8;
          tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes, 1);
          return tsBytes;
        case "uuid":
          if (!UUID_PATTERN2.test(header.value)) {
            throw new Error(`Invalid UUID received: ${header.value}`);
          }
          const uuidBytes = new Uint8Array(17);
          uuidBytes[0] = 9;
          uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1);
          return uuidBytes;
      }
    }
    parse(headers) {
      const out = {};
      let position2 = 0;
      while (position2 < headers.byteLength) {
        const nameLength = headers.getUint8(position2++);
        const name4 = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, nameLength));
        position2 += nameLength;
        switch (headers.getUint8(position2++)) {
          case 0:
            out[name4] = {
              type: BOOLEAN_TAG,
              value: true
            };
            break;
          case 1:
            out[name4] = {
              type: BOOLEAN_TAG,
              value: false
            };
            break;
          case 2:
            out[name4] = {
              type: BYTE_TAG,
              value: headers.getInt8(position2++)
            };
            break;
          case 3:
            out[name4] = {
              type: SHORT_TAG,
              value: headers.getInt16(position2, false)
            };
            position2 += 2;
            break;
          case 4:
            out[name4] = {
              type: INT_TAG,
              value: headers.getInt32(position2, false)
            };
            position2 += 4;
            break;
          case 5:
            out[name4] = {
              type: LONG_TAG,
              value: new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8))
            };
            position2 += 8;
            break;
          case 6:
            const binaryLength = headers.getUint16(position2, false);
            position2 += 2;
            out[name4] = {
              type: BINARY_TAG,
              value: new Uint8Array(headers.buffer, headers.byteOffset + position2, binaryLength)
            };
            position2 += binaryLength;
            break;
          case 7:
            const stringLength = headers.getUint16(position2, false);
            position2 += 2;
            out[name4] = {
              type: STRING_TAG,
              value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position2, stringLength))
            };
            position2 += stringLength;
            break;
          case 8:
            out[name4] = {
              type: TIMESTAMP_TAG,
              value: new Date(new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position2, 8)).valueOf())
            };
            position2 += 8;
            break;
          case 9:
            const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position2, 16);
            position2 += 16;
            out[name4] = {
              type: UUID_TAG,
              value: `${toHex(uuidBytes.subarray(0, 4))}-${toHex(uuidBytes.subarray(4, 6))}-${toHex(uuidBytes.subarray(6, 8))}-${toHex(uuidBytes.subarray(8, 10))}-${toHex(uuidBytes.subarray(10))}`
            };
            break;
          default:
            throw new Error(`Unrecognized header type tag`);
        }
      }
      return out;
    }
  };
  var HEADER_VALUE_TYPE2;
  (function(HEADER_VALUE_TYPE3) {
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp";
    HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid";
  })(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {}));
  var BOOLEAN_TAG = "boolean";
  var BYTE_TAG = "byte";
  var SHORT_TAG = "short";
  var INT_TAG = "integer";
  var LONG_TAG = "long";
  var BINARY_TAG = "binary";
  var STRING_TAG = "string";
  var TIMESTAMP_TAG = "timestamp";
  var UUID_TAG = "uuid";
  var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;

  // node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js
  var PRELUDE_MEMBER_LENGTH = 4;
  var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2;
  var CHECKSUM_LENGTH = 4;
  var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2;
  function splitMessage({ byteLength, byteOffset, buffer }) {
    if (byteLength < MINIMUM_MESSAGE_LENGTH) {
      throw new Error("Provided message too short to accommodate event stream message overhead");
    }
    const view = new DataView(buffer, byteOffset, byteLength);
    const messageLength = view.getUint32(0, false);
    if (byteLength !== messageLength) {
      throw new Error("Reported message length does not match received message length");
    }
    const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false);
    const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false);
    const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false);
    const checksummer = new Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH));
    if (expectedPreludeChecksum !== checksummer.digest()) {
      throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);
    }
    checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)));
    if (expectedMessageChecksum !== checksummer.digest()) {
      throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);
    }
    return {
      headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength),
      body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH))
    };
  }

  // node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js
  var EventStreamCodec = class {
    constructor(toUtf82, fromUtf84) {
      this.headerMarshaller = new HeaderMarshaller(toUtf82, fromUtf84);
      this.messageBuffer = [];
      this.isEndOfStream = false;
    }
    feed(message) {
      this.messageBuffer.push(this.decode(message));
    }
    endOfStream() {
      this.isEndOfStream = true;
    }
    getMessage() {
      const message = this.messageBuffer.pop();
      const isEndOfStream = this.isEndOfStream;
      return {
        getMessage() {
          return message;
        },
        isEndOfStream() {
          return isEndOfStream;
        }
      };
    }
    getAvailableMessages() {
      const messages = this.messageBuffer;
      this.messageBuffer = [];
      const isEndOfStream = this.isEndOfStream;
      return {
        getMessages() {
          return messages;
        },
        isEndOfStream() {
          return isEndOfStream;
        }
      };
    }
    encode({ headers: rawHeaders, body }) {
      const headers = this.headerMarshaller.format(rawHeaders);
      const length3 = headers.byteLength + body.byteLength + 16;
      const out = new Uint8Array(length3);
      const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
      const checksum = new Crc32();
      view.setUint32(0, length3, false);
      view.setUint32(4, headers.byteLength, false);
      view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false);
      out.set(headers, 12);
      out.set(body, headers.byteLength + 12);
      view.setUint32(length3 - 4, checksum.update(out.subarray(8, length3 - 4)).digest(), false);
      return out;
    }
    decode(message) {
      const { headers, body } = splitMessage(message);
      return { headers: this.headerMarshaller.parse(headers), body };
    }
    formatHeaders(rawHeaders) {
      return this.headerMarshaller.format(rawHeaders);
    }
  };

  // node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js
  var MessageDecoderStream = class {
    constructor(options) {
      this.options = options;
    }
    [Symbol.asyncIterator]() {
      return this.asyncIterator();
    }
    async *asyncIterator() {
      for await (const bytes of this.options.inputStream) {
        const decoded = this.options.decoder.decode(bytes);
        yield decoded;
      }
    }
  };

  // node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js
  var MessageEncoderStream = class {
    constructor(options) {
      this.options = options;
    }
    [Symbol.asyncIterator]() {
      return this.asyncIterator();
    }
    async *asyncIterator() {
      for await (const msg of this.options.messageStream) {
        const encoded = this.options.encoder.encode(msg);
        yield encoded;
      }
      if (this.options.includeEndFrame) {
        yield new Uint8Array(0);
      }
    }
  };

  // node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js
  var SmithyMessageDecoderStream = class {
    constructor(options) {
      this.options = options;
    }
    [Symbol.asyncIterator]() {
      return this.asyncIterator();
    }
    async *asyncIterator() {
      for await (const message of this.options.messageStream) {
        const deserialized = await this.options.deserializer(message);
        if (deserialized === void 0)
          continue;
        yield deserialized;
      }
    }
  };

  // node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js
  var SmithyMessageEncoderStream = class {
    constructor(options) {
      this.options = options;
    }
    [Symbol.asyncIterator]() {
      return this.asyncIterator();
    }
    async *asyncIterator() {
      for await (const chunk of this.options.inputStream) {
        const payloadBuf = this.options.serializer(chunk);
        yield payloadBuf;
      }
    }
  };

  // node_modules/@aws-sdk/middleware-websocket/dist-es/get-event-signing-stream.js
  var getEventSigningTransformStream = (initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider) => {
    let priorSignature = initialSignature;
    const transformer5 = {
      start() {
      },
      async transform(chunk, controller) {
        try {
          const now2 = new Date(Date.now() + await systemClockOffsetProvider());
          const dateHeader = {
            ":date": { type: "timestamp", value: now2 }
          };
          const signedMessage = await messageSigner.sign({
            message: {
              body: chunk,
              headers: dateHeader
            },
            priorSignature
          }, {
            signingDate: now2
          });
          priorSignature = signedMessage.signature;
          const serializedSigned = eventStreamCodec.encode({
            headers: {
              ...dateHeader,
              ":chunk-signature": {
                type: "binary",
                value: fromHex(signedMessage.signature)
              }
            },
            body: chunk
          });
          controller.enqueue(serializedSigned);
        } catch (error3) {
          controller.error(error3);
        }
      }
    };
    return new TransformStream({ ...transformer5 });
  };

  // node_modules/@aws-sdk/middleware-websocket/dist-es/EventStreamPayloadHandler.js
  var EventStreamPayloadHandler = class {
    messageSigner;
    eventStreamCodec;
    systemClockOffsetProvider;
    constructor(options) {
      this.messageSigner = options.messageSigner;
      this.eventStreamCodec = new EventStreamCodec(options.utf8Encoder, options.utf8Decoder);
      this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0;
    }
    async handle(next, args, context3 = {}) {
      const request2 = args.request;
      const { body: payload, headers, query } = request2;
      if (!(payload instanceof ReadableStream)) {
        throw new Error("Eventstream payload must be a ReadableStream.");
      }
      const placeHolderStream = new TransformStream();
      request2.body = placeHolderStream.readable;
      let result;
      try {
        result = await next(args);
      } catch (e4) {
        request2.body.cancel();
        throw e4;
      }
      const match3 = (headers["authorization"] || "").match(/Signature=([\w]+)$/);
      const priorSignature = (match3 || [])[1] || query && query["X-Amz-Signature"] || "";
      const signingStream = getEventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider);
      const signedPayload = payload.pipeThrough(signingStream);
      signedPayload.pipeThrough(placeHolderStream);
      return result;
    }
  };

  // node_modules/@aws-sdk/middleware-websocket/dist-es/eventstream-payload-handler-provider.js
  var eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options);

  // node_modules/@aws-sdk/middleware-websocket/dist-es/utils.js
  var isWebSocketRequest = (request2) => request2.protocol === "ws:" || request2.protocol === "wss:";

  // node_modules/@aws-sdk/middleware-websocket/dist-es/WebsocketSignatureV4.js
  var WebsocketSignatureV4 = class {
    signer;
    constructor(options) {
      this.signer = options.signer;
    }
    presign(originalRequest, options = {}) {
      return this.signer.presign(originalRequest, options);
    }
    async sign(toSign, options) {
      if (HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) {
        const signedRequest = await this.signer.presign({ ...toSign, body: "" }, {
          ...options,
          expiresIn: 60,
          unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host"))
        });
        return {
          ...signedRequest,
          body: toSign.body
        };
      } else {
        return this.signer.sign(toSign, options);
      }
    }
  };

  // node_modules/@aws-sdk/middleware-websocket/dist-es/websocket-configuration.js
  var resolveWebSocketConfig = (input) => {
    const { signer } = input;
    return Object.assign(input, {
      signer: async (authScheme) => {
        const signerObj = await signer(authScheme);
        if (validateSigner(signerObj)) {
          return new WebsocketSignatureV4({ signer: signerObj });
        }
        throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.");
      }
    });
  };
  var validateSigner = (signer) => !!signer;

  // node_modules/@aws-sdk/util-format-url/dist-es/index.js
  function formatUrl(request2) {
    const { port, query } = request2;
    let { protocol, path: path3, hostname } = request2;
    if (protocol && protocol.slice(-1) !== ":") {
      protocol += ":";
    }
    if (port) {
      hostname += `:${port}`;
    }
    if (path3 && path3.charAt(0) !== "/") {
      path3 = `/${path3}`;
    }
    let queryString = query ? buildQueryString(query) : "";
    if (queryString && queryString[0] !== "?") {
      queryString = `?${queryString}`;
    }
    let auth = "";
    if (request2.username != null || request2.password != null) {
      const username = request2.username ?? "";
      const password = request2.password ?? "";
      auth = `${username}:${password}@`;
    }
    let fragment = "";
    if (request2.fragment) {
      fragment = `#${request2.fragment}`;
    }
    return `${protocol}//${auth}${hostname}${path3}${queryString}${fragment}`;
  }

  // node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js
  function getChunkedStream(source4) {
    let currentMessageTotalLength = 0;
    let currentMessagePendingLength = 0;
    let currentMessage = null;
    let messageLengthBuffer = null;
    const allocateMessage = (size) => {
      if (typeof size !== "number") {
        throw new Error("Attempted to allocate an event message where size was not a number: " + size);
      }
      currentMessageTotalLength = size;
      currentMessagePendingLength = 4;
      currentMessage = new Uint8Array(size);
      const currentMessageView = new DataView(currentMessage.buffer);
      currentMessageView.setUint32(0, size, false);
    };
    const iterator = async function* () {
      const sourceIterator = source4[Symbol.asyncIterator]();
      while (true) {
        const { value: value3, done } = await sourceIterator.next();
        if (done) {
          if (!currentMessageTotalLength) {
            return;
          } else if (currentMessageTotalLength === currentMessagePendingLength) {
            yield currentMessage;
          } else {
            throw new Error("Truncated event message received.");
          }
          return;
        }
        const chunkLength = value3.length;
        let currentOffset = 0;
        while (currentOffset < chunkLength) {
          if (!currentMessage) {
            const bytesRemaining = chunkLength - currentOffset;
            if (!messageLengthBuffer) {
              messageLengthBuffer = new Uint8Array(4);
            }
            const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining);
            messageLengthBuffer.set(value3.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength);
            currentMessagePendingLength += numBytesForTotal;
            currentOffset += numBytesForTotal;
            if (currentMessagePendingLength < 4) {
              break;
            }
            allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false));
            messageLengthBuffer = null;
          }
          const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset);
          currentMessage.set(value3.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength);
          currentMessagePendingLength += numBytesToWrite;
          currentOffset += numBytesToWrite;
          if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) {
            yield currentMessage;
            currentMessage = null;
            currentMessageTotalLength = 0;
            currentMessagePendingLength = 0;
          }
        }
      }
    };
    return {
      [Symbol.asyncIterator]: iterator
    };
  }

  // node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js
  function getMessageUnmarshaller(deserializer, toUtf82) {
    return async function(message) {
      const { value: messageType } = message.headers[":message-type"];
      if (messageType === "error") {
        const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
        unmodeledError.name = message.headers[":error-code"].value;
        throw unmodeledError;
      } else if (messageType === "exception") {
        const code = message.headers[":exception-type"].value;
        const exception = { [code]: message };
        const deserializedException = await deserializer(exception);
        if (deserializedException.$unknown) {
          const error3 = new Error(toUtf82(message.body));
          error3.name = code;
          throw error3;
        }
        throw deserializedException[code];
      } else if (messageType === "event") {
        const event2 = {
          [message.headers[":event-type"].value]: message
        };
        const deserialized = await deserializer(event2);
        if (deserialized.$unknown)
          return;
        return deserialized;
      } else {
        throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
      }
    };
  }

  // node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js
  var EventStreamMarshaller = class {
    constructor({ utf8Encoder, utf8Decoder }) {
      this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder);
      this.utfEncoder = utf8Encoder;
    }
    deserialize(body, deserializer) {
      const inputStream = getChunkedStream(body);
      return new SmithyMessageDecoderStream({
        messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }),
        deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder)
      });
    }
    serialize(inputStream, serializer) {
      return new MessageEncoderStream({
        messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }),
        encoder: this.eventStreamCodec,
        includeEndFrame: true
      });
    }
  };

  // node_modules/@smithy/eventstream-serde-browser/dist-es/utils.js
  var readableStreamtoIterable = (readableStream) => ({
    [Symbol.asyncIterator]: async function* () {
      const reader = readableStream.getReader();
      try {
        while (true) {
          const { done, value: value3 } = await reader.read();
          if (done)
            return;
          yield value3;
        }
      } finally {
        reader.releaseLock();
      }
    }
  });
  var iterableToReadableStream = (asyncIterable) => {
    const iterator = asyncIterable[Symbol.asyncIterator]();
    return new ReadableStream({
      async pull(controller) {
        const { done, value: value3 } = await iterator.next();
        if (done) {
          return controller.close();
        }
        controller.enqueue(value3);
      }
    });
  };

  // node_modules/@smithy/eventstream-serde-browser/dist-es/EventStreamMarshaller.js
  var EventStreamMarshaller2 = class {
    constructor({ utf8Encoder, utf8Decoder }) {
      this.universalMarshaller = new EventStreamMarshaller({
        utf8Decoder,
        utf8Encoder
      });
    }
    deserialize(body, deserializer) {
      const bodyIterable = isReadableStream2(body) ? readableStreamtoIterable(body) : body;
      return this.universalMarshaller.deserialize(bodyIterable, deserializer);
    }
    serialize(input, serializer) {
      const serialziedIterable = this.universalMarshaller.serialize(input, serializer);
      return typeof ReadableStream === "function" ? iterableToReadableStream(serialziedIterable) : serialziedIterable;
    }
  };
  var isReadableStream2 = (body) => typeof ReadableStream === "function" && body instanceof ReadableStream;

  // node_modules/@smithy/eventstream-serde-browser/dist-es/provider.js
  var eventStreamSerdeProvider = (options) => new EventStreamMarshaller2(options);

  // node_modules/@aws-sdk/middleware-websocket/dist-es/websocket-fetch-handler.js
  var DEFAULT_WS_CONNECTION_TIMEOUT_MS = 2e3;
  var WebSocketFetchHandler = class _WebSocketFetchHandler {
    metadata = {
      handlerProtocol: "websocket/h1.1"
    };
    config;
    configPromise;
    httpHandler;
    sockets = {};
    static create(instanceOrOptions, httpHandler = new FetchHttpHandler()) {
      if (typeof instanceOrOptions?.handle === "function") {
        return instanceOrOptions;
      }
      return new _WebSocketFetchHandler(instanceOrOptions, httpHandler);
    }
    constructor(options, httpHandler = new FetchHttpHandler()) {
      this.httpHandler = httpHandler;
      if (typeof options === "function") {
        this.config = {};
        this.configPromise = options().then((opts) => this.config = opts ?? {});
      } else {
        this.config = options ?? {};
        this.configPromise = Promise.resolve(this.config);
      }
    }
    destroy() {
      for (const [key2, sockets] of Object.entries(this.sockets)) {
        for (const socket of sockets) {
          socket.close(1e3, `Socket closed through destroy() call`);
        }
        delete this.sockets[key2];
      }
    }
    async handle(request2) {
      if (!isWebSocketRequest(request2)) {
        return this.httpHandler.handle(request2);
      }
      const url = formatUrl(request2);
      const socket = new WebSocket(url);
      if (!this.sockets[url]) {
        this.sockets[url] = [];
      }
      this.sockets[url].push(socket);
      socket.binaryType = "arraybuffer";
      this.config = await this.configPromise;
      const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config;
      await this.waitForReady(socket, connectionTimeout);
      const { body } = request2;
      const bodyStream = getIterator(body);
      const asyncIterable = this.connect(socket, bodyStream);
      const outputPayload = toReadableStream(asyncIterable);
      return {
        response: new HttpResponse({
          statusCode: 200,
          body: outputPayload
        })
      };
    }
    updateHttpClientConfig(key2, value3) {
      this.configPromise = this.configPromise.then((config) => {
        config[key2] = value3;
        return config;
      });
    }
    httpHandlerConfigs() {
      return this.config ?? {};
    }
    removeNotUsableSockets(url) {
      this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState));
    }
    waitForReady(socket, connectionTimeout) {
      return new Promise((resolve2, reject) => {
        const timeout2 = setTimeout(() => {
          this.removeNotUsableSockets(socket.url);
          reject({
            $metadata: {
              httpStatusCode: 500
            }
          });
        }, connectionTimeout);
        socket.onopen = () => {
          clearTimeout(timeout2);
          resolve2();
        };
      });
    }
    connect(socket, data3) {
      let streamError = void 0;
      let socketErrorOccurred = false;
      let reject = () => {
      };
      let resolve2 = () => {
      };
      socket.onmessage = (event2) => {
        resolve2({
          done: false,
          value: new Uint8Array(event2.data)
        });
      };
      socket.onerror = (error3) => {
        socketErrorOccurred = true;
        socket.close();
        reject(error3);
      };
      socket.onclose = () => {
        this.removeNotUsableSockets(socket.url);
        if (socketErrorOccurred)
          return;
        if (streamError) {
          reject(streamError);
        } else {
          resolve2({
            done: true,
            value: void 0
          });
        }
      };
      const outputStream = {
        [Symbol.asyncIterator]: () => ({
          next: () => {
            return new Promise((_resolve, _reject) => {
              resolve2 = _resolve;
              reject = _reject;
            });
          }
        })
      };
      const send = async () => {
        try {
          for await (const inputChunk of data3) {
            socket.send(inputChunk);
          }
        } catch (err) {
          streamError = err;
        } finally {
          socket.close(1e3);
        }
      };
      send();
      return outputStream;
    }
  };
  var getIterator = (stream2) => {
    if (stream2[Symbol.asyncIterator]) {
      return stream2;
    }
    if (isReadableStream3(stream2)) {
      return readableStreamtoIterable(stream2);
    }
    return {
      [Symbol.asyncIterator]: async function* () {
        yield stream2;
      }
    };
  };
  var toReadableStream = (asyncIterable) => typeof ReadableStream === "function" ? iterableToReadableStream(asyncIterable) : asyncIterable;
  var isReadableStream3 = (payload) => typeof ReadableStream === "function" && payload instanceof ReadableStream;

  // node_modules/@smithy/util-config-provider/dist-es/types.js
  var SelectorType;
  (function(SelectorType2) {
    SelectorType2["ENV"] = "env";
    SelectorType2["CONFIG"] = "shared config entry";
  })(SelectorType || (SelectorType = {}));

  // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js
  var DEFAULT_USE_DUALSTACK_ENDPOINT = false;

  // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js
  var DEFAULT_USE_FIPS_ENDPOINT = false;

  // node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js
  var isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips"));

  // node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js
  var getRealRegion = (region) => isFipsRegion(region) ? ["fips-aws-global", "aws-fips"].includes(region) ? "us-east-1" : region.replace(/fips-(dkr-|prod-)?|-fips/, "") : region;

  // node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js
  var resolveRegionConfig = (input) => {
    const { region, useFipsEndpoint } = input;
    if (!region) {
      throw new Error("Region is missing");
    }
    return Object.assign(input, {
      region: async () => {
        if (typeof region === "string") {
          return getRealRegion(region);
        }
        const providedRegion = await region();
        return getRealRegion(providedRegion);
      },
      useFipsEndpoint: async () => {
        const providedRegion = typeof region === "string" ? region : await region();
        if (isFipsRegion(providedRegion)) {
          return true;
        }
        return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint();
      }
    });
  };

  // node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js
  var resolveEventStreamSerdeConfig = (input) => Object.assign(input, {
    eventStreamMarshaller: input.eventStreamSerdeProvider(input)
  });

  // node_modules/@smithy/middleware-content-length/dist-es/index.js
  var CONTENT_LENGTH_HEADER = "content-length";
  function contentLengthMiddleware(bodyLengthChecker) {
    return (next) => async (args) => {
      const request2 = args.request;
      if (HttpRequest.isInstance(request2)) {
        const { body, headers } = request2;
        if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) {
          try {
            const length3 = bodyLengthChecker(body);
            request2.headers = {
              ...request2.headers,
              [CONTENT_LENGTH_HEADER]: String(length3)
            };
          } catch (error3) {
          }
        }
      }
      return next({
        ...args,
        request: request2
      });
    };
  }
  var contentLengthMiddlewareOptions = {
    step: "build",
    tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"],
    name: "contentLengthMiddleware",
    override: true
  };
  var getContentLengthPlugin = (options) => ({
    applyToStack: (clientStack) => {
      clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions);
    }
  });

  // node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js
  var resolveParamsForS3 = async (endpointParams) => {
    const bucket = endpointParams?.Bucket || "";
    if (typeof endpointParams.Bucket === "string") {
      endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?"));
    }
    if (isArnBucketName(bucket)) {
      if (endpointParams.ForcePathStyle === true) {
        throw new Error("Path-style addressing cannot be used with ARN buckets");
      }
    } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) {
      endpointParams.ForcePathStyle = true;
    }
    if (endpointParams.DisableMultiRegionAccessPoints) {
      endpointParams.disableMultiRegionAccessPoints = true;
      endpointParams.DisableMRAP = true;
    }
    return endpointParams;
  };
  var DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;
  var IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/;
  var DOTS_PATTERN = /\.\./;
  var isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName);
  var isArnBucketName = (bucketName) => {
    const [arn, partition6, service, , , bucket] = bucketName.split(":");
    const isArn = arn === "arn" && bucketName.split(":").length >= 6;
    const isValidArn = Boolean(isArn && partition6 && service && bucket);
    if (isArn && !isValidArn) {
      throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);
    }
    return isValidArn;
  };

  // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js
  var createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => {
    const configProvider = async () => {
      const configValue = config[configKey] ?? config[canonicalEndpointParamKey];
      if (typeof configValue === "function") {
        return configValue();
      }
      return configValue;
    };
    if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") {
      return async () => {
        const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
        const configValue = credentials?.credentialScope ?? credentials?.CredentialScope;
        return configValue;
      };
    }
    if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") {
      return async () => {
        const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials;
        const configValue = credentials?.accountId ?? credentials?.AccountId;
        return configValue;
      };
    }
    if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") {
      return async () => {
        if (config.isCustomEndpoint === false) {
          return void 0;
        }
        const endpoint = await configProvider();
        if (endpoint && typeof endpoint === "object") {
          if ("url" in endpoint) {
            return endpoint.url.href;
          }
          if ("hostname" in endpoint) {
            const { protocol, hostname, port, path: path3 } = endpoint;
            return `${protocol}//${hostname}${port ? ":" + port : ""}${path3}`;
          }
        }
        return endpoint;
      };
    }
    return configProvider;
  };

  // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js
  var getEndpointFromConfig = async (serviceId) => void 0;

  // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js
  var toEndpointV1 = (endpoint) => {
    if (typeof endpoint === "object") {
      if ("url" in endpoint) {
        return parseUrl(endpoint.url);
      }
      return endpoint;
    }
    return parseUrl(endpoint);
  };

  // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js
  var getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context3) => {
    if (!clientConfig.isCustomEndpoint) {
      let endpointFromConfig;
      if (clientConfig.serviceConfiguredEndpoint) {
        endpointFromConfig = await clientConfig.serviceConfiguredEndpoint();
      } else {
        endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId);
      }
      if (endpointFromConfig) {
        clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig));
        clientConfig.isCustomEndpoint = true;
      }
    }
    const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig);
    if (typeof clientConfig.endpointProvider !== "function") {
      throw new Error("config.endpointProvider is not set.");
    }
    const endpoint = clientConfig.endpointProvider(endpointParams, context3);
    return endpoint;
  };
  var resolveParams = async (commandInput, instructionsSupplier, clientConfig) => {
    const endpointParams = {};
    const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {};
    for (const [name4, instruction] of Object.entries(instructions)) {
      switch (instruction.type) {
        case "staticContextParams":
          endpointParams[name4] = instruction.value;
          break;
        case "contextParams":
          endpointParams[name4] = commandInput[instruction.name];
          break;
        case "clientContextParams":
        case "builtInParams":
          endpointParams[name4] = await createConfigValueProvider(instruction.name, name4, clientConfig)();
          break;
        case "operationContextParams":
          endpointParams[name4] = instruction.get(commandInput);
          break;
        default:
          throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction));
      }
    }
    if (Object.keys(instructions).length === 0) {
      Object.assign(endpointParams, clientConfig);
    }
    if (String(clientConfig.serviceId).toLowerCase() === "s3") {
      await resolveParamsForS3(endpointParams);
    }
    return endpointParams;
  };

  // node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js
  var endpointMiddleware = ({ config, instructions }) => {
    return (next, context3) => async (args) => {
      if (config.isCustomEndpoint) {
        setFeature(context3, "ENDPOINT_OVERRIDE", "N");
      }
      const endpoint = await getEndpointFromInstructions(args.input, {
        getEndpointParameterInstructions() {
          return instructions;
        }
      }, { ...config }, context3);
      context3.endpointV2 = endpoint;
      context3.authSchemes = endpoint.properties?.authSchemes;
      const authScheme = context3.authSchemes?.[0];
      if (authScheme) {
        context3["signing_region"] = authScheme.signingRegion;
        context3["signing_service"] = authScheme.signingName;
        const smithyContext = getSmithyContext(context3);
        const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption;
        if (httpAuthOption) {
          httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, {
            signing_region: authScheme.signingRegion,
            signingRegion: authScheme.signingRegion,
            signing_service: authScheme.signingName,
            signingName: authScheme.signingName,
            signingRegionSet: authScheme.signingRegionSet
          }, authScheme.properties);
        }
      }
      return next({
        ...args
      });
    };
  };

  // node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js
  var endpointMiddlewareOptions = {
    step: "serialize",
    tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"],
    name: "endpointV2Middleware",
    override: true,
    relation: "before",
    toMiddleware: serializerMiddlewareOption.name
  };
  var getEndpointPlugin = (config, instructions) => ({
    applyToStack: (clientStack) => {
      clientStack.addRelativeTo(endpointMiddleware({
        config,
        instructions
      }), endpointMiddlewareOptions);
    }
  });

  // node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js
  var resolveEndpointConfig = (input) => {
    const tls = input.tls ?? true;
    const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input;
    const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0;
    const isCustomEndpoint = !!endpoint;
    const resolvedConfig = Object.assign(input, {
      endpoint: customEndpointProvider,
      tls,
      isCustomEndpoint,
      useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false),
      useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false)
    });
    let configuredEndpointPromise = void 0;
    resolvedConfig.serviceConfiguredEndpoint = async () => {
      if (input.serviceId && !configuredEndpointPromise) {
        configuredEndpointPromise = getEndpointFromConfig(input.serviceId);
      }
      return configuredEndpointPromise;
    };
    return resolvedConfig;
  };

  // node_modules/@smithy/util-retry/dist-es/config.js
  var RETRY_MODES;
  (function(RETRY_MODES2) {
    RETRY_MODES2["STANDARD"] = "standard";
    RETRY_MODES2["ADAPTIVE"] = "adaptive";
  })(RETRY_MODES || (RETRY_MODES = {}));
  var DEFAULT_MAX_ATTEMPTS = 3;
  var DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD;

  // node_modules/@smithy/service-error-classification/dist-es/constants.js
  var THROTTLING_ERROR_CODES = [
    "BandwidthLimitExceeded",
    "EC2ThrottledException",
    "LimitExceededException",
    "PriorRequestNotComplete",
    "ProvisionedThroughputExceededException",
    "RequestLimitExceeded",
    "RequestThrottled",
    "RequestThrottledException",
    "SlowDown",
    "ThrottledException",
    "Throttling",
    "ThrottlingException",
    "TooManyRequestsException",
    "TransactionInProgressException"
  ];
  var TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"];
  var TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504];
  var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"];
  var NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"];

  // node_modules/@smithy/service-error-classification/dist-es/index.js
  var isClockSkewCorrectedError = (error3) => error3.$metadata?.clockSkewCorrected;
  var isBrowserNetworkError = (error3) => {
    const errorMessages = /* @__PURE__ */ new Set([
      "Failed to fetch",
      "NetworkError when attempting to fetch resource",
      "The Internet connection appears to be offline",
      "Load failed",
      "Network request failed"
    ]);
    const isValid2 = error3 && error3 instanceof TypeError;
    if (!isValid2) {
      return false;
    }
    return errorMessages.has(error3.message);
  };
  var isThrottlingError = (error3) => error3.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error3.name) || error3.$retryable?.throttling == true;
  var isTransientError = (error3, depth = 0) => isClockSkewCorrectedError(error3) || TRANSIENT_ERROR_CODES.includes(error3.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error3?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error3?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error3.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error3) || error3.cause !== void 0 && depth <= 10 && isTransientError(error3.cause, depth + 1);
  var isServerError = (error3) => {
    if (error3.$metadata?.httpStatusCode !== void 0) {
      const statusCode = error3.$metadata.httpStatusCode;
      if (500 <= statusCode && statusCode <= 599 && !isTransientError(error3)) {
        return true;
      }
      return false;
    }
    return false;
  };

  // node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js
  var DefaultRateLimiter = class _DefaultRateLimiter {
    constructor(options) {
      this.currentCapacity = 0;
      this.enabled = false;
      this.lastMaxRate = 0;
      this.measuredTxRate = 0;
      this.requestCount = 0;
      this.lastTimestamp = 0;
      this.timeWindow = 0;
      this.beta = options?.beta ?? 0.7;
      this.minCapacity = options?.minCapacity ?? 1;
      this.minFillRate = options?.minFillRate ?? 0.5;
      this.scaleConstant = options?.scaleConstant ?? 0.4;
      this.smooth = options?.smooth ?? 0.8;
      const currentTimeInSeconds = this.getCurrentTimeInSeconds();
      this.lastThrottleTime = currentTimeInSeconds;
      this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds());
      this.fillRate = this.minFillRate;
      this.maxCapacity = this.minCapacity;
    }
    getCurrentTimeInSeconds() {
      return Date.now() / 1e3;
    }
    async getSendToken() {
      return this.acquireTokenBucket(1);
    }
    async acquireTokenBucket(amount) {
      if (!this.enabled) {
        return;
      }
      this.refillTokenBucket();
      if (amount > this.currentCapacity) {
        const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
        await new Promise((resolve2) => _DefaultRateLimiter.setTimeoutFn(resolve2, delay));
      }
      this.currentCapacity = this.currentCapacity - amount;
    }
    refillTokenBucket() {
      const timestamp = this.getCurrentTimeInSeconds();
      if (!this.lastTimestamp) {
        this.lastTimestamp = timestamp;
        return;
      }
      const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate;
      this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount);
      this.lastTimestamp = timestamp;
    }
    updateClientSendingRate(response) {
      let calculatedRate;
      this.updateMeasuredRate();
      if (isThrottlingError(response)) {
        const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate);
        this.lastMaxRate = rateToUse;
        this.calculateTimeWindow();
        this.lastThrottleTime = this.getCurrentTimeInSeconds();
        calculatedRate = this.cubicThrottle(rateToUse);
        this.enableTokenBucket();
      } else {
        this.calculateTimeWindow();
        calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds());
      }
      const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate);
      this.updateTokenBucketRate(newRate);
    }
    calculateTimeWindow() {
      this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3));
    }
    cubicThrottle(rateToUse) {
      return this.getPrecise(rateToUse * this.beta);
    }
    cubicSuccess(timestamp) {
      return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate);
    }
    enableTokenBucket() {
      this.enabled = true;
    }
    updateTokenBucketRate(newRate) {
      this.refillTokenBucket();
      this.fillRate = Math.max(newRate, this.minFillRate);
      this.maxCapacity = Math.max(newRate, this.minCapacity);
      this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity);
    }
    updateMeasuredRate() {
      const t4 = this.getCurrentTimeInSeconds();
      const timeBucket = Math.floor(t4 * 2) / 2;
      this.requestCount++;
      if (timeBucket > this.lastTxRateBucket) {
        const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket);
        this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth));
        this.requestCount = 0;
        this.lastTxRateBucket = timeBucket;
      }
    }
    getPrecise(num) {
      return parseFloat(num.toFixed(8));
    }
  };
  DefaultRateLimiter.setTimeoutFn = setTimeout;

  // node_modules/@smithy/util-retry/dist-es/constants.js
  var DEFAULT_RETRY_DELAY_BASE = 100;
  var MAXIMUM_RETRY_DELAY = 20 * 1e3;
  var THROTTLING_RETRY_DELAY_BASE = 500;
  var INITIAL_RETRY_TOKENS = 500;
  var RETRY_COST = 5;
  var TIMEOUT_RETRY_COST = 10;
  var NO_RETRY_INCREMENT = 1;
  var INVOCATION_ID_HEADER = "amz-sdk-invocation-id";
  var REQUEST_HEADER = "amz-sdk-request";

  // node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js
  var getDefaultRetryBackoffStrategy = () => {
    let delayBase = DEFAULT_RETRY_DELAY_BASE;
    const computeNextBackoffDelay = (attempts) => {
      return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase));
    };
    const setDelayBase = (delay) => {
      delayBase = delay;
    };
    return {
      computeNextBackoffDelay,
      setDelayBase
    };
  };

  // node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js
  var createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => {
    const getRetryCount = () => retryCount;
    const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay);
    const getRetryCost = () => retryCost;
    return {
      getRetryCount,
      getRetryDelay,
      getRetryCost
    };
  };

  // node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js
  var StandardRetryStrategy = class {
    constructor(maxAttempts) {
      this.maxAttempts = maxAttempts;
      this.mode = RETRY_MODES.STANDARD;
      this.capacity = INITIAL_RETRY_TOKENS;
      this.retryBackoffStrategy = getDefaultRetryBackoffStrategy();
      this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts;
    }
    async acquireInitialRetryToken(retryTokenScope) {
      return createDefaultRetryToken({
        retryDelay: DEFAULT_RETRY_DELAY_BASE,
        retryCount: 0
      });
    }
    async refreshRetryTokenForRetry(token, errorInfo) {
      const maxAttempts = await this.getMaxAttempts();
      if (this.shouldRetry(token, errorInfo, maxAttempts)) {
        const errorType = errorInfo.errorType;
        this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE);
        const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());
        const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType;
        const capacityCost = this.getCapacityCost(errorType);
        this.capacity -= capacityCost;
        return createDefaultRetryToken({
          retryDelay,
          retryCount: token.getRetryCount() + 1,
          retryCost: capacityCost
        });
      }
      throw new Error("No retry token available");
    }
    recordSuccess(token) {
      this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT));
    }
    getCapacity() {
      return this.capacity;
    }
    async getMaxAttempts() {
      try {
        return await this.maxAttemptsProvider();
      } catch (error3) {
        console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);
        return DEFAULT_MAX_ATTEMPTS;
      }
    }
    shouldRetry(tokenToRenew, errorInfo, maxAttempts) {
      const attempts = tokenToRenew.getRetryCount() + 1;
      return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType);
    }
    getCapacityCost(errorType) {
      return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST;
    }
    isRetryableError(errorType) {
      return errorType === "THROTTLING" || errorType === "TRANSIENT";
    }
  };

  // node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js
  var AdaptiveRetryStrategy = class {
    constructor(maxAttemptsProvider, options) {
      this.maxAttemptsProvider = maxAttemptsProvider;
      this.mode = RETRY_MODES.ADAPTIVE;
      const { rateLimiter } = options ?? {};
      this.rateLimiter = rateLimiter ?? new DefaultRateLimiter();
      this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider);
    }
    async acquireInitialRetryToken(retryTokenScope) {
      await this.rateLimiter.getSendToken();
      return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);
    }
    async refreshRetryTokenForRetry(tokenToRenew, errorInfo) {
      this.rateLimiter.updateClientSendingRate(errorInfo);
      return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo);
    }
    recordSuccess(token) {
      this.rateLimiter.updateClientSendingRate({});
      this.standardRetryStrategy.recordSuccess(token);
    }
  };

  // node_modules/@smithy/middleware-retry/dist-es/util.js
  var asSdkError = (error3) => {
    if (error3 instanceof Error)
      return error3;
    if (error3 instanceof Object)
      return Object.assign(new Error(), error3);
    if (typeof error3 === "string")
      return new Error(error3);
    return new Error(`AWS SDK error wrapper for ${error3}`);
  };

  // node_modules/@smithy/middleware-retry/dist-es/configurations.js
  var resolveRetryConfig = (input) => {
    const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input;
    const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
    return Object.assign(input, {
      maxAttempts,
      retryStrategy: async () => {
        if (retryStrategy) {
          return retryStrategy;
        }
        const retryMode = await normalizeProvider(_retryMode)();
        if (retryMode === RETRY_MODES.ADAPTIVE) {
          return new AdaptiveRetryStrategy(maxAttempts);
        }
        return new StandardRetryStrategy(maxAttempts);
      }
    });
  };

  // node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js
  var isStreamingPayload = (request2) => request2?.body instanceof ReadableStream;

  // node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js
  var retryMiddleware = (options) => (next, context3) => async (args) => {
    let retryStrategy = await options.retryStrategy();
    const maxAttempts = await options.maxAttempts();
    if (isRetryStrategyV2(retryStrategy)) {
      retryStrategy = retryStrategy;
      let retryToken = await retryStrategy.acquireInitialRetryToken(context3["partition_id"]);
      let lastError = new Error();
      let attempts = 0;
      let totalRetryDelay = 0;
      const { request: request2 } = args;
      const isRequest = HttpRequest.isInstance(request2);
      if (isRequest) {
        request2.headers[INVOCATION_ID_HEADER] = v4_default();
      }
      while (true) {
        try {
          if (isRequest) {
            request2.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`;
          }
          const { response, output: output3 } = await next(args);
          retryStrategy.recordSuccess(retryToken);
          output3.$metadata.attempts = attempts + 1;
          output3.$metadata.totalRetryDelay = totalRetryDelay;
          return { response, output: output3 };
        } catch (e4) {
          const retryErrorInfo = getRetryErrorInfo(e4);
          lastError = asSdkError(e4);
          if (isRequest && isStreamingPayload(request2)) {
            (context3.logger instanceof NoOpLogger ? console : context3.logger)?.warn("An error was encountered in a non-retryable streaming request.");
            throw lastError;
          }
          try {
            retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo);
          } catch (refreshError) {
            if (!lastError.$metadata) {
              lastError.$metadata = {};
            }
            lastError.$metadata.attempts = attempts + 1;
            lastError.$metadata.totalRetryDelay = totalRetryDelay;
            throw lastError;
          }
          attempts = retryToken.getRetryCount();
          const delay = retryToken.getRetryDelay();
          totalRetryDelay += delay;
          await new Promise((resolve2) => setTimeout(resolve2, delay));
        }
      }
    } else {
      retryStrategy = retryStrategy;
      if (retryStrategy?.mode)
        context3.userAgent = [...context3.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]];
      return retryStrategy.retry(next, args);
    }
  };
  var isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined";
  var getRetryErrorInfo = (error3) => {
    const errorInfo = {
      error: error3,
      errorType: getRetryErrorType(error3)
    };
    const retryAfterHint = getRetryAfterHint(error3.$response);
    if (retryAfterHint) {
      errorInfo.retryAfterHint = retryAfterHint;
    }
    return errorInfo;
  };
  var getRetryErrorType = (error3) => {
    if (isThrottlingError(error3))
      return "THROTTLING";
    if (isTransientError(error3))
      return "TRANSIENT";
    if (isServerError(error3))
      return "SERVER_ERROR";
    return "CLIENT_ERROR";
  };
  var retryMiddlewareOptions = {
    name: "retryMiddleware",
    tags: ["RETRY"],
    step: "finalizeRequest",
    priority: "high",
    override: true
  };
  var getRetryPlugin = (options) => ({
    applyToStack: (clientStack) => {
      clientStack.add(retryMiddleware(options), retryMiddlewareOptions);
    }
  });
  var getRetryAfterHint = (response) => {
    if (!HttpResponse.isInstance(response))
      return;
    const retryAfterHeaderName = Object.keys(response.headers).find((key2) => key2.toLowerCase() === "retry-after");
    if (!retryAfterHeaderName)
      return;
    const retryAfter = response.headers[retryAfterHeaderName];
    const retryAfterSeconds = Number(retryAfter);
    if (!Number.isNaN(retryAfterSeconds))
      return new Date(retryAfterSeconds * 1e3);
    const retryAfterDate = new Date(retryAfter);
    return retryAfterDate;
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthSchemeProvider.js
  var defaultBedrockRuntimeHttpAuthSchemeParametersProvider = async (config, context3, input) => {
    return {
      operation: getSmithyContext(context3).operation,
      region: await normalizeProvider(config.region)() || (() => {
        throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
      })()
    };
  };
  function createAwsAuthSigv4HttpAuthOption(authParameters) {
    return {
      schemeId: "aws.auth#sigv4",
      signingProperties: {
        name: "bedrock",
        region: authParameters.region
      },
      propertiesExtractor: (config, context3) => ({
        signingProperties: {
          config,
          context: context3
        }
      })
    };
  }
  function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) {
    return {
      schemeId: "smithy.api#httpBearerAuth",
      propertiesExtractor: ({ profile: profile2, filepath, configFilepath, ignoreCache }, context3) => ({
        identityProperties: {
          profile: profile2,
          filepath,
          configFilepath,
          ignoreCache
        }
      })
    };
  }
  var defaultBedrockRuntimeHttpAuthSchemeProvider = (authParameters) => {
    const options = [];
    switch (authParameters.operation) {
      default: {
        options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
        options.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters));
      }
    }
    return options;
  };
  var resolveHttpAuthSchemeConfig = (config) => {
    const token = memoizeIdentityProvider(config.token, isIdentityExpired, doesIdentityRequireRefresh);
    const config_0 = resolveAwsSdkSigV4Config(config);
    return Object.assign(config_0, {
      authSchemePreference: normalizeProvider(config.authSchemePreference ?? []),
      token
    });
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/EndpointParameters.js
  var resolveClientEndpointParameters = (options) => {
    return Object.assign(options, {
      useDualstackEndpoint: options.useDualstackEndpoint ?? false,
      useFipsEndpoint: options.useFipsEndpoint ?? false,
      defaultSigningName: "bedrock"
    });
  };
  var commonParams = {
    UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" },
    Endpoint: { type: "builtInParams", name: "endpoint" },
    Region: { type: "builtInParams", name: "region" },
    UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/package.json
  var package_default2 = {
    name: "@aws-sdk/client-bedrock-runtime",
    description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
    version: "3.864.0",
    scripts: {
      build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
      "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
      "build:es": "tsc -p tsconfig.es.json",
      "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
      "build:types": "tsc -p tsconfig.types.json",
      "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
      clean: "rimraf ./dist-* && rimraf *.tsbuildinfo",
      "extract:docs": "api-extractor run --local",
      "generate:client": "node ../../scripts/generate-clients/single-service --solo bedrock-runtime"
    },
    main: "./dist-cjs/index.js",
    types: "./dist-types/index.d.ts",
    module: "./dist-es/index.js",
    sideEffects: false,
    dependencies: {
      "@aws-crypto/sha256-browser": "5.2.0",
      "@aws-crypto/sha256-js": "5.2.0",
      "@aws-sdk/core": "3.864.0",
      "@aws-sdk/credential-provider-node": "3.864.0",
      "@aws-sdk/eventstream-handler-node": "3.862.0",
      "@aws-sdk/middleware-eventstream": "3.862.0",
      "@aws-sdk/middleware-host-header": "3.862.0",
      "@aws-sdk/middleware-logger": "3.862.0",
      "@aws-sdk/middleware-recursion-detection": "3.862.0",
      "@aws-sdk/middleware-user-agent": "3.864.0",
      "@aws-sdk/middleware-websocket": "3.862.0",
      "@aws-sdk/region-config-resolver": "3.862.0",
      "@aws-sdk/token-providers": "3.864.0",
      "@aws-sdk/types": "3.862.0",
      "@aws-sdk/util-endpoints": "3.862.0",
      "@aws-sdk/util-user-agent-browser": "3.862.0",
      "@aws-sdk/util-user-agent-node": "3.864.0",
      "@smithy/config-resolver": "^4.1.5",
      "@smithy/core": "^3.8.0",
      "@smithy/eventstream-serde-browser": "^4.0.5",
      "@smithy/eventstream-serde-config-resolver": "^4.1.3",
      "@smithy/eventstream-serde-node": "^4.0.5",
      "@smithy/fetch-http-handler": "^5.1.1",
      "@smithy/hash-node": "^4.0.5",
      "@smithy/invalid-dependency": "^4.0.5",
      "@smithy/middleware-content-length": "^4.0.5",
      "@smithy/middleware-endpoint": "^4.1.18",
      "@smithy/middleware-retry": "^4.1.19",
      "@smithy/middleware-serde": "^4.0.9",
      "@smithy/middleware-stack": "^4.0.5",
      "@smithy/node-config-provider": "^4.1.4",
      "@smithy/node-http-handler": "^4.1.1",
      "@smithy/protocol-http": "^5.1.3",
      "@smithy/smithy-client": "^4.4.10",
      "@smithy/types": "^4.3.2",
      "@smithy/url-parser": "^4.0.5",
      "@smithy/util-base64": "^4.0.0",
      "@smithy/util-body-length-browser": "^4.0.0",
      "@smithy/util-body-length-node": "^4.0.0",
      "@smithy/util-defaults-mode-browser": "^4.0.26",
      "@smithy/util-defaults-mode-node": "^4.0.26",
      "@smithy/util-endpoints": "^3.0.7",
      "@smithy/util-middleware": "^4.0.5",
      "@smithy/util-retry": "^4.0.7",
      "@smithy/util-stream": "^4.2.4",
      "@smithy/util-utf8": "^4.0.0",
      "@types/uuid": "^9.0.1",
      tslib: "^2.6.2",
      uuid: "^9.0.1"
    },
    devDependencies: {
      "@tsconfig/node18": "18.2.4",
      "@types/node": "^18.19.69",
      concurrently: "7.0.0",
      "downlevel-dts": "0.10.1",
      rimraf: "3.0.2",
      typescript: "~5.8.3"
    },
    engines: {
      node: ">=18.0.0"
    },
    typesVersions: {
      "<4.0": {
        "dist-types/*": [
          "dist-types/ts3.4/*"
        ]
      }
    },
    files: [
      "dist-*/**"
    ],
    author: {
      name: "AWS SDK for JavaScript Team",
      url: "https://aws.amazon.com/javascript/"
    },
    license: "Apache-2.0",
    browser: {
      "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser"
    },
    "react-native": {
      "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native"
    },
    homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-bedrock-runtime",
    repository: {
      type: "git",
      url: "https://github.com/aws/aws-sdk-js-v3.git",
      directory: "clients/client-bedrock-runtime"
    }
  };

  // node_modules/@aws-crypto/sha256-browser/build/module/constants.js
  var SHA_256_HASH = { name: "SHA-256" };
  var SHA_256_HMAC_ALGO = {
    name: "HMAC",
    hash: SHA_256_HASH
  };
  var EMPTY_DATA_SHA_256 = new Uint8Array([
    227,
    176,
    196,
    66,
    152,
    252,
    28,
    20,
    154,
    251,
    244,
    200,
    153,
    111,
    185,
    36,
    39,
    174,
    65,
    228,
    100,
    155,
    147,
    76,
    164,
    149,
    153,
    27,
    120,
    82,
    184,
    85
  ]);

  // node_modules/@aws-sdk/util-locate-window/dist-es/index.js
  var fallbackWindow = {};
  function locateWindow() {
    if (typeof window !== "undefined") {
      return window;
    } else if (typeof self !== "undefined") {
      return self;
    }
    return fallbackWindow;
  }

  // node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js
  var Sha256 = (
    /** @class */
    function() {
      function Sha2564(secret) {
        this.toHash = new Uint8Array(0);
        this.secret = secret;
        this.reset();
      }
      Sha2564.prototype.update = function(data3) {
        if (isEmptyData(data3)) {
          return;
        }
        var update3 = convertToBuffer(data3);
        var typedArray = new Uint8Array(this.toHash.byteLength + update3.byteLength);
        typedArray.set(this.toHash, 0);
        typedArray.set(update3, this.toHash.byteLength);
        this.toHash = typedArray;
      };
      Sha2564.prototype.digest = function() {
        var _this = this;
        if (this.key) {
          return this.key.then(function(key2) {
            return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO, key2, _this.toHash).then(function(data3) {
              return new Uint8Array(data3);
            });
          });
        }
        if (isEmptyData(this.toHash)) {
          return Promise.resolve(EMPTY_DATA_SHA_256);
        }
        return Promise.resolve().then(function() {
          return locateWindow().crypto.subtle.digest(SHA_256_HASH, _this.toHash);
        }).then(function(data3) {
          return Promise.resolve(new Uint8Array(data3));
        });
      };
      Sha2564.prototype.reset = function() {
        var _this = this;
        this.toHash = new Uint8Array(0);
        if (this.secret && this.secret !== void 0) {
          this.key = new Promise(function(resolve2, reject) {
            locateWindow().crypto.subtle.importKey("raw", convertToBuffer(_this.secret), SHA_256_HMAC_ALGO, false, ["sign"]).then(resolve2, reject);
          });
          this.key.catch(function() {
          });
        }
      };
      return Sha2564;
    }()
  );

  // node_modules/@aws-crypto/sha256-js/build/module/constants.js
  var BLOCK_SIZE = 64;
  var DIGEST_LENGTH = 32;
  var KEY2 = new Uint32Array([
    1116352408,
    1899447441,
    3049323471,
    3921009573,
    961987163,
    1508970993,
    2453635748,
    2870763221,
    3624381080,
    310598401,
    607225278,
    1426881987,
    1925078388,
    2162078206,
    2614888103,
    3248222580,
    3835390401,
    4022224774,
    264347078,
    604807628,
    770255983,
    1249150122,
    1555081692,
    1996064986,
    2554220882,
    2821834349,
    2952996808,
    3210313671,
    3336571891,
    3584528711,
    113926993,
    338241895,
    666307205,
    773529912,
    1294757372,
    1396182291,
    1695183700,
    1986661051,
    2177026350,
    2456956037,
    2730485921,
    2820302411,
    3259730800,
    3345764771,
    3516065817,
    3600352804,
    4094571909,
    275423344,
    430227734,
    506948616,
    659060556,
    883997877,
    958139571,
    1322822218,
    1537002063,
    1747873779,
    1955562222,
    2024104815,
    2227730452,
    2361852424,
    2428436474,
    2756734187,
    3204031479,
    3329325298
  ]);
  var INIT2 = [
    1779033703,
    3144134277,
    1013904242,
    2773480762,
    1359893119,
    2600822924,
    528734635,
    1541459225
  ];
  var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;

  // node_modules/@aws-crypto/sha256-js/build/module/RawSha256.js
  var RawSha256 = (
    /** @class */
    function() {
      function RawSha2562() {
        this.state = Int32Array.from(INIT2);
        this.temp = new Int32Array(64);
        this.buffer = new Uint8Array(64);
        this.bufferLength = 0;
        this.bytesHashed = 0;
        this.finished = false;
      }
      RawSha2562.prototype.update = function(data3) {
        if (this.finished) {
          throw new Error("Attempted to update an already finished hash.");
        }
        var position2 = 0;
        var byteLength = data3.byteLength;
        this.bytesHashed += byteLength;
        if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) {
          throw new Error("Cannot hash more than 2^53 - 1 bits");
        }
        while (byteLength > 0) {
          this.buffer[this.bufferLength++] = data3[position2++];
          byteLength--;
          if (this.bufferLength === BLOCK_SIZE) {
            this.hashBuffer();
            this.bufferLength = 0;
          }
        }
      };
      RawSha2562.prototype.digest = function() {
        if (!this.finished) {
          var bitsHashed = this.bytesHashed * 8;
          var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
          var undecoratedLength = this.bufferLength;
          bufferView.setUint8(this.bufferLength++, 128);
          if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) {
            for (var i2 = this.bufferLength; i2 < BLOCK_SIZE; i2++) {
              bufferView.setUint8(i2, 0);
            }
            this.hashBuffer();
            this.bufferLength = 0;
          }
          for (var i2 = this.bufferLength; i2 < BLOCK_SIZE - 8; i2++) {
            bufferView.setUint8(i2, 0);
          }
          bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 4294967296), true);
          bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed);
          this.hashBuffer();
          this.finished = true;
        }
        var out = new Uint8Array(DIGEST_LENGTH);
        for (var i2 = 0; i2 < 8; i2++) {
          out[i2 * 4] = this.state[i2] >>> 24 & 255;
          out[i2 * 4 + 1] = this.state[i2] >>> 16 & 255;
          out[i2 * 4 + 2] = this.state[i2] >>> 8 & 255;
          out[i2 * 4 + 3] = this.state[i2] >>> 0 & 255;
        }
        return out;
      };
      RawSha2562.prototype.hashBuffer = function() {
        var _a2 = this, buffer = _a2.buffer, state = _a2.state;
        var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];
        for (var i2 = 0; i2 < BLOCK_SIZE; i2++) {
          if (i2 < 16) {
            this.temp[i2] = (buffer[i2 * 4] & 255) << 24 | (buffer[i2 * 4 + 1] & 255) << 16 | (buffer[i2 * 4 + 2] & 255) << 8 | buffer[i2 * 4 + 3] & 255;
          } else {
            var u5 = this.temp[i2 - 2];
            var t1_1 = (u5 >>> 17 | u5 << 15) ^ (u5 >>> 19 | u5 << 13) ^ u5 >>> 10;
            u5 = this.temp[i2 - 15];
            var t2_1 = (u5 >>> 7 | u5 << 25) ^ (u5 >>> 18 | u5 << 14) ^ u5 >>> 3;
            this.temp[i2] = (t1_1 + this.temp[i2 - 7] | 0) + (t2_1 + this.temp[i2 - 16] | 0);
          }
          var t13 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (KEY2[i2] + this.temp[i2] | 0) | 0) | 0;
          var t22 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0;
          state7 = state6;
          state6 = state5;
          state5 = state4;
          state4 = state3 + t13 | 0;
          state3 = state2;
          state2 = state1;
          state1 = state0;
          state0 = t13 + t22 | 0;
        }
        state[0] += state0;
        state[1] += state1;
        state[2] += state2;
        state[3] += state3;
        state[4] += state4;
        state[5] += state5;
        state[6] += state6;
        state[7] += state7;
      };
      return RawSha2562;
    }()
  );

  // node_modules/@aws-crypto/sha256-js/build/module/jsSha256.js
  var Sha2562 = (
    /** @class */
    function() {
      function Sha2564(secret) {
        this.secret = secret;
        this.hash = new RawSha256();
        this.reset();
      }
      Sha2564.prototype.update = function(toHash) {
        if (isEmptyData(toHash) || this.error) {
          return;
        }
        try {
          this.hash.update(convertToBuffer(toHash));
        } catch (e4) {
          this.error = e4;
        }
      };
      Sha2564.prototype.digestSync = function() {
        if (this.error) {
          throw this.error;
        }
        if (this.outer) {
          if (!this.outer.finished) {
            this.outer.update(this.hash.digest());
          }
          return this.outer.digest();
        }
        return this.hash.digest();
      };
      Sha2564.prototype.digest = function() {
        return __awaiter(this, void 0, void 0, function() {
          return __generator(this, function(_a2) {
            return [2, this.digestSync()];
          });
        });
      };
      Sha2564.prototype.reset = function() {
        this.hash = new RawSha256();
        if (this.secret) {
          this.outer = new RawSha256();
          var inner = bufferFromSecret(this.secret);
          var outer = new Uint8Array(BLOCK_SIZE);
          outer.set(inner);
          for (var i2 = 0; i2 < BLOCK_SIZE; i2++) {
            inner[i2] ^= 54;
            outer[i2] ^= 92;
          }
          this.hash.update(inner);
          this.outer.update(outer);
          for (var i2 = 0; i2 < inner.byteLength; i2++) {
            inner[i2] = 0;
          }
        }
      };
      return Sha2564;
    }()
  );
  function bufferFromSecret(secret) {
    var input = convertToBuffer(secret);
    if (input.byteLength > BLOCK_SIZE) {
      var bufferHash = new RawSha256();
      bufferHash.update(input);
      input = bufferHash.digest();
    }
    var buffer = new Uint8Array(BLOCK_SIZE);
    buffer.set(input);
    return buffer;
  }

  // node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js
  var subtleCryptoMethods = [
    "decrypt",
    "digest",
    "encrypt",
    "exportKey",
    "generateKey",
    "importKey",
    "sign",
    "verify"
  ];
  function supportsWebCrypto(window2) {
    if (supportsSecureRandom(window2) && typeof window2.crypto.subtle === "object") {
      var subtle = window2.crypto.subtle;
      return supportsSubtleCrypto(subtle);
    }
    return false;
  }
  function supportsSecureRandom(window2) {
    if (typeof window2 === "object" && typeof window2.crypto === "object") {
      var getRandomValues2 = window2.crypto.getRandomValues;
      return typeof getRandomValues2 === "function";
    }
    return false;
  }
  function supportsSubtleCrypto(subtle) {
    return subtle && subtleCryptoMethods.every(function(methodName) {
      return typeof subtle[methodName] === "function";
    });
  }

  // node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js
  var Sha2563 = (
    /** @class */
    function() {
      function Sha2564(secret) {
        if (supportsWebCrypto(locateWindow())) {
          this.hash = new Sha256(secret);
        } else {
          this.hash = new Sha2562(secret);
        }
      }
      Sha2564.prototype.update = function(data3, encoding) {
        this.hash.update(convertToBuffer(data3));
      };
      Sha2564.prototype.digest = function() {
        return this.hash.digest();
      };
      Sha2564.prototype.reset = function() {
        this.hash.reset();
      };
      return Sha2564;
    }()
  );

  // node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js
  var import_bowser = __toESM(require_es5());
  var createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => async (config) => {
    const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser.default.parse(window.navigator.userAgent) : void 0;
    const sections = [
      ["aws-sdk-js", clientVersion],
      ["ua", "2.1"],
      [`os/${parsedUA?.os?.name || "other"}`, parsedUA?.os?.version],
      ["lang/js"],
      ["md/browser", `${parsedUA?.browser?.name ?? "unknown"}_${parsedUA?.browser?.version ?? "unknown"}`]
    ];
    if (serviceId) {
      sections.push([`api/${serviceId}`, clientVersion]);
    }
    const appId = await config?.userAgentAppId?.();
    if (appId) {
      sections.push([`app/${appId}`]);
    }
    return sections;
  };

  // node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js
  var invalidProvider = (message) => () => Promise.reject(message);

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/ruleset.js
  var s = "required";
  var t = "fn";
  var u4 = "argv";
  var v2 = "ref";
  var a3 = true;
  var b2 = "isSet";
  var c3 = "booleanEquals";
  var d = "error";
  var e3 = "endpoint";
  var f = "tree";
  var g = "PartitionResult";
  var h2 = { [s]: false, "type": "String" };
  var i = { [s]: true, "default": false, "type": "Boolean" };
  var j = { [v2]: "Endpoint" };
  var k = { [t]: c3, [u4]: [{ [v2]: "UseFIPS" }, true] };
  var l = { [t]: c3, [u4]: [{ [v2]: "UseDualStack" }, true] };
  var m3 = {};
  var n = { [t]: "getAttr", [u4]: [{ [v2]: g }, "supportsFIPS"] };
  var o = { [t]: c3, [u4]: [true, { [t]: "getAttr", [u4]: [{ [v2]: g }, "supportsDualStack"] }] };
  var p = [k];
  var q = [l];
  var r = [{ [v2]: "Region" }];
  var _data = { version: "1.0", parameters: { Region: h2, UseDualStack: i, UseFIPS: i, Endpoint: h2 }, rules: [{ conditions: [{ [t]: b2, [u4]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m3, headers: m3 }, type: e3 }], type: f }], type: f }, { rules: [{ conditions: [{ [t]: b2, [u4]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u4]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c3, [u4]: [a3, n] }, o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m3, headers: m3 }, type: e3 }], type: f }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c3, [u4]: [n, a3] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m3, headers: m3 }, type: e3 }], type: f }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m3, headers: m3 }, type: e3 }], type: f }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", properties: m3, headers: m3 }, type: e3 }], type: f }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] };
  var ruleSet = _data;

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/endpointResolver.js
  var cache2 = new EndpointCache({
    size: 50,
    params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"]
  });
  var defaultEndpointResolver = (endpointParams, context3 = {}) => {
    return cache2.get(endpointParams, () => resolveEndpoint(ruleSet, {
      endpointParams,
      logger: context3.logger
    }));
  };
  customEndpointFunctions.aws = awsEndpointFunctions;

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.shared.js
  var getRuntimeConfig = (config) => {
    return {
      apiVersion: "2023-09-30",
      base64Decoder: config?.base64Decoder ?? fromBase64,
      base64Encoder: config?.base64Encoder ?? toBase64,
      disableHostPrefix: config?.disableHostPrefix ?? false,
      endpointProvider: config?.endpointProvider ?? defaultEndpointResolver,
      extensions: config?.extensions ?? [],
      httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultBedrockRuntimeHttpAuthSchemeProvider,
      httpAuthSchemes: config?.httpAuthSchemes ?? [
        {
          schemeId: "aws.auth#sigv4",
          identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
          signer: new AwsSdkSigV4Signer()
        },
        {
          schemeId: "smithy.api#httpBearerAuth",
          identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"),
          signer: new HttpBearerAuthSigner()
        }
      ],
      logger: config?.logger ?? new NoOpLogger(),
      serviceId: config?.serviceId ?? "Bedrock Runtime",
      urlParser: config?.urlParser ?? parseUrl,
      utf8Decoder: config?.utf8Decoder ?? fromUtf8,
      utf8Encoder: config?.utf8Encoder ?? toUtf8
    };
  };

  // node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js
  var import_bowser2 = __toESM(require_es5());

  // node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js
  var DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"];

  // node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js
  var resolveDefaultsModeConfig = ({ defaultsMode } = {}) => memoize2(async () => {
    const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode;
    switch (mode?.toLowerCase()) {
      case "auto":
        return Promise.resolve(isMobileBrowser() ? "mobile" : "standard");
      case "mobile":
      case "in-region":
      case "cross-region":
      case "standard":
      case "legacy":
        return Promise.resolve(mode?.toLocaleLowerCase());
      case void 0:
        return Promise.resolve("legacy");
      default:
        throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`);
    }
  });
  var isMobileBrowser = () => {
    const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser2.default.parse(window.navigator.userAgent) : void 0;
    const platform = parsedUA?.platform?.type;
    return platform === "tablet" || platform === "mobile";
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.browser.js
  var getRuntimeConfig2 = (config) => {
    const defaultsMode = resolveDefaultsModeConfig(config);
    const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode);
    const clientSharedValues = getRuntimeConfig(config);
    return {
      ...clientSharedValues,
      ...config,
      runtime: "browser",
      defaultsMode,
      bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength,
      credentialDefaultProvider: config?.credentialDefaultProvider ?? ((_) => () => Promise.reject(new Error("Credential is missing"))),
      defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default2.version }),
      eventStreamPayloadHandlerProvider: config?.eventStreamPayloadHandlerProvider ?? eventStreamPayloadHandlerProvider,
      eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider,
      maxAttempts: config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
      region: config?.region ?? invalidProvider("Region is missing"),
      requestHandler: WebSocketFetchHandler.create(config?.requestHandler ?? defaultConfigProvider, FetchHttpHandler.create(defaultConfigProvider)),
      retryMode: config?.retryMode ?? (async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE),
      sha256: config?.sha256 ?? Sha2563,
      streamCollector: config?.streamCollector ?? streamCollector,
      useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)),
      useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT))
    };
  };

  // node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js
  var getAwsRegionExtensionConfiguration = (runtimeConfig) => {
    return {
      setRegion(region) {
        runtimeConfig.region = region;
      },
      region() {
        return runtimeConfig.region;
      }
    };
  };
  var resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => {
    return {
      region: awsRegionExtensionConfiguration.region()
    };
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthExtensionConfiguration.js
  var getHttpAuthExtensionConfiguration = (runtimeConfig) => {
    const _httpAuthSchemes = runtimeConfig.httpAuthSchemes;
    let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider;
    let _credentials = runtimeConfig.credentials;
    let _token = runtimeConfig.token;
    return {
      setHttpAuthScheme(httpAuthScheme) {
        const index4 = _httpAuthSchemes.findIndex((scheme3) => scheme3.schemeId === httpAuthScheme.schemeId);
        if (index4 === -1) {
          _httpAuthSchemes.push(httpAuthScheme);
        } else {
          _httpAuthSchemes.splice(index4, 1, httpAuthScheme);
        }
      },
      httpAuthSchemes() {
        return _httpAuthSchemes;
      },
      setHttpAuthSchemeProvider(httpAuthSchemeProvider) {
        _httpAuthSchemeProvider = httpAuthSchemeProvider;
      },
      httpAuthSchemeProvider() {
        return _httpAuthSchemeProvider;
      },
      setCredentials(credentials) {
        _credentials = credentials;
      },
      credentials() {
        return _credentials;
      },
      setToken(token) {
        _token = token;
      },
      token() {
        return _token;
      }
    };
  };
  var resolveHttpAuthRuntimeConfig = (config) => {
    return {
      httpAuthSchemes: config.httpAuthSchemes(),
      httpAuthSchemeProvider: config.httpAuthSchemeProvider(),
      credentials: config.credentials(),
      token: config.token()
    };
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeExtensions.js
  var resolveRuntimeExtensions = (runtimeConfig, extensions) => {
    const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig));
    extensions.forEach((extension2) => extension2.configure(extensionConfiguration));
    return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration));
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/BedrockRuntimeClient.js
  var BedrockRuntimeClient = class extends Client {
    config;
    constructor(...[configuration]) {
      const _config_0 = getRuntimeConfig2(configuration || {});
      super(_config_0);
      this.initConfig = _config_0;
      const _config_1 = resolveClientEndpointParameters(_config_0);
      const _config_2 = resolveUserAgentConfig(_config_1);
      const _config_3 = resolveRetryConfig(_config_2);
      const _config_4 = resolveRegionConfig(_config_3);
      const _config_5 = resolveHostHeaderConfig(_config_4);
      const _config_6 = resolveEndpointConfig(_config_5);
      const _config_7 = resolveEventStreamSerdeConfig(_config_6);
      const _config_8 = resolveHttpAuthSchemeConfig(_config_7);
      const _config_9 = resolveEventStreamConfig(_config_8);
      const _config_10 = resolveWebSocketConfig(_config_9);
      const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []);
      this.config = _config_11;
      this.middlewareStack.use(getUserAgentPlugin(this.config));
      this.middlewareStack.use(getRetryPlugin(this.config));
      this.middlewareStack.use(getContentLengthPlugin(this.config));
      this.middlewareStack.use(getHostHeaderPlugin(this.config));
      this.middlewareStack.use(getLoggerPlugin(this.config));
      this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
      this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, {
        httpAuthSchemeParametersProvider: defaultBedrockRuntimeHttpAuthSchemeParametersProvider,
        identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({
          "aws.auth#sigv4": config.credentials,
          "smithy.api#httpBearerAuth": config.token
        })
      }));
      this.middlewareStack.use(getHttpSigningPlugin(this.config));
    }
    destroy() {
      super.destroy();
    }
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/BedrockRuntimeServiceException.js
  var BedrockRuntimeServiceException = class _BedrockRuntimeServiceException extends ServiceException {
    constructor(options) {
      super(options);
      Object.setPrototypeOf(this, _BedrockRuntimeServiceException.prototype);
    }
  };

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/models_0.js
  var AccessDeniedException = class _AccessDeniedException extends BedrockRuntimeServiceException {
    name = "AccessDeniedException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "AccessDeniedException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _AccessDeniedException.prototype);
    }
  };
  var AsyncInvokeOutputDataConfig;
  (function(AsyncInvokeOutputDataConfig2) {
    AsyncInvokeOutputDataConfig2.visit = (value3, visitor) => {
      if (value3.s3OutputDataConfig !== void 0)
        return visitor.s3OutputDataConfig(value3.s3OutputDataConfig);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(AsyncInvokeOutputDataConfig || (AsyncInvokeOutputDataConfig = {}));
  var InternalServerException = class _InternalServerException extends BedrockRuntimeServiceException {
    name = "InternalServerException";
    $fault = "server";
    constructor(opts) {
      super({
        name: "InternalServerException",
        $fault: "server",
        ...opts
      });
      Object.setPrototypeOf(this, _InternalServerException.prototype);
    }
  };
  var ThrottlingException = class _ThrottlingException extends BedrockRuntimeServiceException {
    name = "ThrottlingException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ThrottlingException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ThrottlingException.prototype);
    }
  };
  var ValidationException = class _ValidationException extends BedrockRuntimeServiceException {
    name = "ValidationException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ValidationException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ValidationException.prototype);
    }
  };
  var ConflictException = class _ConflictException extends BedrockRuntimeServiceException {
    name = "ConflictException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ConflictException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ConflictException.prototype);
    }
  };
  var ResourceNotFoundException = class _ResourceNotFoundException extends BedrockRuntimeServiceException {
    name = "ResourceNotFoundException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ResourceNotFoundException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ResourceNotFoundException.prototype);
    }
  };
  var ServiceQuotaExceededException = class _ServiceQuotaExceededException extends BedrockRuntimeServiceException {
    name = "ServiceQuotaExceededException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ServiceQuotaExceededException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ServiceQuotaExceededException.prototype);
    }
  };
  var ServiceUnavailableException = class _ServiceUnavailableException extends BedrockRuntimeServiceException {
    name = "ServiceUnavailableException";
    $fault = "server";
    constructor(opts) {
      super({
        name: "ServiceUnavailableException",
        $fault: "server",
        ...opts
      });
      Object.setPrototypeOf(this, _ServiceUnavailableException.prototype);
    }
  };
  var GuardrailImageSource;
  (function(GuardrailImageSource2) {
    GuardrailImageSource2.visit = (value3, visitor) => {
      if (value3.bytes !== void 0)
        return visitor.bytes(value3.bytes);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(GuardrailImageSource || (GuardrailImageSource = {}));
  var GuardrailContentBlock;
  (function(GuardrailContentBlock2) {
    GuardrailContentBlock2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.image !== void 0)
        return visitor.image(value3.image);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(GuardrailContentBlock || (GuardrailContentBlock = {}));
  var GuardrailAutomatedReasoningFinding;
  (function(GuardrailAutomatedReasoningFinding2) {
    GuardrailAutomatedReasoningFinding2.visit = (value3, visitor) => {
      if (value3.valid !== void 0)
        return visitor.valid(value3.valid);
      if (value3.invalid !== void 0)
        return visitor.invalid(value3.invalid);
      if (value3.satisfiable !== void 0)
        return visitor.satisfiable(value3.satisfiable);
      if (value3.impossible !== void 0)
        return visitor.impossible(value3.impossible);
      if (value3.translationAmbiguous !== void 0)
        return visitor.translationAmbiguous(value3.translationAmbiguous);
      if (value3.tooComplex !== void 0)
        return visitor.tooComplex(value3.tooComplex);
      if (value3.noTranslations !== void 0)
        return visitor.noTranslations(value3.noTranslations);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(GuardrailAutomatedReasoningFinding || (GuardrailAutomatedReasoningFinding = {}));
  var CitationLocation;
  (function(CitationLocation2) {
    CitationLocation2.visit = (value3, visitor) => {
      if (value3.documentChar !== void 0)
        return visitor.documentChar(value3.documentChar);
      if (value3.documentPage !== void 0)
        return visitor.documentPage(value3.documentPage);
      if (value3.documentChunk !== void 0)
        return visitor.documentChunk(value3.documentChunk);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(CitationLocation || (CitationLocation = {}));
  var CitationSourceContent;
  (function(CitationSourceContent2) {
    CitationSourceContent2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(CitationSourceContent || (CitationSourceContent = {}));
  var CitationGeneratedContent;
  (function(CitationGeneratedContent2) {
    CitationGeneratedContent2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(CitationGeneratedContent || (CitationGeneratedContent = {}));
  var DocumentContentBlock;
  (function(DocumentContentBlock2) {
    DocumentContentBlock2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(DocumentContentBlock || (DocumentContentBlock = {}));
  var DocumentSource;
  (function(DocumentSource2) {
    DocumentSource2.visit = (value3, visitor) => {
      if (value3.bytes !== void 0)
        return visitor.bytes(value3.bytes);
      if (value3.s3Location !== void 0)
        return visitor.s3Location(value3.s3Location);
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.content !== void 0)
        return visitor.content(value3.content);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(DocumentSource || (DocumentSource = {}));
  var GuardrailConverseImageSource;
  (function(GuardrailConverseImageSource2) {
    GuardrailConverseImageSource2.visit = (value3, visitor) => {
      if (value3.bytes !== void 0)
        return visitor.bytes(value3.bytes);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(GuardrailConverseImageSource || (GuardrailConverseImageSource = {}));
  var GuardrailConverseContentBlock;
  (function(GuardrailConverseContentBlock2) {
    GuardrailConverseContentBlock2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.image !== void 0)
        return visitor.image(value3.image);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(GuardrailConverseContentBlock || (GuardrailConverseContentBlock = {}));
  var ImageSource;
  (function(ImageSource2) {
    ImageSource2.visit = (value3, visitor) => {
      if (value3.bytes !== void 0)
        return visitor.bytes(value3.bytes);
      if (value3.s3Location !== void 0)
        return visitor.s3Location(value3.s3Location);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ImageSource || (ImageSource = {}));
  var ReasoningContentBlock;
  (function(ReasoningContentBlock2) {
    ReasoningContentBlock2.visit = (value3, visitor) => {
      if (value3.reasoningText !== void 0)
        return visitor.reasoningText(value3.reasoningText);
      if (value3.redactedContent !== void 0)
        return visitor.redactedContent(value3.redactedContent);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ReasoningContentBlock || (ReasoningContentBlock = {}));
  var VideoSource;
  (function(VideoSource2) {
    VideoSource2.visit = (value3, visitor) => {
      if (value3.bytes !== void 0)
        return visitor.bytes(value3.bytes);
      if (value3.s3Location !== void 0)
        return visitor.s3Location(value3.s3Location);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(VideoSource || (VideoSource = {}));
  var ToolResultContentBlock;
  (function(ToolResultContentBlock2) {
    ToolResultContentBlock2.visit = (value3, visitor) => {
      if (value3.json !== void 0)
        return visitor.json(value3.json);
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.image !== void 0)
        return visitor.image(value3.image);
      if (value3.document !== void 0)
        return visitor.document(value3.document);
      if (value3.video !== void 0)
        return visitor.video(value3.video);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ToolResultContentBlock || (ToolResultContentBlock = {}));
  var ContentBlock;
  (function(ContentBlock2) {
    ContentBlock2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.image !== void 0)
        return visitor.image(value3.image);
      if (value3.document !== void 0)
        return visitor.document(value3.document);
      if (value3.video !== void 0)
        return visitor.video(value3.video);
      if (value3.toolUse !== void 0)
        return visitor.toolUse(value3.toolUse);
      if (value3.toolResult !== void 0)
        return visitor.toolResult(value3.toolResult);
      if (value3.guardContent !== void 0)
        return visitor.guardContent(value3.guardContent);
      if (value3.cachePoint !== void 0)
        return visitor.cachePoint(value3.cachePoint);
      if (value3.reasoningContent !== void 0)
        return visitor.reasoningContent(value3.reasoningContent);
      if (value3.citationsContent !== void 0)
        return visitor.citationsContent(value3.citationsContent);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ContentBlock || (ContentBlock = {}));
  var PromptVariableValues;
  (function(PromptVariableValues2) {
    PromptVariableValues2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(PromptVariableValues || (PromptVariableValues = {}));
  var SystemContentBlock;
  (function(SystemContentBlock2) {
    SystemContentBlock2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.guardContent !== void 0)
        return visitor.guardContent(value3.guardContent);
      if (value3.cachePoint !== void 0)
        return visitor.cachePoint(value3.cachePoint);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(SystemContentBlock || (SystemContentBlock = {}));
  var ToolChoice;
  (function(ToolChoice2) {
    ToolChoice2.visit = (value3, visitor) => {
      if (value3.auto !== void 0)
        return visitor.auto(value3.auto);
      if (value3.any !== void 0)
        return visitor.any(value3.any);
      if (value3.tool !== void 0)
        return visitor.tool(value3.tool);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ToolChoice || (ToolChoice = {}));
  var ToolInputSchema;
  (function(ToolInputSchema2) {
    ToolInputSchema2.visit = (value3, visitor) => {
      if (value3.json !== void 0)
        return visitor.json(value3.json);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ToolInputSchema || (ToolInputSchema = {}));
  var Tool;
  (function(Tool2) {
    Tool2.visit = (value3, visitor) => {
      if (value3.toolSpec !== void 0)
        return visitor.toolSpec(value3.toolSpec);
      if (value3.cachePoint !== void 0)
        return visitor.cachePoint(value3.cachePoint);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(Tool || (Tool = {}));
  var ConverseOutput;
  (function(ConverseOutput2) {
    ConverseOutput2.visit = (value3, visitor) => {
      if (value3.message !== void 0)
        return visitor.message(value3.message);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ConverseOutput || (ConverseOutput = {}));
  var ModelErrorException = class _ModelErrorException extends BedrockRuntimeServiceException {
    name = "ModelErrorException";
    $fault = "client";
    originalStatusCode;
    resourceName;
    constructor(opts) {
      super({
        name: "ModelErrorException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ModelErrorException.prototype);
      this.originalStatusCode = opts.originalStatusCode;
      this.resourceName = opts.resourceName;
    }
  };
  var ModelNotReadyException = class _ModelNotReadyException extends BedrockRuntimeServiceException {
    name = "ModelNotReadyException";
    $fault = "client";
    $retryable = {};
    constructor(opts) {
      super({
        name: "ModelNotReadyException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ModelNotReadyException.prototype);
    }
  };
  var ModelTimeoutException = class _ModelTimeoutException extends BedrockRuntimeServiceException {
    name = "ModelTimeoutException";
    $fault = "client";
    constructor(opts) {
      super({
        name: "ModelTimeoutException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ModelTimeoutException.prototype);
    }
  };
  var ReasoningContentBlockDelta;
  (function(ReasoningContentBlockDelta2) {
    ReasoningContentBlockDelta2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.redactedContent !== void 0)
        return visitor.redactedContent(value3.redactedContent);
      if (value3.signature !== void 0)
        return visitor.signature(value3.signature);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ReasoningContentBlockDelta || (ReasoningContentBlockDelta = {}));
  var ContentBlockDelta;
  (function(ContentBlockDelta2) {
    ContentBlockDelta2.visit = (value3, visitor) => {
      if (value3.text !== void 0)
        return visitor.text(value3.text);
      if (value3.toolUse !== void 0)
        return visitor.toolUse(value3.toolUse);
      if (value3.reasoningContent !== void 0)
        return visitor.reasoningContent(value3.reasoningContent);
      if (value3.citation !== void 0)
        return visitor.citation(value3.citation);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ContentBlockDelta || (ContentBlockDelta = {}));
  var ContentBlockStart;
  (function(ContentBlockStart2) {
    ContentBlockStart2.visit = (value3, visitor) => {
      if (value3.toolUse !== void 0)
        return visitor.toolUse(value3.toolUse);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ContentBlockStart || (ContentBlockStart = {}));
  var ModelStreamErrorException = class _ModelStreamErrorException extends BedrockRuntimeServiceException {
    name = "ModelStreamErrorException";
    $fault = "client";
    originalStatusCode;
    originalMessage;
    constructor(opts) {
      super({
        name: "ModelStreamErrorException",
        $fault: "client",
        ...opts
      });
      Object.setPrototypeOf(this, _ModelStreamErrorException.prototype);
      this.originalStatusCode = opts.originalStatusCode;
      this.originalMessage = opts.originalMessage;
    }
  };
  var ConverseStreamOutput;
  (function(ConverseStreamOutput2) {
    ConverseStreamOutput2.visit = (value3, visitor) => {
      if (value3.messageStart !== void 0)
        return visitor.messageStart(value3.messageStart);
      if (value3.contentBlockStart !== void 0)
        return visitor.contentBlockStart(value3.contentBlockStart);
      if (value3.contentBlockDelta !== void 0)
        return visitor.contentBlockDelta(value3.contentBlockDelta);
      if (value3.contentBlockStop !== void 0)
        return visitor.contentBlockStop(value3.contentBlockStop);
      if (value3.messageStop !== void 0)
        return visitor.messageStop(value3.messageStop);
      if (value3.metadata !== void 0)
        return visitor.metadata(value3.metadata);
      if (value3.internalServerException !== void 0)
        return visitor.internalServerException(value3.internalServerException);
      if (value3.modelStreamErrorException !== void 0)
        return visitor.modelStreamErrorException(value3.modelStreamErrorException);
      if (value3.validationException !== void 0)
        return visitor.validationException(value3.validationException);
      if (value3.throttlingException !== void 0)
        return visitor.throttlingException(value3.throttlingException);
      if (value3.serviceUnavailableException !== void 0)
        return visitor.serviceUnavailableException(value3.serviceUnavailableException);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ConverseStreamOutput || (ConverseStreamOutput = {}));
  var InvokeModelWithBidirectionalStreamInput;
  (function(InvokeModelWithBidirectionalStreamInput2) {
    InvokeModelWithBidirectionalStreamInput2.visit = (value3, visitor) => {
      if (value3.chunk !== void 0)
        return visitor.chunk(value3.chunk);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(InvokeModelWithBidirectionalStreamInput || (InvokeModelWithBidirectionalStreamInput = {}));
  var InvokeModelWithBidirectionalStreamOutput;
  (function(InvokeModelWithBidirectionalStreamOutput2) {
    InvokeModelWithBidirectionalStreamOutput2.visit = (value3, visitor) => {
      if (value3.chunk !== void 0)
        return visitor.chunk(value3.chunk);
      if (value3.internalServerException !== void 0)
        return visitor.internalServerException(value3.internalServerException);
      if (value3.modelStreamErrorException !== void 0)
        return visitor.modelStreamErrorException(value3.modelStreamErrorException);
      if (value3.validationException !== void 0)
        return visitor.validationException(value3.validationException);
      if (value3.throttlingException !== void 0)
        return visitor.throttlingException(value3.throttlingException);
      if (value3.modelTimeoutException !== void 0)
        return visitor.modelTimeoutException(value3.modelTimeoutException);
      if (value3.serviceUnavailableException !== void 0)
        return visitor.serviceUnavailableException(value3.serviceUnavailableException);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(InvokeModelWithBidirectionalStreamOutput || (InvokeModelWithBidirectionalStreamOutput = {}));
  var ResponseStream;
  (function(ResponseStream2) {
    ResponseStream2.visit = (value3, visitor) => {
      if (value3.chunk !== void 0)
        return visitor.chunk(value3.chunk);
      if (value3.internalServerException !== void 0)
        return visitor.internalServerException(value3.internalServerException);
      if (value3.modelStreamErrorException !== void 0)
        return visitor.modelStreamErrorException(value3.modelStreamErrorException);
      if (value3.validationException !== void 0)
        return visitor.validationException(value3.validationException);
      if (value3.throttlingException !== void 0)
        return visitor.throttlingException(value3.throttlingException);
      if (value3.modelTimeoutException !== void 0)
        return visitor.modelTimeoutException(value3.modelTimeoutException);
      if (value3.serviceUnavailableException !== void 0)
        return visitor.serviceUnavailableException(value3.serviceUnavailableException);
      return visitor._(value3.$unknown[0], value3.$unknown[1]);
    };
  })(ResponseStream || (ResponseStream = {}));
  var InvokeModelRequestFilterSensitiveLog = (obj) => ({
    ...obj,
    ...obj.body && { body: SENSITIVE_STRING }
  });
  var InvokeModelResponseFilterSensitiveLog = (obj) => ({
    ...obj,
    ...obj.body && { body: SENSITIVE_STRING }
  });

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/protocols/Aws_restJson1.js
  var se_InvokeModelCommand = async (input, context3) => {
    const b3 = requestBuilder(input, context3);
    const headers = map3({}, isSerializableHeaderValue, {
      [_ct]: input[_cT] || "application/octet-stream",
      [_a]: input[_a],
      [_xabt]: input[_t2],
      [_xabg]: input[_gI],
      [_xabg_]: input[_gV],
      [_xabpl]: input[_pCL]
    });
    b3.bp("/model/{modelId}/invoke");
    b3.p("modelId", () => input.modelId, "{modelId}", false);
    let body;
    if (input.body !== void 0) {
      body = input.body;
    }
    b3.m("POST").h(headers).b(body);
    return b3.build();
  };
  var de_InvokeModelCommand = async (output3, context3) => {
    if (output3.statusCode !== 200 && output3.statusCode >= 300) {
      return de_CommandError(output3, context3);
    }
    const contents = map3({
      $metadata: deserializeMetadata2(output3),
      [_cT]: [, output3.headers[_ct]],
      [_pCL]: [, output3.headers[_xabpl]]
    });
    const data3 = await collectBody(output3.body, context3);
    contents.body = data3;
    return contents;
  };
  var de_CommandError = async (output3, context3) => {
    const parsedOutput = {
      ...output3,
      body: await parseJsonErrorBody(output3.body, context3)
    };
    const errorCode = loadRestJsonErrorCode(output3, parsedOutput.body);
    switch (errorCode) {
      case "AccessDeniedException":
      case "com.amazonaws.bedrockruntime#AccessDeniedException":
        throw await de_AccessDeniedExceptionRes(parsedOutput, context3);
      case "InternalServerException":
      case "com.amazonaws.bedrockruntime#InternalServerException":
        throw await de_InternalServerExceptionRes(parsedOutput, context3);
      case "ResourceNotFoundException":
      case "com.amazonaws.bedrockruntime#ResourceNotFoundException":
        throw await de_ResourceNotFoundExceptionRes(parsedOutput, context3);
      case "ServiceQuotaExceededException":
      case "com.amazonaws.bedrockruntime#ServiceQuotaExceededException":
        throw await de_ServiceQuotaExceededExceptionRes(parsedOutput, context3);
      case "ThrottlingException":
      case "com.amazonaws.bedrockruntime#ThrottlingException":
        throw await de_ThrottlingExceptionRes(parsedOutput, context3);
      case "ValidationException":
      case "com.amazonaws.bedrockruntime#ValidationException":
        throw await de_ValidationExceptionRes(parsedOutput, context3);
      case "ModelErrorException":
      case "com.amazonaws.bedrockruntime#ModelErrorException":
        throw await de_ModelErrorExceptionRes(parsedOutput, context3);
      case "ModelNotReadyException":
      case "com.amazonaws.bedrockruntime#ModelNotReadyException":
        throw await de_ModelNotReadyExceptionRes(parsedOutput, context3);
      case "ModelTimeoutException":
      case "com.amazonaws.bedrockruntime#ModelTimeoutException":
        throw await de_ModelTimeoutExceptionRes(parsedOutput, context3);
      case "ServiceUnavailableException":
      case "com.amazonaws.bedrockruntime#ServiceUnavailableException":
        throw await de_ServiceUnavailableExceptionRes(parsedOutput, context3);
      case "ModelStreamErrorException":
      case "com.amazonaws.bedrockruntime#ModelStreamErrorException":
        throw await de_ModelStreamErrorExceptionRes(parsedOutput, context3);
      case "ConflictException":
      case "com.amazonaws.bedrockruntime#ConflictException":
        throw await de_ConflictExceptionRes(parsedOutput, context3);
      default:
        const parsedBody = parsedOutput.body;
        return throwDefaultError2({
          output: output3,
          parsedBody,
          errorCode
        });
    }
  };
  var throwDefaultError2 = withBaseException(BedrockRuntimeServiceException);
  var de_AccessDeniedExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new AccessDeniedException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ConflictExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ConflictException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_InternalServerExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new InternalServerException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ModelErrorExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString,
      originalStatusCode: expectInt32,
      resourceName: expectString
    });
    Object.assign(contents, doc);
    const exception = new ModelErrorException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ModelNotReadyExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ModelNotReadyException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ModelStreamErrorExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString,
      originalMessage: expectString,
      originalStatusCode: expectInt32
    });
    Object.assign(contents, doc);
    const exception = new ModelStreamErrorException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ModelTimeoutExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ModelTimeoutException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ResourceNotFoundExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ResourceNotFoundException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ServiceQuotaExceededExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ServiceQuotaExceededException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ServiceUnavailableExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ServiceUnavailableException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ThrottlingExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ThrottlingException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var de_ValidationExceptionRes = async (parsedOutput, context3) => {
    const contents = map3({});
    const data3 = parsedOutput.body;
    const doc = take(data3, {
      message: expectString
    });
    Object.assign(contents, doc);
    const exception = new ValidationException({
      $metadata: deserializeMetadata2(parsedOutput),
      ...contents
    });
    return decorateServiceException(exception, parsedOutput.body);
  };
  var deserializeMetadata2 = (output3) => ({
    httpStatusCode: output3.statusCode,
    requestId: output3.headers["x-amzn-requestid"] ?? output3.headers["x-amzn-request-id"] ?? output3.headers["x-amz-request-id"],
    extendedRequestId: output3.headers["x-amz-id-2"],
    cfId: output3.headers["x-amz-cf-id"]
  });
  var _a = "accept";
  var _cT = "contentType";
  var _ct = "content-type";
  var _gI = "guardrailIdentifier";
  var _gV = "guardrailVersion";
  var _pCL = "performanceConfigLatency";
  var _t2 = "trace";
  var _xabg = "x-amzn-bedrock-guardrailidentifier";
  var _xabg_ = "x-amzn-bedrock-guardrailversion";
  var _xabpl = "x-amzn-bedrock-performanceconfig-latency";
  var _xabt = "x-amzn-bedrock-trace";

  // node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelCommand.js
  var InvokeModelCommand = class extends Command.classBuilder().ep(commonParams).m(function(Command2, cs, config, o2) {
    return [
      getSerdePlugin(config, this.serialize, this.deserialize),
      getEndpointPlugin(config, Command2.getEndpointParameterInstructions())
    ];
  }).s("AmazonBedrockFrontendService", "InvokeModel", {}).n("BedrockRuntimeClient", "InvokeModelCommand").f(InvokeModelRequestFilterSensitiveLog, InvokeModelResponseFilterSensitiveLog).ser(se_InvokeModelCommand).de(de_InvokeModelCommand).build() {
  };

  // amazon.ts
  async function sendPromptToAmazon(prompt) {
    const accessKeyIdElement = document.getElementById("aws-access-key");
    const secretAccessKeyElement = document.getElementById("aws-secret-key");
    const regionElement = document.getElementById("aws-region");
    const accessKeyId = accessKeyIdElement?.value || localStorage.getItem("aws-access-key") || "";
    const secretAccessKey = secretAccessKeyElement?.value || localStorage.getItem("aws-secret-key") || "";
    const region = regionElement?.value || localStorage.getItem("aws-region") || "us-east-1";
    const credentials = {
      accessKeyId,
      secretAccessKey
    };
    const client = new BedrockRuntimeClient({
      region,
      credentials
    });
    let body = {};
    const max_tokens = 65536;
    const modelElement = document.getElementById("language-model-amazon");
    const modelId = modelElement?.value ?? "";
    if (modelId.startsWith("us.anthropic")) {
      body = {
        anthropic_version: "bedrock-2023-05-31",
        max_tokens,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "text",
                text: prompt
              }
            ]
          }
        ]
      };
    } else {
      body = {
        max_completion_tokens: max_tokens,
        messages: [
          {
            role: "user",
            content: [
              {
                type: "text",
                text: prompt
              }
            ]
          }
        ]
      };
    }
    const params2 = {
      modelId,
      body: JSON.stringify(body)
    };
    try {
      const command = new InvokeModelCommand(params2);
      const response = await client.send(command);
      const responseBlob = new Blob([response.body]);
      const responseText = await responseBlob.text();
      const parsedResponse = JSON.parse(responseText);
      console.log("parsedResponse = " + responseText);
      if (modelId.startsWith("us.anthropic")) {
        const anthropicResponse = parsedResponse;
        const responseContents = anthropicResponse.content[0].text;
        return responseContents.trim();
      } else {
        const openaiResponse = parsedResponse;
        const responseContents = openaiResponse.choices[0].message.content.replace(
          /<reasoning>[\s\S]*?<\/reasoning>/g,
          ""
        );
        return responseContents.trim();
      }
    } catch (err) {
      const error3 = err;
      console.error(err);
      return `# Error: ${error3.message}`;
    }
  }

  // azure.ts
  async function sendPromptToAzureOpenAI(prompt, apiKey, apiUrl, aiModel) {
    const apiVersionElement = document.getElementById("azure-api-version");
    const apiVersion = apiVersionElement?.value ?? "2024-02-15-preview";
    const endpoint = `${apiUrl}/openai/deployments/${aiModel}/chat/completions?api-version=${apiVersion}`;
    const body = JSON.stringify({
      messages: [
        {
          role: "system",
          content: "You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```."
        },
        {
          role: "user",
          content: prompt
        }
      ],
      user: "scalene-user"
    });
    console.log(body);
    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "api-key": apiKey
      },
      body
    });
    const data3 = await response.json();
    if (data3.error) {
      if (data3.error.code && data3.error.code in {
        invalid_request_error: true,
        model_not_found: true,
        insufficient_quota: true
      }) {
        return "";
      }
    }
    try {
      if (data3.choices && data3.choices[0]) {
        console.log(
          `Debugging info: Retrieved ${JSON.stringify(data3.choices[0], null, 4)}`
        );
      }
    } catch {
      console.log(
        `Debugging info: Failed to retrieve data.choices from the server. data = ${JSON.stringify(data3)}`
      );
    }
    try {
      if (data3.choices && data3.choices[0]) {
        return data3.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
      }
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    } catch {
      return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
    }
  }

  // utils.ts
  function unescapeUnicode(s2) {
    return s2.replace(/\\u([\dA-F]{4})/gi, function(_match, p1) {
      return String.fromCharCode(parseInt(p1, 16));
    });
  }
  function countSpaces(str) {
    const match3 = str.match(/^\s+/);
    if (match3) {
      return match3[0].length;
    }
    return 0;
  }
  function memory_consumed_str(size_in_mb) {
    const gigabytes = Math.floor(size_in_mb / 1024);
    const terabytes = Math.floor(gigabytes / 1024);
    if (terabytes > 0) {
      return `${(size_in_mb / 1048576).toFixed(0)}T`;
    } else if (gigabytes > 0) {
      return `${(size_in_mb / 1024).toFixed(0)}G`;
    } else {
      return `${size_in_mb.toFixed(0)}M`;
    }
  }
  function time_consumed_str(time_in_ms) {
    const hours = Math.floor(time_in_ms / 36e5);
    const minutes = Math.floor(time_in_ms % 36e5 / 6e4);
    const seconds2 = Math.floor(time_in_ms % 6e4 / 1e3);
    const minutes_exact = time_in_ms % 36e5 / 6e4;
    const seconds_exact = time_in_ms % 6e4 / 1e3;
    if (hours > 0) {
      return `${hours.toFixed(0)}h:${minutes_exact.toFixed(0)}m:${seconds_exact.toFixed(3)}s`;
    } else if (minutes >= 1) {
      return `${minutes.toFixed(0)}m:${seconds_exact.toFixed(3)}s`;
    } else if (seconds2 >= 1) {
      return `${seconds_exact.toFixed(3)}s`;
    } else {
      return `${time_in_ms.toFixed(0)}ms`;
    }
  }

  // gui-elements.ts
  var Lightning = "&#9889;";
  var Explosion = "&#128165;";
  var WhiteLightning = `<span style="opacity:0">${Lightning}</span>`;
  var WhiteExplosion = `<span style="opacity:0">${Explosion}</span>`;
  var RightTriangle = "&#9658";
  var DownTriangle = "&#9660";
  function makeTooltip(title2, value3) {
    const secs = value3 / 100 * globalThis.profile.elapsed_time_sec;
    return `(${title2}) ` + value3.toFixed(1) + "% [" + time_consumed_str(secs * 1e3) + "]";
  }
  function makeBar(python, native, system, params2) {
    const widthThreshold1 = 20;
    const widthThreshold2 = 10;
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            x: 0,
            y: python.toFixed(1),
            c: makeTooltip("Python", python),
            d: python >= widthThreshold1 ? python.toFixed(0) + "%" : python >= widthThreshold2 ? python.toFixed(0) : "",
            q: python / 2
          },
          {
            x: 0,
            y: native.toFixed(1),
            c: makeTooltip("native", native),
            d: native >= widthThreshold1 ? native.toFixed(0) + "%" : native >= widthThreshold2 ? native.toFixed(0) : "",
            q: python + native / 2
          },
          {
            x: 0,
            y: system.toFixed(1),
            c: makeTooltip("system", system),
            d: system >= widthThreshold1 ? system.toFixed(0) + "%" : system >= widthThreshold2 ? system.toFixed(0) : "",
            q: python + native + system / 2
          }
        ]
      },
      layer: [
        {
          mark: { type: "bar" },
          encoding: {
            x: {
              aggregate: "sum",
              field: "y",
              axis: false,
              stack: "zero",
              scale: { domain: [0, 100] }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: false,
              scale: { range: ["darkblue", "#6495ED", "blue"] }
            },
            tooltip: [{ field: "c", type: "nominal", title: "time" }]
          }
        },
        {
          mark: {
            type: "text",
            align: "center",
            baseline: "middle",
            dx: 0
          },
          encoding: {
            x: {
              aggregate: "sum",
              field: "q",
              axis: false
            },
            text: { field: "d" },
            color: { value: "white" },
            tooltip: [{ field: "c", type: "nominal", title: "time" }]
          }
        }
      ]
    };
  }
  function makeAwaitPie(await_pct, params2, startAngle = 0) {
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            category: "await",
            value: await_pct.toFixed(1),
            c: "await: " + await_pct.toFixed(1) + "%"
          },
          {
            category: "other",
            value: (100 - await_pct).toFixed(1),
            c: ""
          }
        ]
      },
      mark: "arc",
      encoding: {
        theta: {
          field: "value",
          type: "quantitative",
          scale: {
            range: [startAngle, startAngle + 2 * Math.PI]
          }
        },
        color: {
          field: "category",
          type: "nominal",
          legend: false,
          scale: {
            domain: ["await", "other"],
            range: ["darkcyan", "#e0f2f1"]
          }
        },
        tooltip: [{ field: "c", type: "nominal", title: "await" }]
      }
    };
  }
  function makeGPUPie(util, gpu_device, params2, startAngle = 0) {
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            category: "in use",
            value: util.toFixed(1),
            c: "in use: " + util.toFixed(1) + "%"
          },
          {
            category: "idle",
            value: (100 - util).toFixed(1),
            c: ""
          }
        ]
      },
      mark: "arc",
      encoding: {
        theta: {
          field: "value",
          type: "quantitative",
          scale: {
            range: [startAngle, startAngle + 2 * Math.PI]
          }
        },
        color: {
          field: "category",
          type: "nominal",
          legend: false,
          scale: {
            domain: ["in use", "idle"],
            range: ["goldenrod", "#f4e6c2"]
          }
        },
        tooltip: [{ field: "c", type: "nominal", title: gpu_device }]
      }
    };
  }
  function makeMemoryPie(native_mem, python_mem, params2) {
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      width: params2.width,
      height: 20,
      padding: 0,
      data: {
        values: [
          {
            category: 1,
            value: native_mem.toFixed(1),
            c: "native: " + native_mem.toFixed(1) + "%"
          },
          {
            category: 2,
            value: python_mem.toFixed(1),
            c: "Python: " + python_mem.toFixed(1) + "%"
          }
        ]
      },
      mark: "arc",
      encoding: {
        theta: {
          field: "value",
          type: "quantitative",
          scale: { domain: [0, 100] }
        },
        color: {
          field: "c",
          type: "nominal",
          legend: false,
          scale: { range: ["darkgreen", "#50C878"] }
        },
        tooltip: [{ field: "c", type: "nominal", title: "memory" }]
      }
    };
  }
  function makeMemoryBar(memory, _title, python_percent, total, color5, params2) {
    const memoryNum = typeof memory === "string" ? parseFloat(memory) : memory;
    const totalNum = typeof total === "string" ? parseFloat(total) : total;
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            x: 0,
            y: python_percent * memoryNum,
            c: "(Python) " + memory_consumed_str(python_percent * memoryNum),
            d: python_percent * memoryNum > totalNum * 0.2 ? memory_consumed_str(python_percent * memoryNum) : "",
            q: python_percent * memoryNum / 2
          },
          {
            x: 0,
            y: (1 - python_percent) * memoryNum,
            c: "(native) " + memory_consumed_str((1 - python_percent) * memoryNum),
            d: (1 - python_percent) * memoryNum > totalNum * 0.2 ? memory_consumed_str((1 - python_percent) * memoryNum) : "",
            q: python_percent * memoryNum + (1 - python_percent) * memoryNum / 2
          }
        ]
      },
      layer: [
        {
          mark: { type: "bar" },
          encoding: {
            x: {
              aggregate: "sum",
              field: "y",
              axis: false,
              scale: { domain: [0, totalNum] }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: false,
              scale: { range: [color5, "#50C878", "green"] }
            }
          }
        },
        {
          mark: {
            type: "text",
            align: "center",
            baseline: "middle",
            dx: 0
          },
          encoding: {
            x: {
              aggregate: "sum",
              field: "q",
              axis: false
            },
            text: { field: "d" },
            color: { value: "white" }
          }
        }
      ]
    };
  }
  function makeSparkline(samples, max_x, max_y, leak_velocity = 0, params2) {
    const values4 = samples.map((v3) => {
      let leak_str = "";
      if (leak_velocity != 0) {
        leak_str = `; possible leak (${memory_consumed_str(leak_velocity)}/s)`;
      }
      return {
        x: v3[0],
        y: v3[1],
        y_text: memory_consumed_str(v3[1]) + " (@ " + time_consumed_str(v3[0] / 1e6) + ")" + leak_str
      };
    });
    let leak_info = "";
    let height2 = params2.height;
    if (leak_velocity != 0) {
      leak_info = "possible leak";
      height2 -= 10;
    }
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      data: { values: values4 },
      width: params2.width,
      height: height2,
      padding: 0,
      title: {
        text: leak_info,
        baseline: "line-bottom",
        color: "red",
        offset: 0,
        lineHeight: 10,
        orient: "bottom",
        fontStyle: "italic"
      },
      encoding: {
        x: {
          field: "x",
          type: "quantitative",
          title: "",
          axis: {
            tickCount: 10,
            tickSize: 0,
            labelExpr: ""
          },
          scale: {
            domain: [0, max_x]
          }
        }
      },
      layer: [
        {
          encoding: {
            y: {
              field: "y",
              type: "quantitative",
              axis: null,
              scale: {
                domain: [0, max_y]
              }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: null,
              scale: {
                range: ["darkgreen"]
              }
            }
          },
          layer: [
            { mark: "line" },
            {
              transform: [{ filter: { param: "hover", empty: false } }],
              mark: "point"
            }
          ]
        },
        {
          mark: "rule",
          encoding: {
            opacity: {
              condition: { value: 0.3, param: "hover", empty: false },
              value: 0
            },
            tooltip: [{ field: "y_text", type: "nominal", title: "memory" }]
          },
          params: [
            {
              name: "hover",
              select: {
                type: "point",
                fields: ["y"],
                nearest: true,
                on: "mousemove"
              }
            }
          ]
        }
      ]
    };
  }
  function makeNRTBar(nrt_time_ms, elapsed_time_sec, params2) {
    const widthThreshold1 = 15;
    const widthThreshold2 = 8;
    const elapsed_time_ms = elapsed_time_sec * 1e3;
    const nrt_percent = elapsed_time_ms > 0 ? nrt_time_ms / elapsed_time_ms * 100 : 0;
    const tooltipText = "NRT: " + nrt_percent.toFixed(1) + "% of elapsed time [" + time_consumed_str(nrt_time_ms) + "]";
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            x: 0,
            y: nrt_percent.toFixed(1),
            c: tooltipText,
            d: nrt_percent >= widthThreshold1 ? nrt_percent.toFixed(0) + "%" : nrt_percent >= widthThreshold2 ? nrt_percent.toFixed(0) : "",
            q: nrt_percent / 2
          }
        ]
      },
      layer: [
        {
          mark: { type: "bar" },
          encoding: {
            x: {
              aggregate: "sum",
              field: "y",
              axis: false,
              stack: "zero",
              scale: { domain: [0, 100] }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: false,
              scale: { range: ["purple"] }
            },
            tooltip: [{ field: "c", type: "nominal", title: "NRT time" }]
          }
        },
        {
          mark: {
            type: "text",
            align: "center",
            baseline: "middle",
            dx: 0
          },
          encoding: {
            x: {
              aggregate: "sum",
              field: "q",
              axis: false
            },
            text: { field: "d" },
            color: { value: "white" },
            tooltip: [{ field: "c", type: "nominal", title: "NRT time" }]
          }
        }
      ]
    };
  }
  function makeNCTimeBar(nc_time_ms, elapsed_time_sec, params2) {
    const widthThreshold1 = 15;
    const widthThreshold2 = 8;
    const elapsed_time_ms = elapsed_time_sec * 1e3;
    const nc_percent = elapsed_time_ms > 0 ? nc_time_ms / elapsed_time_ms * 100 : 0;
    const tooltipText = "NC: " + nc_percent.toFixed(1) + "% of elapsed time [" + time_consumed_str(nc_time_ms) + "]";
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            x: 0,
            y: nc_percent.toFixed(1),
            c: tooltipText,
            d: nc_percent >= widthThreshold1 ? nc_percent.toFixed(0) + "%" : nc_percent >= widthThreshold2 ? nc_percent.toFixed(0) : "",
            q: nc_percent / 2
          }
        ]
      },
      layer: [
        {
          mark: { type: "bar" },
          encoding: {
            x: {
              aggregate: "sum",
              field: "y",
              axis: false,
              stack: "zero",
              scale: { domain: [0, 100] }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: false,
              scale: { range: ["darkorange"] }
            },
            tooltip: [{ field: "c", type: "nominal", title: "NC time" }]
          }
        },
        {
          mark: {
            type: "text",
            align: "center",
            baseline: "middle",
            dx: 0
          },
          encoding: {
            x: {
              aggregate: "sum",
              field: "q",
              axis: false
            },
            text: { field: "d" },
            color: { value: "white" },
            tooltip: [{ field: "c", type: "nominal", title: "NC time" }]
          }
        }
      ]
    };
  }
  function makeTotalNeuronBar(total_time_ms, elapsed_time_sec, label, color5, params2) {
    const widthThreshold1 = 15;
    const widthThreshold2 = 8;
    const elapsed_time_ms = elapsed_time_sec * 1e3;
    const time_percent = elapsed_time_ms > 0 ? total_time_ms / elapsed_time_ms * 100 : 0;
    const tooltipText = `${label}: ${time_percent.toFixed(1)}% of elapsed time [${time_consumed_str(total_time_ms)}]`;
    return {
      $schema: "https://vega.github.io/schema/vega-lite/v5.json",
      config: {
        view: {
          stroke: "transparent"
        }
      },
      autosize: {
        contains: "padding"
      },
      width: params2.width,
      height: params2.height,
      padding: 0,
      data: {
        values: [
          {
            x: 0,
            y: time_percent.toFixed(1),
            c: tooltipText,
            d: time_percent >= widthThreshold1 ? time_percent.toFixed(0) + "%" : time_percent >= widthThreshold2 ? time_percent.toFixed(0) : "",
            q: time_percent / 2
          }
        ]
      },
      layer: [
        {
          mark: { type: "bar" },
          encoding: {
            x: {
              aggregate: "sum",
              field: "y",
              axis: false,
              stack: "zero",
              scale: { domain: [0, 100] }
            },
            color: {
              field: "c",
              type: "nominal",
              legend: false,
              scale: { range: [color5] }
            },
            tooltip: [{ field: "c", type: "nominal", title: label + " time" }]
          }
        },
        {
          mark: {
            type: "text",
            align: "center",
            baseline: "middle",
            dx: 0
          },
          encoding: {
            x: {
              aggregate: "sum",
              field: "q",
              axis: false
            },
            text: { field: "d" },
            color: { value: "white" },
            tooltip: [{ field: "c", type: "nominal", title: label + " time" }]
          }
        }
      ]
    };
  }

  // optimizations.ts
  async function copyOnClick(event2, message) {
    event2.preventDefault();
    event2.stopPropagation();
    await navigator.clipboard.writeText(message);
  }
  function extractCode(text4) {
    if (!text4) {
      return text4;
    }
    const lines = text4.split("\n");
    let i2 = 0;
    while (i2 < lines.length && lines[i2].trim() === "") {
      i2++;
    }
    const first_line = lines[i2].trim();
    let code_block;
    if (first_line === "```") {
      code_block = text4.slice(3);
    } else if (first_line.startsWith("```")) {
      const word = first_line.slice(3).trim();
      if (word.length > 0 && !word.includes(" ")) {
        code_block = text4.slice(first_line.length);
      } else {
        code_block = text4;
      }
    } else {
      code_block = text4;
    }
    const end_index = code_block.indexOf("```");
    if (end_index !== -1) {
      code_block = code_block.slice(0, end_index);
    }
    return code_block;
  }
  function generateScaleneOptimizedCodeRequest(context3, sourceCode, line4, recommendedLibraries = [], includeGpuOptimizations = false, GPUdeviceName = "GPU") {
    const defaultLibraries = [
      "NumPy",
      "Scikit-learn",
      "Pandas",
      "TensorFlow",
      "PyTorch"
    ];
    const highPerformanceLibraries = [
      .../* @__PURE__ */ new Set([...defaultLibraries, ...recommendedLibraries])
    ];
    const promptParts = [
      "Optimize the following Python code to make it more efficient WITHOUT CHANGING ITS RESULTS.\n\n",
      context3.trim(),
      "\n# Start of code\n",
      sourceCode.trim(),
      "\n# End of code\n\n",
      "Rewrite the above Python code from 'Start of code' to 'End of code', aiming for clear and simple optimizations. ",
      "Your output should consist only of valid Python code, with brief explanatory comments prefaced with #. ",
      "Include a detailed explanatory comment before the code, starting with '# Proposed optimization:'. ",
      `Leverage high-performance native libraries, especially those utilizing ${GPUdeviceName}, for significant performance improvements. `,
      "Consider using the following other libraries, if appropriate:\n",
      highPerformanceLibraries.map((e4) => "  import " + e4).join("\n") + "\n",
      "Eliminate as many for loops, while loops, and list or dict comprehensions as possible, replacing them with vectorized equivalents. ",
      "Quantify the expected speedup in terms of orders of magnitude if possible. ",
      "Fix any errors in the optimized code. "
    ];
    if (includeGpuOptimizations) {
      promptParts.push(
        `Use ${GPUdeviceName}-accelerated libraries whenever it would substantially increase performance. `
      );
    }
    promptParts.push(
      "Consider the following insights gathered from the Scalene profiler for optimization:\n"
    );
    const total_cpu_percent = line4.n_cpu_percent_python + line4.n_cpu_percent_c + line4.n_sys_percent;
    promptParts.push(
      `- CPU time: percent spent in the Python interpreter: ${(100 * line4.n_cpu_percent_python / total_cpu_percent).toFixed(2)}%
`
    );
    promptParts.push(
      `- CPU time: percent spent executing native code: ${(100 * line4.n_cpu_percent_c / total_cpu_percent).toFixed(2)}%
`
    );
    promptParts.push(
      `- CPU time: percent of system time: ${(100 * line4.n_sys_percent / total_cpu_percent).toFixed(2)}%
`
    );
    promptParts.push(
      `- Core utilization: ${(100 * line4.n_core_utilization / total_cpu_percent).toFixed(2)}%
`
    );
    promptParts.push(
      `- Peak memory usage: ${line4.n_peak_mb.toFixed(0)}MB (${(100 * line4.n_python_fraction).toFixed(2)}% Python memory)
`
    );
    if (line4.n_copy_mb_s > 1) {
      promptParts.push(
        `- Megabytes copied per second by memcpy/strcpy: ${line4.n_copy_mb_s.toFixed(2)}
`
      );
    }
    if (includeGpuOptimizations) {
      promptParts.push(
        `- GPU percent utilization: ${(100 * line4.n_gpu_percent).toFixed(2)}%
`
      );
    }
    promptParts.push(`Optimized code:`);
    return promptParts.join("");
  }
  function extractPythonCodeBlock(markdown) {
    const pattern = /```python\s*([\s\S]*?)```|```([\s\S]*?)```/g;
    let match3;
    let extractedCode = "";
    while ((match3 = pattern.exec(markdown)) !== null) {
      const codeBlock = match3[1] ? match3[1] : match3[2];
      if (extractedCode && codeBlock) extractedCode += "\n\n";
      extractedCode += codeBlock;
    }
    return extractedCode;
  }
  async function optimizeCode(imports, code, line4, context3) {
    const useGPUCheckbox = document.getElementById("use-gpu-checkbox");
    const useGPUs = useGPUCheckbox?.checked ?? false;
    const recommendedLibraries = ["sklearn"];
    if (useGPUs) {
      recommendedLibraries.push("cupy");
    } else {
      recommendedLibraries.push("numpy");
    }
    const acceleratorNameElement = document.getElementById("accelerator-name");
    const GPUdeviceName = acceleratorNameElement?.innerHTML || "GPU";
    const bigPrompt = generateScaleneOptimizedCodeRequest(
      context3,
      code,
      line4,
      recommendedLibraries,
      useGPUs,
      GPUdeviceName
    );
    const useGPUstring = useGPUs ? ` or ${GPUdeviceName}-optimizations ` : " ";
    let apiKey = "";
    const serviceSelect = document.getElementById("service-select");
    const aiService = serviceSelect?.value ?? "";
    if (aiService === "openai") {
      const apiKeyElement = document.getElementById("api-key");
      apiKey = apiKeyElement?.value ?? "";
    } else if (aiService === "anthropic") {
      const anthropicApiKeyElement = document.getElementById("anthropic-api-key");
      apiKey = anthropicApiKeyElement?.value ?? "";
    } else if (aiService === "gemini") {
      const geminiApiKeyElement = document.getElementById("gemini-api-key");
      apiKey = geminiApiKeyElement?.value ?? "";
    } else if (aiService === "azure-openai") {
      const azureApiKeyElement = document.getElementById("azure-api-key");
      apiKey = azureApiKeyElement?.value ?? "";
    }
    if ((aiService === "openai" || aiService === "azure-openai") && !apiKey) {
      alert(
        "To activate proposed optimizations, enter an OpenAI API key in AI optimization options."
      );
      const aiOptOptions = document.getElementById("ai-optimization-options");
      if (aiOptOptions) {
        aiOptOptions.open = true;
      }
      return "";
    }
    if (aiService === "anthropic" && !apiKey) {
      alert(
        "To activate proposed optimizations, enter an Anthropic API key in AI optimization options."
      );
      const aiOptOptions = document.getElementById("ai-optimization-options");
      if (aiOptOptions) {
        aiOptOptions.open = true;
      }
      return "";
    }
    if (aiService === "gemini" && !apiKey) {
      alert(
        "To activate proposed optimizations, enter a Google Gemini API key in AI optimization options."
      );
      const aiOptOptions = document.getElementById("ai-optimization-options");
      if (aiOptOptions) {
        aiOptOptions.open = true;
      }
      return "";
    }
    let lineOf = " ";
    if (code.split("\n").length <= 2) {
      lineOf = " line of ";
    }
    let libraries = "import sklearn";
    if (useGPUs) {
      libraries += "\nimport cupy";
    } else {
      libraries += "\nimport numpy as np";
    }
    const optimizePerformancePrompt = `Optimize the following${lineOf}Python code:

${context3}

# Start of code

${code}

# End of code

Rewrite the above Python code only from "Start of code" to "End of code", to make it more efficient WITHOUT CHANGING ITS RESULTS. Assume the code has already executed all these imports; do NOT include them in the optimized code:

${imports}

Use native libraries if that would make it faster than pure Python. Consider using the following other libraries, if appropriate:

${libraries}

Your output should only consist of valid Python code. Output the resulting Python with brief explanations only included as comments prefaced with #. Include a detailed explanatory comment before the code, starting with the text "# Proposed optimization:". Make the code as clear and simple as possible, while also making it as fast and memory-efficient as possible. Use vectorized operations${useGPUstring}whenever it would substantially increase performance, and quantify the speedup in terms of orders of magnitude. Eliminate as many for loops, while loops, and list or dict comprehensions as possible, replacing them with vectorized equivalents. If the performance is not likely to increase, leave the code unchanged. Fix any errors in the optimized code. Optimized${lineOf}code:`;
    const memoryEfficiencyPrompt = `Optimize the following${lineOf} Python code:

${context3}

# Start of code

${code}


# End of code

Rewrite the above Python code only from "Start of code" to "End of code", to make it more memory-efficient WITHOUT CHANGING ITS RESULTS. Assume the code has already executed all these imports; do NOT include them in the optimized code:

${imports}

Use native libraries if that would make it more space efficient than pure Python. Consider using the following other libraries, if appropriate:

${libraries}

Your output should only consist of valid Python code. Output the resulting Python with brief explanations only included as comments prefaced with #. Include a detailed explanatory comment before the code, starting with the text "# Proposed optimization:". Make the code as clear and simple as possible, while also making it as fast and memory-efficient as possible. Use native libraries whenever possible to reduce memory consumption; invoke del on variables and array elements as soon as it is safe to do so. If the memory consumption is not likely to be reduced, leave the code unchanged. Fix any errors in the optimized code. Optimized${lineOf}code:`;
    const optimizePerfCheckbox = document.getElementById("optimize-performance");
    const optimizePerf = optimizePerfCheckbox?.checked ?? true;
    let prompt;
    if (optimizePerf) {
      prompt = optimizePerformancePrompt;
    } else {
      prompt = memoryEfficiencyPrompt;
    }
    prompt = bigPrompt;
    switch (aiService) {
      case "openai": {
        console.log(prompt);
        const result = await sendPromptToOpenAI(prompt, apiKey);
        return extractCode(result);
      }
      case "anthropic": {
        console.log("Running " + aiService);
        console.log(prompt);
        const result = await sendPromptToAnthropic(prompt, apiKey);
        return extractCode(result);
      }
      case "gemini": {
        console.log("Running " + aiService);
        console.log(prompt);
        const result = await sendPromptToGemini(prompt, apiKey);
        return extractCode(result);
      }
      case "local": {
        console.log("Running " + aiService);
        console.log(prompt);
        const modelElement = document.getElementById("language-model-local");
        const ipElement = document.getElementById("local-ip");
        const portElement = document.getElementById("local-port");
        const result = await sendPromptToOllama(
          prompt,
          modelElement?.value ?? "",
          ipElement?.value ?? "",
          portElement?.value ?? ""
        );
        if (result.includes("```")) {
          return extractPythonCodeBlock(result);
        } else {
          return result;
        }
      }
      case "amazon": {
        console.log("Running " + aiService);
        console.log(prompt);
        const result = await sendPromptToAmazon(prompt);
        return extractCode(result);
      }
      case "azure-openai": {
        console.log("Running " + aiService);
        console.log(prompt);
        const azureUrlElement = document.getElementById("azure-api-url");
        const azureCustomModelElement = document.getElementById("azure-custom-model");
        const azureModelSelectElement = document.getElementById("language-model-azure");
        const azureOpenAiEndpoint = azureUrlElement?.value ?? "";
        const azureCustomModel = azureCustomModelElement?.value?.trim() || "";
        const azureOpenAiModel = azureCustomModel || azureModelSelectElement?.value || "gpt-5.2";
        const result = await sendPromptToAzureOpenAI(
          prompt,
          apiKey,
          azureOpenAiEndpoint,
          azureOpenAiModel
        );
        return extractCode(result);
      }
      default:
        return "";
    }
  }
  function proposeOptimization(filename, file_number, line4, params2) {
    filename = unescape(filename);
    const useRegion = params2["regions"];
    const prof = globalThis.profile;
    const this_file = prof.files[filename].lines;
    const imports = prof.files[filename].imports.join("\n");
    const start_region_line = this_file[line4.lineno - 1]["start_region_line"];
    const end_region_line = this_file[line4.lineno - 1]["end_region_line"];
    let context3;
    const code_line = this_file[line4.lineno - 1]["line"];
    let code_region;
    if (useRegion) {
      code_region = this_file.slice(start_region_line - 1, end_region_line).map((e4) => e4["line"]).join("");
      context3 = this_file.slice(
        Math.max(0, start_region_line - 10),
        Math.min(start_region_line - 1, this_file.length)
      ).map((e4) => e4["line"]).join("");
    } else {
      code_region = code_line;
      context3 = this_file.slice(
        Math.max(0, line4.lineno - 10),
        Math.min(line4.lineno - 1, this_file.length)
      ).map((e4) => e4["line"]).join("");
    }
    const leadingSpaceCount = countSpaces(code_line) + 3;
    const indent = WhiteLightning + WhiteExplosion + "&nbsp;".repeat(leadingSpaceCount - 1);
    const elt = document.getElementById(`code-${file_number}-${line4.lineno}`);
    (async () => {
      const serviceSelect = document.getElementById("service-select");
      const service = serviceSelect?.value ?? "";
      if (service === "openai") {
        const apiKeyElement = document.getElementById("api-key");
        const isValid2 = await isValidApiKey(apiKeyElement?.value ?? "");
        if (!isValid2) {
          alert(
            "You must enter a valid OpenAI API key to activate proposed optimizations."
          );
          const aiOptOptions = document.getElementById("ai-optimization-options");
          if (aiOptOptions) {
            aiOptOptions.open = true;
          }
          return;
        }
      }
      if (service === "anthropic") {
        const apiKeyElement = document.getElementById("anthropic-api-key");
        if (!apiKeyElement?.value) {
          alert(
            "You must enter an Anthropic API key to activate proposed optimizations."
          );
          const aiOptOptions = document.getElementById("ai-optimization-options");
          if (aiOptOptions) {
            aiOptOptions.open = true;
          }
          return;
        }
      }
      if (service === "gemini") {
        const apiKeyElement = document.getElementById("gemini-api-key");
        if (!apiKeyElement?.value) {
          alert(
            "You must enter a Google Gemini API key to activate proposed optimizations."
          );
          const aiOptOptions = document.getElementById("ai-optimization-options");
          if (aiOptOptions) {
            aiOptOptions.open = true;
          }
          return;
        }
      }
      if (service === "local") {
        const localModelsList = document.getElementById("local-models-list");
        if (localModelsList?.style.display === "none") {
          alert(
            "You must be connected to a running Ollama server to activate proposed optimizations."
          );
          const aiOptOptions = document.getElementById("ai-optimization-options");
          if (aiOptOptions) {
            aiOptOptions.open = true;
          }
          return;
        }
      }
      if (elt) {
        elt.innerHTML = `<em>${indent}working...</em>`;
      }
      let message = await optimizeCode(imports, code_region, line4, context3);
      if (!message) {
        if (elt) {
          elt.innerHTML = "";
        }
        return;
      }
      message = message.replace(/\r?\n/g, "\n");
      const formattedCode = message.split("\n").map(
        (line5) => indent + Prism.highlight(line5, Prism.languages.python, "python")
      ).join("<br />");
      if (elt) {
        elt.innerHTML = `<hr><span title="click to copy" style="cursor: copy" id="opt-${file_number}-${line4.lineno}">${formattedCode}</span>`;
      }
      const thisElt = document.getElementById(
        `opt-${file_number}-${line4.lineno}`
      );
      if (thisElt) {
        thisElt.addEventListener("click", async (e4) => {
          await copyOnClick(e4, message);
          thisElt.style.cursor = "auto";
          await new Promise((resolve2) => setTimeout(resolve2, 125));
          thisElt.style.cursor = "copy";
        });
      }
    })();
  }

  // persistence.ts
  var envKeyMap = {
    "api-key": "openai",
    "anthropic-api-key": "anthropic",
    "gemini-api-key": "gemini",
    "azure-api-key": "azure",
    "azure-api-url": "azureUrl",
    "aws-access-key": "awsAccessKey",
    "aws-secret-key": "awsSecretKey",
    "aws-region": "awsRegion"
  };
  function restoreState(el) {
    const savedValue = localStorage.getItem(el.id);
    if (savedValue !== null) {
      switch (el.type) {
        case "checkbox":
        case "radio":
          el.checked = savedValue === "true";
          break;
        default:
          el.value = savedValue;
          break;
      }
    } else {
      const envKey = envKeyMap[el.id];
      if (envKey && typeof envApiKeys !== "undefined" && envApiKeys[envKey]) {
        el.value = envApiKeys[envKey];
      }
    }
  }
  function saveState(el) {
    el.addEventListener("change", () => {
      switch (el.type) {
        case "checkbox":
        case "radio":
          localStorage.setItem(el.id, String(el.checked));
          break;
        default:
          localStorage.setItem(el.id, el.value);
          break;
      }
    });
  }
  function processPersistentElements() {
    const persistentElements = document.querySelectorAll(".persistent");
    persistentElements.forEach((el) => {
      restoreState(el);
    });
    persistentElements.forEach((el) => {
      saveState(el);
    });
  }
  var observeDOM = () => {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.addedNodes) {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === 1) {
              const element3 = node;
              if (element3.matches && element3.matches(".persistent")) {
                const inputElement = element3;
                restoreState(inputElement);
                inputElement.addEventListener("change", () => saveState(inputElement));
              }
            }
          });
        }
      });
    });
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  };

  // scalene-gui.ts
  window.Buffer = import_buffer3.Buffer;
  window.checkApiKey = checkApiKey;
  function vsNavigate(filename, lineno) {
    try {
      const vscode = window.acquireVsCodeApi();
      vscode.postMessage({
        command: "jumpToLine",
        filePath: filename,
        lineNumber: lineno
      });
    } catch {
    }
  }
  var maxLinesPerRegion = 50;
  var showedExplosion = {};
  function proposeOptimizationRegion(filename, file_number, line4) {
    proposeOptimization(
      filename,
      file_number,
      JSON.parse(decodeURIComponent(line4)),
      { regions: true }
    );
  }
  function proposeOptimizationLine(filename, file_number, line4) {
    proposeOptimization(
      filename,
      file_number,
      JSON.parse(decodeURIComponent(line4)),
      { regions: false }
    );
  }
  var CPUColor = "blue";
  var MemoryColor = "green";
  var CopyColor = "goldenrod";
  var AsyncColor = "darkcyan";
  var columns = [];
  function stringLines(lines) {
    const docstringLines = /* @__PURE__ */ new Set();
    let inDocstring = false;
    let docstringDelimiter = null;
    for (let i2 = 0; i2 < lines.length; i2++) {
      const line4 = lines[i2];
      let searchIndex = 0;
      const wasInDocstring = inDocstring;
      while (true) {
        const nextTripleSingle = line4.indexOf("'''", searchIndex);
        const nextTripleDouble = line4.indexOf('"""', searchIndex);
        let nextIndex = -1;
        let foundDelimiter = null;
        if (nextTripleSingle !== -1 && (nextTripleDouble === -1 || nextTripleSingle < nextTripleDouble)) {
          nextIndex = nextTripleSingle;
          foundDelimiter = "'''";
        } else if (nextTripleDouble !== -1 && (nextTripleSingle === -1 || nextTripleDouble < nextTripleSingle)) {
          nextIndex = nextTripleDouble;
          foundDelimiter = '"""';
        }
        if (nextIndex === -1) {
          break;
        }
        searchIndex = nextIndex + 3;
        if (!inDocstring) {
          inDocstring = true;
          docstringDelimiter = foundDelimiter;
        } else {
          if (docstringDelimiter === foundDelimiter) {
            inDocstring = false;
            docstringDelimiter = null;
          }
        }
      }
      if (wasInDocstring || inDocstring) {
        docstringLines.add(i2);
      }
    }
    return docstringLines;
  }
  function makeTableHeader(fname, gpu, gpu_device, memory, params2, hasNeuronData, async_profile = false) {
    let tableTitle;
    if (params2["functions"]) {
      tableTitle = "function profile";
    } else {
      tableTitle = "line profile";
    }
    columns = [
      {
        title: ["time", ""],
        color: CPUColor,
        width: 0,
        info: "Execution time (Python + native + system)"
      }
    ];
    if (async_profile) {
      columns.push({
        title: ["await", "%"],
        color: AsyncColor,
        width: 0,
        info: "Percentage of async await time spent at this line"
      });
    }
    if (hasNeuronData) {
      columns.push({
        title: ["Unused Device", "%"],
        color: "darkred",
        width: 0,
        info: "Percentage of CPU samples where device was not being utilized concurrently"
      });
    }
    if (memory) {
      columns = columns.concat([
        {
          title: ["memory", "peak"],
          color: MemoryColor,
          width: 0,
          info: "Peak amount of memory allocated by line / function"
        },
        {
          title: ["memory", "average"],
          color: MemoryColor,
          width: 0,
          info: "Average amount of memory allocated by line / function"
        },
        {
          title: ["memory", "timeline"],
          color: MemoryColor,
          width: 0,
          info: "Memory footprint over time"
        },
        {
          title: ["memory", "activity"],
          color: MemoryColor,
          width: 0,
          info: "% of bytes allocated by line / function over total bytes allocated in file"
        },
        {
          title: ["copy", ""],
          color: CopyColor,
          width: 0,
          info: "Rate of copying memory"
        }
      ]);
    }
    if (gpu && !hasNeuronData) {
      columns.push({
        title: [gpu_device, "util."],
        color: CopyColor,
        width: 0,
        info: `% utilization of ${gpu_device} by line / function (may be inaccurate if ${gpu_device} is not dedicated)`
      });
      columns.push({
        title: [gpu_device, "memory"],
        color: CopyColor,
        width: 0,
        info: `Peak ${gpu_device} memory allocated by line / function (may be inaccurate if ${gpu_device} is not dedicated)`
      });
    }
    if (hasNeuronData) {
      columns.push({
        title: ["NRT", "%"],
        color: "purple",
        width: 0,
        info: "Neural Runtime percentage"
      });
      columns.push({
        title: ["NC", "time"],
        color: "darkorange",
        width: 0,
        info: "Neuron Compute time"
      });
    }
    columns.push({ title: ["", ""], color: "black", width: 100 });
    let s2 = "";
    s2 += '<thead class="thead-light">';
    s2 += '<tr data-sort-method="thead">';
    for (const col of columns) {
      s2 += `<th class="F${escape(
        fname
      )}-nonline"><font style="font-variant: small-caps; text-decoration: underline; width:${col.width}" color=${col.color}>`;
      if (col.info) {
        s2 += `<a style="cursor:pointer;" title="${col.info}">${col.title[0]}</a>`;
      } else {
        s2 += `<a style="cursor:pointer;">${col.title[0]}</a>`;
      }
      s2 += "</font>&nbsp;&nbsp;</th>";
    }
    let id2;
    if (params2["functions"]) {
      id2 = "functionProfile";
    } else {
      id2 = "lineProfile";
    }
    s2 += `<th id=${escape(fname) + "-" + id2} style="width:10000"><font style="font-variant: small-caps; text-decoration: underline">${tableTitle}</font><font style="font-size:small; font-style: italic">&nbsp; (click to reset order)</font></th>`;
    s2 += "</tr>";
    s2 += '<tr data-sort-method="thead">';
    for (const col of columns) {
      s2 += `<th style="width:${col.width}"><em><font style="font-size: small" color=${col.color}>${col.title[1]}</font></em></th>`;
    }
    s2 += `<th><code>${fname}</code></th></tr>`;
    s2 += "</thead>";
    return s2;
  }
  function applyFileDisplayMode(fileId, mode) {
    const rows = document.querySelectorAll(`tr[data-file="${fileId}"]`);
    for (const row of rows) {
      if (mode === "all") {
        row.style.display = "";
      } else if (mode === "profiled-lines") {
        if (row.classList.contains("empty-profile") || row.classList.contains("function-context")) {
          row.style.display = "none";
        } else {
          row.style.display = "";
        }
      } else {
        if (row.classList.contains("empty-profile")) {
          row.style.display = "none";
        } else {
          row.style.display = "";
        }
      }
    }
  }
  function onFileDisplayModeChange(fileId) {
    const select2 = document.getElementById(`display-mode-${fileId}`);
    if (select2) {
      applyFileDisplayMode(fileId, select2.value);
    }
  }
  function toggleReduced() {
  }
  function makeProfileLine(line4, inDocstring, filename, file_number, prof, cpu_bars, memory_bars, memory_sparklines, memory_activity, gpu_pies, propose_optimizations, nrt_bars, nc_bars, nc_nrt_pies, total_nc_time_for_file, hasNeuronData, profiledFunctions = /* @__PURE__ */ new Set(), async_profile = false, await_pies = [], pieAngles = { await: 0, gpu: 0 }) {
    let total_time = line4.n_cpu_percent_python + line4.n_cpu_percent_c + line4.n_sys_percent;
    let total_region_time = 0;
    let region_has_memory_results = 0;
    let region_has_gpu_results = false;
    for (let lineno = line4.start_region_line; lineno < line4.end_region_line; lineno++) {
      const currline = prof["files"][filename]["lines"][lineno];
      total_region_time += currline.n_cpu_percent_python + currline.n_cpu_percent_c + currline.n_sys_percent;
      region_has_memory_results += currline.n_avg_mb + currline.n_peak_mb + currline.memory_samples.length + (currline.n_usage_fraction >= 0.01 ? 1 : 0);
      region_has_gpu_results = region_has_gpu_results || line4.n_gpu_percent >= 1;
    }
    if (propose_optimizations) {
      if (total_time < 1 && line4.start_region_line === line4.end_region_line) {
        propose_optimizations = false;
      }
      if (line4.start_region_line !== line4.end_region_line) {
        if (total_region_time < 1) {
          propose_optimizations = false;
        }
      }
    }
    const has_memory_results = line4.n_avg_mb + line4.n_peak_mb + line4.memory_samples.length + (line4.n_usage_fraction >= 0.01 ? 1 : 0);
    const has_gpu_results = line4.n_gpu_percent >= 1;
    const has_nrt_results = line4.nrt_time_ms !== void 0 && line4.nrt_time_ms > 0 || line4.nc_time_ms !== void 0 && line4.nc_time_ms > 0;
    const start_region_line = line4.start_region_line;
    const end_region_line = line4.end_region_line;
    let explosionString;
    let showExplosion;
    const regionKey = `${start_region_line - 1},${end_region_line}`;
    if (start_region_line === end_region_line || regionKey in showedExplosion) {
      explosionString = WhiteExplosion;
      showExplosion = false;
    } else {
      explosionString = Explosion;
      if (start_region_line && end_region_line) {
        showedExplosion[regionKey] = true;
        showExplosion = true;
      } else {
        showExplosion = false;
      }
    }
    showExplosion = showExplosion && end_region_line - start_region_line <= maxLinesPerRegion;
    const has_async_results = async_profile && (line4.n_async_await_percent || 0) >= 1;
    const hasProfileData = total_time > 1 || has_memory_results || has_gpu_results && prof.gpu && !hasNeuronData || has_nrt_results || has_async_results || showExplosion && start_region_line !== end_region_line && (total_region_time >= 1 || region_has_memory_results || region_has_gpu_results && prof.gpu && !hasNeuronData);
    const functionKey = line4.start_function_line > 0 ? `${line4.start_function_line},${line4.end_function_line}` : "";
    const inProfiledFunction = functionKey !== "" && profiledFunctions.has(functionKey);
    let s2 = "";
    let rowClass = "";
    if (!hasProfileData) {
      if (inProfiledFunction) {
        rowClass = "function-context";
      } else {
        rowClass = "empty-profile";
      }
    }
    const fileId = `file-${file_number}`;
    s2 += `<tr class="${rowClass}" data-file="${fileId}">`;
    const total_time_str = String(total_time.toFixed(1)).padStart(10, " ");
    s2 += `<td style="height: 20; width: 100; vertical-align: middle" align="left" data-sort='${total_time_str}'>`;
    s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="cpu_bar${cpu_bars.length}"></span>`;
    if (total_time) {
      cpu_bars.push(
        makeBar(
          line4.n_cpu_percent_python,
          line4.n_cpu_percent_c,
          line4.n_sys_percent,
          { height: 20, width: 100 }
        )
      );
    } else {
      cpu_bars.push(null);
    }
    s2 += "</td>";
    if (async_profile) {
      const await_pct = line4.n_async_await_percent || 0;
      if (await_pct >= 1) {
        s2 += `<td style="width: 50; vertical-align: middle; text-align: center" data-sort="${await_pct}">`;
        s2 += `<span style="height: 20; width: 30; vertical-align: middle" id="await_pie${await_pies.length}"></span>`;
        s2 += "</td>";
        await_pies.push(
          makeAwaitPie(await_pct, { height: 20, width: 30 }, pieAngles.await)
        );
        pieAngles.await += await_pct / 100 * 2 * Math.PI;
      } else {
        s2 += '<td style="width: 50"></td>';
        await_pies.push(null);
      }
    }
    if (hasNeuronData) {
      if ((total_time >= 1 || has_nrt_results) && line4.cpu_samples_nc_overlap_percent !== void 0) {
        const overlap_percent = line4.cpu_samples_nc_overlap_percent || 0;
        const unused_percent = 100 - overlap_percent;
        let color5 = "green";
        if (unused_percent >= 60) {
          color5 = "darkred";
        } else if (unused_percent >= 30) {
          color5 = "goldenrod";
        }
        s2 += `<td style="width: 100; vertical-align: middle; padding-right: 8px;" align="right" data-sort='${unused_percent.toFixed(
          1
        )}'>`;
        s2 += `<font style="font-size: small" color="${color5}">${unused_percent.toFixed(
          1
        )}%&nbsp;&nbsp;&nbsp;</font>`;
        s2 += "</td>";
      } else {
        s2 += '<td style="width: 100; padding-right: 8px;"></td>';
      }
    }
    if (prof.memory) {
      s2 += `<td style="height: 20; width: 100; vertical-align: middle" align="left" data-sort='${String(
        line4.n_peak_mb.toFixed(0)
      ).padStart(10, "0")}'>`;
      s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="memory_bar${memory_bars.length}"></span>`;
      if (line4.n_peak_mb) {
        memory_bars.push(
          makeMemoryBar(
            line4.n_peak_mb.toFixed(0),
            "peak memory",
            parseFloat(String(line4.n_python_fraction)),
            prof.max_footprint_mb.toFixed(2),
            "darkgreen",
            { height: 20, width: 100 }
          )
        );
      } else {
        memory_bars.push(null);
      }
      s2 += `<td style="height: 20; width: 100; vertical-align: middle" align="left" data-sort='${String(
        line4.n_avg_mb.toFixed(0)
      ).padStart(10, "0")}'>`;
      s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="memory_bar${memory_bars.length}"></span>`;
      s2 += "</td>";
      if (line4.n_avg_mb) {
        memory_bars.push(
          makeMemoryBar(
            line4.n_avg_mb.toFixed(0),
            "average memory",
            parseFloat(String(line4.n_python_fraction)),
            prof.max_footprint_mb.toFixed(2),
            "darkgreen",
            { height: 20, width: 100 }
          )
        );
      } else {
        memory_bars.push(null);
      }
      s2 += "</td>";
      s2 += `<td style='vertical-align: middle; width: 100'><span style="height:20; width: 100; vertical-align: middle" id="memory_sparkline${memory_sparklines.length}"></span>`;
      s2 += "</td>";
      if (line4.memory_samples.length > 0) {
        let leak_velocity = 0;
        if ("leaks" in prof.files[filename]) {
          const leaks = prof.files[filename].leaks;
          if (leaks && line4.lineno in leaks) {
            leak_velocity = leaks[line4.lineno].velocity_mb_s;
          }
        }
        memory_sparklines.push(
          makeSparkline(
            line4.memory_samples,
            prof.elapsed_time_sec * 1e9,
            prof.max_footprint_mb,
            leak_velocity,
            { height: 20, width: 75 }
          )
        );
      } else {
        memory_sparklines.push(null);
      }
      s2 += '<td style="width: 100; vertical-align: middle" align="center">';
      if (line4.n_usage_fraction >= 0.01) {
        s2 += `<span style="height: 20; width: 30; vertical-align: middle" id="memory_activity${memory_activity.length}"></span>`;
        memory_activity.push(
          makeMemoryPie(
            100 * line4.n_usage_fraction * (1 - parseFloat(String(line4.n_python_fraction))),
            100 * line4.n_usage_fraction * parseFloat(String(line4.n_python_fraction)),
            { width: 30 }
          )
        );
      } else {
        memory_activity.push(null);
      }
      s2 += "</td>";
      if (line4.n_copy_mb_s < 1) {
        s2 += '<td style="width: 100"></td>';
      } else {
        s2 += `<td style="width: 100; vertical-align: middle" align="right"><font style="font-size: small" color="${CopyColor}">${line4.n_copy_mb_s.toFixed(
          0
        )}&nbsp;&nbsp;&nbsp;</font></td>`;
      }
    }
    if (prof.gpu && !hasNeuronData) {
      if (line4.n_gpu_percent < 1) {
        s2 += '<td style="width: 100"></td>';
      } else {
        s2 += `<td style="width: 50; vertical-align: middle" align="right" data-sort="${line4.n_gpu_percent}">`;
        s2 += `<span style="height: 20; width: 30; vertical-align: middle" id="gpu_pie${gpu_pies.length}"></span>`;
        s2 += "</td>";
        gpu_pies.push(
          makeGPUPie(line4.n_gpu_percent, prof.gpu_device, {
            height: 20,
            width: 30
          }, pieAngles.gpu)
        );
        pieAngles.gpu += line4.n_gpu_percent / 100 * 2 * Math.PI;
      }
      if (line4.n_gpu_peak_memory_mb < 1 || line4.n_gpu_percent < 1) {
        s2 += '<td style="width: 100"></td>';
      } else {
        let mem = line4.n_gpu_peak_memory_mb;
        let memStr = "MB";
        if (mem >= 1024) {
          mem /= 1024;
          memStr = "GB";
        }
        s2 += `<td style="width: 100; vertical-align: middle" align="right"><font style="font-size: small" color="${CopyColor}">${mem.toFixed(
          0
        )}${memStr}&nbsp;&nbsp;</font></td>`;
      }
    }
    if (hasNeuronData) {
      if (line4.nrt_time_ms !== void 0 && line4.nrt_time_ms > 0 || line4.nrt_percent !== void 0 && line4.nrt_percent > 0) {
        const sortValue = line4.nrt_time_ms || line4.nrt_percent || 0;
        s2 += `<td style="height: 20; width: 100; vertical-align: middle" align="left" data-sort='${sortValue.toFixed(
          1
        )}'>`;
        s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="nrt_bar${nrt_bars.length}"></span>`;
        s2 += "</td>";
        nrt_bars.push(
          makeNRTBar(line4.nrt_time_ms || 0, prof.elapsed_time_sec, {
            height: 20,
            width: 100
          })
        );
      } else {
        s2 += '<td style="width: 100"></td>';
        nrt_bars.push(null);
      }
      if (line4.nc_time_ms !== void 0 && line4.nc_time_ms > 0) {
        s2 += `<td style="height: 20; width: 100; vertical-align: middle" align="left" data-sort='${line4.nc_time_ms.toFixed(
          1
        )}'>`;
        s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="nc_bar${nc_bars.length}"></span>`;
        s2 += "</td>";
        nc_bars.push(
          makeNCTimeBar(line4.nc_time_ms, prof.elapsed_time_sec, {
            height: 20,
            width: 100
          })
        );
      } else {
        s2 += '<td style="width: 100"></td>';
        nc_bars.push(null);
      }
    }
    const empty_profile = total_time || has_memory_results || has_gpu_results && prof.gpu && !hasNeuronData || has_nrt_results || end_region_line !== start_region_line ? "" : "empty-profile";
    s2 += `<td align="right" class="dummy ${empty_profile}" style="vertical-align: middle; width: 50" data-sort="${line4.lineno}"><span onclick="vsNavigate('${escape(filename)}',${line4.lineno})"><font color="gray" style="font-size: 70%; vertical-align: middle" >${line4.lineno}&nbsp;</font></span></td>`;
    const regionOptimizationString = propose_optimizations && showExplosion ? `${explosionString}&nbsp;` : `${WhiteExplosion}&nbsp;`;
    line4.line = unescapeUnicode(line4.line);
    const codeLine = Prism2.highlight(line4.line, Prism2.languages.python, "python");
    let optionalInDocstring = "";
    if (inDocstring) {
      optionalInDocstring = "token comment";
    }
    s2 += `<td style="height:10" align="left" bgcolor="whitesmoke" style="vertical-align: middle" data-sort="${line4.lineno}">`;
    const newLine = structuredClone(line4);
    if (propose_optimizations && showExplosion) {
      let mb_copied = 0;
      for (let lineno = start_region_line; lineno < end_region_line; lineno++) {
        const currline = prof["files"][filename]["lines"][lineno];
        mb_copied += currline.n_copy_mb * prof.elapsed_time_sec;
        newLine.n_cpu_percent_python += currline.n_cpu_percent_python;
        newLine.n_cpu_percent_c += currline.n_cpu_percent_c;
        newLine.n_sys_percent += currline.n_sys_percent;
        newLine.n_gpu_percent += currline.n_gpu_percent;
        if (currline.n_peak_mb > newLine.n_peak_mb) {
          newLine.n_peak_mb = currline.n_peak_mb;
          newLine.n_python_fraction = currline.n_python_fraction;
        }
        newLine.n_core_utilization += (currline.n_cpu_percent_python + currline.n_cpu_percent_c) * currline.n_core_utilization;
      }
      newLine.n_copy_mb_s = mb_copied / prof.elapsed_time_sec;
      s2 += `<span style="vertical-align: middle; cursor: pointer" title="Propose an optimization for the entire region starting here." onclick="proposeOptimizationRegion('${escape(
        filename
      )}', ${file_number}, '${encodeURIComponent(
        JSON.stringify(newLine)
      )}'); event.preventDefault()">${regionOptimizationString}</span>`;
    } else {
      s2 += regionOptimizationString;
    }
    const lineOptimizationString = propose_optimizations ? `${Lightning}` : `${WhiteLightning}`;
    if (propose_optimizations) {
      s2 += `<span style="vertical-align: middle; cursor: pointer" title="Propose an optimization for this line." onclick="proposeOptimizationLine('${escape(
        filename
      )}', ${file_number}, '${encodeURIComponent(
        JSON.stringify(line4)
      )}'); event.preventDefault()">${lineOptimizationString}</span>`;
    } else {
      s2 += lineOptimizationString;
    }
    s2 += `<pre style="height: 10; display: inline; white-space: pre-wrap; overflow-x: auto; border: 0px; vertical-align: middle"><code class="language-python ${optionalInDocstring} ${empty_profile}">${codeLine}<span id="code-${file_number}-${line4.lineno}" bgcolor="white"></span></code></pre></td>`;
    s2 += "</tr>";
    return s2;
  }
  var allIds = [];
  function collapseAll() {
    for (const id2 of allIds) {
      collapseDisplay(id2);
    }
  }
  function expandAll() {
    for (const id2 of allIds) {
      expandDisplay(id2);
    }
  }
  function collapseDisplay(id2) {
    const d2 = document.getElementById(`profile-${id2}`);
    if (d2) {
      d2.style.display = "none";
    }
    const btn = document.getElementById(`button-${id2}`);
    if (btn) {
      btn.innerHTML = RightTriangle;
    }
  }
  function expandDisplay(id2) {
    const d2 = document.getElementById(`profile-${id2}`);
    if (d2) {
      d2.style.display = "block";
    }
    const btn = document.getElementById(`button-${id2}`);
    if (btn) {
      btn.innerHTML = DownTriangle;
    }
  }
  function toggleDisplay(id2) {
    const d2 = document.getElementById(`profile-${id2}`);
    if (d2) {
      if (d2.style.display === "block") {
        d2.style.display = "none";
        const btn = document.getElementById(`button-${id2}`);
        if (btn) {
          btn.innerHTML = RightTriangle;
        }
      } else {
        d2.style.display = "block";
        const btn = document.getElementById(`button-${id2}`);
        if (btn) {
          btn.innerHTML = DownTriangle;
        }
      }
    }
  }
  String.prototype.padWithNonBreakingSpaces = function(targetLength) {
    const nbsp = "&nbsp;";
    let padding3 = "";
    let currentLength = this.length * nbsp.length;
    targetLength *= nbsp.length;
    while (currentLength < targetLength) {
      padding3 += nbsp;
      currentLength += nbsp.length;
    }
    return padding3 + this;
  };
  async function display(prof) {
    showedExplosion = {};
    let cpu_python = 0;
    let cpu_native = 0;
    let cpu_system = 0;
    let mem_python = 0;
    let max_alloc = 0;
    const cp = {};
    const cn = {};
    const cs = {};
    const mp = {};
    const ma2 = {};
    const total_nc_time = {};
    const total_nrt_time = {};
    let hasNeuronData = false;
    for (const f2 in prof.files) {
      cp[f2] = 0;
      cn[f2] = 0;
      cs[f2] = 0;
      mp[f2] = 0;
      ma2[f2] = 0;
      total_nc_time[f2] = 0;
      total_nrt_time[f2] = 0;
      for (const l2 in prof.files[f2].lines) {
        const line4 = prof.files[f2].lines[l2];
        cp[f2] += line4.n_cpu_percent_python;
        cn[f2] += line4.n_cpu_percent_c;
        cs[f2] += line4.n_sys_percent;
        if (line4.n_peak_mb > ma2[f2]) {
          ma2[f2] = line4.n_peak_mb;
          mp[f2] += line4.n_peak_mb * line4.n_python_fraction;
        }
        max_alloc += line4.n_malloc_mb;
        if (line4.nc_time_ms !== void 0 && line4.nc_time_ms > 0) {
          total_nc_time[f2] += line4.nc_time_ms;
          hasNeuronData = true;
        }
        if (line4.nrt_time_ms !== void 0 && line4.nrt_time_ms > 0) {
          total_nrt_time[f2] += line4.nrt_time_ms;
          hasNeuronData = true;
        }
        if (line4.nrt_percent !== void 0 && line4.nrt_percent > 0) {
          hasNeuronData = true;
        }
      }
      cpu_python += cp[f2];
      cpu_native += cn[f2];
      cpu_system += cs[f2];
      mem_python += mp[f2];
    }
    const old_key = window.localStorage.getItem("scalene-api-key");
    if (old_key) {
      const apiKeyElement = document.getElementById("api-key");
      if (apiKeyElement) {
        apiKeyElement.value = old_key;
      }
      checkApiKey(old_key);
    }
    const selectedService = window.localStorage.getItem("scalene-service-select");
    if (selectedService) {
      const serviceSelect = document.getElementById("service-select");
      if (serviceSelect) {
        serviceSelect.value = selectedService;
      }
      toggleServiceFields();
    }
    const gpu_checkbox = document.getElementById("use-gpu-checkbox");
    if (gpu_checkbox && gpu_checkbox.checked !== prof.gpu) {
      gpu_checkbox.click();
    }
    if (prof.gpu) {
      const acceleratorName = document.getElementById("accelerator-name");
      if (acceleratorName) {
        acceleratorName.innerHTML = prof.gpu_device;
      }
    }
    globalThis.profile = prof;
    const memory_sparklines = [];
    const memory_activity = [];
    const gpu_pies = [];
    const await_pies = [];
    const memory_bars = [];
    const nrt_bars = [];
    const nc_bars = [];
    const nc_nrt_pies = [];
    let tableID = 0;
    let s2 = "";
    s2 += '<span class="row justify-content-center">';
    s2 += '<span class="col-auto">';
    s2 += '<table width="50%" class="table text-center table-condensed">';
    s2 += "<tr>";
    s2 += `<td><font style="font-size: small"><b>Time:</b> <font color="darkblue">Python</font> | <font color="#6495ED">native</font> | <font color="blue">system</font><br /></font></td>`;
    s2 += '<td width="10"></td>';
    if (prof.memory) {
      s2 += `<td><font style="font-size: small"><b>Memory:</b> <font color="darkgreen">Python</font> | <font color="#50C878">native</font><br /></font></td>`;
      s2 += '<td width="10"></td>';
      s2 += '<td valign="middle" style="vertical-align: middle">';
      s2 += `<font style="font-size: small"><b>Memory timeline: </b>(max: ${memory_consumed_str(
        prof.max_footprint_mb
      )}, growth: ${prof.growth_rate.toFixed(1)}%)</font>`;
      s2 += "</td>";
    }
    s2 += "</tr>";
    s2 += "<tr>";
    s2 += '<td height="10"><span style="height: 20; width: 200; vertical-align: middle" id="cpu_bar0"></span></td>';
    s2 += "<td></td>";
    if (prof.memory) {
      s2 += '<td height="20"><span style="height: 20; width: 150; vertical-align: middle" id="memory_bar0"></span></td>';
      s2 += "<td></td>";
      s2 += '<td align="left"><span style="vertical-align: middle" id="memory_sparkline0"></span></td>';
      memory_sparklines.push(
        makeSparkline(
          prof.samples,
          prof.elapsed_time_sec * 1e9,
          prof.max_footprint_mb,
          0,
          { height: 20, width: 200 }
        )
      );
    }
    s2 += "</tr>";
    const cpu_bars = [];
    cpu_bars.push(
      makeBar(cpu_python, cpu_native, cpu_system, { height: 20, width: 200 })
    );
    if (prof.memory) {
      memory_bars.push(
        makeMemoryBar(
          prof.max_footprint_mb.toFixed(2),
          "memory",
          mem_python / max_alloc,
          prof.max_footprint_mb.toFixed(2),
          "darkgreen",
          { height: 20, width: 150 }
        )
      );
    }
    s2 += '<tr><td colspan="10">';
    s2 += `<span class="text-center"><font style="font-size: 90%; font-style: italic; font-color: darkgray">hover over bars to see breakdowns; click on <font style="font-variant:small-caps; text-decoration:underline">column headers</font> to sort.</font></span>`;
    s2 += "</td></tr>";
    s2 += "</table>";
    s2 += "</span>";
    s2 += "</span>";
    if (JSON.stringify(prof) === "{}") {
      s2 += `
    <form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
      <div class="form-group">
	<div class="d-flex justify-content-center">
	  <label for='fileinput' style="padding: 5px 5px; border-radius: 5px; border: 1px ridge black; font-size: 0.8rem; height: auto;">Select a profile (.json)</label>
	  <input style="height: 0; width: 10; opacity:0" type='file' id='fileinput' accept='.json' onchange="loadFile();">
	</div>
      </div>
    </form>
    </div>`;
      const p3 = document.getElementById("profile");
      if (p3) {
        p3.innerHTML = s2;
      }
      return;
    }
    s2 += '<br class="text-left"><span style="font-size: 80%; color: blue; cursor : pointer;" onClick="expandAll()">&nbsp;show all</span> | <span style="font-size: 80%; color: blue; cursor : pointer;" onClick="collapseAll()">hide all</span></br>';
    s2 += '<div class="container-fluid">';
    let files4 = Object.entries(prof.files);
    files4.sort((x5, y5) => {
      return y5[1].percent_cpu_time - x5[1].percent_cpu_time;
    });
    let fileIteration = 0;
    allIds = [];
    const excludedFiles = /* @__PURE__ */ new Set();
    for (const ff of files4) {
      fileIteration++;
      if (ff[1].percent_cpu_time < 1 && ma2[ff[0]] < 0.01 * max_alloc) {
        excludedFiles.add(ff);
        continue;
      }
      const id2 = `file-${fileIteration}`;
      allIds.push(id2);
      s2 += '<p class="text-left sticky-top bg-white bg-opacity-75" style="backdrop-filter: blur(2px)">';
      let displayStr = "display:block;";
      let triangle = DownTriangle;
      if (fileIteration !== 1) {
        displayStr = "display:none;";
        triangle = RightTriangle;
      }
      s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="cpu_bar${cpu_bars.length}"></span>&nbsp;`;
      cpu_bars.push(
        makeBar(cp[ff[0]], cn[ff[0]], cs[ff[0]], { height: 20, width: 100 })
      );
      if (prof.memory) {
        s2 += `<span style="height: 20; width: 100; vertical-align: middle" id="memory_bar${memory_bars.length}"></span>`;
        memory_bars.push(
          makeMemoryBar(
            ma2[ff[0]],
            "peak memory",
            mp[ff[0]] / ma2[ff[0]],
            prof.max_footprint_mb.toFixed(2),
            "darkgreen",
            { height: 20, width: 100 }
          )
        );
      }
      s2 += `<font style="font-size: 90%">% of time = ${ff[1].percent_cpu_time.toFixed(1).padWithNonBreakingSpaces(5)}% (${time_consumed_str(
        ff[1].percent_cpu_time / 100 * prof.elapsed_time_sec * 1e3
      ).padWithNonBreakingSpaces(8)} / ${time_consumed_str(
        prof.elapsed_time_sec * 1e3
      ).padWithNonBreakingSpaces(8)})`;
      if (hasNeuronData && total_nrt_time[ff[0]] > 0) {
        s2 += `<br /><span style="height: 20; width: 100; vertical-align: middle" id="nrt_bar${nrt_bars.length}"></span>&nbsp;`;
        nrt_bars.push(
          makeTotalNeuronBar(total_nrt_time[ff[0]], prof.elapsed_time_sec, "NRT", "purple", {
            height: 20,
            width: 100
          })
        );
        const nrt_percent = total_nrt_time[ff[0]] / 1e3 / prof.elapsed_time_sec * 100;
        s2 += `% of nrt time = ${nrt_percent.toFixed(1).padWithNonBreakingSpaces(5)}% (${time_consumed_str(
          total_nrt_time[ff[0]]
        ).padWithNonBreakingSpaces(8)} / ${time_consumed_str(
          prof.elapsed_time_sec * 1e3
        ).padWithNonBreakingSpaces(8)})`;
      }
      if (hasNeuronData && total_nc_time[ff[0]] > 0) {
        s2 += `<br /><span style="height: 20; width: 100; vertical-align: middle" id="nc_bar${nc_bars.length}"></span>&nbsp;`;
        nc_bars.push(
          makeTotalNeuronBar(total_nc_time[ff[0]], prof.elapsed_time_sec, "NC", "darkorange", {
            height: 20,
            width: 100
          })
        );
        const nc_percent = total_nc_time[ff[0]] / 1e3 / prof.elapsed_time_sec * 100;
        s2 += `% of nc time = ${nc_percent.toFixed(1).padWithNonBreakingSpaces(5)}% (${time_consumed_str(
          total_nc_time[ff[0]]
        ).padWithNonBreakingSpaces(8)} / ${time_consumed_str(
          prof.elapsed_time_sec * 1e3
        ).padWithNonBreakingSpaces(8)})`;
      }
      s2 += `</font>`;
      s2 += `<br /><span id="button-${id2}" title="Click to show or hide profile." style="cursor: pointer; color: blue;" onClick="toggleDisplay('${id2}')">`;
      s2 += `${triangle}`;
      s2 += "</span>";
      s2 += `<code> ${ff[0]}</code>`;
      s2 += ` <select id="display-mode-${id2}" style="font-size: 80%; margin-left: 10px;" onchange="onFileDisplayModeChange('${id2}')">`;
      s2 += `<option value="profiled-functions" selected>profiled functions</option>`;
      s2 += `<option value="profiled-lines">profiled lines only</option>`;
      s2 += `<option value="all">all lines</option>`;
      s2 += `</select>`;
      s2 += `</p>`;
      s2 += `<div style="${displayStr}" id="profile-${id2}">`;
      s2 += `<table class="profile table table-hover table-condensed" id="table-${tableID}">`;
      tableID++;
      s2 += makeTableHeader(ff[0], prof.gpu, prof.gpu_device, prof.memory, {
        functions: false
      }, hasNeuronData, prof.async_profile || false);
      s2 += "<tbody>";
      const linesArray = ff[1].lines.map((entry2) => entry2.line);
      const docstringLines = stringLines(linesArray);
      const profiledFunctions = /* @__PURE__ */ new Set();
      for (const line4 of ff[1].lines) {
        const total_time = line4.n_cpu_percent_python + line4.n_cpu_percent_c + line4.n_sys_percent;
        const has_memory_results = line4.n_avg_mb + line4.n_peak_mb + line4.memory_samples.length + (line4.n_usage_fraction >= 0.01 ? 1 : 0);
        const has_gpu_results = line4.n_gpu_percent >= 1;
        const has_nrt_results = line4.nrt_time_ms !== void 0 && line4.nrt_time_ms > 0 || line4.nc_time_ms !== void 0 && line4.nc_time_ms > 0;
        const hasProfileData = total_time > 1 || has_memory_results || has_gpu_results && prof.gpu && !hasNeuronData || has_nrt_results;
        if (hasProfileData && line4.start_function_line > 0) {
          const functionKey = `${line4.start_function_line},${line4.end_function_line}`;
          profiledFunctions.add(functionKey);
        }
      }
      let prevLineno = -1;
      let index4 = -1;
      const linePieAngles = { await: 0, gpu: 0 };
      for (const l2 in ff[1].lines) {
        index4 += 1;
        const line4 = ff[1].lines[l2];
        if (false) {
          if (line4.lineno > prevLineno + 1) {
            s2 += "<tr>";
            for (let i2 = 0; i2 < columns.length; i2++) {
              s2 += "<td></td>";
            }
            s2 += `<td class="F${escape(
              ff[0]
            )}-blankline" style="line-height: 1px; background-color: lightgray" data-sort="${prevLineno + 1}">&nbsp;</td>`;
            s2 += "</tr>";
          }
        }
        prevLineno = line4.lineno;
        s2 += makeProfileLine(
          line4,
          docstringLines.has(index4),
          ff[0],
          fileIteration,
          prof,
          cpu_bars,
          memory_bars,
          memory_sparklines,
          memory_activity,
          gpu_pies,
          true,
          nrt_bars,
          nc_bars,
          nc_nrt_pies,
          total_nc_time[ff[0]],
          hasNeuronData,
          profiledFunctions,
          prof.async_profile || false,
          await_pies,
          linePieAngles
        );
      }
      s2 += "</tbody>";
      s2 += "</table>";
      if (prof.files[ff[0]].functions.length) {
        s2 += `<table class="profile table table-hover table-condensed" id="table-${tableID}">`;
        s2 += makeTableHeader(ff[0], prof.gpu, prof.gpu_device, prof.memory, {
          functions: true
        }, hasNeuronData, prof.async_profile || false);
        s2 += "<tbody>";
        tableID++;
        const fnPieAngles = { await: 0, gpu: 0 };
        for (const l2 in prof.files[ff[0]].functions) {
          const line4 = prof.files[ff[0]].functions[l2];
          s2 += makeProfileLine(
            line4,
            false,
            ff[0],
            fileIteration,
            prof,
            cpu_bars,
            memory_bars,
            memory_sparklines,
            memory_activity,
            gpu_pies,
            false,
            nrt_bars,
            nc_bars,
            nc_nrt_pies,
            total_nc_time[ff[0]],
            hasNeuronData,
            /* @__PURE__ */ new Set(),
            prof.async_profile || false,
            await_pies,
            fnPieAngles
          );
        }
        s2 += "</table>";
      }
      s2 += "</div>";
      if (fileIteration < files4.length) {
        s2 += "<hr>";
      }
    }
    files4 = files4.filter((x5) => !excludedFiles.has(x5));
    s2 += "</div>";
    const p2 = document.getElementById("profile");
    if (p2) {
      p2.innerHTML = s2;
    }
    for (const ff of files4) {
      const allHeaders = document.getElementsByClassName(
        `F${escape(ff[0])}-nonline`
      );
      for (let i2 = 0; i2 < allHeaders.length; i2++) {
        allHeaders[i2].addEventListener("click", () => {
          const all = document.getElementsByClassName(
            `F${escape(ff[0])}-blankline`
          );
          for (let i3 = 0; i3 < all.length; i3++) {
            all[i3].style.display = "none";
          }
        });
      }
    }
    for (const ff of files4) {
      const lineProfileHeader = document.getElementById(`${escape(ff[0])}-lineProfile`);
      if (lineProfileHeader) {
        lineProfileHeader.addEventListener("click", () => {
          const all = document.getElementsByClassName(
            `F${escape(ff[0])}-blankline`
          );
          for (let i2 = 0; i2 < all.length; i2++) {
            if (all[i2].style.display === "none") {
              all[i2].style.display = "block";
            }
          }
        });
      }
    }
    for (let i2 = 0; i2 < tableID; i2++) {
      const tableElement = document.getElementById(`table-${i2}`);
      if (tableElement) {
        new tablesort_default(tableElement, { ascending: true });
      }
    }
    memory_sparklines.forEach((p3, index4) => {
      if (p3) {
        (async () => {
          await embed(`#memory_sparkline${index4}`, p3, {
            actions: false,
            renderer: "svg"
          });
        })();
      }
    });
    function embedCharts(charts, prefix) {
      charts.forEach((chart, index4) => {
        if (chart) {
          (async () => {
            await embed(`#${prefix}${index4}`, chart, { actions: false });
          })();
        }
      });
    }
    embedCharts(cpu_bars, "cpu_bar");
    embedCharts(gpu_pies, "gpu_pie");
    embedCharts(await_pies, "await_pie");
    embedCharts(memory_activity, "memory_activity");
    embedCharts(memory_bars, "memory_bar");
    if (hasNeuronData) {
      for (let i2 = 0; i2 < nrt_bars.length; i2++) {
        if (nrt_bars[i2]) {
          (async () => {
            await embed(`#nrt_bar${i2}`, nrt_bars[i2], { actions: false });
          })();
        }
      }
      for (let i2 = 0; i2 < nc_bars.length; i2++) {
        if (nc_bars[i2]) {
          (async () => {
            await embed(`#nc_bar${i2}`, nc_bars[i2], { actions: false });
          })();
        }
      }
    }
    for (const id2 of allIds) {
      applyFileDisplayMode(id2, "profiled-functions");
    }
    if (prof.program) {
      document.title = "Scalene - " + prof.program;
    } else {
      document.title = "Scalene";
    }
  }
  function load3(profile2) {
    (async () => {
      await display(profile2);
    })();
  }
  function loadFetch() {
    (async () => {
      const resp = await fetch("profile.json");
      const profile2 = await resp.json();
      load3(profile2);
    })();
  }
  function loadFile() {
    const input = document.getElementById("fileinput");
    if (input && input.files && input.files[0]) {
      const file = input.files[0];
      const fr = new FileReader();
      fr.onload = doSomething;
      fr.readAsText(file);
    }
  }
  function doSomething(e4) {
    const target2 = e4.target;
    if (target2 && target2.result) {
      const lines = target2.result;
      const profile2 = JSON.parse(lines);
      load3(profile2);
    }
  }
  function loadDemo() {
    load3(example_profile);
  }
  var serviceFieldMap = {
    openai: "openai-fields",
    anthropic: "anthropic-fields",
    gemini: "gemini-fields",
    amazon: "amazon-fields",
    local: "local-fields",
    "azure-openai": "azure-openai-fields"
  };
  function toggleServiceFields() {
    const serviceSelect = document.getElementById("service-select");
    const service = serviceSelect?.value ?? "openai";
    window.localStorage.setItem("scalene-service-select", service);
    Object.entries(serviceFieldMap).forEach(([key2, fieldId]) => {
      const field3 = document.getElementById(fieldId);
      if (field3) {
        field3.classList.toggle("active", key2 === service);
      }
    });
  }
  function togglePassword(button) {
    const input = button.previousElementSibling;
    if (input) {
      if (input.type === "password") {
        input.type = "text";
        button.textContent = "Hide";
      } else {
        input.type = "password";
        button.textContent = "Show";
      }
    }
  }
  function toggleAdvanced(toggle2) {
    const advancedOptions = toggle2.nextElementSibling;
    if (advancedOptions) {
      const isShown = advancedOptions.classList.toggle("show");
      toggle2.innerHTML = (isShown ? "&#9660;" : "&#9654;") + " Advanced options";
    }
  }
  function populateModelSelect(selectId, models, currentValue) {
    const select2 = document.getElementById(selectId);
    if (!select2 || models.length === 0) return;
    const savedValue = currentValue || select2.value;
    select2.innerHTML = "";
    models.forEach((model) => {
      const option = document.createElement("option");
      option.value = model;
      option.textContent = model;
      select2.appendChild(option);
    });
    if (models.includes(savedValue)) {
      select2.value = savedValue;
    }
  }
  async function refreshOpenAIModels() {
    const apiKeyElement = document.getElementById("api-key");
    const apiKey = apiKeyElement?.value ?? "";
    if (!apiKey) {
      alert("Please enter an OpenAI API key first.");
      return;
    }
    const buttons = document.querySelectorAll("#openai-fields .btn-refresh");
    buttons.forEach((btn) => {
      btn.classList.add("loading");
      btn.disabled = true;
      btn.textContent = "...";
    });
    try {
      const models = await fetchOpenAIModels(apiKey);
      if (models.length > 0) {
        populateModelSelect("language-model-openai", models);
      } else {
        console.log("No models returned, keeping defaults");
      }
    } catch (error3) {
      console.error("Failed to fetch OpenAI models:", error3);
    } finally {
      buttons.forEach((btn) => {
        btn.classList.remove("loading");
        btn.disabled = false;
        btn.innerHTML = "&#8635;";
      });
    }
  }
  async function refreshGeminiModels() {
    const apiKeyElement = document.getElementById("gemini-api-key");
    const apiKey = apiKeyElement?.value ?? "";
    if (!apiKey) {
      alert("Please enter a Gemini API key first.");
      return;
    }
    const buttons = document.querySelectorAll("#gemini-fields .btn-refresh");
    buttons.forEach((btn) => {
      btn.classList.add("loading");
      btn.disabled = true;
      btn.textContent = "...";
    });
    try {
      const models = await fetchGeminiModels(apiKey);
      if (models.length > 0) {
        populateModelSelect("language-model-gemini", models);
      } else {
        console.log("No models returned, keeping defaults");
      }
    } catch (error3) {
      console.error("Failed to fetch Gemini models:", error3);
    } finally {
      buttons.forEach((btn) => {
        btn.classList.remove("loading");
        btn.disabled = false;
        btn.innerHTML = "&#8635;";
      });
    }
  }
  function revealInstallMessage() {
    const installMsg = document.getElementById("install-models-message");
    const localModelsList = document.getElementById("local-models-list");
    if (installMsg) {
      installMsg.style.display = "block";
    }
    if (localModelsList) {
      localModelsList.style.display = "none";
    }
  }
  function createSelectElement(modelNames) {
    const select2 = document.createElement("select");
    select2.style.fontSize = "0.8rem";
    select2.id = "language-model-local";
    select2.classList.add("persistent");
    select2.name = "language-model-local-label";
    modelNames.forEach((modelName) => {
      const option = document.createElement("option");
      option.value = modelName;
      option.textContent = modelName;
      option.id = modelName;
      select2.appendChild(option);
    });
    return select2;
  }
  function replaceDivWithSelect() {
    const localIpElement = document.getElementById("local-ip");
    const localPortElement = document.getElementById("local-port");
    const local_ip = localIpElement?.value ?? "127.0.0.1";
    const local_port = localPortElement?.value ?? "11434";
    fetchModelNames(local_ip, local_port, revealInstallMessage).then(
      (modelNames) => {
        const selectElement = createSelectElement(modelNames);
        const div = document.getElementById("language-local-models");
        if (div) {
          div.innerHTML = "";
          div.appendChild(selectElement);
        } else {
          console.error('Div with ID "language-local-models" not found.');
        }
      }
    );
  }
  replaceDivWithSelect();
  function getFirstProvider() {
    const serviceSelect = document.getElementById("service-select");
    return serviceSelect?.options[0]?.value ?? "amazon";
  }
  function getDefaultProvider() {
    const firstProvider = getFirstProvider();
    if (typeof envApiKeys === "undefined") {
      return firstProvider;
    }
    if (envApiKeys.awsAccessKey && envApiKeys.awsSecretKey) return "amazon";
    if (envApiKeys.anthropic) return "anthropic";
    if (envApiKeys.azure) return "azure-openai";
    if (envApiKeys.gemini) return "gemini";
    if (envApiKeys.openai) return "openai";
    return firstProvider;
  }
  function initializeDefaultProvider() {
    const serviceSelect = document.getElementById("service-select");
    if (serviceSelect) {
      const savedService = localStorage.getItem("service-select");
      if (!savedService) {
        serviceSelect.value = getDefaultProvider();
      }
      toggleServiceFields();
    }
  }
  document.addEventListener("DOMContentLoaded", () => {
    initializeDefaultProvider();
    processPersistentElements();
  });
  observeDOM();
  function sendHeartbeat() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "/heartbeat", true);
    xhr.send();
  }
  window.addEventListener("load", () => {
    load3(profile);
  });
  setInterval(sendHeartbeat, 1e4);
  window.vsNavigate = vsNavigate;
  window.proposeOptimizationRegion = proposeOptimizationRegion;
  window.proposeOptimizationLine = proposeOptimizationLine;
  window.collapseAll = collapseAll;
  window.expandAll = expandAll;
  window.toggleDisplay = toggleDisplay;
  window.toggleReduced = toggleReduced;
  window.onFileDisplayModeChange = onFileDisplayModeChange;
  window.load = load3;
  window.loadFetch = loadFetch;
  window.loadFile = loadFile;
  window.loadDemo = loadDemo;
  window.toggleServiceFields = toggleServiceFields;
  window.togglePassword = togglePassword;
  window.toggleAdvanced = toggleAdvanced;
  window.refreshOpenAIModels = refreshOpenAIModels;
  window.refreshGeminiModels = refreshGeminiModels;
  return __toCommonJS(scalene_gui_exports);
})();
/**
 * Prism: Lightweight, robust, elegant syntax highlighting
 *
 * @license MIT <https://opensource.org/licenses/MIT>
 * @author Lea Verou <https://lea.verou.me>
 * @namespace
 * @public
 */
/*! Bundled license information:

ieee754/index.js:
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)

buffer/index.js:
  (*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

vega-embed/build/vega-embed.module.js:
  (*!
   * https://github.com/Starcounter-Jack/JSON-Patch
   * (c) 2017-2022 Joachim Wester
   * MIT licensed
   *)
  (*!
   * https://github.com/Starcounter-Jack/JSON-Patch
   * (c) 2017-2021 Joachim Wester
   * MIT license
   *)
*/
