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, mod2) => function __require() {
  return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
};
var __export = (target, all) => {
  for (var name2 in all)
    __defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from2, except, desc2) => {
  if (from2 && typeof from2 === "object" || typeof from2 === "function") {
    for (let key of __getOwnPropNames(from2))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from2[key], enumerable: !(desc2 = __getOwnPropDesc(from2, key)) || desc2.enumerable });
  }
  return to;
};
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __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 || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
  mod2
));

// ../../../node_modules/binary-search-bounds/search-bounds.js
var require_search_bounds = __commonJS({
  "../../../node_modules/binary-search-bounds/search-bounds.js"(exports, module) {
    "use strict";
    function ge(a2, y3, c4, l, h) {
      var i = h + 1;
      while (l <= h) {
        var m = l + h >>> 1, x3 = a2[m];
        var p = c4 !== void 0 ? c4(x3, y3) : x3 - y3;
        if (p >= 0) {
          i = m;
          h = m - 1;
        } else {
          l = m + 1;
        }
      }
      return i;
    }
    function gt2(a2, y3, c4, l, h) {
      var i = h + 1;
      while (l <= h) {
        var m = l + h >>> 1, x3 = a2[m];
        var p = c4 !== void 0 ? c4(x3, y3) : x3 - y3;
        if (p > 0) {
          i = m;
          h = m - 1;
        } else {
          l = m + 1;
        }
      }
      return i;
    }
    function lt2(a2, y3, c4, l, h) {
      var i = l - 1;
      while (l <= h) {
        var m = l + h >>> 1, x3 = a2[m];
        var p = c4 !== void 0 ? c4(x3, y3) : x3 - y3;
        if (p < 0) {
          i = m;
          l = m + 1;
        } else {
          h = m - 1;
        }
      }
      return i;
    }
    function le(a2, y3, c4, l, h) {
      var i = l - 1;
      while (l <= h) {
        var m = l + h >>> 1, x3 = a2[m];
        var p = c4 !== void 0 ? c4(x3, y3) : x3 - y3;
        if (p <= 0) {
          i = m;
          l = m + 1;
        } else {
          h = m - 1;
        }
      }
      return i;
    }
    function eq2(a2, y3, c4, l, h) {
      while (l <= h) {
        var m = l + h >>> 1, x3 = a2[m];
        var p = c4 !== void 0 ? c4(x3, y3) : x3 - y3;
        if (p === 0) {
          return m;
        }
        if (p <= 0) {
          l = m + 1;
        } else {
          h = m - 1;
        }
      }
      return -1;
    }
    function norm2(a2, y3, c4, l, h, f) {
      if (typeof c4 === "function") {
        return f(a2, y3, c4, l === void 0 ? 0 : l | 0, h === void 0 ? a2.length - 1 : h | 0);
      }
      return f(a2, y3, void 0, c4 === void 0 ? 0 : c4 | 0, l === void 0 ? a2.length - 1 : l | 0);
    }
    module.exports = {
      ge: function(a2, y3, c4, l, h) {
        return norm2(a2, y3, c4, l, h, ge);
      },
      gt: function(a2, y3, c4, l, h) {
        return norm2(a2, y3, c4, l, h, gt2);
      },
      lt: function(a2, y3, c4, l, h) {
        return norm2(a2, y3, c4, l, h, lt2);
      },
      le: function(a2, y3, c4, l, h) {
        return norm2(a2, y3, c4, l, h, le);
      },
      eq: function(a2, y3, c4, l, h) {
        return norm2(a2, y3, c4, l, h, eq2);
      }
    };
  }
});

// ../../../node_modules/interval-tree-1d/interval-tree.js
var require_interval_tree = __commonJS({
  "../../../node_modules/interval-tree-1d/interval-tree.js"(exports, module) {
    "use strict";
    var bounds = require_search_bounds();
    var NOT_FOUND = 0;
    var SUCCESS = 1;
    var EMPTY = 2;
    module.exports = createWrapper;
    function IntervalTreeNode(mid2, left2, right2, leftPoints, rightPoints) {
      this.mid = mid2;
      this.left = left2;
      this.right = right2;
      this.leftPoints = leftPoints;
      this.rightPoints = rightPoints;
      this.count = (left2 ? left2.count : 0) + (right2 ? right2.count : 0) + leftPoints.length;
    }
    var proto = IntervalTreeNode.prototype;
    function copy4(a2, b) {
      a2.mid = b.mid;
      a2.left = b.left;
      a2.right = b.right;
      a2.leftPoints = b.leftPoints;
      a2.rightPoints = b.rightPoints;
      a2.count = b.count;
    }
    function rebuild(node, intervals) {
      var ntree = createIntervalTree(intervals);
      node.mid = ntree.mid;
      node.left = ntree.left;
      node.right = ntree.right;
      node.leftPoints = ntree.leftPoints;
      node.rightPoints = ntree.rightPoints;
      node.count = ntree.count;
    }
    function rebuildWithInterval(node, interval4) {
      var intervals = node.intervals([]);
      intervals.push(interval4);
      rebuild(node, intervals);
    }
    function rebuildWithoutInterval(node, interval4) {
      var intervals = node.intervals([]);
      var idx = intervals.indexOf(interval4);
      if (idx < 0) {
        return NOT_FOUND;
      }
      intervals.splice(idx, 1);
      rebuild(node, intervals);
      return SUCCESS;
    }
    proto.intervals = function(result) {
      result.push.apply(result, this.leftPoints);
      if (this.left) {
        this.left.intervals(result);
      }
      if (this.right) {
        this.right.intervals(result);
      }
      return result;
    };
    proto.insert = function(interval4) {
      var weight = this.count - this.leftPoints.length;
      this.count += 1;
      if (interval4[1] < this.mid) {
        if (this.left) {
          if (4 * (this.left.count + 1) > 3 * (weight + 1)) {
            rebuildWithInterval(this, interval4);
          } else {
            this.left.insert(interval4);
          }
        } else {
          this.left = createIntervalTree([interval4]);
        }
      } else if (interval4[0] > this.mid) {
        if (this.right) {
          if (4 * (this.right.count + 1) > 3 * (weight + 1)) {
            rebuildWithInterval(this, interval4);
          } else {
            this.right.insert(interval4);
          }
        } else {
          this.right = createIntervalTree([interval4]);
        }
      } else {
        var l = bounds.ge(this.leftPoints, interval4, compareBegin);
        var r = bounds.ge(this.rightPoints, interval4, compareEnd);
        this.leftPoints.splice(l, 0, interval4);
        this.rightPoints.splice(r, 0, interval4);
      }
    };
    proto.remove = function(interval4) {
      var weight = this.count - this.leftPoints;
      if (interval4[1] < this.mid) {
        if (!this.left) {
          return NOT_FOUND;
        }
        var rw = this.right ? this.right.count : 0;
        if (4 * rw > 3 * (weight - 1)) {
          return rebuildWithoutInterval(this, interval4);
        }
        var r = this.left.remove(interval4);
        if (r === EMPTY) {
          this.left = null;
          this.count -= 1;
          return SUCCESS;
        } else if (r === SUCCESS) {
          this.count -= 1;
        }
        return r;
      } else if (interval4[0] > this.mid) {
        if (!this.right) {
          return NOT_FOUND;
        }
        var lw = this.left ? this.left.count : 0;
        if (4 * lw > 3 * (weight - 1)) {
          return rebuildWithoutInterval(this, interval4);
        }
        var r = this.right.remove(interval4);
        if (r === EMPTY) {
          this.right = null;
          this.count -= 1;
          return SUCCESS;
        } else if (r === SUCCESS) {
          this.count -= 1;
        }
        return r;
      } else {
        if (this.count === 1) {
          if (this.leftPoints[0] === interval4) {
            return EMPTY;
          } else {
            return NOT_FOUND;
          }
        }
        if (this.leftPoints.length === 1 && this.leftPoints[0] === interval4) {
          if (this.left && this.right) {
            var p = this;
            var n = this.left;
            while (n.right) {
              p = n;
              n = n.right;
            }
            if (p === this) {
              n.right = this.right;
            } else {
              var l = this.left;
              var r = this.right;
              p.count -= n.count;
              p.right = n.left;
              n.left = l;
              n.right = r;
            }
            copy4(this, n);
            this.count = (this.left ? this.left.count : 0) + (this.right ? this.right.count : 0) + this.leftPoints.length;
          } else if (this.left) {
            copy4(this, this.left);
          } else {
            copy4(this, this.right);
          }
          return SUCCESS;
        }
        for (var l = bounds.ge(this.leftPoints, interval4, compareBegin); l < this.leftPoints.length; ++l) {
          if (this.leftPoints[l][0] !== interval4[0]) {
            break;
          }
          if (this.leftPoints[l] === interval4) {
            this.count -= 1;
            this.leftPoints.splice(l, 1);
            for (var r = bounds.ge(this.rightPoints, interval4, compareEnd); r < this.rightPoints.length; ++r) {
              if (this.rightPoints[r][1] !== interval4[1]) {
                break;
              } else if (this.rightPoints[r] === interval4) {
                this.rightPoints.splice(r, 1);
                return SUCCESS;
              }
            }
          }
        }
        return NOT_FOUND;
      }
    };
    function reportLeftRange(arr, hi, cb) {
      for (var i = 0; i < arr.length && arr[i][0] <= hi; ++i) {
        var r = cb(arr[i]);
        if (r) {
          return r;
        }
      }
    }
    function reportRightRange(arr, lo, cb) {
      for (var i = arr.length - 1; i >= 0 && arr[i][1] >= lo; --i) {
        var r = cb(arr[i]);
        if (r) {
          return r;
        }
      }
    }
    function reportRange(arr, cb) {
      for (var i = 0; i < arr.length; ++i) {
        var r = cb(arr[i]);
        if (r) {
          return r;
        }
      }
    }
    proto.queryPoint = function(x3, cb) {
      if (x3 < this.mid) {
        if (this.left) {
          var r = this.left.queryPoint(x3, cb);
          if (r) {
            return r;
          }
        }
        return reportLeftRange(this.leftPoints, x3, cb);
      } else if (x3 > this.mid) {
        if (this.right) {
          var r = this.right.queryPoint(x3, cb);
          if (r) {
            return r;
          }
        }
        return reportRightRange(this.rightPoints, x3, cb);
      } else {
        return reportRange(this.leftPoints, cb);
      }
    };
    proto.queryInterval = function(lo, hi, cb) {
      if (lo < this.mid && this.left) {
        var r = this.left.queryInterval(lo, hi, cb);
        if (r) {
          return r;
        }
      }
      if (hi > this.mid && this.right) {
        var r = this.right.queryInterval(lo, hi, cb);
        if (r) {
          return r;
        }
      }
      if (hi < this.mid) {
        return reportLeftRange(this.leftPoints, hi, cb);
      } else if (lo > this.mid) {
        return reportRightRange(this.rightPoints, lo, cb);
      } else {
        return reportRange(this.leftPoints, cb);
      }
    };
    function compareNumbers(a2, b) {
      return a2 - b;
    }
    function compareBegin(a2, b) {
      var d = a2[0] - b[0];
      if (d) {
        return d;
      }
      return a2[1] - b[1];
    }
    function compareEnd(a2, b) {
      var d = a2[1] - b[1];
      if (d) {
        return d;
      }
      return a2[0] - b[0];
    }
    function createIntervalTree(intervals) {
      if (intervals.length === 0) {
        return null;
      }
      var pts = [];
      for (var i = 0; i < intervals.length; ++i) {
        pts.push(intervals[i][0], intervals[i][1]);
      }
      pts.sort(compareNumbers);
      var mid2 = pts[pts.length >> 1];
      var leftIntervals = [];
      var rightIntervals = [];
      var centerIntervals = [];
      for (var i = 0; i < intervals.length; ++i) {
        var s2 = intervals[i];
        if (s2[1] < mid2) {
          leftIntervals.push(s2);
        } else if (mid2 < s2[0]) {
          rightIntervals.push(s2);
        } else {
          centerIntervals.push(s2);
        }
      }
      var leftPoints = centerIntervals;
      var rightPoints = centerIntervals.slice();
      leftPoints.sort(compareBegin);
      rightPoints.sort(compareEnd);
      return new IntervalTreeNode(
        mid2,
        createIntervalTree(leftIntervals),
        createIntervalTree(rightIntervals),
        leftPoints,
        rightPoints
      );
    }
    function IntervalTree2(root2) {
      this.root = root2;
    }
    var tproto = IntervalTree2.prototype;
    tproto.insert = function(interval4) {
      if (this.root) {
        this.root.insert(interval4);
      } else {
        this.root = new IntervalTreeNode(interval4[0], null, null, [interval4], [interval4]);
      }
    };
    tproto.remove = function(interval4) {
      if (this.root) {
        var r = this.root.remove(interval4);
        if (r === EMPTY) {
          this.root = null;
        }
        return r !== NOT_FOUND;
      }
      return false;
    };
    tproto.queryPoint = function(p, cb) {
      if (this.root) {
        return this.root.queryPoint(p, cb);
      }
    };
    tproto.queryInterval = function(lo, hi, cb) {
      if (lo <= hi && this.root) {
        return this.root.queryInterval(lo, hi, cb);
      }
    };
    Object.defineProperty(tproto, "count", {
      get: function() {
        if (this.root) {
          return this.root.count;
        }
        return 0;
      }
    });
    Object.defineProperty(tproto, "intervals", {
      get: function() {
        if (this.root) {
          return this.root.intervals([]);
        }
        return [];
      }
    });
    function createWrapper(intervals) {
      if (!intervals || intervals.length === 0) {
        return new IntervalTree2(null);
      }
      return new IntervalTree2(createIntervalTree(intervals));
    }
  }
});

// ../../mosaic/core/dist/src/util/throttle.js
var NIL = {};
function throttle(callback, debounce = false) {
  let curr;
  let next;
  let pending = NIL;
  function invoke(event) {
    curr = callback(event)?.catch(() => {
    }).finally(() => {
      if (next) {
        const { event: value } = next;
        next = null;
        invoke(value);
      } else {
        curr = null;
      }
    }) || null;
  }
  function enqueue(event) {
    next = { event };
  }
  function process(event) {
    if (curr)
      enqueue(event);
    else
      invoke(event);
  }
  function delay(event) {
    if (pending !== event) {
      requestAnimationFrame(() => {
        const e = pending;
        pending = NIL;
        process(e);
      });
    }
    pending = event;
  }
  return debounce ? delay : process;
}

// ../../mosaic/core/dist/src/MosaicClient.js
function isMosaicClient(x3) {
  return x3 instanceof MosaicClient;
}
var MosaicClient = class {
  _filterBy;
  _requestUpdate;
  _coordinator;
  _pending;
  _enabled;
  _initialized;
  _request;
  /**
   * Create a new client instance.
   * @param filterSelection An optional selection to
   *  interactively filter this client's data. If provided, a coordinator
   *  will re-query and update the client when the selection updates.
   */
  constructor(filterSelection) {
    this._filterBy = filterSelection;
    this._requestUpdate = throttle(() => this.requestQuery(), true);
    this._coordinator = null;
    this._pending = Promise.resolve();
    this._enabled = true;
    this._initialized = false;
    this._request = null;
  }
  /**
   * @returns this client's connected coordinator.
   */
  get coordinator() {
    return this._coordinator;
  }
  /**
   * Set this client's connected coordinator.
   */
  set coordinator(coordinator2) {
    this._coordinator = coordinator2;
  }
  /**
   * Return this client's enabled state.
   */
  get enabled() {
    return this._enabled;
  }
  /**
   * Set this client's enabled state;
   */
  set enabled(state) {
    state = !!state;
    if (this._enabled !== state) {
      this._enabled = state;
      if (state) {
        if (!this._initialized) {
          this.initialize();
        } else if (this._request) {
          this.requestQuery(this._request === true ? void 0 : this._request);
        }
        this._request = null;
      }
    }
  }
  /**
   * Return a Promise that resolves once the client has updated.
   */
  get pending() {
    return this._pending;
  }
  /**
   * @returns this client's filter selection.
   */
  get filterBy() {
    return this._filterBy;
  }
  /**
   * Return a boolean indicating if the client query can be sped up with
   * materialized views of pre-aggregated data. Should return true if changes
   * to the filterBy selection do not change the groupby domain of the client
   * query.
   */
  get filterStable() {
    return true;
  }
  /**
   * Prepare the client before the `query()` method is called. Subclasses
   * should override this method as needed, potentially issuing one or more
   * queries to gather data or metadata needed prior to `query` calls.
   */
  async prepare() {
  }
  /**
   * Return a query specifying the data needed by this client.
   * @param filter The filtering criteria to apply in the query.
   * @returns The client query
   */
  query(filter3) {
    return null;
  }
  /**
   * Called by the coordinator to inform the client that a query is pending.
   * @returns this
   */
  queryPending() {
    return this;
  }
  /**
   * Called by the coordinator to return a query result.
   * @param data The query result.
   * @returns this
   */
  queryResult(data) {
    return this;
  }
  /**
   * Called by the coordinator to report a query execution error.
   * @param error
   * @returns this
   */
  queryError(error2) {
    return this;
  }
  /**
   * Request the coordinator to execute a query for this client.
   * If an explicit query is not provided, the client `query` method will
   * be called, filtered by the current `filterBy` selection. This method has
   * no effect if the client is not connected to a coordinator. If the client
   * is connected by currently disabled, the request will be serviced if the
   * client is later enabled.
   * @param query The query to request. If unspecified, the query
   *  will be determined by the client's `query` method and the current
   *  `filterBy` selection state.
   */
  requestQuery(query) {
    if (this._enabled) {
      const q = query || this.query(this.filterBy?.predicate(this));
      return this._coordinator.requestQuery(this, q);
    } else {
      this._request = query ?? true;
      return null;
    }
  }
  /**
   * Request that the coordinator perform a throttled update of this client
   * using the default query. Unlike requestQuery, for which every call results
   * in an executed query, multiple calls to requestUpdate may be consolidated
   * into a single update. This method has no effect if the client is not
   * connected to a coordinator. If the client is connected but currently
   * disabled, the request will be serviced if the client is later enabled.
   */
  requestUpdate() {
    if (this._enabled) {
      this._requestUpdate();
    } else {
      this.requestQuery();
    }
  }
  /**
   * Reset this client, calling the prepare method and query requests. This
   * method has no effect if the client is not registered with a coordinator.
   */
  initialize() {
    if (!this._enabled) {
      this._initialized = false;
    } else if (this._coordinator) {
      this._initialized = true;
      this._pending = this.prepare().then(() => this.requestQuery());
    }
  }
  /**
   * Remove this client: disconnect from the coordinator and free up any
   * resource use. This method has no effect if the client is not connected
   * to a coordinator.
   *
   * If overriding this method in a client subclass, be sure to also
   * disconnect from the coordinator.
   */
  destroy() {
    this._enabled = false;
    this.coordinator?.disconnect(this);
  }
  /**
   * Requests a client update, for example to (re-)render an interface
   * component.
   */
  update() {
    return this;
  }
};

// ../../../node_modules/@uwdata/flechette/src/constants.js
var MAGIC = Uint8Array.of(65, 82, 82, 79, 87, 49);
var EOS = Uint8Array.of(255, 255, 255, 255, 0, 0, 0, 0);
var Version = (
  /** @type {const} */
  {
    /** 0.1.0 (October 2016). */
    V1: 0,
    /** 0.2.0 (February 2017). Non-backwards compatible with V1. */
    V2: 1,
    /** 0.3.0 -> 0.7.1 (May - December 2017). Non-backwards compatible with V2. */
    V3: 2,
    /** >= 0.8.0 (December 2017). Non-backwards compatible with V3. */
    V4: 3,
    /**
     * >= 1.0.0 (July 2020). Backwards compatible with V4 (V5 readers can read V4
     * metadata and IPC messages). Implementations are recommended to provide a
     * V4 compatibility mode with V5 format changes disabled.
     *
     * Incompatible changes between V4 and V5:
     * - Union buffer layout has changed.
     *   In V5, Unions don't have a validity bitmap buffer.
     */
    V5: 4
  }
);
var MessageHeader = (
  /** @type {const} */
  {
    NONE: 0,
    /**
     * A Schema describes the columns in a record batch.
     */
    Schema: 1,
    /**
     * For sending dictionary encoding information. Any Field can be
     * dictionary-encoded, but in this case none of its children may be
     * dictionary-encoded.
     * There is one vector / column per dictionary, but that vector / column
     * may be spread across multiple dictionary batches by using the isDelta
     * flag.
     */
    DictionaryBatch: 2,
    /**
     * A data header describing the shared memory layout of a "record" or "row"
     * batch. Some systems call this a "row batch" internally and others a "record
     * batch".
     */
    RecordBatch: 3,
    /**
     * EXPERIMENTAL: Metadata for n-dimensional arrays, aka "tensors" or
     * "ndarrays". Arrow implementations in general are not required to implement
     * this type.
     *
     * Not currently supported by Flechette.
     */
    Tensor: 4,
    /**
     * EXPERIMENTAL: Metadata for n-dimensional sparse arrays, aka "sparse
     * tensors". Arrow implementations in general are not required to implement
     * this type.
     *
     * Not currently supported by Flechette.
     */
    SparseTensor: 5
  }
);
var Type = (
  /** @type {const} */
  {
    /**
     * Dictionary types compress data by using a set of integer indices to
     * lookup potentially repeated vales in a separate dictionary of values.
     *
     * This type entry is provided for API convenience, it does not occur
     * in actual Arrow IPC binary data.
     */
    Dictionary: -1,
    /** No data type. Included for flatbuffer compatibility. */
    NONE: 0,
    /** Null values only. */
    Null: 1,
    /** Integers, either signed or unsigned, with 8, 16, 32, or 64 bit widths. */
    Int: 2,
    /** Floating point numbers with 16, 32, or 64 bit precision. */
    Float: 3,
    /** Opaque binary data. */
    Binary: 4,
    /** Unicode with UTF-8 encoding. */
    Utf8: 5,
    /** Booleans represented as 8 bit bytes. */
    Bool: 6,
    /**
     * Exact decimal value represented as an integer value in two's complement.
     * Currently only 128-bit (16-byte) and 256-bit (32-byte) integers are used.
     * The representation uses the endianness indicated in the schema.
     */
    Decimal: 7,
    /**
     * Date is either a 32-bit or 64-bit signed integer type representing an
     * elapsed time since UNIX epoch (1970-01-01), stored in either of two units:
     * - Milliseconds (64 bits) indicating UNIX time elapsed since the epoch (no
     * leap seconds), where the values are evenly divisible by 86400000
     * - Days (32 bits) since the UNIX epoch
     */
    Date: 8,
    /**
     * Time is either a 32-bit or 64-bit signed integer type representing an
     * elapsed time since midnight, stored in either of four units: seconds,
     * milliseconds, microseconds or nanoseconds.
     *
     * The integer `bitWidth` depends on the `unit` and must be one of the following:
     * - SECOND and MILLISECOND: 32 bits
     * - MICROSECOND and NANOSECOND: 64 bits
     *
     * The allowed values are between 0 (inclusive) and 86400 (=24*60*60) seconds
     * (exclusive), adjusted for the time unit (for example, up to 86400000
     * exclusive for the MILLISECOND unit).
     * This definition doesn't allow for leap seconds. Time values from
     * measurements with leap seconds will need to be corrected when ingesting
     * into Arrow (for example by replacing the value 86400 with 86399).
     */
    Time: 9,
    /**
     * Timestamp is a 64-bit signed integer representing an elapsed time since a
     * fixed epoch, stored in either of four units: seconds, milliseconds,
     * microseconds or nanoseconds, and is optionally annotated with a timezone.
     *
     * Timestamp values do not include any leap seconds (in other words, all
     * days are considered 86400 seconds long).
     *
     * The timezone is an optional string for the name of a timezone, one of:
     *
     *  - As used in the Olson timezone database (the "tz database" or
     *    "tzdata"), such as "America/New_York".
     *  - An absolute timezone offset of the form "+XX:XX" or "-XX:XX",
     *    such as "+07:30".
     *
     * Whether a timezone string is present indicates different semantics about
     * the data.
     */
    Timestamp: 10,
    /**
     * A "calendar" interval which models types that don't necessarily
     * have a precise duration without the context of a base timestamp (e.g.
     * days can differ in length during day light savings time transitions).
     * All integers in the units below are stored in the endianness indicated
     * by the schema.
     *
     *  - YEAR_MONTH - Indicates the number of elapsed whole months, stored as
     *    4-byte signed integers.
     *  - DAY_TIME - Indicates the number of elapsed days and milliseconds (no
     *    leap seconds), stored as 2 contiguous 32-bit signed integers (8-bytes
     *    in total). Support of this IntervalUnit is not required for full arrow
     *    compatibility.
     *  - MONTH_DAY_NANO - A triple of the number of elapsed months, days, and
     *    nanoseconds. The values are stored contiguously in 16-byte blocks.
     *    Months and days are encoded as 32-bit signed integers and nanoseconds
     *    is encoded as a 64-bit signed integer. Nanoseconds does not allow for
     *    leap seconds. Each field is independent (e.g. there is no constraint
     *    that nanoseconds have the same sign as days or that the quantity of
     *    nanoseconds represents less than a day's worth of time).
     */
    Interval: 11,
    /**
     * List (vector) data supporting variably-sized lists.
     * A list has a single child data type for list entries.
     */
    List: 12,
    /**
     * A struct consisting of multiple named child data types.
     */
    Struct: 13,
    /**
     * A union is a complex type with parallel child data types. By default ids
     * in the type vector refer to the offsets in the children. Optionally
     * typeIds provides an indirection between the child offset and the type id.
     * For each child `typeIds[offset]` is the id used in the type vector.
     */
    Union: 14,
    /**
     * Binary data where each entry has the same fixed size.
     */
    FixedSizeBinary: 15,
    /**
     * List (vector) data where every list has the same fixed size.
     * A list has a single child data type for list entries.
     */
    FixedSizeList: 16,
    /**
     * A Map is a logical nested type that is represented as
     * List<entries: Struct<key: K, value: V>>
     *
     * In this layout, the keys and values are each respectively contiguous. We do
     * not constrain the key and value types, so the application is responsible
     * for ensuring that the keys are hashable and unique. Whether the keys are sorted
     * may be set in the metadata for this field.
     *
     * In a field with Map type, the field has a child Struct field, which then
     * has two children: key type and the second the value type. The names of the
     * child fields may be respectively "entries", "key", and "value", but this is
     * not enforced.
     *
     * Map
     * ```text
     *   - child[0] entries: Struct
     *   - child[0] key: K
     *   - child[1] value: V
     *  ```
     * Neither the "entries" field nor the "key" field may be nullable.
     *
     * The metadata is structured so that Arrow systems without special handling
     * for Map can make Map an alias for List. The "layout" attribute for the Map
     * field must have the same contents as a List.
     */
    Map: 17,
    /**
     * An absolute length of time unrelated to any calendar artifacts. For the
     * purposes of Arrow implementations, adding this value to a Timestamp
     * ("t1") naively (i.e. simply summing the two numbers) is acceptable even
     * though in some cases the resulting Timestamp (t2) would not account for
     * leap-seconds during the elapsed time between "t1" and "t2". Similarly,
     * representing the difference between two Unix timestamp is acceptable, but
     * would yield a value that is possibly a few seconds off from the true
     * elapsed time.
     *
     * The resolution defaults to millisecond, but can be any of the other
     * supported TimeUnit values as with Timestamp and Time types. This type is
     * always represented as an 8-byte integer.
     */
    Duration: 18,
    /**
     * Same as Binary, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeBinary: 19,
    /**
     * Same as Utf8, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeUtf8: 20,
    /**
     * Same as List, but with 64-bit offsets, allowing representation of
     * extremely large data values.
     */
    LargeList: 21,
    /**
     * Contains two child arrays, run_ends and values. The run_ends child array
     * must be a 16/32/64-bit integer array which encodes the indices at which
     * the run with the value in each corresponding index in the values child
     * array ends. Like list/struct types, the value array can be of any type.
     */
    RunEndEncoded: 22,
    /**
     * Logically the same as Binary, but the internal representation uses a view
     * struct that contains the string length and either the string's entire data
     * inline (for small strings) or an inlined prefix, an index of another buffer,
     * and an offset pointing to a slice in that buffer (for non-small strings).
     *
     * Since it uses a variable number of data buffers, each Field with this type
     * must have a corresponding entry in `variadicBufferCounts`.
     */
    BinaryView: 23,
    /**
     * Logically the same as Utf8, but the internal representation uses a view
     * struct that contains the string length and either the string's entire data
     * inline (for small strings) or an inlined prefix, an index of another buffer,
     * and an offset pointing to a slice in that buffer (for non-small strings).
     *
     * Since it uses a variable number of data buffers, each Field with this type
     * must have a corresponding entry in `variadicBufferCounts`.
     */
    Utf8View: 24,
    /**
     * Represents the same logical types that List can, but contains offsets and
     * sizes allowing for writes in any order and sharing of child values among
     * list values.
     */
    ListView: 25,
    /**
     * Same as ListView, but with 64-bit offsets and sizes, allowing to represent
     * extremely large data values.
     */
    LargeListView: 26
  }
);
var Precision = (
  /** @type {const} */
  {
    /** 16-bit floating point number. */
    HALF: 0,
    /** 32-bit floating point number. */
    SINGLE: 1,
    /** 64-bit floating point number. */
    DOUBLE: 2
  }
);
var DateUnit = (
  /** @type {const} */
  {
    /* Days (as 32 bit int) since the UNIX epoch. */
    DAY: 0,
    /**
     * Milliseconds (as 64 bit int) indicating UNIX time elapsed since the epoch
     * (no leap seconds), with values evenly divisible by 86400000.
     */
    MILLISECOND: 1
  }
);
var TimeUnit = (
  /** @type {const} */
  {
    /** Seconds. */
    SECOND: 0,
    /** Milliseconds. */
    MILLISECOND: 1,
    /** Microseconds. */
    MICROSECOND: 2,
    /** Nanoseconds. */
    NANOSECOND: 3
  }
);
var IntervalUnit = (
  /** @type {const} */
  {
    /**
     * Indicates the number of elapsed whole months, stored as 4-byte signed
     * integers.
     */
    YEAR_MONTH: 0,
    /**
     * Indicates the number of elapsed days and milliseconds (no leap seconds),
     * stored as 2 contiguous 32-bit signed integers (8-bytes in total). Support
     * of this IntervalUnit is not required for full arrow compatibility.
     */
    DAY_TIME: 1,
    /**
     * A triple of the number of elapsed months, days, and nanoseconds.
     * The values are stored contiguously in 16-byte blocks. Months and days are
     * encoded as 32-bit signed integers and nanoseconds is encoded as a 64-bit
     * signed integer. Nanoseconds does not allow for leap seconds. Each field is
     * independent (e.g. there is no constraint that nanoseconds have the same
     * sign as days or that the quantity of nanoseconds represents less than a
     * day's worth of time).
     */
    MONTH_DAY_NANO: 2
  }
);
var UnionMode = (
  /** @type {const} */
  {
    /** Sparse union layout with full arrays for each sub-type. */
    Sparse: 0,
    /** Dense union layout with offsets into value arrays. */
    Dense: 1
  }
);

// ../../../node_modules/@uwdata/flechette/src/util/arrays.js
var uint8Array = Uint8Array;
var uint16Array = Uint16Array;
var uint32Array = Uint32Array;
var uint64Array = BigUint64Array;
var int8Array = Int8Array;
var int16Array = Int16Array;
var int32Array = Int32Array;
var int64Array = BigInt64Array;
var float32Array = Float32Array;
var float64Array = Float64Array;
function isArrayBufferLike(data) {
  return data instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && data instanceof SharedArrayBuffer;
}
function intArrayType(bitWidth, signed) {
  const i = Math.log2(bitWidth) - 3;
  return (signed ? [int8Array, int16Array, int32Array, int64Array] : [uint8Array, uint16Array, uint32Array, uint64Array])[i];
}
var TypedArray = Object.getPrototypeOf(Int8Array);
function bisect(offsets, index2) {
  let a2 = 0;
  let b = offsets.length;
  if (b <= 2147483648) {
    do {
      const mid2 = a2 + b >>> 1;
      if (offsets[mid2] <= index2) a2 = mid2 + 1;
      else b = mid2;
    } while (a2 < b);
  } else {
    do {
      const mid2 = Math.trunc((a2 + b) / 2);
      if (offsets[mid2] <= index2) a2 = mid2 + 1;
      else b = mid2;
    } while (a2 < b);
  }
  return a2;
}

// ../../../node_modules/@uwdata/flechette/src/util/objects.js
function check(value, test, message) {
  if (test(value)) return value;
  throw new Error(message(value));
}
function checkOneOf(value, set3, message) {
  set3 = Array.isArray(set3) ? set3 : Object.values(set3);
  return check(
    value,
    (value2) => set3.includes(value2),
    message ?? (() => `${value} must be one of ${set3}`)
  );
}
function keyFor(object, value) {
  for (const [key, val] of Object.entries(object)) {
    if (val === value) return key;
  }
  return "<Unknown>";
}

// ../../../node_modules/@uwdata/flechette/src/data-types.js
var invalidDataType = (typeId) => `Unsupported data type: "${keyFor(Type, typeId)}" (id ${typeId})`;
var field = (name2, type2, nullable = true, metadata = null) => ({
  name: name2,
  type: type2,
  nullable,
  metadata
});
function isField(value) {
  return Object.hasOwn(value, "name") && isDataType(value.type);
}
function isDataType(value) {
  return typeof value?.typeId === "number";
}
function asField(value, defaultName = "", defaultNullable = true) {
  return isField(value) ? value : field(
    defaultName,
    check(value, isDataType, () => `Data type expected.`),
    defaultNullable
  );
}
var dictionary = (type2, indexType, ordered = false, id2 = -1) => ({
  typeId: Type.Dictionary,
  id: id2,
  dictionary: type2,
  indices: indexType || int32(),
  ordered
});
var int = (bitWidth = 32, signed = true) => ({
  typeId: Type.Int,
  bitWidth: checkOneOf(bitWidth, [8, 16, 32, 64]),
  signed,
  values: intArrayType(bitWidth, signed)
});
var int32 = () => int(32);
var float = (precision = 2) => ({
  typeId: Type.Float,
  precision: checkOneOf(precision, Precision),
  values: [uint16Array, float32Array, float64Array][precision]
});
var binary = () => ({
  typeId: Type.Binary,
  offsets: int32Array
});
var utf8 = () => ({
  typeId: Type.Utf8,
  offsets: int32Array
});
var decimal = (precision, scale3, bitWidth = 128) => ({
  typeId: Type.Decimal,
  precision,
  scale: scale3,
  bitWidth: checkOneOf(bitWidth, [32, 64, 128, 256]),
  values: bitWidth === 32 ? int32Array : uint64Array
});
var date = (unit3) => ({
  typeId: Type.Date,
  unit: checkOneOf(unit3, DateUnit),
  values: unit3 === DateUnit.DAY ? int32Array : int64Array
});
var time = (unit3 = TimeUnit.MILLISECOND, bitWidth = 32) => ({
  typeId: Type.Time,
  unit: checkOneOf(unit3, TimeUnit),
  bitWidth: checkOneOf(bitWidth, [32, 64]),
  values: bitWidth === 32 ? int32Array : int64Array
});
var timestamp = (unit3 = TimeUnit.MILLISECOND, timezone = null) => ({
  typeId: Type.Timestamp,
  unit: checkOneOf(unit3, TimeUnit),
  timezone,
  values: int64Array
});
var interval = (unit3 = IntervalUnit.MONTH_DAY_NANO) => ({
  typeId: Type.Interval,
  unit: checkOneOf(unit3, IntervalUnit),
  values: unit3 === IntervalUnit.MONTH_DAY_NANO ? void 0 : int32Array
});
var list = (child) => ({
  typeId: Type.List,
  children: [asField(child)],
  offsets: int32Array
});
var struct = (children2) => ({
  typeId: Type.Struct,
  children: Array.isArray(children2) && isField(children2[0]) ? (
    /** @type {Field[]} */
    children2
  ) : Object.entries(children2).map(([name2, type2]) => field(name2, type2))
});
var union = (mode3, children2, typeIds, typeIdForValue) => {
  typeIds ??= children2.map((v2, i) => i);
  return {
    typeId: Type.Union,
    mode: checkOneOf(mode3, UnionMode),
    typeIds,
    typeMap: typeIds.reduce((m, id2, i) => (m[id2] = i, m), {}),
    children: children2.map((v2, i) => asField(v2, `_${i}`)),
    typeIdForValue,
    offsets: int32Array
  };
};
var fixedSizeBinary = (stride) => ({
  typeId: Type.FixedSizeBinary,
  stride
});
var fixedSizeList = (child, stride) => ({
  typeId: Type.FixedSizeList,
  stride,
  children: [asField(child)]
});
var mapType = (keysSorted, child) => ({
  typeId: Type.Map,
  keysSorted,
  children: [child],
  offsets: int32Array
});
var duration = (unit3 = TimeUnit.MILLISECOND) => ({
  typeId: Type.Duration,
  unit: checkOneOf(unit3, TimeUnit),
  values: int64Array
});
var largeBinary = () => ({
  typeId: Type.LargeBinary,
  offsets: int64Array
});
var largeUtf8 = () => ({
  typeId: Type.LargeUtf8,
  offsets: int64Array
});
var largeList = (child) => ({
  typeId: Type.LargeList,
  children: [asField(child)],
  offsets: int64Array
});
var runEndEncoded = (runsField, valuesField) => ({
  typeId: Type.RunEndEncoded,
  children: [
    check(
      asField(runsField, "run_ends"),
      (field3) => field3.type.typeId === Type.Int,
      () => "Run-ends must have an integer type."
    ),
    asField(valuesField, "values")
  ]
});
var listView = (child) => ({
  typeId: Type.ListView,
  children: [asField(child, "value")],
  offsets: int32Array
});
var largeListView = (child) => ({
  typeId: Type.LargeListView,
  children: [asField(child, "value")],
  offsets: int64Array
});

// ../../../node_modules/@uwdata/flechette/src/util/numbers.js
var f64 = new float64Array(2);
var buf = f64.buffer;
var i64 = new int64Array(buf);
var u32 = new uint32Array(buf);
var i32 = new int32Array(buf);
var u8 = new uint8Array(buf);
function toNumber(value) {
  if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER) {
    throw Error(`BigInt exceeds integer number representation: ${value}`);
  }
  return Number(value);
}
function divide(num, div2) {
  return Number(num / div2) + Number(num % div2) / Number(div2);
}
var asUint64 = (v2) => BigInt.asUintN(64, v2);
function fromDecimal64(buf2, offset2) {
  return BigInt.asIntN(64, buf2[offset2]);
}
function fromDecimal128(buf2, offset2) {
  const i = offset2 << 1;
  let x3;
  if (BigInt.asIntN(64, buf2[i + 1]) < 0) {
    x3 = asUint64(~buf2[i]) | asUint64(~buf2[i + 1]) << 64n;
    x3 = -(x3 + 1n);
  } else {
    x3 = buf2[i] | buf2[i + 1] << 64n;
  }
  return x3;
}
function fromDecimal256(buf2, offset2) {
  const i = offset2 << 2;
  let x3;
  if (BigInt.asIntN(64, buf2[i + 3]) < 0) {
    x3 = asUint64(~buf2[i]) | asUint64(~buf2[i + 1]) << 64n | asUint64(~buf2[i + 2]) << 128n | asUint64(~buf2[i + 3]) << 192n;
    x3 = -(x3 + 1n);
  } else {
    x3 = buf2[i] | buf2[i + 1] << 64n | buf2[i + 2] << 128n | buf2[i + 3] << 192n;
  }
  return x3;
}

// ../../../node_modules/@uwdata/flechette/src/util/strings.js
var textDecoder = new TextDecoder("utf-8");
var textEncoder = new TextEncoder();
function decodeUtf8(buf2) {
  return textDecoder.decode(buf2);
}

// ../../../node_modules/@uwdata/flechette/src/util/read.js
var SIZEOF_INT = 4;
function decodeBit(bitmap2, index2) {
  return (bitmap2[index2 >> 3] & 1 << index2 % 8) !== 0;
}
function readObject(buf2, index2) {
  const pos = index2 + readInt32(buf2, index2);
  const vtable = pos - readInt32(buf2, pos);
  const size = readInt16(buf2, vtable);
  return (index3, read, fallback = null) => {
    if (index3 < size) {
      const off = readInt16(buf2, vtable + index3);
      if (off) return read(buf2, pos + off);
    }
    return fallback;
  };
}
function readOffset(buf2, offset2) {
  return offset2;
}
function readBoolean(buf2, offset2) {
  return !!readInt8(buf2, offset2);
}
function readInt8(buf2, offset2) {
  return readUint8(buf2, offset2) << 24 >> 24;
}
function readUint8(buf2, offset2) {
  return buf2[offset2];
}
function readInt16(buf2, offset2) {
  return readUint16(buf2, offset2) << 16 >> 16;
}
function readUint16(buf2, offset2) {
  return buf2[offset2] | buf2[offset2 + 1] << 8;
}
function readInt32(buf2, offset2) {
  return buf2[offset2] | buf2[offset2 + 1] << 8 | buf2[offset2 + 2] << 16 | buf2[offset2 + 3] << 24;
}
function readUint32(buf2, offset2) {
  return readInt32(buf2, offset2) >>> 0;
}
function readInt64(buf2, offset2) {
  return toNumber(BigInt.asIntN(
    64,
    BigInt(readUint32(buf2, offset2)) + (BigInt(readUint32(buf2, offset2 + SIZEOF_INT)) << 32n)
  ));
}
function readString(buf2, index2) {
  let offset2 = index2 + readInt32(buf2, index2);
  const length4 = readInt32(buf2, offset2);
  offset2 += SIZEOF_INT;
  return decodeUtf8(buf2.subarray(offset2, offset2 + length4));
}
function readVector(buf2, offset2, stride, extract) {
  if (!offset2) return [];
  const base = offset2 + readInt32(buf2, offset2);
  return Array.from(
    { length: readInt32(buf2, base) },
    (_, i) => extract(buf2, base + SIZEOF_INT + i * stride)
  );
}

// ../../../node_modules/@uwdata/flechette/src/util/struct.js
var RowIndex = Symbol("rowIndex");
function proxyFactory(names, batches) {
  class RowObject {
    /**
     * Create a new proxy row object representing a struct or table row.
     * @param {number} index The record batch row index.
     */
    constructor(index2) {
      this[RowIndex] = index2;
    }
    /**
     * Return a JSON-compatible object representation.
     */
    toJSON() {
      return structObject(names, batches, this[RowIndex]);
    }
  }
  ;
  const proto = RowObject.prototype;
  for (let i = 0; i < names.length; ++i) {
    if (Object.hasOwn(proto, names[i])) continue;
    const batch = batches[i];
    Object.defineProperty(proto, names[i], {
      get() {
        return batch.at(this[RowIndex]);
      },
      enumerable: true
    });
  }
  return (index2) => new RowObject(index2);
}
function objectFactory(names, batches) {
  return (index2) => structObject(names, batches, index2);
}
function structObject(names, batches, index2) {
  const obj = {};
  for (let i = 0; i < names.length; ++i) {
    obj[names[i]] = batches[i].at(index2);
  }
  return obj;
}

// ../../../node_modules/@uwdata/flechette/src/batch.js
function isDirectBatch(batch) {
  return batch instanceof DirectBatch;
}
var Batch = class {
  /**
   * The array type to use when extracting data from the batch.
   * A null value indicates that the array type should match
   * the type of the batch's values array.
   * @type {ArrayConstructor | TypedArrayConstructor | null}
   */
  static ArrayType = null;
  /**
   * Create a new column batch.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {TypedArray} [options.values] Values buffer
   * @param {OffsetArray} [options.offsets] Offsets buffer
   * @param {OffsetArray} [options.sizes] Sizes buffer
   * @param {Batch[]} [options.children] Children batches
   */
  constructor({
    length: length4,
    nullCount,
    type: type2,
    validity,
    values: values2,
    offsets,
    sizes,
    children: children2
  }) {
    this.length = length4;
    this.nullCount = nullCount;
    this.type = type2;
    this.validity = validity;
    this.values = values2;
    this.offsets = offsets;
    this.sizes = sizes;
    this.children = children2;
    if (!nullCount || !this.validity) {
      this.at = (index2) => this.value(index2);
    }
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Batch";
  }
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {T | null} The value.
   */
  at(index2) {
    return this.isValid(index2) ? this.value(index2) : null;
  }
  /**
   * Check if a value at the given index is valid (non-null).
   * @param {number} index The value index.
   * @returns {boolean} True if valid, false otherwise.
   */
  isValid(index2) {
    return decodeBit(this.validity, index2);
  }
  /**
   * Return the value at the given index. This method does not check the
   * validity bitmap and is intended primarily for internal use. In most
   * cases, callers should use the `at()` method instead.
   * @param {number} index The value index
   * @returns {T} The value, ignoring the validity bitmap.
   */
  value(index2) {
    return (
      /** @type {T} */
      this.values[index2]
    );
  }
  /**
   * Extract an array of values within the given index range. Unlike
   * Array.slice, all arguments are required and may not be negative indices.
   * @param {number} start The starting index, inclusive
   * @param {number} end The ending index, exclusive
   * @returns {ValueArray<T?>} The slice of values
   */
  slice(start2, end) {
    const n = end - start2;
    const values2 = Array(n);
    for (let i = 0; i < n; ++i) {
      values2[i] = this.at(start2 + i);
    }
    return values2;
  }
  /**
   * Return an iterator over the values in this batch.
   * @returns {Iterator<T?>}
   */
  *[Symbol.iterator]() {
    for (let i = 0; i < this.length; ++i) {
      yield this.at(i);
    }
  }
};
var DirectBatch = class extends Batch {
  /**
   * Create a new column batch with direct value array access.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {TypedArray} options.values Values buffer
   */
  constructor(options) {
    super(options);
    const { length: length4, values: values2 } = this;
    this.values = values2.subarray(0, length4);
  }
  /**
   * Extract an array of values within the given index range. Unlike
   * Array.slice, all arguments are required and may not be negative indices.
   * When feasible, a zero-copy subarray of a typed array is returned.
   * @param {number} start The starting index, inclusive
   * @param {number} end The ending index, exclusive
   * @returns {ValueArray<T?>} The slice of values
   */
  slice(start2, end) {
    return this.nullCount ? super.slice(start2, end) : this.values.subarray(start2, end);
  }
  /**
   * Return an iterator over the values in this batch.
   * @returns {Iterator<T?>}
   */
  [Symbol.iterator]() {
    return this.nullCount ? super[Symbol.iterator]() : (
      /** @type {Iterator<T?>} */
      this.values[Symbol.iterator]()
    );
  }
};
var NumberBatch = class extends Batch {
  static ArrayType = float64Array;
};
var ArrayBatch = class extends Batch {
  static ArrayType = Array;
};
var NullBatch = class extends ArrayBatch {
  /**
   * @param {number} index The value index
   * @returns {null}
   */
  value(index2) {
    return null;
  }
};
var Int64Batch = class extends NumberBatch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return toNumber(
      /** @type {bigint} */
      this.values[index2]
    );
  }
};
var Float16Batch = class extends NumberBatch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    const v2 = (
      /** @type {number} */
      this.values[index2]
    );
    const expo = (v2 & 31744) >> 10;
    const sigf = (v2 & 1023) / 1024;
    const sign4 = (-1) ** ((v2 & 32768) >> 15);
    switch (expo) {
      case 31:
        return sign4 * (sigf ? Number.NaN : 1 / 0);
      case 0:
        return sign4 * (sigf ? 6103515625e-14 * sigf : 0);
    }
    return sign4 * 2 ** (expo - 15) * (1 + sigf);
  }
};
var BoolBatch = class extends ArrayBatch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return decodeBit(
      /** @type {Uint8Array} */
      this.values,
      index2
    );
  }
};
var Decimal32NumberBatch = class extends NumberBatch {
  constructor(options) {
    super(options);
    const { scale: scale3 } = (
      /** @type {DecimalType} */
      this.type
    );
    this.scale = 10 ** scale3;
  }
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return (
      /** @type {number} */
      this.values[index2] / this.scale
    );
  }
};
var DecimalBatch = class extends Batch {
  constructor(options) {
    super(options);
    const { bitWidth, scale: scale3 } = (
      /** @type {DecimalType} */
      this.type
    );
    this.decimal = bitWidth === 64 ? fromDecimal64 : bitWidth === 128 ? fromDecimal128 : fromDecimal256;
    this.scale = 10n ** BigInt(scale3);
  }
};
var DecimalNumberBatch = class extends DecimalBatch {
  static ArrayType = float64Array;
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return divide(
      this.decimal(
        /** @type {BigUint64Array} */
        this.values,
        index2
      ),
      this.scale
    );
  }
};
var DecimalBigIntBatch = class extends DecimalBatch {
  static ArrayType = Array;
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return this.decimal(
      /** @type {BigUint64Array} */
      this.values,
      index2
    );
  }
};
var DateBatch = class extends ArrayBatch {
  /**
   * Create a new date batch.
   * @param {Batch<number>} batch A batch of timestamp values.
   */
  constructor(batch) {
    super(batch);
    this.source = batch;
  }
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return new Date(this.source.value(index2));
  }
};
var DateDayBatch = class extends NumberBatch {
  /**
   * @param {number} index The value index
   * @returns {number}
   */
  value(index2) {
    return 864e5 * /** @type {number} */
    this.values[index2];
  }
};
var DateDayMillisecondBatch = Int64Batch;
var TimestampSecondBatch = class extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return super.value(index2) * 1e3;
  }
};
var TimestampMillisecondBatch = Int64Batch;
var TimestampMicrosecondBatch = class extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return divide(
      /** @type {bigint} */
      this.values[index2],
      1000n
    );
  }
};
var TimestampNanosecondBatch = class extends Int64Batch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    return divide(
      /** @type {bigint} */
      this.values[index2],
      1000000n
    );
  }
};
var IntervalDayTimeBatch = class extends ArrayBatch {
  /**
   * @param {number} index The value index
   * @returns {Int32Array}
   */
  value(index2) {
    const values2 = (
      /** @type {Int32Array} */
      this.values
    );
    return values2.subarray(index2 << 1, index2 + 1 << 1);
  }
};
var IntervalMonthDayNanoBatch = class extends ArrayBatch {
  /**
   * @param {number} index The value index
   */
  value(index2) {
    const values2 = (
      /** @type {Uint8Array} */
      this.values
    );
    const base = index2 << 4;
    return Float64Array.of(
      readInt32(values2, base),
      readInt32(values2, base + 4),
      readInt64(values2, base + 8)
    );
  }
};
var offset32 = ({ values: values2, offsets }, index2) => values2.subarray(offsets[index2], offsets[index2 + 1]);
var offset64 = ({ values: values2, offsets }, index2) => values2.subarray(toNumber(offsets[index2]), toNumber(offsets[index2 + 1]));
var BinaryBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index2) {
    return offset32(this, index2);
  }
};
var LargeBinaryBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index2) {
    return offset64(this, index2);
  }
};
var Utf8Batch = class extends ArrayBatch {
  /**
   * @param {number} index
   */
  value(index2) {
    return decodeUtf8(offset32(this, index2));
  }
};
var LargeUtf8Batch = class extends ArrayBatch {
  /**
   * @param {number} index
   */
  value(index2) {
    return decodeUtf8(offset64(this, index2));
  }
};
var ListBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index2) {
    const offsets = (
      /** @type {Int32Array} */
      this.offsets
    );
    return this.children[0].slice(offsets[index2], offsets[index2 + 1]);
  }
};
var LargeListBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index2) {
    const offsets = (
      /** @type {BigInt64Array} */
      this.offsets
    );
    return this.children[0].slice(toNumber(offsets[index2]), toNumber(offsets[index2 + 1]));
  }
};
var ListViewBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index2) {
    const a2 = (
      /** @type {number} */
      this.offsets[index2]
    );
    const b = a2 + /** @type {number} */
    this.sizes[index2];
    return this.children[0].slice(a2, b);
  }
};
var LargeListViewBatch = class extends ArrayBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index2) {
    const a2 = (
      /** @type {bigint} */
      this.offsets[index2]
    );
    const b = a2 + /** @type {bigint} */
    this.sizes[index2];
    return this.children[0].slice(toNumber(a2), toNumber(b));
  }
};
var FixedBatch = class extends ArrayBatch {
  constructor(options) {
    super(options);
    this.stride = this.type.stride;
  }
};
var FixedBinaryBatch = class extends FixedBatch {
  /**
   * @param {number} index
   * @returns {Uint8Array}
   */
  value(index2) {
    const { stride, values: values2 } = this;
    return (
      /** @type {Uint8Array} */
      values2.subarray(index2 * stride, (index2 + 1) * stride)
    );
  }
};
var FixedListBatch = class extends FixedBatch {
  /**
   * @param {number} index
   * @returns {ValueArray<V>}
   */
  value(index2) {
    const { children: children2, stride } = this;
    return children2[0].slice(index2 * stride, (index2 + 1) * stride);
  }
};
function pairs({ children: children2, offsets }, index2) {
  const [keys, vals] = children2[0].children;
  const start2 = offsets[index2];
  const end = offsets[index2 + 1];
  const entries = [];
  for (let i = start2; i < end; ++i) {
    entries.push([keys.at(i), vals.at(i)]);
  }
  return entries;
}
var MapEntryBatch = class extends ArrayBatch {
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {[K, V][]} The map entries as an array of [key, value] arrays.
   */
  value(index2) {
    return (
      /** @type {[K, V][]} */
      pairs(this, index2)
    );
  }
};
var MapBatch = class extends ArrayBatch {
  /**
   * Return the value at the given index.
   * @param {number} index The value index.
   * @returns {Map<K, V>} The map value.
   */
  value(index2) {
    return new Map(
      /** @type {[K, V][]} */
      pairs(this, index2)
    );
  }
};
var SparseUnionBatch = class extends ArrayBatch {
  /**
   * Create a new column batch.
   * @param {object} options
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {Int32Array} [options.offsets] Offsets buffer
   * @param {Batch[]} options.children Children batches
   * @param {Int8Array} options.typeIds Union type ids buffer
   * @param {Record<string, number>} options.map A typeId to children index map
   */
  constructor({ typeIds, ...options }) {
    super(options);
    this.typeIds = typeIds;
    this.typeMap = this.type.typeMap;
  }
  /**
   * @param {number} index The value index.
   */
  value(index2, offset2 = index2) {
    const { typeIds, children: children2, typeMap } = this;
    return children2[typeMap[typeIds[index2]]].at(offset2);
  }
};
var DenseUnionBatch = class extends SparseUnionBatch {
  /**
   * @param {number} index The value index.
   */
  value(index2) {
    return super.value(
      index2,
      /** @type {number} */
      this.offsets[index2]
    );
  }
};
var StructBatch = class extends ArrayBatch {
  constructor(options, factory = objectFactory) {
    super(options);
    this.names = this.type.children.map((child) => child.name);
    this.factory = factory(this.names, this.children);
  }
  /**
   * @param {number} index The value index.
   * @returns {Record<string, any>}
   */
  value(index2) {
    return this.factory(index2);
  }
};
var StructProxyBatch = class extends StructBatch {
  constructor(options) {
    super(options, proxyFactory);
  }
};
var RunEndEncodedBatch = class extends ArrayBatch {
  /**
   * @param {number} index The value index.
   */
  value(index2) {
    const [{ values: runs }, vals] = this.children;
    return vals.at(
      bisect(
        /** @type {IntegerArray} */
        runs,
        index2
      )
    );
  }
};
var DictionaryBatch = class extends ArrayBatch {
  /**
   * Register the backing dictionary. Dictionaries are added
   * after batch creation as the complete dictionary may not
   * be finished across multiple record batches.
   * @param {Column<T>} dictionary
   * The dictionary of column values.
   */
  setDictionary(dictionary2) {
    this.dictionary = dictionary2;
    this.cache = dictionary2.cache();
    return this;
  }
  /**
   * @param {number} index The value index.
   */
  value(index2) {
    return this.cache[this.key(index2)];
  }
  /**
   * @param {number} index The value index.
   * @returns {number} The dictionary key
   */
  key(index2) {
    return (
      /** @type {number} */
      this.values[index2]
    );
  }
};
var ViewBatch = class extends ArrayBatch {
  /**
   * Create a new view batch.
   * @param {object} options Batch options.
   * @param {number} options.length The length of the batch
   * @param {number} options.nullCount The null value count
   * @param {DataType} options.type The data type.
   * @param {Uint8Array} [options.validity] Validity bitmap buffer
   * @param {Uint8Array} options.values Values buffer
   * @param {Uint8Array[]} options.data View data buffers
   */
  constructor({ data, ...options }) {
    super(options);
    this.data = data;
  }
  /**
   * Get the binary data at the provided index.
   * @param {number} index The value index.
   * @returns {Uint8Array}
   */
  view(index2) {
    const { values: values2, data } = this;
    const offset2 = index2 << 4;
    let start2 = offset2 + 4;
    let buf2 = (
      /** @type {Uint8Array} */
      values2
    );
    const length4 = readInt32(buf2, offset2);
    if (length4 > 12) {
      start2 = readInt32(buf2, offset2 + 12);
      buf2 = data[readInt32(buf2, offset2 + 8)];
    }
    return buf2.subarray(start2, start2 + length4);
  }
};
var BinaryViewBatch = class extends ViewBatch {
  /**
   * @param {number} index The value index.
   */
  value(index2) {
    return this.view(index2);
  }
};
var Utf8ViewBatch = class extends ViewBatch {
  /**
   * @param {number} index The value index.
   */
  value(index2) {
    return decodeUtf8(this.view(index2));
  }
};

// ../../../node_modules/@uwdata/flechette/src/column.js
function columnBuilder(type2) {
  let data = [];
  return {
    add(batch) {
      data.push(batch);
      return this;
    },
    clear: () => data = [],
    done: () => new Column(data, type2)
  };
}
var Column = class {
  /**
   * Create a new column instance.
   * @param {Batch<T>[]} data The value batches.
   * @param {DataType} [type] The column data type.
   *  If not specified, the type is extracted from the batches.
   */
  constructor(data, type2 = data[0]?.type) {
    this.type = type2;
    this.length = data.reduce((m, c4) => m + c4.length, 0);
    this.nullCount = data.reduce((m, c4) => m + c4.nullCount, 0);
    this.data = data;
    const n = data.length;
    const offsets = new Int32Array(n + 1);
    if (n === 1) {
      const [batch] = data;
      offsets[1] = batch.length;
      this.at = (index2) => batch.at(index2);
    } else {
      for (let i = 0, s2 = 0; i < n; ++i) {
        offsets[i + 1] = s2 += data[i].length;
      }
    }
    this.offsets = offsets;
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Column";
  }
  /**
   * Return an iterator over the values in this column.
   * @returns {Iterator<T?>}
   */
  [Symbol.iterator]() {
    const data = this.data;
    return data.length === 1 ? data[0][Symbol.iterator]() : batchedIterator(data);
  }
  /**
   * Return the column value at the given index. If a column has multiple
   * batches, this method performs binary search over the batch lengths to
   * determine the batch from which to retrieve the value. The search makes
   * lookup less efficient than a standard array access. If making a full
   * scan of a column, consider extracting arrays via `toArray()` or using an
   * iterator (`for (const value of column) {...}`).
   * @param {number} index The row index.
   * @returns {T | null} The value.
   */
  at(index2) {
    const { data, offsets } = this;
    const i = bisect(offsets, index2) - 1;
    return data[i]?.at(index2 - offsets[i]);
  }
  /**
   * Return the column value at the given index. This method is the same as
   * `at()` and is provided for better compatibility with Apache Arrow JS.
   * @param {number} index The row index.
   * @returns {T | null} The value.
   */
  get(index2) {
    return this.at(index2);
  }
  /**
   * Extract column values into a single array instance. When possible,
   * a zero-copy subarray of the input Arrow data is returned.
   * @returns {ValueArray<T?>}
   */
  toArray() {
    const { length: length4, nullCount, data } = this;
    const copy4 = !nullCount && isDirectBatch(data[0]);
    const n = data.length;
    if (copy4 && n === 1) {
      return data[0].values;
    }
    const ArrayType = !n || nullCount > 0 ? Array : data[0].constructor.ArrayType ?? data[0].values.constructor;
    const array4 = new ArrayType(length4);
    return copy4 ? copyArray(array4, data) : extractArray(array4, data);
  }
  /**
   * Return an array of cached column values.
   * Used internally to accelerate dictionary types.
   */
  cache() {
    return this._cache ?? (this._cache = this.toArray());
  }
};
function* batchedIterator(data) {
  for (let i = 0; i < data.length; ++i) {
    const iter = data[i][Symbol.iterator]();
    for (let next = iter.next(); !next.done; next = iter.next()) {
      yield next.value;
    }
  }
}
function copyArray(array4, data) {
  for (let i = 0, offset2 = 0; i < data.length; ++i) {
    const { values: values2 } = data[i];
    array4.set(values2, offset2);
    offset2 += values2.length;
  }
  return array4;
}
function extractArray(array4, data) {
  let index2 = -1;
  for (let i = 0; i < data.length; ++i) {
    const batch = data[i];
    for (let j = 0; j < batch.length; ++j) {
      array4[++index2] = batch.at(j);
    }
  }
  return array4;
}

// ../../../node_modules/@uwdata/flechette/src/table.js
var Table = class _Table {
  /**
   * Create a new table with the given schema and columns (children).
   * @param {Schema} schema The table schema.
   * @param {Column[]} children The table columns.
   * @param {boolean} [useProxy=false] Flag indicating if row proxy
   *  objects should be used to represent table rows (default `false`).
   */
  constructor(schema, children2, useProxy = false) {
    const names = schema.fields.map((f) => f.name);
    this.schema = schema;
    this.names = names;
    this.children = children2;
    this.factory = useProxy ? proxyFactory : objectFactory;
    const gen = [];
    this.getFactory = (b) => gen[b] ?? (gen[b] = this.factory(names, children2.map((c4) => c4.data[b])));
  }
  /**
   * Provide an informative object string tag.
   */
  get [Symbol.toStringTag]() {
    return "Table";
  }
  /**
   * The number of columns in this table.
   * @return {number} The number of columns.
   */
  get numCols() {
    return this.names.length;
  }
  /**
   * The number of rows in this table.
   * @return {number} The number of rows.
   */
  get numRows() {
    return this.children[0]?.length ?? 0;
  }
  /**
   * Return the child column at the given index position.
   * @template {T[keyof T]} R
   * @param {number} index The column index.
   * @returns {Column<R>}
   */
  getChildAt(index2) {
    return this.children[index2];
  }
  /**
   * Return the first child column with the given name.
   * @template {keyof T} P
   * @param {P} name The column name.
   * @returns {Column<T[P]>}
   */
  getChild(name2) {
    const i = this.names.findIndex((x3) => x3 === name2);
    return i > -1 ? this.children[i] : void 0;
  }
  /**
   * Construct a new table containing only columns at the specified indices.
   * The order of columns in the new table matches the order of input indices.
   * @template {T[keyof T]} V
   * @param {number[]} indices The indices of columns to keep.
   * @param {string[]} [as] Optional new names for selected columns.
   * @returns {Table<{ [key: string]: V }>} A new table with selected columns.
   */
  selectAt(indices2, as = []) {
    const { children: children2, factory, schema } = this;
    const { fields } = schema;
    return new _Table(
      {
        ...schema,
        fields: indices2.map((i, j) => renameField(fields[i], as[j]))
      },
      indices2.map((i) => children2[i]),
      factory === proxyFactory
    );
  }
  /**
   * Construct a new table containing only columns with the specified names.
   * If columns have duplicate names, the first (with lowest index) is used.
   * The order of columns in the new table matches the order of input names.
   * @template {keyof T} K
   * @param {K[]} names Names of columns to keep.
   * @param {string[]} [as] Optional new names for selected columns.
   * @returns A new table with columns matching the specified names.
   */
  select(names, as) {
    const all = (
      /** @type {K[]} */
      this.names
    );
    const indices2 = names.map((name2) => all.indexOf(name2));
    return this.selectAt(indices2, as);
  }
  /**
   * Return an object mapping column names to extracted value arrays.
   * @returns {{ [P in keyof T]: ValueArray<T[P]> }}
   */
  toColumns() {
    const { children: children2, names } = this;
    const cols = {};
    names.forEach((name2, i) => cols[name2] = children2[i]?.toArray() ?? []);
    return cols;
  }
  /**
   * Return an array of objects representing the rows of this table.
   * @returns {{ [P in keyof T]: T[P] }[]}
   */
  toArray() {
    const { children: children2, getFactory, numRows } = this;
    const data = children2[0]?.data ?? [];
    const output = Array(numRows);
    for (let b = 0, row = -1; b < data.length; ++b) {
      const f = getFactory(b);
      for (let i = 0; i < data[b].length; ++i) {
        output[++row] = f(i);
      }
    }
    return output;
  }
  /**
   * Return an iterator over objects representing the rows of this table.
   * @returns {Generator<{ [P in keyof T]: T[P] }, any, any>}
   */
  *[Symbol.iterator]() {
    const { children: children2, getFactory } = this;
    const data = children2[0]?.data ?? [];
    for (let b = 0; b < data.length; ++b) {
      const f = getFactory(b);
      for (let i = 0; i < data[b].length; ++i) {
        yield f(i);
      }
    }
  }
  /**
   * Return a row object for the given index.
   * @param {number} index The row index.
   * @returns {{ [P in keyof T]: T[P] }} The row object.
   */
  at(index2) {
    const { children: children2, getFactory, numRows } = this;
    if (index2 < 0 || index2 >= numRows) return null;
    const [{ offsets }] = children2;
    const b = bisect(offsets, index2) - 1;
    return getFactory(b)(index2 - offsets[b]);
  }
  /**
   * Return a row object for the given index. This method is the same as
   * `at()` and is provided for better compatibility with Apache Arrow JS.
   * @param {number} index The row index.
   * @returns {{ [P in keyof T]: T[P] }} The row object.
   */
  get(index2) {
    return this.at(index2);
  }
};
function renameField(field3, name2) {
  return name2 != null && name2 !== field3.name ? { ...field3, name: name2 } : field3;
}

// ../../../node_modules/@uwdata/flechette/src/batch-type.js
function batchType(type2, options = {}) {
  const { typeId, bitWidth, mode: mode3, precision, unit: unit3 } = (
    /** @type {any} */
    type2
  );
  const { useBigInt, useDate, useDecimalInt, useMap, useProxy } = options;
  switch (typeId) {
    case Type.Null:
      return NullBatch;
    case Type.Bool:
      return BoolBatch;
    case Type.Int:
    case Type.Time:
    case Type.Duration:
      return useBigInt || bitWidth < 64 ? DirectBatch : Int64Batch;
    case Type.Float:
      return precision ? DirectBatch : Float16Batch;
    case Type.Date:
      return wrap(
        unit3 === DateUnit.DAY ? DateDayBatch : DateDayMillisecondBatch,
        useDate && DateBatch
      );
    case Type.Timestamp:
      return wrap(
        unit3 === TimeUnit.SECOND ? TimestampSecondBatch : unit3 === TimeUnit.MILLISECOND ? TimestampMillisecondBatch : unit3 === TimeUnit.MICROSECOND ? TimestampMicrosecondBatch : TimestampNanosecondBatch,
        useDate && DateBatch
      );
    case Type.Decimal:
      return bitWidth === 32 ? useDecimalInt ? DirectBatch : Decimal32NumberBatch : useDecimalInt ? DecimalBigIntBatch : DecimalNumberBatch;
    case Type.Interval:
      return unit3 === IntervalUnit.DAY_TIME ? IntervalDayTimeBatch : unit3 === IntervalUnit.YEAR_MONTH ? DirectBatch : IntervalMonthDayNanoBatch;
    case Type.FixedSizeBinary:
      return FixedBinaryBatch;
    case Type.Utf8:
      return Utf8Batch;
    case Type.LargeUtf8:
      return LargeUtf8Batch;
    case Type.Binary:
      return BinaryBatch;
    case Type.LargeBinary:
      return LargeBinaryBatch;
    case Type.BinaryView:
      return BinaryViewBatch;
    case Type.Utf8View:
      return Utf8ViewBatch;
    case Type.List:
      return ListBatch;
    case Type.LargeList:
      return LargeListBatch;
    case Type.Map:
      return useMap ? MapBatch : MapEntryBatch;
    case Type.ListView:
      return ListViewBatch;
    case Type.LargeListView:
      return LargeListViewBatch;
    case Type.FixedSizeList:
      return FixedListBatch;
    case Type.Struct:
      return useProxy ? StructProxyBatch : StructBatch;
    case Type.RunEndEncoded:
      return RunEndEncodedBatch;
    case Type.Dictionary:
      return DictionaryBatch;
    case Type.Union:
      return mode3 ? DenseUnionBatch : SparseUnionBatch;
  }
  throw new Error(invalidDataType(typeId));
}
function wrap(BaseClass, WrapperClass) {
  return WrapperClass ? class WrapBatch extends WrapperClass {
    constructor(options) {
      super(new BaseClass(options));
    }
  } : BaseClass;
}

// ../../../node_modules/@uwdata/flechette/src/decode/block.js
function decodeBlock(buf2, index2) {
  return {
    offset: readInt64(buf2, index2),
    metadataLength: readInt32(buf2, index2 + 8),
    bodyLength: readInt64(buf2, index2 + 16)
  };
}
function decodeBlocks(buf2, index2) {
  return readVector(buf2, index2, 24, decodeBlock);
}

// ../../../node_modules/@uwdata/flechette/src/decode/record-batch.js
function decodeRecordBatch(buf2, index2, version) {
  const get3 = readObject(buf2, index2);
  if (get3(10, readOffset, 0)) {
    throw new Error("Record batch compression not implemented");
  }
  const offset2 = version < Version.V4 ? 8 : 0;
  return {
    length: get3(4, readInt64, 0),
    nodes: readVector(buf2, get3(6, readOffset), 16, (buf3, pos) => ({
      length: readInt64(buf3, pos),
      nullCount: readInt64(buf3, pos + 8)
    })),
    regions: readVector(buf2, get3(8, readOffset), 16 + offset2, (buf3, pos) => ({
      offset: readInt64(buf3, pos + offset2),
      length: readInt64(buf3, pos + offset2 + 8)
    })),
    variadic: readVector(buf2, get3(12, readOffset), 8, readInt64)
  };
}

// ../../../node_modules/@uwdata/flechette/src/decode/dictionary-batch.js
function decodeDictionaryBatch(buf2, index2, version) {
  const get3 = readObject(buf2, index2);
  return {
    id: get3(4, readInt64, 0),
    data: get3(6, (buf3, off) => decodeRecordBatch(buf3, off, version)),
    /**
     * If isDelta is true the values in the dictionary are to be appended to a
     * dictionary with the indicated id. If isDelta is false this dictionary
     * should replace the existing dictionary.
     */
    isDelta: get3(8, readBoolean, false)
  };
}

// ../../../node_modules/@uwdata/flechette/src/decode/data-type.js
function decodeDataType(buf2, index2, typeId, children2) {
  checkOneOf(typeId, Type, invalidDataType);
  const get3 = readObject(buf2, index2);
  switch (typeId) {
    // types without flatbuffer objects
    case Type.Binary:
      return binary();
    case Type.Utf8:
      return utf8();
    case Type.LargeBinary:
      return largeBinary();
    case Type.LargeUtf8:
      return largeUtf8();
    case Type.List:
      return list(children2[0]);
    case Type.ListView:
      return listView(children2[0]);
    case Type.LargeList:
      return largeList(children2[0]);
    case Type.LargeListView:
      return largeListView(children2[0]);
    case Type.Struct:
      return struct(children2);
    case Type.RunEndEncoded:
      return runEndEncoded(children2[0], children2[1]);
    // types with flatbuffer objects
    case Type.Int:
      return int(
        // @ts-ignore
        get3(4, readInt32, 0),
        // bitwidth
        get3(6, readBoolean, false)
        // signed
      );
    case Type.Float:
      return float(
        // @ts-ignore
        get3(4, readInt16, Precision.HALF)
        // precision
      );
    case Type.Decimal:
      return decimal(
        get3(4, readInt32, 0),
        // precision
        get3(6, readInt32, 0),
        // scale
        // @ts-ignore
        get3(8, readInt32, 128)
        // bitwidth
      );
    case Type.Date:
      return date(
        // @ts-ignore
        get3(4, readInt16, DateUnit.MILLISECOND)
        // unit
      );
    case Type.Time:
      return time(
        // @ts-ignore
        get3(4, readInt16, TimeUnit.MILLISECOND),
        // unit
        get3(6, readInt32, 32)
        // bitWidth
      );
    case Type.Timestamp:
      return timestamp(
        // @ts-ignore
        get3(4, readInt16, TimeUnit.SECOND),
        // unit
        get3(6, readString)
        // timezone
      );
    case Type.Interval:
      return interval(
        // @ts-ignore
        get3(4, readInt16, IntervalUnit.YEAR_MONTH)
        // unit
      );
    case Type.Duration:
      return duration(
        // @ts-ignore
        get3(4, readInt16, TimeUnit.MILLISECOND)
        // unit
      );
    case Type.FixedSizeBinary:
      return fixedSizeBinary(
        get3(4, readInt32, 0)
        // stride
      );
    case Type.FixedSizeList:
      return fixedSizeList(
        children2[0],
        get3(4, readInt32, 0)
        // stride
      );
    case Type.Map:
      return mapType(
        get3(4, readBoolean, false),
        // keysSorted
        children2[0]
      );
    case Type.Union:
      return union(
        // @ts-ignore
        get3(4, readInt16, UnionMode.Sparse),
        // mode
        children2,
        readVector(buf2, get3(6, readOffset), 4, readInt32)
        // type ids
      );
  }
  return { typeId };
}

// ../../../node_modules/@uwdata/flechette/src/decode/metadata.js
function decodeMetadata(buf2, index2) {
  const entries = readVector(buf2, index2, 4, (buf3, pos) => {
    const get3 = readObject(buf3, pos);
    return (
      /** @type {[string, string]} */
      [
        get3(4, readString),
        // 4: key (string)
        get3(6, readString)
        // 6: key (string)
      ]
    );
  });
  return entries.length ? new Map(entries) : null;
}

// ../../../node_modules/@uwdata/flechette/src/decode/schema.js
function decodeSchema(buf2, index2, version) {
  const get3 = readObject(buf2, index2);
  return {
    version,
    endianness: (
      /** @type {Endianness_} */
      get3(4, readInt16, 0)
    ),
    fields: get3(6, decodeSchemaFields, []),
    metadata: get3(8, decodeMetadata)
  };
}
function decodeSchemaFields(buf2, fieldsOffset) {
  return readVector(buf2, fieldsOffset, 4, decodeField);
}
function decodeField(buf2, index2) {
  const get3 = readObject(buf2, index2);
  const typeId = get3(8, readUint8, Type.NONE);
  const typeOffset = get3(10, readOffset, 0);
  const dict = get3(12, decodeDictionary);
  const children2 = get3(14, (buf3, off) => decodeFieldChildren(buf3, off));
  let type2 = decodeDataType(buf2, typeOffset, typeId, children2);
  if (dict) {
    dict.dictionary = type2;
    type2 = dict;
  }
  return {
    name: get3(4, readString),
    type: type2,
    nullable: get3(6, readBoolean, false),
    metadata: get3(16, decodeMetadata)
  };
}
function decodeFieldChildren(buf2, fieldOffset) {
  const children2 = readVector(buf2, fieldOffset, 4, decodeField);
  return children2.length ? children2 : null;
}
function decodeDictionary(buf2, index2) {
  if (!index2) return null;
  const get3 = readObject(buf2, index2);
  return dictionary(
    null,
    // data type will be populated by caller
    get3(6, decodeInt, int32()),
    // index type
    get3(8, readBoolean, false),
    // ordered
    get3(4, readInt64, 0)
    // id
  );
}
function decodeInt(buf2, index2) {
  return (
    /** @type {IntType} */
    decodeDataType(buf2, index2, Type.Int)
  );
}

// ../../../node_modules/@uwdata/flechette/src/decode/message.js
var invalidMessageMetadata = (expected, actual) => `Expected to read ${expected} metadata bytes, but only read ${actual}.`;
var invalidMessageBodyLength = (expected, actual) => `Expected to read ${expected} bytes for message body, but only read ${actual}.`;
var invalidMessageType = (type2) => `Unsupported message type: ${type2} (${keyFor(MessageHeader, type2)})`;
function decodeMessage(buf2, index2) {
  let metadataLength = readInt32(buf2, index2) || 0;
  index2 += SIZEOF_INT;
  if (metadataLength === -1) {
    metadataLength = readInt32(buf2, index2) || 0;
    index2 += SIZEOF_INT;
  }
  if (metadataLength === 0) return null;
  const head = buf2.subarray(index2, index2 += metadataLength);
  if (head.byteLength < metadataLength) {
    throw new Error(invalidMessageMetadata(metadataLength, head.byteLength));
  }
  const get3 = readObject(head, 0);
  const version = (
    /** @type {Version_} */
    get3(4, readInt16, Version.V1)
  );
  const type2 = (
    /** @type {MessageHeader_} */
    get3(6, readUint8, MessageHeader.NONE)
  );
  const offset2 = get3(8, readOffset, 0);
  const bodyLength = get3(10, readInt64, 0);
  let content;
  if (offset2) {
    const decoder = type2 === MessageHeader.Schema ? decodeSchema : type2 === MessageHeader.DictionaryBatch ? decodeDictionaryBatch : type2 === MessageHeader.RecordBatch ? decodeRecordBatch : null;
    if (!decoder) throw new Error(invalidMessageType(type2));
    content = decoder(head, offset2, version);
    if (bodyLength > 0) {
      const body = buf2.subarray(index2, index2 += bodyLength);
      if (body.byteLength < bodyLength) {
        throw new Error(invalidMessageBodyLength(bodyLength, body.byteLength));
      }
      content.body = body;
    }
  }
  return { version, type: type2, index: index2, content };
}

// ../../../node_modules/@uwdata/flechette/src/decode/decode-ipc.js
function decodeIPC(data) {
  const source = isArrayBufferLike(data) ? new Uint8Array(data) : data;
  return source instanceof Uint8Array && isArrowFileFormat(source) ? decodeIPCFile(source) : decodeIPCStream(source);
}
function isArrowFileFormat(buf2) {
  if (!buf2 || buf2.length < 4) return false;
  for (let i = 0; i < 6; ++i) {
    if (MAGIC[i] !== buf2[i]) return false;
  }
  return true;
}
function decodeIPCStream(data) {
  const stream = [data].flat();
  let schema;
  const records = [];
  const dictionaries = [];
  for (const buf2 of stream) {
    if (!(buf2 instanceof Uint8Array)) {
      throw new Error(`IPC data batch was not a Uint8Array.`);
    }
    let offset2 = 0;
    while (true) {
      const m = decodeMessage(buf2, offset2);
      if (m === null) break;
      offset2 = m.index;
      if (!m.content) continue;
      switch (m.type) {
        case MessageHeader.Schema:
          if (!schema) schema = m.content;
          break;
        case MessageHeader.RecordBatch:
          records.push(m.content);
          break;
        case MessageHeader.DictionaryBatch:
          dictionaries.push(m.content);
          break;
      }
    }
  }
  return (
    /** @type {ArrowData} */
    { schema, dictionaries, records, metadata: null }
  );
}
function decodeIPCFile(data) {
  const offset2 = data.byteLength - (MAGIC.length + 4);
  const length4 = readInt32(data, offset2);
  const get3 = readObject(data, offset2 - length4);
  const version = (
    /** @type {Version_} */
    get3(4, readInt16, Version.V1)
  );
  const dicts = get3(8, decodeBlocks, []);
  const recs = get3(10, decodeBlocks, []);
  return (
    /** @type {ArrowData} */
    {
      schema: get3(6, (buf2, index2) => decodeSchema(buf2, index2, version)),
      dictionaries: dicts.map(({ offset: offset3 }) => decodeMessage(data, offset3).content),
      records: recs.map(({ offset: offset3 }) => decodeMessage(data, offset3).content),
      metadata: get3(12, decodeMetadata)
    }
  );
}

// ../../../node_modules/@uwdata/flechette/src/decode/table-from-ipc.js
function tableFromIPC(data, options) {
  return createTable(decodeIPC(data), options);
}
function createTable(data, options = {}) {
  const { schema = { fields: [] }, dictionaries, records } = data;
  const { version, fields } = schema;
  const dictionaryMap = /* @__PURE__ */ new Map();
  const context = contextGenerator(options, version, dictionaryMap);
  const dictionaryTypes = /* @__PURE__ */ new Map();
  visitSchemaFields(schema, (field3) => {
    const type2 = field3.type;
    if (type2.typeId === Type.Dictionary) {
      dictionaryTypes.set(type2.id, type2.dictionary);
    }
  });
  const dicts = /* @__PURE__ */ new Map();
  for (const dict of dictionaries) {
    const { id: id2, data: data2, isDelta, body } = dict;
    const type2 = dictionaryTypes.get(id2);
    const batch = visit(type2, context({ ...data2, body }));
    if (!dicts.has(id2)) {
      if (isDelta) {
        throw new Error("Delta update can not be first dictionary batch.");
      }
      dicts.set(id2, columnBuilder(type2).add(batch));
    } else {
      const dict2 = dicts.get(id2);
      if (!isDelta) dict2.clear();
      dict2.add(batch);
    }
  }
  dicts.forEach((value, key) => dictionaryMap.set(key, value.done()));
  const cols = fields.map((f) => columnBuilder(f.type));
  for (const batch of records) {
    const ctx = context(batch);
    fields.forEach((f, i) => cols[i].add(visit(f.type, ctx)));
  }
  return new Table(schema, cols.map((c4) => c4.done()), options.useProxy);
}
function visitSchemaFields(schema, visitor) {
  schema.fields.forEach(function visitField(field3) {
    visitor(field3);
    field3.type.dictionary?.children?.forEach(visitField);
    field3.type.children?.forEach(visitField);
  });
}
function contextGenerator(options, version, dictionaryMap) {
  const base = {
    version,
    options,
    dictionary: (id2) => dictionaryMap.get(id2)
  };
  return (batch) => {
    const { length: length4, nodes, regions, variadic, body } = batch;
    let nodeIndex = -1;
    let bufferIndex = -1;
    let variadicIndex = -1;
    return {
      ...base,
      length: length4,
      node: () => nodes[++nodeIndex],
      buffer: (ArrayType) => {
        const { length: length5, offset: offset2 } = regions[++bufferIndex];
        return ArrayType ? new ArrayType(body.buffer, body.byteOffset + offset2, length5 / ArrayType.BYTES_PER_ELEMENT) : body.subarray(offset2, offset2 + length5);
      },
      variadic: () => variadic[++variadicIndex],
      visit(children2) {
        return children2.map((f) => visit(f.type, this));
      }
    };
  };
}
function visit(type2, ctx) {
  const { typeId } = type2;
  const { length: length4, options, node, buffer: buffer2, variadic, version } = ctx;
  const BatchType = batchType(type2, options);
  if (typeId === Type.Null) {
    return new BatchType({ length: length4, nullCount: length4, type: type2 });
  }
  const base = { ...node(), type: type2 };
  switch (typeId) {
    // validity and data value buffers
    case Type.Bool:
    case Type.Int:
    case Type.Time:
    case Type.Duration:
    case Type.Float:
    case Type.Decimal:
    case Type.Date:
    case Type.Timestamp:
    case Type.Interval:
    case Type.FixedSizeBinary:
      return new BatchType({
        ...base,
        validity: buffer2(),
        values: buffer2(type2.values)
      });
    // validity, offset, and value buffers
    case Type.Utf8:
    case Type.LargeUtf8:
    case Type.Binary:
    case Type.LargeBinary:
      return new BatchType({
        ...base,
        validity: buffer2(),
        offsets: buffer2(type2.offsets),
        values: buffer2()
      });
    // views with variadic buffers
    case Type.BinaryView:
    case Type.Utf8View:
      return new BatchType({
        ...base,
        validity: buffer2(),
        values: buffer2(),
        // views buffer
        data: Array.from({ length: variadic() }, () => buffer2())
        // data buffers
      });
    // validity, offset, and list child
    case Type.List:
    case Type.LargeList:
    case Type.Map:
      return new BatchType({
        ...base,
        validity: buffer2(),
        offsets: buffer2(type2.offsets),
        children: ctx.visit(type2.children)
      });
    // validity, offset, size, and list child
    case Type.ListView:
    case Type.LargeListView:
      return new BatchType({
        ...base,
        validity: buffer2(),
        offsets: buffer2(type2.offsets),
        sizes: buffer2(type2.offsets),
        children: ctx.visit(type2.children)
      });
    // validity and children
    case Type.FixedSizeList:
    case Type.Struct:
      return new BatchType({
        ...base,
        validity: buffer2(),
        children: ctx.visit(type2.children)
      });
    // children only
    case Type.RunEndEncoded:
      return new BatchType({
        ...base,
        children: ctx.visit(type2.children)
      });
    // dictionary
    case Type.Dictionary: {
      const { id: id2, indices: indices2 } = type2;
      return new BatchType({
        ...base,
        validity: buffer2(),
        values: buffer2(indices2.values)
      }).setDictionary(ctx.dictionary(id2));
    }
    // union
    case Type.Union: {
      if (version < Version.V5) {
        buffer2();
      }
      return new BatchType({
        ...base,
        typeIds: buffer2(int8Array),
        offsets: type2.mode === UnionMode.Sparse ? null : buffer2(type2.offsets),
        children: ctx.visit(type2.children)
      });
    }
    // unsupported type
    default:
      throw new Error(invalidDataType(typeId));
  }
}

// ../../../node_modules/@uwdata/flechette/src/encode/schema.js
var isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;

// ../../mosaic/core/dist/src/util/decode-ipc.js
function decodeIPC2(data, options = { useDate: true }) {
  return tableFromIPC(data, options);
}

// ../../mosaic/core/dist/src/connectors/socket.js
var SocketConnector = class {
  _uri;
  _queue;
  _connected;
  _request;
  _ws;
  _events;
  /**
   * @param options Connector options.
   * @param options.uri The URI for the DuckDB REST server.
   * @param options.ipc Arrow IPC extraction options.
   */
  constructor({ uri = "ws://localhost:3000/", ipc = void 0 } = {}) {
    this._uri = uri;
    this._queue = [];
    this._connected = false;
    this._request = null;
    this._ws = null;
    const c4 = this;
    this._events = {
      open() {
        c4._connected = true;
        c4.next();
      },
      close() {
        c4._connected = false;
        c4._request = null;
        c4._ws = null;
        while (c4._queue.length) {
          c4._queue.shift().reject("Socket closed");
        }
      },
      error(event) {
        if (c4._request) {
          const { reject } = c4._request;
          c4._request = null;
          c4.next();
          reject(event);
        } else {
          console.error("WebSocket error: ", event);
        }
      },
      message(msg) {
        const { data } = msg;
        if (c4._request) {
          const { query, resolve, reject } = c4._request;
          c4._request = null;
          c4.next();
          if (typeof data === "string") {
            const json = JSON.parse(data);
            json.error ? reject(json.error) : resolve(json);
          } else if (query.type === "exec") {
            resolve();
          } else if (query.type === "arrow") {
            resolve(decodeIPC2(data, ipc));
          } else {
            throw new Error(`Unexpected socket data: ${data}`);
          }
        } else {
          console.log("WebSocket message: ", data);
        }
      }
    };
  }
  get connected() {
    return this._connected;
  }
  init() {
    this._ws = new WebSocket(this._uri);
    this._ws.binaryType = "arraybuffer";
    for (const type2 in this._events) {
      this._ws.addEventListener(type2, this._events[type2]);
    }
  }
  enqueue(query, resolve, reject) {
    if (this._ws == null)
      this.init();
    this._queue.push({ query, resolve, reject });
    if (this._connected && !this._request)
      this.next();
  }
  next() {
    if (this._queue.length) {
      this._request = this._queue.shift();
      this._ws.send(JSON.stringify(this._request.query));
    }
  }
  query(query) {
    return new Promise((resolve, reject) => this.enqueue(query, resolve, reject));
  }
};

// ../../mosaic/sql/dist/src/constants.js
var COLUMN_REF = "COLUMN_REF";
var COLUMN_PARAM = "COLUMN_PARAM";
var TABLE_REF = "TABLE_REF";
var LITERAL = "LITERAL";
var INTERVAL = "INTERVAL";
var LIST = "LIST";
var UNNEST = "UNNEST";
var ORDER_BY = "ORDER_BY";
var CAST = "CAST";
var CASE = "CASE";
var WHEN = "WHEN";
var COLLATE = "COLLATE";
var UNARY_OPERATOR = "UNARY";
var UNARY_POSTFIX_OPERATOR = "UNARY_POSTFIX";
var BINARY_OPERATOR = "BINARY";
var BETWEEN_OPERATOR = "BETWEEN";
var NOT_BETWEEN_OPERATOR = "NOT_BETWEEN";
var LOGICAL_OPERATOR = "LOGICAL_OPERATOR";
var IN_OPERATOR = "IN";
var FUNCTION = "FUNCTION";
var AGGREGATE = "AGGREGATE";
var WINDOW = "WINDOW";
var WINDOW_FUNCTION = "WINDOW_FUNCTION";
var WINDOW_DEF = "WINDOW_DEF";
var WINDOW_FRAME = "WINDOW_FRAME";
var WINDOW_EXTENT_EXPR = "WINDOW_EXTENT_EXPR";
var EXPRESSION = "EXPRESSION";
var FRAGMENT = "FRAGMENT";
var VERBATIM = "VERBATIM";
var PARAM = "PARAM";
var WITH_CLAUSE = "WITH_CLAUSE";
var WINDOW_CLAUSE = "WINDOW_CLAUSE";
var SELECT_CLAUSE = "SELECT_CLAUSE";
var FROM_CLAUSE = "FROM_CLAUSE";
var SAMPLE_CLAUSE = "SAMPLE_CLAUSE";
var SELECT_QUERY = "SELECT_QUERY";
var DESCRIBE_QUERY = "DESCRIBE_QUERY";
var SET_OPERATION = "SET_OPERATION";
var SCALAR_SUBQUERY = "SCALAR_SUBQUERY";

// ../../mosaic/sql/dist/src/ast/node.js
function isNode(value) {
  return value instanceof SQLNode;
}
var SQLNode = class {
  /** The SQL AST node type. */
  type;
  /**
   * Instantiate a SQL AST node.
   * @param type The SQL AST node type.
   */
  constructor(type2) {
    this.type = type2;
  }
  /**
   * Create a shallow clone of this SQL AST node.
   * @returns The shallow clone node.
   */
  clone() {
    const clone = new this.constructor();
    for (const key in this) {
      clone[key] = this[key];
    }
    return clone;
  }
};
var ExprNode = class extends SQLNode {
};

// ../../mosaic/sql/dist/src/ast/literal.js
var LiteralNode = class extends ExprNode {
  /** The literal value. */
  value;
  /**
   * Instantiate an literal node.
   * @param value The literal value.
   */
  constructor(value) {
    super(LITERAL);
    this.value = value;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return literalToSQL(this.value);
  }
};
function literalToSQL(value) {
  switch (typeof value) {
    case "number":
      return Number.isFinite(value) ? `${value}` : "NULL";
    case "string":
      return `'${value.replaceAll(`'`, `''`)}'`;
    case "boolean":
      return value ? "TRUE" : "FALSE";
    default:
      if (value == null) {
        return "NULL";
      } else if (value instanceof Date) {
        const ts = +value;
        if (Number.isNaN(ts))
          return "NULL";
        const y3 = value.getUTCFullYear();
        const m = value.getUTCMonth();
        const d = value.getUTCDate();
        return ts === Date.UTC(y3, m, d) ? `DATE '${y3}-${m + 1}-${d}'` : `epoch_ms(${ts})`;
      } else if (value instanceof RegExp) {
        return `'${value.source}'`;
      } else {
        return `${value}`;
      }
  }
}

// ../../mosaic/sql/dist/src/ast/param.js
var ParamNode = class extends ExprNode {
  /** The dynamic parameter. */
  param;
  /**
   * Instantiate a param node with a dynamic parameter.
   * @param param The dynamic parameter.
   */
  constructor(param) {
    super(PARAM);
    this.param = param;
  }
  /**
   * Returns the current parameter value.
   */
  get value() {
    return this.param.value;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return literalToSQL(this.value);
  }
};

// ../../mosaic/sql/dist/src/ast/function.js
var FunctionNode = class extends ExprNode {
  /** The function name. */
  name;
  /** The function arguments. */
  args;
  /**
   * Instantiate a function node.
   * @param name The function name.
   * @param args The function arguments.
   */
  constructor(name2, args = []) {
    super(FUNCTION);
    this.name = name2;
    this.args = args;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { name: name2, args } = this;
    return `${name2}(${args.join(", ")})`;
  }
};

// ../../mosaic/sql/dist/src/util/function.js
function fn(name2, ...args) {
  return new FunctionNode(name2, argsList(args).map(asNode));
}
function aggFn(name2, ...args) {
  return new AggregateNode(name2, argsList(args).map(asNode));
}
function winFn(name2, ...args) {
  return new WindowNode(new WindowFunctionNode(name2, argsList(args).map(asNode)));
}
function exprList(list3, cast2) {
  return list3.flat().filter((x3) => x3 != null).map((x3) => cast2(x3));
}
function nodeList(list3) {
  return exprList(list3, asNode);
}
function argsList(list3) {
  const n = list3.length;
  let i = n;
  for (; i > 0 && list3[i - 1] === void 0; --i)
    ;
  return i < n ? list3.slice(0, i) : list3;
}

// ../../mosaic/sql/dist/src/util/string.js
function parseIdentifier(id2) {
  return id2.split(".");
}
function quoteIdentifier(value) {
  return `"${value}"`;
}
function unquote(s2) {
  return s2 && isDoubleQuoted(s2) ? s2.slice(1, -1) : s2;
}
function isDoubleQuoted(s2) {
  return s2[0] === '"' && s2[s2.length - 1] === '"';
}

// ../../mosaic/sql/dist/src/ast/window.js
var WindowClauseNode = class extends SQLNode {
  /** The window name. */
  name;
  /** The window definition. */
  def;
  /**
   * Instantiate a window clause node.
   * @param name The window name.
   * @param def The window definition.
   */
  constructor(name2, def) {
    super(WINDOW_CLAUSE);
    this.name = name2;
    this.def = def;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `${quoteIdentifier(this.name)} AS ${this.def}`;
  }
};
var WindowNode = class _WindowNode extends ExprNode {
  func;
  def;
  /**
   * Instantiate a window node.
   * @param func The window function call.
   * @param over The window definition or name.
   */
  constructor(func, over2 = new WindowDefNode()) {
    super(WINDOW);
    this.func = func;
    this.def = over2;
  }
  /**
   * Return an updated window over a named window definition.
   * @param name The window definition name.
   * @returns A new window node.
   */
  over(name2) {
    return new _WindowNode(this.func, this.def.over(name2));
  }
  /**
   * Return an updated window with the given partitions.
   * @param expr The partition by criteria.
   * @returns A new window node.
   */
  partitionby(...expr) {
    return new _WindowNode(this.func, this.def.partitionby(...expr));
  }
  /**
   * Return an updated window with the given ordering.
   * @param expr The order by criteria.
   * @returns A new window node.
   */
  orderby(...expr) {
    return new _WindowNode(this.func, this.def.orderby(...expr));
  }
  /**
   * Return an updated window with the given frame definition.
   * @param framedef The frame definition.
   * @returns A new window node.
   */
  frame(framedef) {
    return new _WindowNode(this.func, this.def.frame(framedef));
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `${this.func} OVER ${this.def}`;
  }
};
var WindowFunctionNode = class extends ExprNode {
  /** The window function name. */
  name;
  /** The window function arguments. */
  args;
  /** Flag to ignore null values. */
  ignoreNulls;
  /** Order by expression for window arguments. */
  order;
  /**
   * Instantiate a window function call node.
   * @param name The window function name.
   * @param args The window function arguments.
   * @param ignoreNulls Flag to ignore null values.
   * @param argOrder Order expressions for window arguments.
   *  Note that this argument ordering is distinct from the window ordering.
   */
  constructor(name2, args = [], ignoreNulls = false, argOrder = []) {
    super(WINDOW_FUNCTION);
    this.name = name2;
    this.args = args;
    this.ignoreNulls = ignoreNulls;
    this.order = nodeList([argOrder]);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { name: name2, args, ignoreNulls, order } = this;
    const arg = [
      args.join(", "),
      order.length ? `ORDER BY ${order.join(", ")}` : "",
      ignoreNulls ? "IGNORE NULLS" : ""
    ].filter((x3) => x3).join(" ");
    return `${name2}(${arg})`;
  }
};
var WindowDefNode = class extends SQLNode {
  /** The base window definition name. */
  name;
  /** The partition by criteria. */
  partition;
  /** The order by criteria. */
  order;
  /** The window frame definition. */
  framedef;
  /**
   * Instantiate a window definition node.
   * @param name The base window definition name.
   * @param partition The partition by criteria.
   * @param order The order by criteria.
   * @param framedef The window frame definition.
   */
  constructor(name2, partition, order, framedef) {
    super(WINDOW_DEF);
    this.name = name2;
    this.partition = partition;
    this.order = order;
    this.framedef = framedef;
  }
  /**
   * Return an updated window definition with the given base name.
   * @param name The base window definition name.
   * @returns A new window definition node.
   */
  over(name2) {
    return deriveDef(this, { name: name2 });
  }
  /**
   * Return an updated window definition with the given partitions.
   * @param expr The partition by criteria.
   * @returns A new window definition node.
   */
  partitionby(...expr) {
    return deriveDef(this, { partition: nodeList(expr) });
  }
  /**
   * Return an updated window definition with the given ordering.
   * @param expr The order by criteria.
   * @returns A new window definition node.
   */
  orderby(...expr) {
    return deriveDef(this, { order: nodeList(expr) });
  }
  /**
   * Return an updated window definition with the given frame definition.
   * @param framedef The frame definition.
   * @return A new window definition node.
   */
  frame(framedef) {
    return deriveDef(this, { framedef });
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { name: name2, partition, order, framedef } = this;
    const base = name2 && quoteIdentifier(name2);
    const def = [
      base,
      partition?.length && `PARTITION BY ${partition.join(", ")}`,
      order?.length && `ORDER BY ${order.join(", ")}`,
      framedef
    ].filter((x3) => x3);
    return base && def.length < 2 ? base : `(${def.join(" ")})`;
  }
};
function deriveDef(def, options) {
  return new WindowDefNode(options.name ?? def.name, options.partition ?? def.partition, options.order ?? def.order, options.framedef ?? def.framedef);
}

// ../../mosaic/sql/dist/src/ast/column-ref.js
function isColumnRef(value) {
  return value instanceof ColumnRefNode;
}
var ColumnRefNode = class extends ExprNode {
  /** The table reference. */
  table;
  /**
   * Instantiate a column reference node.
   * @param type The AST node type.
   * @param table The table reference.
   */
  constructor(type2, table3) {
    super(type2);
    this.table = table3;
  }
  /**
   * Returns the column name.
   */
  get column() {
    return "";
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { column: column3, table: table3 } = this;
    const tref = `${table3 ?? ""}`;
    const id2 = column3 === "*" ? "*" : quoteIdentifier(column3);
    return (tref ? tref + "." : "") + id2;
  }
};
var ColumnNameRefNode = class extends ColumnRefNode {
  /** The column name. */
  name;
  /**
   * Instantiate a column reference node.
   * @param name The column name.
   * @param table The table reference.
   */
  constructor(name2, table3) {
    super(COLUMN_REF, table3);
    this.name = name2;
  }
  /**
   * Returns the column name.
   */
  get column() {
    return this.name;
  }
};

// ../../mosaic/sql/dist/src/ast/column-param.js
function isColumnParam(value) {
  return value instanceof ColumnParamNode;
}
var ColumnParamNode = class extends ColumnRefNode {
  /** The column name as a parameter node */
  param;
  /**
   * Instantiate a column param node.
   * @param param The column name as a parameter node.
   * @param table The table reference.
   */
  constructor(param, table3) {
    super(COLUMN_PARAM, table3);
    this.param = param;
  }
  /**
   * Returns the column name.
   */
  get column() {
    return `${this.param.value}`;
  }
};

// ../../mosaic/sql/dist/src/util/type-check.js
function isString(value) {
  return typeof value === "string";
}
function isArray2(value) {
  return Array.isArray(value);
}
function isParamLike(value) {
  if (value) {
    const v2 = value;
    return typeof v2?.addEventListener === "function" && v2.dynamic !== false && "value" in v2;
  }
  return false;
}

// ../../mosaic/sql/dist/src/functions/column.js
function column(name2, table3) {
  const tref = asTableRef(table3);
  return isParamLike(name2) ? new ColumnParamNode(new ParamNode(name2), tref) : new ColumnNameRefNode(name2, tref);
}

// ../../mosaic/sql/dist/src/ast/verbatim.js
var VerbatimNode = class extends ExprNode {
  /** The verbatim content to include. */
  value;
  /** A type hint for analyzing verbatim content. */
  hint;
  /**
   * Instantiate a raw node with verbatim content.
   * @param value The verbatim content to include.
   * @param hint A type hint for analyzing verbatim content.
   */
  constructor(value, hint) {
    super(VERBATIM);
    this.value = value;
    this.hint = hint;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return this.value;
  }
};

// ../../mosaic/sql/dist/src/functions/literal.js
function literal(value) {
  return new LiteralNode(value);
}
function verbatim(value, hint) {
  return new VerbatimNode(value, hint);
}

// ../../mosaic/sql/dist/src/ast/table-ref.js
function isTableRef(value) {
  return value instanceof TableRefNode;
}
var TableRefNode = class extends ExprNode {
  /** The table name, including namespaces. */
  table;
  /**
   * Instantiate a table reference node.
   * @param table The table name.
   */
  constructor(table3) {
    super(TABLE_REF);
    this.table = [table3].flat();
  }
  /**
   * The table name without database or schema namespaces.
   */
  get name() {
    return this.table[this.table.length - 1];
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return this.table.map((t) => quoteIdentifier(t)).join(".");
  }
};

// ../../mosaic/sql/dist/src/functions/table-ref.js
function tableRef(...ids) {
  const args = exprList(ids, String);
  return args?.length ? new TableRefNode(args) : void 0;
}

// ../../mosaic/sql/dist/src/util/ast.js
function asNode(value) {
  return isString(value) ? parseColumnRef(value) : asLiteral(value);
}
function asVerbatim(value) {
  return isString(value) ? verbatim(value) : asLiteral(value);
}
function asLiteral(value) {
  return value instanceof ExprNode ? value : isParamLike(value) ? new ParamNode(value) : literal(value);
}
function asTableRef(value) {
  return getTableRef(value);
}
function maybeTableRef(value) {
  return getTableRef(value);
}
function getTableRef(value) {
  return isString(value) ? parseTableRef(value) : isArray2(value) ? tableRef(value) : value;
}
function parseColumnRef(ref) {
  const ids = parseIdentifier(ref);
  return column(ids.pop(), tableRef(ids));
}
function parseTableRef(ref) {
  return tableRef(parseIdentifier(ref));
}
function over() {
  return new WindowDefNode();
}

// ../../mosaic/sql/dist/src/ast/aggregate.js
var AggregateNode = class _AggregateNode extends ExprNode {
  /** The aggregate function name. */
  name;
  /** The aggregate function arguments. */
  args;
  /** The distinct flag. */
  isDistinct;
  /** Filter criteria. */
  filter;
  /** Order by expression for order-sensitive aggregates. */
  order;
  /**
   * Instantiate an aggregate function node.
   * @param name The aggregate function name.
   * @param args The aggregate function arguments.
   * @param distinct The distinct flag.
   * @param filter Filter expression.
   * @param argOrder Order by expression.
   */
  constructor(name2, args, distinct2 = false, filter3 = null, argOrder = []) {
    super(AGGREGATE);
    this.name = name2;
    this.args = args;
    this.isDistinct = distinct2;
    this.filter = filter3;
    this.order = nodeList([argOrder]);
  }
  /**
   * Return a new derived aggregate over distinct values.
   * @param isDistinct The distinct flag.
   * @returns A new aggregate node.
   */
  distinct(isDistinct2 = true) {
    return new _AggregateNode(this.name, this.args, isDistinct2, this.filter, this.order);
  }
  /**
   * Return a new derived aggregate function that filters values.
   * @param The filter expression.
   * @returns A new aggregate node.
   */
  where(filter3) {
    if (isString(filter3))
      filter3 = asVerbatim(filter3);
    return new _AggregateNode(this.name, this.args, this.isDistinct, filter3, this.order);
  }
  /**
   * Return a new derived aggregate function that sorts values prior to aggregation.
   * @param order The order by expression.
   * @returns A new aggregate node.
   */
  argOrder(order) {
    return new _AggregateNode(this.name, this.args, this.isDistinct, this.filter, order);
  }
  /**
   * Return a new window function over this aggregate.
   * @returns A new window node.
   */
  window() {
    return new WindowNode(this);
  }
  /**
   * Return a new window function over this aggregate with the given partitions.
   * @param expr The partition by criteria.
   * @returns A new window node.
   */
  partitionby(...expr) {
    return this.window().partitionby(...expr);
  }
  /**
   * Return a new window function over this aggregate with the given ordering.
   * @param expr The order by criteria.
   * @returns A new window node.
   */
  orderby(...expr) {
    return this.window().orderby(...expr);
  }
  /**
   * Return a new window function over this aggregate with the given frame.
   * @param framedef The window frame definition.
   * @returns A new window node.
   */
  frame(framedef) {
    return this.window().frame(framedef);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { name: name2, args, isDistinct: isDistinct2, filter: filter3, order } = this;
    const arg = [
      isDistinct2 ? "DISTINCT" : "",
      args?.length ? args.join(", ") : name2.toLowerCase() === "count" ? "*" : "",
      order.length ? `ORDER BY ${order.join(", ")}` : ""
    ].filter((x3) => x3).join(" ");
    const filt = filter3 ? ` FILTER (WHERE ${filter3})` : "";
    return `${name2}(${arg})${filt}`;
  }
};
var aggregateNames = [
  "any_value",
  "approx_count_distinct",
  "approx_quantile",
  "arbitrary",
  "arg_max",
  "arg_max_null",
  "arg_min",
  "arg_min_null",
  "array_agg",
  "avg",
  "bit_and",
  "bit_or",
  "bit_xor",
  "bitstring_agg",
  "bool_and",
  "bool_or",
  "corr",
  "count",
  "count_star",
  "covar_pop",
  "covar_samp",
  "entropy",
  "favg",
  "first",
  "fsum",
  "geomean",
  "kurtosis_pop",
  "kurtosis",
  "last",
  "mad",
  "max",
  "max_by",
  "median",
  "min",
  "min_by",
  "mode",
  "product",
  "quantile",
  "quantile_cont",
  "quantile_disc",
  "regr_avgx",
  "regr_avgy",
  "regr_count",
  "regr_intercept",
  "regr_r2",
  "regr_sxx",
  "regr_sxy",
  "regr_syy",
  "regr_slope",
  "reservoir_quantile",
  "skewness",
  "stddev",
  "stddev_pop",
  "stddev_samp",
  "string_agg",
  "sum",
  "variance",
  "var_pop",
  "var_samp"
];

// ../../mosaic/sql/dist/src/ast/between-op.js
var AbstractBetweenOpNode = class extends ExprNode {
  /** The input expression. */
  expr;
  /** The range extent. */
  extent;
  /**
   * Instantiate an abstract between operator node.
   * @param type The node type.
   * @param expr The input expression.
   * @param extent The range extent.
   */
  constructor(type2, expr, extent4) {
    super(type2);
    this.expr = expr;
    this.extent = extent4;
  }
  /**
   * Generate a SQL query string for this node.
   * @param op The operator to apply.
   */
  toSQL(op) {
    const { extent: r, expr } = this;
    return r ? `(${expr} ${op} ${r[0]} AND ${r[1]})` : "";
  }
};
var BetweenOpNode = class extends AbstractBetweenOpNode {
  /**
   * Instantiate a between operator node.
   * @param expr The input expression.
   * @param extent The range extent.
   */
  constructor(expr, extent4) {
    super(BETWEEN_OPERATOR, expr, extent4);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return super.toSQL("BETWEEN");
  }
};
var NotBetweenOpNode = class extends AbstractBetweenOpNode {
  /**
   * Instantiate a not between operator node.
   * @param expr The input expression.
   * @param extent The range extent.
   */
  constructor(expr, extent4) {
    super(NOT_BETWEEN_OPERATOR, expr, extent4);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return super.toSQL("NOT BETWEEN");
  }
};

// ../../mosaic/sql/dist/src/ast/binary-op.js
var BinaryOpNode = class extends ExprNode {
  /** The operator type. */
  op;
  /** The left input expression. */
  left;
  /** The right input expression. */
  right;
  /**
   * Instantiate a binary operator node.
   * @param op The operator type.
   * @param left The left input expression.
   * @param right The right input expression.
   */
  constructor(op, left2, right2) {
    super(BINARY_OPERATOR);
    this.op = op;
    this.left = left2;
    this.right = right2;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `(${this.left} ${this.op} ${this.right})`;
  }
};

// ../../mosaic/sql/dist/src/ast/case.js
var CaseNode = class _CaseNode extends ExprNode {
  /** The optional base expression. */
  expr;
  /** An array of WHEN/THEN expression nodes. */
  _when;
  /** An ELSE expression. */
  _else;
  /**
   * Instantiate a case node.
   * @param expr An optional base expression, that comes
   *  immediately after the CASE keyword. If specified, this case statement
   *  acts like a switch statement, with WHEN expressions as values to
   *  match against the switch value rather than boolean conditions.
   * @param when An array of WHEN/THEN expression nodes.
   * @param elseExpr An ELSE expression.
   */
  constructor(expr = void 0, when = [], elseExpr = void 0) {
    super(CASE);
    this.expr = expr;
    this._when = when;
    this._else = elseExpr;
  }
  /**
   * Return a new case node with the given conditional added as
   * the last WHEN / THEN pair.
   * @param cond The WHEN condition expression.
   * @param value The THEN value expression.
   */
  when(cond2, value) {
    return new _CaseNode(this.expr, this._when.concat(new WhenNode(asNode(cond2), asNode(value))), this._else);
  }
  /**
   * Return a new case node with the given ELSE expression.
   * @param expr The ELSE expression.
   */
  else(expr) {
    return new _CaseNode(this.expr, this._when, asNode(expr));
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return "CASE " + (this.expr ? `${this.expr} ` : "") + this._when.join(" ") + (this._else ? ` ELSE ${this._else}` : "") + " END";
  }
};
var WhenNode = class extends SQLNode {
  /** The condition expression. */
  when;
  /** The value expression. */
  then;
  /**
   * Instantiate a case node.
   * @param when The WHEN condition expression.
   * @param then The THEN value expression.
   */
  constructor(when, then) {
    super(WHEN);
    this.when = when;
    this.then = then;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `WHEN ${this.when} THEN ${this.then}`;
  }
};

// ../../mosaic/sql/dist/src/ast/cast.js
var CastNode = class extends ExprNode {
  /** The expression to type cast. */
  expr;
  /** The type to cast to. */
  cast;
  /**
   * Instantiate a cast node.
   * @param expr The expression to type cast.
   * @param type The type to cast to.
   */
  constructor(expr, type2) {
    super(CAST);
    this.expr = expr;
    this.cast = type2;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `(${this.expr})::${this.cast}`;
  }
};

// ../../mosaic/sql/dist/src/ast/fragment.js
var FragmentNode = class extends ExprNode {
  /** The consecutive parts making up the fragment. */
  spans;
  /**
   * Instantiate a fragment node with arbitrary content.
   * @param spans The consecutive parts making up the fragment.
   */
  constructor(spans) {
    super(FRAGMENT);
    this.spans = spans;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return this.spans.join("");
  }
};

// ../../mosaic/sql/dist/src/ast/sample.js
var SampleClauseNode = class extends SQLNode {
  /** The sample size as either a row count or percentage. */
  size;
  /** Flag if the sampling unit is rows (`false`) or percentage (`true`). */
  perc;
  /** The sampling method. */
  method;
  /** The random seed. */
  seed;
  /**
   * Instantiate a sample clause node.
   * @param size The sample size as either a row count or percentage.
   * @param perc Flag indicating if the sampling unit is
   *   rows (`false`) or a percentage (`true`).
   * @param method The sampling method. If unspecified,
   *   a default method is applied based on the sampling unit.
   * @param seed The random seed.
   */
  constructor(size, perc = false, method, seed) {
    super(SAMPLE_CLAUSE);
    this.size = size;
    this.perc = perc;
    this.method = method;
    this.seed = seed;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { size, perc, method, seed } = this;
    const m = method ? `${method} ` : "";
    const s2 = seed != null ? ` REPEATABLE (${seed})` : "";
    return `${m}(${size}${perc ? "%" : " ROWS"})${s2}`;
  }
};

// ../../mosaic/sql/dist/src/ast/select.js
var SelectClauseNode = class extends SQLNode {
  /** The select expression. */
  expr;
  /** The output name. */
  alias;
  /**
   * Instantiate a select node.
   * @param expr The select expression.
   * @param alias The output name.
   */
  constructor(expr, alias) {
    super(SELECT_CLAUSE);
    this.expr = expr;
    this.alias = alias;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { expr, alias } = this;
    return !alias || isColumnRefFor(expr, alias) ? `${expr}` : `${expr} AS ${quoteIdentifier(alias)}`;
  }
};
function isColumnRefFor(expr, name2) {
  return expr instanceof ColumnRefNode && expr.table == null && expr.column === name2;
}

// ../../mosaic/sql/dist/src/ast/with.js
var WithClauseNode = class extends SQLNode {
  /** The common table expression (CTE) name. */
  name;
  /** The common table expression (CTE) query. */
  query;
  /** The common table expression (CTE) materialization flag. */
  materialized;
  /**
   * Instantiate a with clause node for a common table expression (CTE).
   * @param name The common table expression (CTE) name.
   * @param query The common table expression (CTE) query.
   * @param materialized The common table expression (CTE)
   *  materialization flag. If `true`, forces materialization of the CTE.
   *  If `false`, materialization is not performed. Otherwise (for example, if
   *  `undefined` or `null`), materialization is decided by the database.
   */
  constructor(name2, query, materialized = null) {
    super(WITH_CLAUSE);
    this.name = name2;
    this.query = query;
    this.materialized = materialized;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const flag = this.materialized;
    const mat = flag === true ? " MATERIALIZED" : flag === false ? " NOT MATERIALIZED" : "";
    return `"${this.name}" AS${mat} (${this.query})`;
  }
};

// ../../mosaic/sql/dist/src/ast/query.js
function isQuery(value) {
  return value instanceof Query;
}
function isSelectQuery(value) {
  return value instanceof SelectQuery;
}
function isDescribeQuery(value) {
  return value instanceof DescribeQuery;
}
var Query = class extends ExprNode {
  /**
   * Create a new WITH clause with the given CTE queries.
   * @param expr The WITH CTE queries.
   */
  static with(...expr) {
    return new WithClause(...expr);
  }
  /**
   * Create a new select query with the given SELECT expressions.
   * @param expr The SELECT expressions.
   */
  static select(...expr) {
    return new SelectQuery().select(...expr);
  }
  /**
   * Create a new select query with the given FROM expressions.
   * @param expr The FROM expressions.
   */
  static from(...expr) {
    return new SelectQuery().from(...expr);
  }
  /**
   * Create a new UNION set operation over the given queries.
   * @param queries The queries.
   */
  static union(...queries) {
    return new SetOperation("UNION", queries.flat());
  }
  /**
   * Create a new UNION BY NAME set operation over the given queries.
   * @param queries The queries.
   */
  static unionByName(...queries) {
    return new SetOperation("UNION BY NAME", queries.flat());
  }
  /**
   * Create a new UNION ALL set operation over the given queries.
   * @param queries The queries.
   */
  static unionAll(...queries) {
    return new SetOperation("UNION ALL", queries.flat());
  }
  /**
   * Create a new UNION ALL BY NAME set operation over the given queries.
   * @param queries The queries.
   */
  static unionAllByName(...queries) {
    return new SetOperation("UNION ALL BY NAME", queries.flat());
  }
  /**
   * Create a new INTERSECT set operation over the given queries.
   * @param queries The queries.
   */
  static intersect(...queries) {
    return new SetOperation("INTERSECT", queries.flat());
  }
  /**
   * Create a new INTERSECT ALL set operation over the given queries.
   * @param queries The queries.
   */
  static intersectAll(...queries) {
    return new SetOperation("INTERSECT ALL", queries.flat());
  }
  /**
   * Create a new EXCEPT set operation over the given queries.
   * @param queries The queries.
   */
  static except(...queries) {
    return new SetOperation("EXCEPT", queries.flat());
  }
  /**
   * Create a new EXCEPT ALL set operation over the given queries.
   * @param queries The queries.
   */
  static exceptAll(...queries) {
    return new SetOperation("EXCEPT ALL", queries.flat());
  }
  /**
   * Create a new describe query for the given input query.
   * @param query The query to describe.
   */
  static describe(query) {
    return new DescribeQuery(query);
  }
  _with = [];
  _orderby = [];
  _limitPerc = false;
  _limit;
  _offset;
  cteFor = null;
  /**
   * Instantiate a new query.
   */
  constructor(type2) {
    super(type2);
  }
  /**
   * Return a list of subqueries.
   */
  get subqueries() {
    return [];
  }
  /**
   * Clone this query.
   */
  clone() {
    return this;
  }
  /**
   * Add a pointer to the query for which this query is a CTE.
   * @param query The query for which this query is a CTE.
   */
  setCteFor(query) {
    this.cteFor = query;
  }
  /**
   * Add WITH common table expressions (CTEs).
   * @param expr Expressions to add.
   */
  with(...expr) {
    const list3 = [];
    const add3 = (name2, q) => {
      const query = q.clone();
      query.setCteFor(this);
      list3.push(new WithClauseNode(name2, query));
    };
    expr.flat().forEach((e) => {
      if (e instanceof WithClauseNode)
        list3.push(e);
      else if (e != null)
        for (const name2 in e)
          add3(name2, e[name2]);
    });
    this._with = this._with.concat(list3);
    return this;
  }
  /**
   * Add ORDER BY expressions.
   * @param expr Expressions to add.
   */
  orderby(...expr) {
    this._orderby = this._orderby.concat(nodeList(expr));
    return this;
  }
  /**
   * Set the query result LIMIT as a percentage value.
   * @param value The limit percentage value.
   */
  limitPercent(value) {
    this._limitPerc = true;
    this._limit = asNode(value);
    return this;
  }
  /**
   * Set the query result LIMIT.
   * @param value The limit value.
   */
  limit(value) {
    this._limitPerc = false;
    this._limit = asNode(value);
    return this;
  }
  /**
   * Set the query result OFFSET.
   * @param value The offset value.
   */
  offset(value) {
    this._offset = asNode(value);
    return this;
  }
};
var SelectQuery = class _SelectQuery extends Query {
  _select = [];
  _from = [];
  _where = [];
  _sample;
  _groupby = [];
  _having = [];
  _window = [];
  _qualify = [];
  _distinct = false;
  /**
   * Instantiate a new select query.
   */
  constructor() {
    super(SELECT_QUERY);
  }
  /**
   * Return a list of subqueries.
   */
  get subqueries() {
    const q = this.cteFor || this;
    const w = q instanceof _SelectQuery ? q._with : [];
    const cte2 = w.reduce((obj, c4) => (obj[c4.name] = c4.query, obj), {});
    const queries = [];
    this._from.forEach(({ expr }) => {
      if (isQuery(expr)) {
        queries.push(expr);
      } else if (isTableRef(expr)) {
        const subq = cte2[expr.name];
        if (subq)
          queries.push(subq);
      }
    });
    return queries;
  }
  /**
   * Clone this query.
   */
  clone() {
    return Object.assign(new _SelectQuery(), this);
  }
  /**
   * Add SELECT expressions.
   * @param expr Expressions to add.
   */
  select(...expr) {
    const keys = /* @__PURE__ */ new Set();
    const list3 = [];
    const add3 = (v2, as) => {
      const key = unquote(as);
      keys.add(key);
      if (v2)
        list3.push(new SelectClauseNode(asNode(v2), key));
    };
    expr.flat().forEach((e) => {
      if (e == null)
        return;
      else if (isString(e))
        add3(e, e);
      else if (isColumnRef(e))
        add3(e, e.column);
      else if (isArray2(e))
        add3(e[1], e[0]);
      else if (isNode(e))
        add3(e, `${e}`);
      else
        for (const alias in e)
          add3(e[alias], alias);
    });
    this._select = this._select.filter((x3) => !keys.has(x3.alias)).concat(list3);
    return this;
  }
  /**
   * Set SELECT expressions, replacing any prior expressions.
   * @param expr Expressions to add.
   */
  setSelect(...expr) {
    this._select = [];
    return this.select(...expr);
  }
  /**
   * Indicate if this query should retrieve distinct values only.
   * @param value The distinct flag
   */
  distinct(value = true) {
    this._distinct = !!value;
    return this;
  }
  /**
   * Add table FROM expressions.
   * @param expr Expressions to add.
   */
  from(...expr) {
    const list3 = [];
    const add3 = (v2, as) => {
      list3.push(new FromClauseNode(maybeTableRef(v2), unquote(as)));
    };
    expr.flat().forEach((e) => {
      if (e == null)
        return;
      else if (e instanceof FromClauseNode)
        list3.push(e);
      else if (isString(e))
        add3(e, e);
      else if (isTableRef(e))
        add3(e, e.name);
      else if (isNode(e))
        add3(e);
      else if (isArray2(e))
        add3(e[1], e[0]);
      else
        for (const alias in e)
          add3(e[alias], alias);
    });
    this._from = this._from.concat(list3);
    return this;
  }
  /**
   * Set FROM expressions, replacing any prior expressions.
   * @param expr Expressions to add.
   */
  setFrom(...expr) {
    this._from = [];
    return this.from(...expr);
  }
  /**
   * Set SAMPLE settings.
   * @param value Either a sample clause node or the sample size as either
   *  a row count or percentage.
   * @param method The sampling method to use.
   * @param seed The random seed.
   */
  sample(value, method, seed) {
    let clause;
    if (typeof value === "number") {
      const perc = value > 0 && value < 1;
      const size = perc ? value * 100 : Math.floor(value);
      clause = new SampleClauseNode(size, perc, method, seed);
    } else {
      clause = value;
    }
    this._sample = clause ?? void 0;
    return this;
  }
  /**
   * Add WHERE expressions.
   * @param expr Expressions to add.
   */
  where(...expr) {
    this._where = this._where.concat(exprList(expr, asVerbatim));
    return this;
  }
  /**
   * Set WHERE expressions, replacing any prior expressions.
   * @param expr Expressions to add.
   */
  setWhere(...expr) {
    this._where = [];
    return this.where(...expr);
  }
  /**
   * Add GROUP BY expressions.
   * @param expr Expressions to add.
   */
  groupby(...expr) {
    this._groupby = this._groupby.concat(nodeList(expr));
    return this;
  }
  /**
   * Set GROUP BY expressions, replacing any prior expressions.
   * @param expr Expressions to add.
   */
  setGroupby(...expr) {
    this._groupby = [];
    return this.groupby(...expr);
  }
  /**
   * Add HAVING expressions.
   * @param expr Expressions to add.
   */
  having(...expr) {
    this._having = this._having.concat(exprList(expr, asVerbatim));
    return this;
  }
  /**
   * Add WINDOW definitions.
   * @param expr Window definitions to add.
   */
  window(...expr) {
    const list3 = [];
    expr.flat().forEach((e) => {
      if (e != null)
        for (const name2 in e) {
          list3.push(new WindowClauseNode(unquote(name2), e[name2]));
        }
    });
    this._window = this._window.concat(list3);
    return this;
  }
  /**
   * Add QUALIFY expressions.
   * @param expr Expressions to add.
   */
  qualify(...expr) {
    this._qualify = this._qualify.concat(exprList(expr, asVerbatim));
    return this;
  }
  /**
   * Generate a SQL query string.
   */
  toString() {
    const { _with, _select, _distinct, _from, _sample, _where, _groupby, _having, _window, _qualify, _orderby, _limitPerc, _limit, _offset } = this;
    const sql2 = [];
    if (_with.length)
      sql2.push(`WITH ${_with.join(", ")}`);
    sql2.push(`SELECT${_distinct ? " DISTINCT" : ""} ${_select.join(", ")}`);
    if (_from.length)
      sql2.push(`FROM ${_from.join(", ")}`);
    if (_where.length) {
      const clauses = _where.map(String).filter((x3) => x3).join(" AND ");
      if (clauses)
        sql2.push(`WHERE ${clauses}`);
    }
    if (_sample)
      sql2.push(`USING SAMPLE ${_sample}`);
    if (_groupby.length) {
      sql2.push(`GROUP BY ${_groupby.join(", ")}`);
    }
    if (_having.length) {
      const clauses = _having.map(String).filter((x3) => x3).join(" AND ");
      if (clauses)
        sql2.push(`HAVING ${clauses}`);
    }
    if (_window.length)
      sql2.push(`WINDOW ${_window.join(", ")}`);
    if (_qualify.length) {
      const clauses = _qualify.map(String).filter((x3) => x3).join(" AND ");
      if (clauses)
        sql2.push(`QUALIFY ${clauses}`);
    }
    if (_orderby.length)
      sql2.push(`ORDER BY ${_orderby.join(", ")}`);
    if (_limit)
      sql2.push(`LIMIT ${_limit}${_limitPerc ? "%" : ""}`);
    if (_offset)
      sql2.push(`OFFSET ${_offset}`);
    return sql2.join(" ");
  }
};
var DescribeQuery = class _DescribeQuery extends SQLNode {
  query;
  /**
   * Instantiate a describe query.
   * @param query The query to describe.
   */
  constructor(query) {
    super(DESCRIBE_QUERY);
    this.query = query;
  }
  /**
   * Clone this describe query.
   */
  clone() {
    return new _DescribeQuery(this.query.clone());
  }
  /**
   * Generate a SQL query string.
   */
  toString() {
    return `DESCRIBE ${this.query}`;
  }
};
var SetOperation = class _SetOperation extends Query {
  /** The set operation to perform. */
  op;
  /** The input queries to the set operation. */
  queries;
  /**
   * Instantiate a new set operation instance.
   * @param op The set operation.
   * @param queries The subqueries.
   */
  constructor(op, queries) {
    super(SET_OPERATION);
    this.op = op;
    this.queries = queries;
  }
  /**
   * Add a pointer to the query for which this query is a CTE.
   * @param query The query for which this query is a CTE.
   */
  setCteFor(query) {
    super.setCteFor(query);
    const { queries, cteFor } = this;
    if (cteFor)
      queries.forEach((q) => q.setCteFor(cteFor));
  }
  /**
   * Return a list of subqueries.
   */
  get subqueries() {
    return this.queries;
  }
  /**
   * Clone this set operation.
   */
  clone() {
    const { op, queries, ...rest } = this;
    return Object.assign(new _SetOperation(op, queries), rest);
  }
  /**
   * Generate a SQL query string.
   */
  toString() {
    const { op, queries, _with, _orderby, _limitPerc, _limit, _offset } = this;
    const sql2 = [];
    if (_with.length)
      sql2.push(`WITH ${_with.join(", ")}`);
    sql2.push(queries.join(` ${op} `));
    if (_orderby.length)
      sql2.push(`ORDER BY ${_orderby.join(", ")}`);
    if (_limit)
      sql2.push(`LIMIT ${_limit}${_limitPerc ? "%" : ""}`);
    if (_offset)
      sql2.push(`OFFSET ${_offset}`);
    return sql2.join(" ");
  }
};
var WithClause = class {
  /** The common table expressions (CTE). */
  _with;
  /**
   * Instantiate a new WITH clause instance.
   * @param expr The WITH CTE queries.
   */
  constructor(...expr) {
    this._with = expr;
  }
  /**
   * Create a new select query with the given SELECT expressions.
   * @param expr The SELECT expressions.
   */
  select(...expr) {
    return Query.select(...expr).with(...this._with);
  }
  /**
   * Create a new select query with the given FROM expressions.
   * @param expr The FROM expressions.
   */
  from(...expr) {
    return Query.from(...expr).with(...this._with);
  }
  /**
   * Create a new UNION set operation over the given queries.
   * @param queries The queries.
   */
  union(...queries) {
    return Query.union(...queries).with(...this._with);
  }
  /**
   * Create a new UNION BY NAME set operation over the given queries.
   * @param queries The queries.
   */
  unionByName(...queries) {
    return Query.unionByName(...queries).with(...this._with);
  }
  /**
   * Create a new UNION ALL set operation over the given queries.
   * @param queries The queries.
   */
  unionAll(...queries) {
    return Query.unionAll(...queries).with(...this._with);
  }
  /**
   * Create a new UNION ALL BY NAME set operation over the given queries.
   * @param queries The queries.
   */
  unionAllByName(...queries) {
    return Query.unionAllByName(...queries).with(...this._with);
  }
  /**
   * Create a new INTERSECT set operation over the given queries.
   * @param queries The queries.
   */
  intersect(...queries) {
    return Query.intersect(...queries).with(...this._with);
  }
  /**
   * Create a new INTERSECT ALL set operation over the given queries.
   * @param queries The queries.
   */
  intersectAll(...queries) {
    return Query.intersectAll(...queries).with(...this._with);
  }
  /**
   * Create a new EXCEPT set operation over the given queries.
   * @param queries The queries.
   */
  except(...queries) {
    return Query.except(...queries).with(...this._with);
  }
  /**
   * Create a new EXCEPT ALL set operation over the given queries.
   * @param queries The queries.
   */
  exceptAll(...queries) {
    return Query.exceptAll(...queries).with(...this._with);
  }
};

// ../../mosaic/sql/dist/src/ast/from.js
var FromClauseNode = class extends SQLNode {
  /** The from expression. */
  expr;
  /** The output name. */
  alias;
  /** The table sample. */
  sample;
  /**
   * Instantiate a from node.
   * @param expr The from expression.
   * @param alias The output name.
   * @param sample The table sample.
   */
  constructor(expr, alias, sample) {
    super(FROM_CLAUSE);
    this.expr = expr;
    this.alias = alias;
    this.sample = sample;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { expr, alias, sample } = this;
    const ref = isQuery(expr) ? `(${expr})` : `${expr}`;
    const from2 = alias && !(isTableRef(expr) && expr.table.join(".") === alias) ? `${ref} AS ${quoteIdentifier(alias)}` : `${ref}`;
    return `${from2}${sample ? ` TABLESAMPLE ${sample}` : ""}`;
  }
};

// ../../mosaic/sql/dist/src/ast/in-op.js
var InOpNode = class extends ExprNode {
  /** The input expression. */
  expr;
  /** The value set. */
  values;
  /**
   * Instantiate an in operator node.
   * @param expr The input expression.
   * @param values The value set.
   */
  constructor(expr, values2) {
    super(IN_OPERATOR);
    this.expr = expr;
    this.values = values2;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `(${this.expr} IN (${this.values.join(", ")}))`;
  }
};

// ../../mosaic/sql/dist/src/ast/interval.js
var IntervalNode = class extends ExprNode {
  /** The interval name. */
  name;
  /** The interval steps. */
  steps;
  /**
   * Instantiate an interval node.
   * @param name The interval name.
   * @param steps The interval steps.
   */
  constructor(name2, steps = 1) {
    super(INTERVAL);
    this.name = name2;
    this.steps = steps;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `INTERVAL ${this.steps} ${this.name}`;
  }
};

// ../../mosaic/sql/dist/src/ast/list.js
var ListNode = class extends ExprNode {
  /** The array of values. */
  values;
  /**
   * Instantiate a list node.
   * @param values
   */
  constructor(values2) {
    super(LIST);
    this.values = values2;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `[${this.values.join(", ")}]`;
  }
};

// ../../mosaic/sql/dist/src/ast/logical-op.js
var LogicalOpNode = class extends ExprNode {
  /** The logical operator */
  op;
  /** The clause expressions. */
  clauses;
  /**
   * Instantiate a logical operator node.
   * @param op The logical operation.
   * @param clauses The input clause expressions.
   */
  constructor(op, clauses) {
    super(LOGICAL_OPERATOR);
    this.op = op;
    this.clauses = clauses;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const c4 = this.clauses;
    return c4.length === 0 ? "" : c4.length === 1 ? `${c4[0]}` : `(${c4.join(` ${this.op} `)})`;
  }
};
var AndNode = class extends LogicalOpNode {
  /**
   * Instantiate a logical AND operator node.
   * @param clauses The input clause expressions.
   */
  constructor(clauses) {
    super("AND", clauses);
  }
};
var OrNode = class extends LogicalOpNode {
  /**
   * Instantiate a logical OR operator node.
   * @param clauses The input clause expressions.
   */
  constructor(clauses) {
    super("OR", clauses);
  }
};

// ../../mosaic/sql/dist/src/ast/order-by.js
var OrderByNode = class extends ExprNode {
  /** The expression to order by. */
  expr;
  /** Flag indicating descending order. */
  desc;
  /** Flag indicating if null values should be sorted first. */
  nullsFirst;
  /**
   * Instantiate an order by entry node.
   * @param expr The expression to order by.
   * @param desc Flag indicating descending order.
   * @param nullsFirst Flag indicating if null values should be sorted first.
   */
  constructor(expr, desc2, nullsFirst) {
    super(ORDER_BY);
    this.expr = expr;
    this.desc = desc2;
    this.nullsFirst = nullsFirst;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { expr, desc: desc2, nullsFirst } = this;
    const dir = desc2 ? " DESC" : desc2 === false ? " ASC" : "";
    const nf = nullsFirst ? " NULLS FIRST" : nullsFirst === false ? " NULLS LAST" : "";
    return `${expr}${dir}${nf}`;
  }
};

// ../../mosaic/sql/dist/src/ast/unary-op.js
var AbstractUnaryOpNode = class extends ExprNode {
  /** The operator type. */
  op;
  /** The input expression. */
  expr;
  /**
   * Instantiate an abstract unary operator node.
   * @param type The node type.
   * @param op The operator type.
   * @param expr The input expression.
   */
  constructor(type2, op, expr) {
    super(type2);
    this.op = op;
    this.expr = expr;
  }
};
var UnaryOpNode = class extends AbstractUnaryOpNode {
  /**
   * Instantiate a unary operator node.
   * @param op The operator type.
   * @param expr The input expression.
   */
  constructor(op, expr) {
    super(UNARY_OPERATOR, op, expr);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `(${this.op} ${this.expr})`;
  }
};
var UnaryPostfixOpNode = class extends AbstractUnaryOpNode {
  /**
   * Instantiate a unary operator node.
   * @param op The operator type.
   * @param expr The input expression.
   */
  constructor(op, expr) {
    super(UNARY_POSTFIX_OPERATOR, op, expr);
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    return `(${this.expr} ${this.op})`;
  }
};

// ../../mosaic/sql/dist/src/ast/unnest.js
var UnnestNode = class extends ExprNode {
  /** An expression that resolves to a list or a struct */
  expr;
  recursive;
  maxDepth;
  /**
   * Instantiate an Unnest node.
   * @param expr
   * @param recursive
   * @param maxDepth
   */
  constructor(expr, recursive = false, maxDepth2 = 0) {
    super(UNNEST);
    this.expr = expr;
    this.recursive = recursive;
    this.maxDepth = maxDepth2;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const recursive = this.recursive ? ", recursive := true" : "";
    const maxDepth2 = this.maxDepth > 0 ? `, max_depth := ${this.maxDepth}` : "";
    return `UNNEST(${this.expr}${recursive}${maxDepth2})`;
  }
};

// ../../mosaic/sql/dist/src/ast/window-frame.js
var ROWS = "ROWS";
var RANGE = "RANGE";
var GROUPS = "GROUPS";
var PRECEDING = "PRECEDING";
var FOLLOWING = "FOLLOWING";
var CURRENT_ROW = "CURRENT ROW";
var UNBOUNDED = "UNBOUNDED";
var WindowFrameNode = class extends SQLNode {
  /** The frame type, one of ROWS, RANGE, or GROUPS. */
  frameType;
  /** The window frame extent. */
  extent;
  /** The window frame exclusion criteria. */
  exclude;
  /**
   * Instantiate a window frame definition node.
   * @param frameType The frame type, one of ROWS, RANGE, or GROUPS.
   * @param extent The window frame extent.
   * @param exclude The window frame exclusion criteria.
   */
  constructor(frameType, extent4, exclude) {
    super(WINDOW_FRAME);
    this.frameType = frameType;
    this.extent = isParamLike(extent4) ? new ParamNode(extent4) : extent4;
    this.exclude = exclude;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { frameType, exclude, extent: extent4 } = this;
    const [prev, next] = isNode(extent4) ? extent4.value : extent4;
    const a2 = asFrameExpr(prev, PRECEDING);
    const b = asFrameExpr(next, FOLLOWING);
    return `${frameType} BETWEEN ${a2} AND ${b}${exclude ? ` ${exclude}` : ""}`;
  }
};
function asFrameExpr(value, scope) {
  return value instanceof WindowFrameExprNode ? value : value != null && typeof value !== "number" ? `${value} ${scope}` : value === 0 ? CURRENT_ROW : !(value && Number.isFinite(value)) ? `${UNBOUNDED} ${scope}` : `${Math.abs(value)} ${scope}`;
}
var WindowFrameExprNode = class extends SQLNode {
  /** The window frame extent. */
  scope;
  /**
   * The window frame extent expression. This value should be null
   * in the case of current row or unbounded extent values.
   */
  expr;
  /**
   * Instantiate a window frame definition node.
   * @param scope The frame scope, one of PRECEDING, FOLLOWING, or CURRENT ROW.
   * @param expr The window frame extent expression.
   */
  constructor(scope, expr = null) {
    super(WINDOW_EXTENT_EXPR);
    this.scope = scope;
    this.expr = expr;
  }
  /**
   * Generate a SQL query string for this node.
   */
  toString() {
    const { scope, expr } = this;
    return scope === CURRENT_ROW ? scope : `${expr ?? UNBOUNDED} ${scope}`;
  }
};

// ../../mosaic/sql/dist/src/functions/aggregate.js
function argmax(y3, x3) {
  return aggFn("arg_max", y3, x3);
}
function argmin(y3, x3) {
  return aggFn("arg_min", y3, x3);
}
function arrayAgg(expr) {
  return aggFn("array_agg", expr);
}
function avg(expr) {
  return aggFn("avg", expr);
}
function corr(x3, y3) {
  return aggFn("corr", x3, y3);
}
function count(expr) {
  return aggFn("count", expr);
}
function covariance(x3, y3) {
  return aggFn("covar_samp", x3, y3);
}
function covarPop(x3, y3) {
  return aggFn("covar_pop", x3, y3);
}
function entropy(expr) {
  return aggFn("entropy", expr);
}
function first(expr) {
  return aggFn("first", expr);
}
function geomean(expr) {
  return aggFn("geomean", expr);
}
function kurtosis(expr) {
  return aggFn("kurtosis", expr);
}
function mad(expr) {
  return aggFn("mad", expr);
}
function max(expr) {
  return aggFn("max", expr);
}
function median(expr) {
  return aggFn("median", expr);
}
function min(expr) {
  return aggFn("min", expr);
}
function mode(expr) {
  return aggFn("mode", expr);
}
function last(expr) {
  return aggFn("last", expr);
}
function product(expr) {
  return aggFn("product", expr);
}
function quantile(expr, p) {
  return aggFn("quantile", expr, p);
}
function regrAvgX(x3, y3) {
  return aggFn("regr_avgx", x3, y3);
}
function regrAvgY(x3, y3) {
  return aggFn("regr_avgy", x3, y3);
}
function regrCount(x3, y3) {
  return aggFn("regr_count", x3, y3);
}
function regrIntercept(x3, y3) {
  return aggFn("regr_intercept", x3, y3);
}
function regrSXX(x3, y3) {
  return aggFn("regr_sxx", x3, y3);
}
function regrSYY(x3, y3) {
  return aggFn("regr_syy", x3, y3);
}
function regrSlope(x3, y3) {
  return aggFn("regr_slope", x3, y3);
}
function skewness(expr) {
  return aggFn("skewness", expr);
}
function stddev(expr) {
  return aggFn("stddev", expr);
}
function stddevPop(expr) {
  return aggFn("stddev_pop", expr);
}
function stringAgg(expr) {
  return aggFn("string_agg", expr);
}
function sum(expr) {
  return aggFn("sum", expr);
}
function variance(expr) {
  return aggFn("var_samp", expr);
}
function varPop(expr) {
  return aggFn("var_pop", expr);
}

// ../../mosaic/sql/dist/src/functions/case.js
function cond(when, then, other) {
  return when ? new CaseNode(void 0, [new WhenNode(asNode(when), asNode(then))], asNode(other)) : new CaseNode();
}

// ../../mosaic/sql/dist/src/functions/cast.js
function cast(expr, type2) {
  return new CastNode(asNode(expr), type2);
}
function int322(expr) {
  return cast(expr, "INTEGER");
}
function float322(expr) {
  return cast(expr, "FLOAT");
}
function float642(expr) {
  return cast(expr, "DOUBLE");
}

// ../../mosaic/sql/dist/src/functions/cte.js
function cte(name2, query, materialized = null) {
  return new WithClauseNode(name2, query, materialized);
}

// ../../mosaic/sql/dist/src/functions/interval.js
function interval2(unit3, steps) {
  return new IntervalNode(unit3, steps);
}
function years(steps) {
  return interval2("YEARS", steps);
}
function months(steps) {
  return interval2("MONTHS", steps);
}
function days(steps) {
  return interval2("DAYS", steps);
}
function hours(steps) {
  return interval2("HOURS", steps);
}
function minutes(steps) {
  return interval2("MINUTES", steps);
}
function seconds(steps) {
  return interval2("SECONDS", steps);
}
function milliseconds(steps) {
  return interval2("MILLISECONDS", steps);
}
function microseconds(steps) {
  return interval2("MICROSECONDS", steps);
}

// ../../mosaic/sql/dist/src/functions/datetime.js
function epoch_ms(expr) {
  return fn("epoch_ms", expr);
}
function dateBin(expr, unit3, steps = 1) {
  return fn("time_bucket", interval2(unit3, steps), expr);
}
function dateMonth(expr) {
  return fn("make_date", 2012, fn("month", expr), 1);
}
function dateMonthDay(expr) {
  const d = asNode(expr);
  return fn("make_date", 2012, fn("month", d), fn("day", d));
}
function dateDay2(expr) {
  return fn("make_date", 2012, 1, fn("day", expr));
}

// ../../mosaic/sql/dist/src/functions/list.js
function list2(values2) {
  return new ListNode(argsList(values2).map(asLiteral));
}
function asList(values2) {
  return Array.isArray(values2) ? list2(values2) : asNode(values2);
}
function listHasAll(list1, list22) {
  return fn("list_has_all", asList(list1), asList(list22));
}
function listHasAny(list1, list22) {
  return fn("list_has_any", asList(list1), asList(list22));
}

// ../../mosaic/sql/dist/src/functions/numeric.js
function greatest(...expr) {
  return fn("greatest", ...expr);
}
function exp(expr) {
  return fn("exp", expr);
}
function log(expr) {
  return fn("log", expr);
}
function ln(expr) {
  return fn("ln", expr);
}
function sign(expr) {
  return fn("sign", expr);
}
function abs(expr) {
  return fn("abs", expr);
}
function sqrt(expr) {
  return fn("sqrt", expr);
}
function ceil(expr) {
  return fn("ceil", expr);
}
function floor(expr) {
  return fn("floor", expr);
}
function round(expr, places) {
  return fn("round", expr, places);
}

// ../../mosaic/sql/dist/src/functions/operators.js
function unaryOp(op, expr) {
  return new UnaryOpNode(op, asNode(expr));
}
function unaryPostfixOp(op, expr) {
  return new UnaryPostfixOpNode(op, asNode(expr));
}
function binaryOp(op, left2, right2) {
  return new BinaryOpNode(op, asNode(left2), asNode(right2));
}
function and(...clauses) {
  return new AndNode(nodeList(clauses));
}
function or(...clauses) {
  return new OrNode(nodeList(clauses));
}
function not(expr) {
  return unaryOp("NOT", expr);
}
function isNull(expr) {
  return unaryPostfixOp("IS NULL", expr);
}
function isNotNull(expr) {
  return unaryPostfixOp("IS NOT NULL", expr);
}
function bitAnd(left2, right2) {
  return binaryOp("&", left2, right2);
}
function add(left2, right2) {
  return binaryOp("+", left2, right2);
}
function sub(left2, right2) {
  return binaryOp("-", left2, right2);
}
function mul(left2, right2) {
  return binaryOp("*", left2, right2);
}
function div(left2, right2) {
  return binaryOp("/", left2, right2);
}
function pow(left2, right2) {
  return binaryOp("**", left2, right2);
}
function eq(left2, right2) {
  return binaryOp("=", left2, right2);
}
function neq(left2, right2) {
  return binaryOp("<>", left2, right2);
}
function lt(left2, right2) {
  return binaryOp("<", left2, right2);
}
function gt(left2, right2) {
  return binaryOp(">", left2, right2);
}
function lte(left2, right2) {
  return binaryOp("<=", left2, right2);
}
function gte(left2, right2) {
  return binaryOp(">=", left2, right2);
}
function isDistinct(left2, right2) {
  return binaryOp("IS DISTINCT FROM", left2, right2);
}
function isNotDistinct(left2, right2) {
  return binaryOp("IS NOT DISTINCT FROM", left2, right2);
}
function isBetween(expr, extent4) {
  return new BetweenOpNode(asNode(expr), extent4?.map(asNode));
}
function isNotBetween(expr, extent4) {
  return new NotBetweenOpNode(asNode(expr), extent4?.map(asNode));
}
function isIn(expr, values2) {
  return new InOpNode(asNode(expr), values2.map(asNode));
}

// ../../mosaic/sql/dist/src/functions/order-by.js
function asc(expr, nullsFirst) {
  return new OrderByNode(asNode(expr), false, nullsFirst);
}
function desc(expr, nullsFirst) {
  return new OrderByNode(asNode(expr), true, nullsFirst);
}

// ../../mosaic/sql/dist/src/functions/spatial.js
function geojson(expr) {
  return fn("st_asgeojson", expr);
}
function x(expr) {
  return fn("st_x", expr);
}
function y(expr) {
  return fn("st_y", expr);
}
function centroid(expr) {
  return fn("st_centroid", expr);
}
function centroidX(expr) {
  return x(centroid(expr));
}
function centroidY(expr) {
  return y(centroid(expr));
}

// ../../mosaic/sql/dist/src/functions/sql-template-tag.js
function sql(strings, ...exprs) {
  return new FragmentNode(parseSQL(strings, exprs));
}
function parseSQL(strings, exprs) {
  const spans = [strings[0]];
  const n = exprs.length;
  for (let i = 0, k2 = 0; i < n; ) {
    const e = exprs[i];
    if (isNode(e)) {
      spans[++k2] = e;
    } else if (isParamLike(e)) {
      spans[++k2] = new ParamNode(e);
    } else {
      spans[k2] += isString(e) ? e : `${literal(e)}`;
    }
    const s2 = strings[++i];
    if (isNode(spans[k2])) {
      spans[++k2] = s2;
    } else {
      spans[k2] += s2;
    }
  }
  return spans.filter((s2) => s2).map((s2) => isString(s2) ? new VerbatimNode(s2) : s2);
}

// ../../mosaic/sql/dist/src/functions/string.js
function strFn(name2, expr, ...args) {
  return fn(name2, expr, ...argsList(args).map(asLiteral));
}
function regexp_matches(string2, pattern, options) {
  return strFn("regexp_matches", string2, pattern, options);
}
function contains(string2, search_string) {
  return strFn("contains", string2, search_string);
}
function prefix(string2, search_string) {
  return strFn("starts_with", string2, search_string);
}
function suffix(string2, search_string) {
  return strFn("ends_with", string2, search_string);
}
function lower(string2) {
  return strFn("lower", string2);
}

// ../../mosaic/sql/dist/src/functions/unnest.js
function unnest(value, recursive = false, maxDepth2 = 0) {
  return new UnnestNode(asNode(value), recursive, maxDepth2);
}

// ../../mosaic/sql/dist/src/functions/util.js
function coalesce(...expr) {
  return fn("coalesce", ...expr);
}

// ../../mosaic/sql/dist/src/functions/window.js
function row_number() {
  return winFn("row_number");
}
function rank() {
  return winFn("rank");
}
function dense_rank() {
  return winFn("dense_rank");
}
function percent_rank() {
  return winFn("percent_rank");
}
function cume_dist() {
  return winFn("cume_dist");
}
function ntile(num_buckets) {
  return winFn("ntile", num_buckets);
}
function lag(expr, offset2, defaultValue) {
  return winFn("lag", expr, offset2, defaultValue);
}
function lead(expr, offset2, defaultValue) {
  return winFn("lead", expr, offset2, defaultValue);
}
function first_value(expr) {
  return winFn("first_value", expr);
}
function last_value(expr) {
  return winFn("last_value", expr);
}
function nth_value(expr, nth) {
  return winFn("nth_value", expr, nth);
}

// ../../mosaic/sql/dist/src/functions/window-frame.js
function frameRows(extent4, exclude) {
  return new WindowFrameNode(ROWS, extent4, exclude);
}
function frameRange(extent4, exclude) {
  return new WindowFrameNode(RANGE, extent4, exclude);
}
function frameGroups(extent4, exclude) {
  return new WindowFrameNode(GROUPS, extent4, exclude);
}

// ../../mosaic/sql/dist/src/visit/recurse.js
var recurse = {
  [AGGREGATE]: ["args", "order", "filter"],
  [BETWEEN_OPERATOR]: ["expr", "extent"],
  [BINARY_OPERATOR]: ["left", "right"],
  [CASE]: ["expr", "_when", "_else"],
  [CAST]: ["expr"],
  [COLLATE]: ["expr"],
  [COLUMN_PARAM]: ["param", "table"],
  [COLUMN_REF]: ["table"],
  [DESCRIBE_QUERY]: ["query"],
  [EXPRESSION]: ["node"],
  [FRAGMENT]: ["spans"],
  [FROM_CLAUSE]: ["expr"],
  [FUNCTION]: ["args"],
  [IN_OPERATOR]: ["expr", "values"],
  [LOGICAL_OPERATOR]: ["clauses"],
  [NOT_BETWEEN_OPERATOR]: ["expr", "extent"],
  [ORDER_BY]: ["expr"],
  [PARAM]: ["value"],
  [SCALAR_SUBQUERY]: ["subquery"],
  [SELECT_CLAUSE]: ["expr"],
  [SELECT_QUERY]: ["_with", "_select", "_from", "_where", "_sample", "_groupby", "_having", "_window", "_qualify", "_orderby"],
  [SET_OPERATION]: ["queries", "_orderby"],
  [UNARY_OPERATOR]: ["expr"],
  [UNARY_POSTFIX_OPERATOR]: ["expr"],
  [UNNEST]: ["expr"],
  [WHEN]: ["when", "then"],
  [WINDOW]: ["func", "def"],
  [WINDOW_CLAUSE]: ["def"],
  [WINDOW_DEF]: ["partition", "order", "framedef"],
  [WINDOW_EXTENT_EXPR]: ["expr"],
  [WINDOW_FRAME]: ["extent"],
  [WINDOW_FUNCTION]: ["args"],
  [WITH_CLAUSE]: ["query"]
};

// ../../mosaic/sql/dist/src/visit/rewrite.js
function rewrite(node, map5) {
  if (map5.has(node)) {
    return map5.get(node);
  } else if (isNode(node)) {
    const props = recurse[node.type];
    const n = props?.length ?? 0;
    if (n > 0) {
      node = node.clone();
      for (let i = 0; i < n; ++i) {
        const prop = props[i];
        const child = node[prop];
        if (Array.isArray(child)) {
          const a2 = node[prop] = child.slice();
          const m = child.length;
          for (let j = 0; j < m; ++j) {
            a2[j] = rewrite(child[j], map5);
          }
        } else if (child) {
          node[prop] = rewrite(child, map5);
        }
      }
    }
  }
  return node;
}

// ../../mosaic/sql/dist/src/visit/walk.js
function walk(node, visit2) {
  if (!isNode(node))
    return;
  const result = visit2(node);
  if (result)
    return result;
  const props = recurse[node.type];
  const n = props?.length ?? 0;
  for (let i = 0; i < n; ++i) {
    const value = node[props[i]];
    if (Array.isArray(value)) {
      const m = value.length;
      for (let j = 0; j < m; ++j) {
        if (value[j] && Number(walk(value[j], visit2)) < 0) {
          return result;
        }
      }
    } else if (value && Number(walk(value, visit2)) < 0) {
      return -1;
    }
  }
}

// ../../mosaic/sql/dist/src/visit/visitors.js
var aggrRegExp = new RegExp(`^(${aggregateNames.join("|")})$`);
var funcRegExp = /(\\'|\\"|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\w+\()/g;
function hasVerbatimAggregate(s2) {
  return s2.split(funcRegExp).some((tok) => tok.endsWith("(") && aggrRegExp.test(tok.slice(0, -1)));
}
function isAggregateExpression(root2) {
  let agg = 0;
  walk(root2, (node) => {
    switch (node.type) {
      case WINDOW:
        return -1;
      // aggs can't include windows
      case AGGREGATE:
        agg |= 1;
        return -1;
      case FRAGMENT:
      case VERBATIM: {
        let s2 = `${node}`.toLowerCase();
        const sub2 = s2.indexOf("(select ");
        if (sub2 >= 0)
          s2 = s2.slice(0, sub2);
        if (s2.includes(") over "))
          return -1;
        if (hasVerbatimAggregate(s2)) {
          agg |= 2;
          return -1;
        }
        return 1;
      }
    }
  });
  return agg;
}
function collectAggregates(root2) {
  const aggs = /* @__PURE__ */ new Set();
  walk(root2, (node) => {
    if (node.type === AGGREGATE) {
      aggs.add(node);
    }
  });
  return Array.from(aggs);
}
function collectColumns(root2) {
  const cols = {};
  walk(root2, (node) => {
    if (node.type === COLUMN_REF || node.type === COLUMN_PARAM) {
      cols[`${node}`] = node;
    }
  });
  return Object.values(cols);
}
function collectParams(root2) {
  const params = /* @__PURE__ */ new Set();
  walk(root2, (node) => {
    if (node.type === PARAM) {
      params.add(node.param);
    }
  });
  return Array.from(params);
}

// ../../mosaic/sql/dist/src/load/create.js
function createTable2(name2, query, { replace = false, temp = false, view = false } = {}) {
  return "CREATE" + (replace ? " OR REPLACE " : " ") + (temp ? "TEMP " : "") + (view ? "VIEW" : "TABLE") + (replace ? " " : " IF NOT EXISTS ") + name2 + " AS " + query;
}
function createSchema(name2, { strict = false } = {}) {
  return "CREATE SCHEMA " + (strict ? "" : "IF NOT EXISTS ") + name2;
}

// ../../mosaic/sql/dist/src/load/extension.js
function loadExtension(name2) {
  return `INSTALL ${name2}; LOAD ${name2}`;
}

// ../../mosaic/sql/dist/src/load/sql-from.js
function sqlFrom(data, { columns = Object.keys(data?.[0] || {}) } = {}) {
  let keys = [];
  if (Array.isArray(columns)) {
    keys = columns;
    columns = keys.reduce((m, k2) => (m[k2] = k2, m), {});
  } else if (columns) {
    keys = Object.keys(columns);
  }
  if (!keys.length) {
    throw new Error("Can not create table from empty column set.");
  }
  const subq = [];
  for (const datum2 of data) {
    const sel = keys.map((k2) => `${asLiteral(datum2[k2])} AS "${columns[k2]}"`);
    subq.push(`(SELECT ${sel.join(", ")})`);
  }
  return subq.join(" UNION ALL ");
}

// ../../mosaic/sql/dist/src/load/load.js
function load(method, tableName, fileName, options = {}, defaults22 = {}) {
  const { select: select2 = ["*"], where, view, temp, replace, ...file } = options;
  const params = parameters({ ...defaults22, ...file });
  const read = `${method}('${fileName}'${params ? ", " + params : ""})`;
  const filter3 = where ? ` WHERE ${where}` : "";
  const query = `SELECT ${select2.join(", ")} FROM ${read}${filter3}`;
  return createTable2(tableName, query, { view, temp, replace });
}
function loadCSV(tableName, fileName, options) {
  return load("read_csv", tableName, fileName, options, { auto_detect: true, sample_size: -1 });
}
function loadJSON(tableName, fileName, options) {
  return load("read_json", tableName, fileName, options, { auto_detect: true, format: "auto" });
}
function loadParquet(tableName, fileName, options) {
  return load("read_parquet", tableName, fileName, options);
}
function loadSpatial(tableName, fileName, options = {}) {
  const { options: opt, ...rest } = options;
  if (opt) {
    const open = Array.isArray(opt) ? opt.join(", ") : typeof opt === "string" ? opt : Object.entries(opt).map(([key, value]) => `${key}=${value}`).join(", ");
    Object.assign(rest, { open_options: open.toUpperCase() });
  }
  return load("st_read", tableName, fileName, rest);
}
function loadObjects(tableName, data, options = {}) {
  const { select: select2 = ["*"], ...opt } = options;
  const values2 = sqlFrom(data);
  const query = select2.length === 1 && select2[0] === "*" ? values2 : `SELECT ${select2} FROM ${values2}`;
  return createTable2(tableName, query, opt);
}
function parameters(options) {
  return Object.entries(options).map(([key, value]) => `${key}=${toDuckDBValue(value)}`).join(", ");
}
function toDuckDBValue(value) {
  switch (typeof value) {
    case "boolean":
      return String(value);
    case "string":
      return `'${value}'`;
    case "undefined":
    case "object":
      if (value == null) {
        return "NULL";
      } else if (Array.isArray(value)) {
        return "[" + value.map((v2) => toDuckDBValue(v2)).join(", ") + "]";
      } else {
        return "{" + Object.entries(value).map(([k2, v2]) => `'${k2}': ${toDuckDBValue(v2)}`).join(", ") + "}";
      }
    default:
      return `${value}`;
  }
}

// ../../mosaic/sql/dist/src/transforms/bin-1d.js
function bin1d(x3, lo, hi, bins, reverse3 = false) {
  const diff = reverse3 ? sub(hi, float642(x3)) : sub(float642(x3), lo);
  const scale3 = hi === lo ? 0 : bins / (hi - lo);
  return scale3 ? mul(diff, float642(scale3)) : diff;
}

// ../../mosaic/sql/dist/src/transforms/bin-2d.js
function bin2d(q, xp, yp, aggs, xn, groupby) {
  return q.select({
    index: add(int322(floor(xp)), mul(int322(floor(yp)), xn)),
    ...aggs
  }).groupby("index", groupby);
}

// ../../mosaic/sql/dist/src/transforms/util/bin-step.js
function binSpec(min5, max4, options) {
  let { step, steps = 25 } = options;
  const { minstep = 0, nice: nice3 = true, base } = options;
  if (nice3 !== false) {
    const span = max4 - min5;
    const logb = base ? Math.log(base) : Math.LN10;
    step = step || binStep(span, steps, minstep, logb);
    let v2 = Math.log(step);
    const precision = v2 >= 0 ? 0 : ~~(-v2 / logb) + 1;
    const eps2 = Math.pow(10, -precision - 1);
    v2 = Math.floor(min5 / step + eps2) * step;
    min5 = min5 < v2 ? v2 - step : v2;
    max4 = Math.ceil(max4 / step) * step;
    steps = Math.round((max4 - min5) / step);
  }
  return { min: min5, max: max4, steps };
}
function binStep(span, steps, minstep = 0, logb = Math.LN10) {
  let v2;
  const level = Math.ceil(Math.log(steps) / logb);
  let step = Math.max(minstep, Math.pow(10, Math.round(Math.log(span) / logb) - level));
  while (Math.ceil(span / step) > steps) {
    step *= 10;
  }
  const div2 = [5, 2];
  for (let i = 0, n = div2.length; i < n; ++i) {
    v2 = step / div2[i];
    if (v2 >= minstep && span / v2 <= steps)
      step = v2;
  }
  return step;
}

// ../../mosaic/sql/dist/src/transforms/util/time-interval.js
var YEAR = "year";
var MONTH = "month";
var DAY = "day";
var HOUR = "hour";
var MINUTE = "minute";
var SECOND = "second";
var MILLISECOND = "millisecond";
var MICROSECOND = "microsecond";
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;
var units = [
  { unit: SECOND, step: 1, dt: durationSecond },
  { unit: SECOND, step: 5, dt: durationSecond * 5 },
  { unit: SECOND, step: 15, dt: durationSecond * 15 },
  { unit: SECOND, step: 30, dt: durationSecond * 30 },
  { unit: MINUTE, step: 1, dt: durationMinute },
  { unit: MINUTE, step: 5, dt: durationMinute * 5 },
  { unit: MINUTE, step: 15, dt: durationMinute * 15 },
  { unit: MINUTE, step: 30, dt: durationMinute * 30 },
  { unit: HOUR, step: 1, dt: durationHour },
  { unit: HOUR, step: 3, dt: durationHour * 3 },
  { unit: HOUR, step: 6, dt: durationHour * 6 },
  { unit: HOUR, step: 12, dt: durationHour * 12 },
  { unit: DAY, step: 1, dt: durationDay },
  { unit: DAY, step: 7, dt: durationWeek },
  { unit: MONTH, step: 1, dt: durationMonth },
  { unit: MONTH, step: 3, dt: durationMonth * 3 },
  { unit: YEAR, step: 1, dt: durationYear }
];
function timeInterval(min5, max4, steps) {
  const span = +max4 - +min5;
  const t = span / steps;
  const i = bisect2(units, t, (v2) => v2.dt);
  let unit3;
  let step;
  if (i === units.length) {
    unit3 = YEAR;
    step = binStep(span / durationYear, steps);
  } else if (i) {
    ({ unit: unit3, step } = units[t / units[i - 1].dt < units[i].dt / t ? i - 1 : i]);
  } else {
    step = binStep(span, steps);
    unit3 = step >= 1 ? MILLISECOND : MICROSECOND;
    step = step >= 1 ? step : step * 1e3;
  }
  return { unit: unit3, step };
}
function bisect2(a2, x3, value) {
  const compare1 = (a3, b) => Number(a3) - Number(b);
  const compare2 = (d, x4) => compare1(value(d), x4);
  let lo = 0;
  let hi = a2.length;
  if (lo < hi) {
    if (compare1(x3, x3) !== 0)
      return hi;
    do {
      const mid2 = lo + hi >>> 1;
      if (compare2(a2[mid2], x3) <= 0)
        lo = mid2 + 1;
      else
        hi = mid2;
    } while (lo < hi);
  }
  return lo;
}

// ../../mosaic/sql/dist/src/transforms/bin-date.js
function binDate(field3, extent4, options = {}) {
  const { offset: offset2 = 0 } = options;
  const { unit: unit3, step = 1 } = options.interval ? { unit: options.interval, step: options.step } : timeInterval(extent4[0], extent4[1], options.steps || 40);
  const bin3 = dateBin(field3, unit3, step);
  return offset2 ? add(bin3, interval2(unit3, offset2 * step)) : bin3;
}

// ../../mosaic/sql/dist/src/util/identity.js
function identity(x3) {
  return x3;
}

// ../../mosaic/sql/dist/src/transforms/scales.js
function scaleLinear() {
  return {
    apply: identity,
    invert: identity,
    sqlApply: asNode,
    sqlInvert: identity
  };
}
function scaleLog({ base = null } = {}) {
  if (base == null || base === Math.E) {
    return {
      apply: Math.log,
      invert: Math.exp,
      sqlApply: (c4) => ln(c4),
      sqlInvert: (c4) => exp(c4)
    };
  } else if (base === 10) {
    return {
      apply: Math.log10,
      invert: (x3) => Math.pow(10, x3),
      sqlApply: (c4) => log(c4),
      sqlInvert: (c4) => pow(10, c4)
    };
  } else {
    const b = +base;
    return {
      apply: (x3) => Math.log(x3) / Math.log(b),
      invert: (x3) => Math.pow(b, x3),
      sqlApply: (c4) => div(ln(c4), ln(b)),
      sqlInvert: (c4) => pow(b, c4)
    };
  }
}
function scaleSymlog({ constant: constant2 = 1 } = {}) {
  const _ = +constant2;
  return {
    apply: (x3) => Math.sign(x3) * Math.log1p(Math.abs(x3)),
    invert: (x3) => Math.sign(x3) * Math.exp(Math.abs(x3) - _),
    sqlApply: (c4) => (c4 = asNode(c4), mul(sign(c4), ln(add(_, abs(c4))))),
    sqlInvert: (c4) => mul(sign(c4), sub(exp(abs(c4)), _))
  };
}
function scaleSqrt() {
  return {
    apply: (x3) => Math.sign(x3) * Math.sqrt(Math.abs(x3)),
    invert: (x3) => Math.sign(x3) * x3 * x3,
    sqlApply: (c4) => (c4 = asNode(c4), mul(sign(c4), sqrt(abs(c4)))),
    sqlInvert: (c4) => mul(sign(c4), pow(c4, 2))
  };
}
function scalePow({ exponent = 1 } = {}) {
  const e = +exponent;
  return {
    apply: (x3) => Math.sign(x3) * Math.pow(Math.abs(x3), e),
    invert: (x3) => Math.sign(x3) * Math.pow(Math.abs(x3), 1 / e),
    sqlApply: (c4) => (c4 = asNode(c4), mul(sign(c4), pow(abs(c4), e))),
    sqlInvert: (c4) => mul(sign(c4), pow(abs(c4), div(1, e)))
  };
}
function scaleTime() {
  return {
    apply: (x3) => Number(x3),
    invert: (x3) => new Date(x3),
    sqlApply: (c4) => c4 instanceof Date ? literal(+c4) : isDateLiteral(c4) ? literal(Number(c4.value)) : epoch_ms(c4),
    sqlInvert: identity
  };
}
var scales = {
  identity: scaleLinear,
  linear: scaleLinear,
  log: scaleLog,
  symlog: scaleSymlog,
  sqrt: scaleSqrt,
  pow: scalePow,
  time: scaleTime,
  utc: scaleTime
};
function scaleTransform(options) {
  const scale3 = scales[options.type];
  if (!scale3)
    throw new Error(`Unrecognized scale type: ${options.type}`);
  return { ...options, ...scale3(options) };
}
function isDateLiteral(x3) {
  return x3 instanceof LiteralNode && x3.value instanceof Date;
}

// ../../mosaic/sql/dist/src/transforms/bin-histogram.js
function binHistogram(field3, extent4, options = {}, transform3 = scaleTransform({ type: "linear" })) {
  const [min5, max4] = extent4;
  const { offset: offset2 = 0 } = options;
  const { apply: apply2, sqlApply, sqlInvert } = transform3;
  const b = binSpec(apply2(min5), apply2(max4), options);
  const col = sqlApply(field3);
  const alpha = (b.max - b.min) / b.steps;
  let expr = b.min === 0 ? col : sub(col, b.min);
  if (alpha !== 1)
    expr = div(expr, float642(alpha));
  expr = floor(offset2 ? add(offset2, expr) : expr);
  if (alpha !== 1)
    expr = mul(alpha, expr);
  if (b.min !== 0)
    expr = add(b.min, expr);
  return sqlInvert(expr);
}

// ../../mosaic/sql/dist/src/transforms/bin-linear-1d.js
function binLinear1d(query, x3, weight = void 0, groupby = []) {
  const w = weight ? ((x4) => mul(x4, weight)) : ((x4) => x4);
  const p0 = floor(x3);
  const p1 = add(p0, 1);
  return Query.from(Query.unionAll(query.clone().select({ i: int322(p0), w: w(sub(p1, x3)) }), query.clone().select({ i: int322(p1), w: w(sub(x3, p0)) }))).select({ index: "i", density: sum("w") }, groupby).groupby("index", groupby).having(neq("density", 0));
}

// ../../mosaic/sql/dist/src/transforms/bin-linear-2d.js
function binLinear2d(q, xp, yp, weight, xn, groupby = []) {
  const w = weight ? (x3) => mul(x3, weight) : identity;
  const subq = (i, w2) => q.clone().select({ xp, yp, i, w: w2 });
  const index2 = (x3, y3) => add(x3, mul(y3, xn));
  const xu = int322(floor(xp));
  const yu = int322(floor(yp));
  const xv = add(xu, 1);
  const yv = add(yu, 1);
  const xpu = sub(xp, xu);
  const xvp = sub(xv, xp);
  const ypu = sub(yp, yu);
  const yvp = sub(yv, yp);
  return Query.from(Query.unionAll(
    // grid[xu + yu * xn] += (xv - xp) * (yv - yp) * wi
    subq(index2(xu, yu), w(mul(xvp, yvp))),
    // grid[xu + yv * xn] += (xv - xp) * (yp - yu) * wi
    subq(index2(xu, yv), w(mul(xvp, ypu))),
    // grid[xv + yu * xn] += (xp - xu) * (yv - yp) * wi
    subq(index2(xv, yu), w(mul(xpu, yvp))),
    // grid[xv + yv * xn] += (xp - xu) * (yp - yu) * wi
    subq(index2(xv, yv), w(mul(xpu, ypu)))
  )).select({ index: "i", density: sum("w") }, groupby).groupby("index", groupby).having(neq("density", 0));
}

// ../../mosaic/sql/dist/src/transforms/line-density.js
function lineDensity(q, x3, y3, z, xn, yn, groupby = [], normalize4 = true) {
  q.select({
    x: int322(floor(x3)),
    y: int322(floor(y3))
  });
  const groups2 = groupby.concat(z);
  const pairs3 = Query.from(q).select(groups2, {
    x0: "x",
    y0: "y",
    dx: sub(lead("x").over("sw"), "x"),
    dy: sub(lead("y").over("sw"), "y")
  }).window({
    sw: over().partitionby(groups2).orderby(asc("x"))
  }).qualify([
    or(lt("x0", xn), lt(add("x0", "dx"), xn)),
    or(lt("y0", yn), lt(add("y0", "dy"), yn)),
    or(gt("x0", 0), gt(add("x0", "dx"), 0)),
    or(gt("y0", 0), gt(add("y0", "dy"), 0))
  ]);
  const num = Query.select({ x: greatest(max(abs("dx")), max(abs("dy"))) }).from("pairs");
  const indices2 = Query.select({
    i: int322(sql`UNNEST(range((${num})))`)
  });
  const raster3 = Query.unionAll(Query.select(groups2, {
    x: add("x0", "i"),
    y: add("y0", int322(round(div(mul("i", "dy"), "dx"))))
  }).from("pairs", "indices").where([lte(abs("dy"), abs("dx")), lt("i", abs("dx"))]), Query.select(groups2, {
    x: add("x0", int322(round(div(mul(mul(sign("dy"), "i"), "dx"), "dy")))),
    y: add("y0", mul(sign("dy"), "i"))
  }).from("pairs", "indices").where([gt(abs("dy"), abs("dx")), lt("i", abs("dy"))]), Query.select(groups2, { x: "x0", y: "y0" }).from("pairs").where(isNull("dx")));
  const points2 = Query.from("raster").select(groups2, "x", "y", normalize4 ? { w: div(1, count().partitionby(["x"].concat(groups2))) } : null).where([lte(0, "x"), lt("x", xn), lte(0, "y"), lt("y", yn)]);
  return Query.with({ pairs: pairs3, indices: indices2, raster: raster3, points: points2 }).from("points").select(groupby, {
    index: add("x", mul("y", int322(xn))),
    density: normalize4 ? sum("w") : count()
  }).groupby("index", groupby);
}

// ../../mosaic/sql/dist/src/transforms/m4.js
function m4(input3, bin3, x3, y3, groups2 = []) {
  const pixel = int322(floor(bin3));
  const useCTE = isQuery(input3);
  const from2 = useCTE ? "input" : input3;
  const query = useCTE ? Query.with(cte(String(from2), input3, true)) : Query;
  const q = (sel) => Query.from(from2).select(sel).groupby(pixel, groups2);
  return query.union(q([{ [x3]: min(x3), [y3]: argmin(y3, x3) }, ...groups2]), q([{ [x3]: max(x3), [y3]: argmax(y3, x3) }, ...groups2]), q([{ [x3]: argmin(x3, y3), [y3]: min(y3) }, ...groups2]), q([{ [x3]: argmax(x3, y3), [y3]: max(y3) }, ...groups2])).orderby(groups2, x3);
}

// ../../mosaic/core/dist/src/util/hash.js
function fnv_hash(v2) {
  let a2 = 2166136261;
  for (let i = 0, n = v2.length; i < n; ++i) {
    const c4 = v2.charCodeAt(i);
    const d = c4 & 65280;
    if (d)
      a2 = fnv_multiply(a2 ^ d >> 8);
    a2 = fnv_multiply(a2 ^ c4 & 255);
  }
  return fnv_mix(a2) >>> 0;
}
function fnv_multiply(a2) {
  return a2 + (a2 << 1) + (a2 << 4) + (a2 << 7) + (a2 << 8) + (a2 << 24);
}
function fnv_mix(a2) {
  a2 += a2 << 13;
  a2 ^= a2 >>> 7;
  a2 += a2 << 3;
  a2 ^= a2 >>> 17;
  a2 += a2 << 5;
  return a2 & 4294967295;
}

// ../../mosaic/core/dist/src/preagg/sufficient-statistics.js
function sufficientStatistics(node, preagg, avg2) {
  switch (node.name) {
    case "count":
    case "count_star":
      return sumCountExpr(preagg, node);
    case "sum":
      return sumExpr(preagg, node);
    case "avg":
      return avgExpr(preagg, node);
    case "geomean":
      return geomeanExpr(preagg, node);
    case "arg_max":
      return argmaxExpr(preagg, node);
    case "arg_min":
      return argminExpr(preagg, node);
    // variance statistics drop the original aggregate operation
    // in favor of tracking sufficient statistics
    case "variance":
    case "var_samp":
      return varianceExpr(preagg, node, avg2);
    case "var_pop":
      return varianceExpr(preagg, node, avg2, false);
    case "stddev":
    case "stddev_samp":
      return sqrt(varianceExpr(preagg, node, avg2));
    case "stddev_pop":
      return sqrt(varianceExpr(preagg, node, avg2, false));
    case "covar_samp":
      return covarianceExpr(preagg, node, avg2);
    case "covar_pop":
      return covarianceExpr(preagg, node, avg2, false);
    case "corr":
      return corrExpr(preagg, node, avg2);
    // regression statistics
    case "regr_count":
      return regrCountExpr(preagg, node).expr;
    case "regr_avgx":
      return regrAvgXExpr(preagg, node);
    case "regr_avgy":
      return regrAvgYExpr(preagg, node);
    case "regr_syy":
      return regrVarExpr(preagg, 0, node, avg2);
    case "regr_sxx":
      return regrVarExpr(preagg, 1, node, avg2);
    case "regr_sxy":
      return covarianceExpr(preagg, node, avg2, null);
    case "regr_slope":
      return regrSlopeExpr(preagg, node, avg2);
    case "regr_intercept":
      return regrInterceptExpr(preagg, node, avg2);
    case "regr_r2":
      return pow(corrExpr(preagg, node, avg2), 2);
    // aggregates that commute directly
    case "max":
    case "min":
    case "bit_and":
    case "bit_or":
    case "bit_xor":
    case "bool_and":
    case "bool_or":
    case "product": {
      const name2 = colName(node);
      preagg[name2] = node;
      return sql`${node.name}("${name2}")`;
    }
    // unsupported aggregate, return null to indicate failure
    default:
      return null;
  }
}
function colName(node) {
  return "pre_" + fnv_hash(`${node}`).toString(16);
}
function addStat(preagg, expr, node) {
  const filter3 = node?.filter;
  if (filter3) {
    expr = expr.filter ? expr.where(and(filter3, expr.filter)) : expr.where(filter3);
  }
  const name2 = colName(expr);
  preagg[name2] = expr;
  return name2;
}
function countExpr(preagg, node) {
  const name2 = addStat(preagg, count(node.args[0]), node);
  return { expr: coalesce(sum(name2), 0), name: name2 };
}
function sumCountExpr(preagg, node) {
  return coalesce(sumExpr(preagg, node), 0);
}
function sumExpr(preagg, node) {
  return sum(addStat(preagg, node));
}
function avgExpr(preagg, node) {
  const as = addStat(preagg, node);
  const { expr, name: name2 } = countExpr(preagg, node);
  return div(sum(mul(as, name2)), expr);
}
function geomeanExpr(preagg, node) {
  const x3 = node.args[0];
  const expr = addStat(preagg, sum(ln(x3)), node);
  const { expr: n } = countExpr(preagg, node);
  return exp(div(sum(expr), n));
}
function argmaxExpr(preagg, node) {
  const expr = addStat(preagg, node);
  const maxy = addStat(preagg, max(node.args[1]), node);
  return argmax(expr, maxy);
}
function argminExpr(preagg, node) {
  const expr = addStat(preagg, node);
  const miny = addStat(preagg, min(node.args[1]), node);
  return argmin(expr, miny);
}
function varianceExpr(preagg, node, avg2, correction = true) {
  const x3 = node.args[0];
  const { expr: n } = countExpr(preagg, node);
  const delta = sub(x3, avg2(x3));
  const rssq = addStat(preagg, sum(pow(delta, 2)), node);
  const rsum = addStat(preagg, sum(delta), node);
  const denom = correction ? sub(n, 1) : n;
  return div(sub(sum(rssq), div(pow(sum(rsum), 2), n)), denom);
}
function covarianceExpr(preagg, node, avg2, correction = true) {
  const { expr: n } = regrCountExpr(preagg, node);
  const sxy = regrSumXYExpr(preagg, node, avg2);
  const sx = regrSumExpr(preagg, 1, node, avg2);
  const sy = regrSumExpr(preagg, 0, node, avg2);
  const num = sub(sxy, div(mul(sx, sy), n));
  return correction === null ? num : correction ? div(num, sub(n, 1)) : div(num, n);
}
function corrExpr(preagg, node, avg2) {
  const { expr: n } = regrCountExpr(preagg, node);
  const sxy = regrSumXYExpr(preagg, node, avg2);
  const sxx = regrSumSqExpr(preagg, 1, node, avg2);
  const syy = regrSumSqExpr(preagg, 0, node, avg2);
  const sx = regrSumExpr(preagg, 1, node, avg2);
  const sy = regrSumExpr(preagg, 0, node, avg2);
  const vx = sub(sxx, div(pow(sx, 2), n));
  const vy = sub(syy, div(pow(sy, 2), n));
  return div(sub(sxy, div(mul(sx, sy), n)), sqrt(mul(vx, vy)));
}
function regrCountExpr(preagg, node) {
  const [x3, y3] = node.args;
  const n = addStat(preagg, regrCount(x3, y3), node);
  return { expr: sum(n), name: n };
}
function regrSumExpr(preagg, i, node, avg2) {
  const args = node.args;
  const v2 = args[i];
  const o = args[1 - i];
  const rsum = sum(sub(v2, avg2(v2))).where(isNotNull(o));
  return sum(addStat(preagg, rsum, node));
}
function regrSumSqExpr(preagg, i, node, avg2) {
  const args = node.args;
  const v2 = args[i];
  const u4 = args[1 - i];
  const ssq = sum(pow(sub(v2, avg2(v2)), 2)).where(isNotNull(u4));
  return sum(addStat(preagg, ssq, node));
}
function regrSumXYExpr(preagg, node, avg2) {
  const [y3, x3] = node.args;
  const sxy = sum(mul(sub(x3, avg2(x3)), sub(y3, avg2(y3))));
  return sum(addStat(preagg, sxy, node));
}
function regrAvgXExpr(preagg, node) {
  const [y3, x3] = node.args;
  const { expr: n, name: name2 } = regrCountExpr(preagg, node);
  const a2 = addStat(preagg, regrAvgX(y3, x3), node);
  return div(sum(mul(a2, name2)), n);
}
function regrAvgYExpr(preagg, node) {
  const [y3, x3] = node.args;
  const { expr: n, name: name2 } = regrCountExpr(preagg, node);
  const a2 = addStat(preagg, regrAvgY(y3, x3), node);
  return div(sum(mul(a2, name2)), n);
}
function regrVarExpr(preagg, i, node, avg2) {
  const { expr: n } = regrCountExpr(preagg, node);
  const sum4 = regrSumExpr(preagg, i, node, avg2);
  const ssq = regrSumSqExpr(preagg, i, node, avg2);
  return sub(ssq, div(pow(sum4, 2), n));
}
function regrSlopeExpr(preagg, node, avg2) {
  const cov = covarianceExpr(preagg, node, avg2, null);
  const varx = regrVarExpr(preagg, 1, node, avg2);
  return div(cov, varx);
}
function regrInterceptExpr(preagg, node, avg2) {
  const ax = regrAvgXExpr(preagg, node);
  const ay = regrAvgYExpr(preagg, node);
  const m = regrSlopeExpr(preagg, node, avg2);
  return sub(ay, mul(m, ax));
}

// ../../mosaic/core/dist/src/preagg/preagg-columns.js
function preaggColumns(client) {
  if (!client.filterStable)
    return null;
  const q = client.query();
  if (!isSelectQuery(q))
    return null;
  const from2 = getBase(q, (q2) => {
    const ref = q2._from[0]?.expr;
    return isTableRef(ref) ? ref.name : ref;
  });
  if (typeof from2 !== "string")
    return null;
  const aggrs = /* @__PURE__ */ new Map();
  const preagg = {};
  const output = {};
  const group3 = [];
  const avg2 = (ref) => {
    const name2 = ref.column;
    const expr = getBase(q, (q2) => q2._select.find((c4) => c4.alias === name2)?.expr);
    return sql`(SELECT avg(${expr ?? ref}) FROM "${from2}")`;
  };
  for (const { alias, expr } of q._select) {
    if (isAggregateExpression(expr) > 1)
      return null;
    const nodes = collectAggregates(expr);
    if (nodes.length === 0) {
      group3.push(alias);
      preagg[alias] = expr;
    } else {
      for (const node of nodes) {
        if (node.isDistinct)
          return null;
        const agg = sufficientStatistics(node, preagg, avg2);
        if (!agg)
          return null;
        aggrs.set(node, agg);
      }
      output[alias] = rewrite(expr, aggrs);
    }
  }
  if (!aggrs.size)
    return null;
  return { group: group3, preagg, output };
}
function getBase(query, get3) {
  const subq = query.subqueries;
  if (isSelectQuery(query) && subq.length === 0) {
    return get3(query);
  }
  const base = getBase(subq[0], get3);
  for (let i = 1; i < subq.length; ++i) {
    const value = getBase(subq[i], get3);
    if (value === void 0)
      continue;
    if (value !== base)
      return NaN;
  }
  return base;
}

// ../../mosaic/core/dist/src/preagg/PreAggregator.js
var Skip = { skip: true, result: null };
var PreAggregator = class {
  entries;
  active;
  mc;
  _schema;
  _enabled;
  /**
   * Create a new manager of materialized views of pre-aggregated data.
   * @param coordinator A Mosaic coordinator.
   * @param options Pre-aggregation options.
   */
  constructor(coordinator2, { schema = "mosaic", enabled = true } = {}) {
    this.entries = /* @__PURE__ */ new Map();
    this.active = null;
    this.mc = coordinator2;
    this._schema = schema;
    this._enabled = enabled;
  }
  /**
   * Set the enabled state of this manager. If false, any local state is
   * cleared and subsequent request calls will return null until re-enabled.
   * This method has no effect on any pre-aggregated tables already in the
   * database.
   * @param state The enabled state to set.
   */
  set enabled(state) {
    if (this._enabled !== state) {
      if (!state)
        this.clear();
      this._enabled = state;
    }
  }
  /**
   * Get the enabled state of this manager.
   * @returns The current enabled state.
   */
  get enabled() {
    return this._enabled;
  }
  /**
   * Set the database schema used for pre-aggregated materialized view tables.
   * Upon changes, any local state is cleared. This method does _not_ drop any
   * existing materialized views, use `dropSchema` before changing the schema
   * to also remove existing materalized views in the database.
   * @param schema The schema name to set.
   */
  set schema(schema) {
    if (this._schema !== schema) {
      this.clear();
      this._schema = schema;
    }
  }
  /**
   * Get the database schema used for pre-aggregated materialized view tables.
   * @returns The current schema name.
   */
  get schema() {
    return this._schema;
  }
  /**
   * Issues a query through the coordinator to drop the current schema for
   * pre-aggregated materialized views. *All* materialized view tables in the
   * schema will be removed and local state is cleared. Call this method if
   * the underlying base tables have been updated, causing materialized view
   * to become stale and inaccurate. Use this method with care! Once dropped,
   * the schema will be repopulated by future pre-aggregation requests.
   * @returns A query result promise.
   */
  dropSchema() {
    this.clear();
    return this.mc.exec(`DROP SCHEMA IF EXISTS "${this.schema}" CASCADE`);
  }
  /**
   * Clear the cache of pre-aggregation entries for the current active
   * selection clause. This method does _not_ drop any existing materialized
   * views. Use `dropSchema` to remove existing materialized view tables from
   * the database.
   */
  clear() {
    this.entries.clear();
    this.active = null;
  }
  /**
   * Return pre-aggregation information for the active state of a
   * client-selection pair, or null if the client has unstable filters.
   * This method has multiple possible side effects, including materialized
   * view creation and updating internal caches.
   * @param client A Mosaic client.
   * @param selection A Mosaic selection to filter the client by.
   * @param activeClause A representative active selection
   *  clause for which to generate materialized views of pre-aggregates.
   * @returns Information and query generator
   * for pre-aggregated tables, or null if the client has unstable filters.
   */
  request(client, selection2, activeClause) {
    if (!this.enabled || activeClause == null)
      return null;
    const { entries, mc, schema } = this;
    const { source } = activeClause;
    if (!source)
      return null;
    if (this.active) {
      if (this.active.source !== source)
        this.clear();
      if (this.active?.source === null)
        return null;
    }
    let { active } = this;
    if (!active) {
      if (activeClause.predicate == null)
        return null;
      this.active = active = activeColumns(activeClause);
      if (active.source === null)
        return null;
    }
    if (entries.has(client)) {
      return entries.get(client);
    }
    const preaggCols = preaggColumns(client);
    let info;
    if (!preaggCols) {
      info = null;
    } else if (selection2.skip(client, activeClause)) {
      info = Skip;
    } else {
      const filter3 = selection2.remove(source).predicate(client);
      info = preaggregateInfo(client.query(filter3), active, preaggCols, schema);
      info.result = mc.exec([
        `CREATE SCHEMA IF NOT EXISTS ${schema}`,
        createTable2(info.table, info.create, { temp: false })
      ]);
      info.result.catch((e) => mc.logger().error(e));
    }
    entries.set(client, info);
    return info;
  }
};
function activeColumns(clause) {
  const { source, meta } = clause;
  const clausePred = clause.predicate;
  const clauseCols = collectColumns(clausePred).map((c4) => c4.column);
  let predicate;
  let columns;
  if (!meta || !clauseCols) {
    return { source: null, columns, predicate };
  }
  switch (meta.type) {
    case "point":
      predicate = (x3) => x3;
      columns = Object.fromEntries(clauseCols.map((col) => [`${col}`, asNode(col)]));
      break;
    case "interval": {
      const { scales: scales2, bin: bin3, pixelSize = 1 } = meta;
      if (!scales2)
        break;
      const bins = scales2.map((s2) => binInterval(s2, pixelSize, bin3));
      if (bins.some((b) => !b)) {
      } else if (bins.length === 1) {
        predicate = (p) => p ? isBetween("active0", p.extent?.map(bins[0])) : [];
        columns = { active0: bins[0](clausePred.expr) };
      } else {
        predicate = (p) => p ? and(p.clauses.map((c4, i) => isBetween(`active${i}`, c4.extent?.map(bins[i])))) : [];
        columns = Object.fromEntries(clausePred.clauses.map((p, i) => [`active${i}`, bins[i](p.expr)]));
      }
    }
  }
  return { source: columns ? source : null, columns, predicate };
}
var BIN = { ceil, round };
function binInterval(scale3, pixelSize, bin3) {
  const { type: type2, domain, range: range3, apply: apply2, sqlApply } = scaleTransform(scale3);
  if (!apply2)
    return;
  const binFn = BIN[`${bin3}`.toLowerCase()] || floor;
  const dom = domain.map((x3) => Number(x3));
  const lo = apply2(Math.min(...dom));
  const hi = apply2(Math.max(...dom));
  const s2 = (type2 === "identity" ? 1 : Math.abs(range3[1] - range3[0]) / (hi - lo)) / pixelSize;
  const scalar = s2 === 1 ? (x3) => x3 : (x3) => mul(float642(s2), x3);
  const diff = lo === 0 ? (x3) => x3 : (x3) => sub(x3, float642(lo));
  return (value) => int322(binFn(scalar(diff(sqlApply(value)))));
}
function preaggregateInfo(clientQuery, active, preaggCols, schema) {
  const { group: group3, output, preagg } = preaggCols;
  const { columns } = active;
  const query = clientQuery.setSelect({ ...preagg, ...columns }).groupby(Object.keys(columns));
  const [subq] = query.subqueries;
  if (subq) {
    const cols = Object.values(columns).flatMap((c4) => collectColumns(c4).map((c5) => c5.column));
    subqueryPushdown(subq, cols);
  }
  const having = query._having;
  const order = query._orderby;
  query._having = [];
  query._orderby = [];
  const create4 = query.toString();
  const id2 = (fnv_hash(create4) >>> 0).toString(16);
  const table3 = `${schema}.preagg_${id2}`;
  const select2 = Query.select(group3, output).from(table3).groupby(group3).having(having).orderby(order);
  return new PreAggregateInfo({ table: table3, create: create4, active, select: select2 });
}
function subqueryPushdown(query, cols) {
  const memo2 = /* @__PURE__ */ new Set();
  const pushdown = (q) => {
    if (memo2.has(q))
      return;
    memo2.add(q);
    if (isSelectQuery(q) && q._from.length) {
      q.select(cols);
      if (isAggregateQuery(q)) {
        const set3 = new Set(q._groupby.flatMap((x3) => x3 instanceof ColumnNameRefNode ? [x3.name] : []));
        q.groupby(cols.filter((c4) => !set3.has(c4)));
      }
    }
    q.subqueries.forEach(pushdown);
  };
  pushdown(query);
}
function isAggregateQuery(query) {
  return query._groupby.length > 0 || query._select.some((node) => isAggregateExpression(node));
}
var PreAggregateInfo = class {
  /** The name of the materialized view. */
  table;
  /** The SQL query used to generate the materialized view. */
  create;
  /** A result promise returned for the materialized view creation query. */
  result;
  /** Definitions and predicate function for the active columns,
   * which are dynamically filtered by the active clause. */
  active;
  /** Select query (sans where clause) for materialized views. */
  select;
  /** Boolean flag indicating a client that should be skipped.
   * This value is always false for a created materialized view. */
  skip;
  /**
   * Create a new pre-aggregation information instance.
   * @param options Options object.
   */
  constructor({ table: table3, create: create4, active, select: select2 }) {
    this.table = table3;
    this.create = create4;
    this.result = null;
    this.active = active;
    this.select = select2;
    this.skip = false;
  }
  /**
   * Generate a materialized view query for the given predicate.
   * @param predicate The current active clause predicate.
   * @returns A materialized view query.
   */
  query(predicate) {
    return this.select.clone().where(this.active.predicate(predicate));
  }
};

// ../../mosaic/core/dist/src/util/void-logger.js
function voidLogger() {
  return {
    debug() {
    },
    info() {
    },
    log() {
    },
    warn() {
    },
    error() {
    },
    group() {
    },
    groupCollapsed() {
    },
    groupEnd() {
    }
  };
}

// ../../mosaic/core/dist/src/util/query-result.js
var QueryState = Object.freeze({
  pending: Symbol("pending"),
  ready: Symbol("ready"),
  error: Symbol("error"),
  done: Symbol("done")
});
var QueryResult = class extends Promise {
  _resolve;
  _reject;
  _state;
  _value;
  /**
   * Create a new query result Promise.
   */
  constructor() {
    let resolve;
    let reject;
    super((r, e) => {
      resolve = r;
      reject = e;
    });
    this._resolve = resolve;
    this._reject = reject;
    this._state = QueryState.pending;
    this._value = void 0;
  }
  /**
   * Resolve the result Promise with a prepared value or the provided value.
   * This method will only succeed if either a value is provided or the promise is ready.
   * @param value The result value.
   * @returns This QueryResult instance.
   */
  fulfill(value) {
    if (this._value !== void 0) {
      if (value !== void 0) {
        throw Error("Promise is ready and fulfill has a provided value");
      }
      this._resolve(this._value);
    } else if (value === void 0) {
      throw Error("Promise is neither ready nor has provided value");
    } else {
      this._resolve(value);
    }
    this._state = QueryState.done;
    return this;
  }
  /**
   * Prepare to resolve with the provided value.
   * @param value The result value.
   * @returns This QueryResult instance.
   */
  ready(value) {
    this._state = QueryState.ready;
    this._value = value;
    return this;
  }
  /**
   * Rejects the result Promise with the provided error.
   * @param error The error value.
   * @returns This QueryResult instance.
   */
  reject(error2) {
    this._state = QueryState.error;
    this._reject(error2);
    return this;
  }
  /**
   * Returns the state of this query result.
   * @returns The current state symbol.
   */
  get state() {
    return this._state;
  }
};
QueryResult.prototype.constructor = Promise;

// ../../mosaic/core/dist/src/QueryConsolidator.js
function wait(callback) {
  if (typeof requestAnimationFrame !== "undefined") {
    return requestAnimationFrame(callback);
  } else if (typeof setImmediate !== "undefined") {
    return setImmediate(callback);
  } else {
    return setTimeout(callback);
  }
}
function consolidator(enqueue, cache) {
  let pending = [];
  let id2 = 0;
  function run() {
    const groups2 = entryGroups(pending, cache);
    pending = [];
    id2 = 0;
    for (const group3 of groups2) {
      consolidate(group3, enqueue);
      processResults(group3, cache);
    }
  }
  return {
    add(entry, priority) {
      if (entry.request.type === "arrow") {
        id2 ||= wait(() => run());
        pending.push({ entry, priority, index: pending.length });
      } else {
        enqueue(entry, priority);
      }
    }
  };
}
function entryGroups(entries, cache) {
  const groups2 = [];
  const groupMap = /* @__PURE__ */ new Map();
  for (const query of entries) {
    const { entry: { request } } = query;
    const key = consolidationKey(request.query, cache);
    if (!groupMap.has(key)) {
      const list3 = [];
      groups2.push(list3);
      groupMap.set(key, list3);
    }
    groupMap.get(key).push(query);
  }
  return groups2;
}
function consolidationKey(query, cache) {
  const sql2 = `${query}`;
  if (isSelectQuery(query) && !cache.get(sql2)) {
    if (query._where.length || query._qualify.length || query._having.length || query._orderby.length || query._distinct) {
      return sql2;
    }
    const q = query.clone().setSelect("*");
    const groupby = query._groupby;
    if (groupby.length) {
      const map5 = {};
      query._select.forEach(({ alias, expr }) => map5[alias] = expr);
      q.setGroupby(groupby.map((e) => isColumnRef(e) && map5[e.column] || e));
    } else if (query._select.some((e) => isAggregateExpression(e.expr))) {
      q.setGroupby("ALL");
    }
    return `${q}`;
  } else {
    return sql2;
  }
}
function consolidate(group3, enqueue) {
  if (shouldConsolidate(group3)) {
    enqueue({
      request: {
        type: "arrow",
        cache: false,
        query: group3.query = consolidatedQuery(group3)
      },
      result: group3.result = new QueryResult()
    });
  } else {
    for (const { entry, priority } of group3) {
      enqueue(entry, priority);
    }
  }
}
function shouldConsolidate(group3) {
  if (group3.length > 1) {
    const sql2 = `${group3[0].entry.request.query}`;
    for (let i = 1; i < group3.length; ++i) {
      if (sql2 !== `${group3[i].entry.request.query}`) {
        return true;
      }
    }
  }
  return false;
}
function consolidatedQuery(group3) {
  const maps = group3.maps = [];
  const fields = /* @__PURE__ */ new Map();
  for (const item of group3) {
    const query2 = item.entry.request.query;
    const fieldMap = [];
    maps.push(fieldMap);
    for (const { alias, expr } of query2._select) {
      const e = `${expr}`;
      if (!fields.has(e)) {
        fields.set(e, [`col${fields.size}`, expr]);
      }
      const [name2] = fields.get(e);
      fieldMap.push([name2, alias]);
    }
  }
  const query = group3[0].entry.request.query.clone();
  const groupby = query._groupby;
  if (groupby.length) {
    const map5 = {};
    group3.maps[0].forEach(([name2, as]) => map5[as] = name2);
    query.setGroupby(groupby.map((e) => isColumnRef(e) && map5[e.column] || e));
  }
  return query.setSelect(Array.from(fields.values()));
}
async function processResults(group3, cache) {
  const { maps, query, result } = group3;
  if (!maps)
    return;
  let data;
  try {
    data = await result;
  } catch (err) {
    for (const { entry } of group3) {
      entry.result.reject(err);
    }
    return;
  }
  const describe = isDescribeQuery(query);
  group3.forEach(({ entry }, index2) => {
    const { request, result: result2 } = entry;
    const map5 = maps[index2];
    const extract = describe && map5 ? filterResult(data, map5) : map5 ? projectResult(data, map5) : data;
    if (request.cache) {
      cache.set(String(request.query), extract);
    }
    result2.fulfill(extract);
  });
}
function projectResult(data, map5) {
  return data.select(map5.map((x3) => x3[0]), map5.map((x3) => x3[1]));
}
function filterResult(data, map5) {
  const lookup = new Map(map5);
  const result = [];
  for (const d of data) {
    if (lookup.has(d.column_name)) {
      result.push({ ...d, column_name: lookup.get(d.column_name) });
    }
  }
  return result;
}

// ../../mosaic/core/dist/src/util/cache.js
var requestIdle = typeof requestIdleCallback !== "undefined" ? requestIdleCallback : setTimeout;
function voidCache() {
  return {
    get: () => void 0,
    set: (key, value) => value,
    clear: () => {
    }
  };
}
function lruCache({
  max: max4 = 1e3,
  // max entries
  ttl = 3 * 60 * 60 * 1e3
  // time-to-live, default 3 hours
} = {}) {
  let cache = /* @__PURE__ */ new Map();
  function evict() {
    const expire = performance.now() - ttl;
    let lruKey = null;
    let lruLast = Infinity;
    for (const [key, value] of cache) {
      const { last: last2 } = value;
      if (last2 < lruLast) {
        lruKey = key;
        lruLast = last2;
      }
      if (expire > last2) {
        cache.delete(key);
      }
    }
    if (lruKey) {
      cache.delete(lruKey);
    }
  }
  return {
    get(key) {
      const entry = cache.get(key);
      if (entry) {
        entry.last = performance.now();
        return entry.value;
      }
    },
    set(key, value) {
      cache.set(key, { last: performance.now(), value });
      if (cache.size > max4)
        requestIdle(evict);
      return value;
    },
    clear() {
      cache = /* @__PURE__ */ new Map();
    }
  };
}

// ../../mosaic/core/dist/src/util/priority-queue.js
var PriorityQueue = class {
  queue;
  /**
   * Create a new priority queue instance.
   * @param ranks An integer number of rank-order priority levels.
   */
  constructor(ranks) {
    this.queue = Array.from({ length: ranks }, () => ({ head: null, tail: null }));
  }
  /**
   * Indicate if the queue is empty.
   * @returns true if empty, false otherwise.
   */
  isEmpty() {
    return this.queue.every((list3) => !list3.head);
  }
  /**
   * Insert an item into the queue with a given priority rank.
   * @param item The item to add.
   * @param rank The integer priority rank.
   * Priority ranks are integers starting at zero.
   * Lower ranks indicate higher priority.
   */
  insert(item, rank3) {
    const list3 = this.queue[rank3];
    if (!list3) {
      throw new Error(`Invalid queue priority rank: ${rank3}`);
    }
    const node = { item, next: null };
    if (list3.head === null) {
      list3.head = list3.tail = node;
    } else {
      list3.tail = list3.tail.next = node;
    }
  }
  /**
   * Remove a set of items from the queue, regardless of priority rank.
   * If a provided item is not in the queue it will be ignored.
   * @param test A predicate function to test
   * if an item should be removed (true to drop, false to keep).
   */
  remove(test) {
    for (const list3 of this.queue) {
      let { head, tail } = list3;
      for (let prev = null, curr = head; curr; prev = curr, curr = curr.next) {
        if (test(curr.item)) {
          if (curr === head) {
            head = curr.next;
          } else {
            prev.next = curr.next;
          }
          if (curr === tail)
            tail = prev || head;
        }
      }
      list3.head = head;
      list3.tail = tail;
    }
  }
  /**
   * Remove and return the next highest priority item.
   * @returns The next item in the queue,
   * or undefined if this queue is empty.
   */
  next() {
    for (const list3 of this.queue) {
      const { head } = list3;
      if (head !== null) {
        list3.head = head.next;
        if (list3.tail === head) {
          list3.tail = null;
        }
        return head.item;
      }
    }
  }
};

// ../../mosaic/core/dist/src/QueryManager.js
var Priority = Object.freeze({ High: 0, Normal: 1, Low: 2 });
var QueryManager = class {
  queue;
  db;
  clientCache;
  _logger;
  _logQueries;
  _consolidate;
  /** Requests pending with the query manager. */
  pendingResults;
  maxConcurrentRequests;
  pendingExec;
  constructor(maxConcurrentRequests = 32) {
    this.queue = new PriorityQueue(3);
    this.db = null;
    this.clientCache = null;
    this._logger = voidLogger();
    this._logQueries = false;
    this._consolidate = null;
    this.pendingResults = [];
    this.maxConcurrentRequests = maxConcurrentRequests;
    this.pendingExec = false;
  }
  next() {
    if (this.queue.isEmpty() || this.pendingResults.length > this.maxConcurrentRequests || this.pendingExec) {
      return;
    }
    const entry = this.queue.next();
    if (!entry)
      return;
    const { request, result } = entry;
    this.pendingResults.push(result);
    if (request.type === "exec")
      this.pendingExec = true;
    this.submit(request, result).finally(() => {
      while (this.pendingResults.length && this.pendingResults[0].state !== QueryState.pending) {
        const result2 = this.pendingResults.shift();
        if (result2.state === QueryState.ready) {
          result2.fulfill();
        } else if (result2.state === QueryState.done) {
          this._logger.warn("Found resolved query in pending results.");
        }
      }
      if (request.type === "exec")
        this.pendingExec = false;
      this.next();
    });
  }
  /**
   * Add an entry to the query queue with a priority.
   * @param entry The entry to add.
   * @param priority The query priority, defaults to `Priority.Normal`.
   */
  enqueue(entry, priority = Priority.Normal) {
    this.queue.insert(entry, priority);
    this.next();
  }
  /**
   * Submit the query to the connector.
   * @param request The request.
   * @param result The query result.
   */
  async submit(request, result) {
    try {
      const { query, type: type2, cache = false, options } = request;
      const sql2 = query ? `${query}` : null;
      if (cache) {
        const cached = this.clientCache.get(sql2);
        if (cached) {
          const data2 = await cached;
          this._logger.debug("Cache");
          result.ready(data2);
          return;
        }
      }
      const t03 = performance.now();
      if (this._logQueries) {
        this._logger.debug("Query", { type: type2, sql: sql2, ...options });
      }
      const promise = this.db.query({ type: type2, sql: sql2, ...options });
      if (cache)
        this.clientCache.set(sql2, promise);
      const data = await promise;
      if (cache)
        this.clientCache.set(sql2, data);
      this._logger.debug(`Request: ${(performance.now() - t03).toFixed(1)}`);
      result.ready(type2 === "exec" ? null : data);
    } catch (err) {
      result.reject(err);
    }
  }
  cache(value) {
    return value !== void 0 ? this.clientCache = value === true ? lruCache() : value || voidCache() : this.clientCache;
  }
  logger(value) {
    return value ? this._logger = value : this._logger;
  }
  logQueries(value) {
    return value !== void 0 ? this._logQueries = !!value : this._logQueries;
  }
  connector(connector) {
    return connector ? this.db = connector : this.db;
  }
  /**
   * Indicate if query consolidation should be performed.
   * @param flag Whether to enable consolidation
   */
  consolidate(flag) {
    if (flag && !this._consolidate) {
      this._consolidate = consolidator(this.enqueue.bind(this), this.clientCache);
    } else if (!flag && this._consolidate) {
      this._consolidate = null;
    }
  }
  /**
   * Request a query result.
   * @param request The request.
   * @param priority The query priority, defaults to `Priority.Normal`.
   * @returns A query result promise.
   */
  request(request, priority = Priority.Normal) {
    const result = new QueryResult();
    const entry = { request, result };
    if (this._consolidate) {
      this._consolidate.add(entry, priority);
    } else {
      this.enqueue(entry, priority);
    }
    return result;
  }
  cancel(requests) {
    const set3 = new Set(requests);
    if (set3.size) {
      this.queue.remove(({ result }) => {
        if (set3.has(result)) {
          result.reject("Canceled");
          return true;
        }
        return false;
      });
      for (const result of this.pendingResults) {
        if (set3.has(result)) {
          result.reject("Canceled");
        }
      }
    }
  }
  clear() {
    this.queue.remove(({ result }) => {
      result.reject("Cleared");
      return true;
    });
    for (const result of this.pendingResults) {
      result.reject("Cleared");
    }
    this.pendingResults = [];
  }
};

// ../../mosaic/core/dist/src/Coordinator.js
var _instance;
function coordinator(instance) {
  if (instance) {
    _instance = instance;
  } else if (_instance == null) {
    _instance = new Coordinator();
  }
  return _instance;
}
var Coordinator = class {
  manager;
  preaggregator;
  clients = /* @__PURE__ */ new Set();
  filterGroups = /* @__PURE__ */ new Map();
  _logger = voidLogger();
  /**
   * @param db Database connector. Defaults to a web socket connection.
   * @param options Coordinator options.
   * @param options.logger The logger to use, defaults to `console`.
   * @param options.manager The query manager to use.
   * @param options.cache Boolean flag to enable/disable query caching.
   * @param options.consolidate Boolean flag to enable/disable query consolidation.
   * @param options.preagg Options for the Pre-aggregator.
   */
  constructor(db = new SocketConnector(), options = {}) {
    const { logger = console, manager = new QueryManager(), cache = true, consolidate: consolidate2 = true, preagg = {} } = options;
    this.manager = manager;
    this.manager.cache(cache);
    this.manager.consolidate(consolidate2);
    this.databaseConnector(db);
    this.logger(logger);
    this.clear();
    this.preaggregator = new PreAggregator(this, preagg);
  }
  /**
   * Clear the coordinator state.
   * @param options Options object.
   * @param options.clients If true, disconnect all clients.
   * @param options.cache If true, clear the query cache.
   */
  clear(options = {}) {
    const { clients = true, cache = true } = options;
    this.manager.clear();
    if (clients) {
      this.filterGroups?.forEach((group3) => group3.disconnect());
      this.filterGroups = /* @__PURE__ */ new Map();
      this.clients?.forEach((client) => this.disconnect(client));
      this.clients = /* @__PURE__ */ new Set();
    }
    if (cache)
      this.manager.cache().clear();
  }
  databaseConnector(db) {
    return db ? this.manager.connector(db) : this.manager.connector();
  }
  /**
   * Get or set the logger.
   * @param logger The logger to use.
   * @returns The current logger
   */
  logger(logger) {
    if (arguments.length) {
      this._logger = logger || voidLogger();
      this.manager.logger(this._logger);
    }
    return this._logger;
  }
  // -- Query Management ----
  /**
   * Cancel previously submitted query requests. These queries will be
   * canceled if they are queued but have not yet been submitted.
   * @param requests An array of query result objects, such as those returned by the `query` method.
   */
  cancel(requests) {
    this.manager.cancel(requests);
  }
  /**
   * Issue a query for which no result (return value) is needed.
   * @param query The query or an array of queries. Each query should be either a Query builder object or a SQL string.
   * @param options An options object.
   * @param options.priority The query priority, defaults to `Priority.Normal`.
   * @returns A query result promise.
   */
  exec(query, options = {}) {
    const { priority = Priority.Normal } = options;
    query = Array.isArray(query) ? query.filter((x3) => x3).join(";\n") : query;
    return this.manager.request({ type: "exec", query }, priority);
  }
  query(query, options = {}) {
    const { type: type2 = "arrow", cache = true, priority = Priority.Normal, ...otherOptions } = options;
    return this.manager.request({ type: type2, query, cache, options: otherOptions }, priority);
  }
  prefetch(query, options = {}) {
    return this.query(query, { ...options, cache: true, priority: Priority.Low });
  }
  // -- Client Management ----
  /**
   * Update client data by submitting the given query and returning the()
   * data (or error) to the client.
   * @param client A Mosaic client.
   * @param query The data query.
   * @param priority The query priority.
   * @returns A Promise that resolves upon completion of the update.
   */
  updateClient(client, query, priority = Priority.Normal) {
    client.queryPending();
    return client._pending = this.query(query, { priority }).then((data) => client.queryResult(data).update(), (err) => {
      this._logger?.error(err);
      client.queryError(err);
    }).catch((err) => this._logger?.error(err));
  }
  /**
   * Issue a query request for a client. If the query is null or undefined,
   * the client is simply updated. Otherwise `updateClient` is called. As a
   * side effect, this method clears the current preaggregator state.
   * @param client The client to update.
   * @param query The query to issue.
   */
  requestQuery(client, query) {
    this.preaggregator.clear();
    return query ? this.updateClient(client, query) : Promise.resolve(client.update());
  }
  /**
   * Connect a client to the coordinator.
   * Throws an error if the client is already connected.
   * @param client The Mosaic client to connect.
   */
  connect(client) {
    const { clients } = this;
    if (clients?.has(client)) {
      throw new Error("Client already connected.");
    }
    clients?.add(client);
    client.coordinator = this;
    client.initialize();
    connectSelection(this, client.filterBy, client);
  }
  /**
   * Disconnect a client from the coordinator.
   * This method has no effect if the client is already disconnected.
   * @param client The Mosaic client to disconnect.
   */
  disconnect(client) {
    const { clients, filterGroups } = this;
    if (!clients?.has(client))
      return;
    clients.delete(client);
    client.coordinator = null;
    const group3 = filterGroups?.get(client.filterBy);
    if (group3) {
      group3.clients.delete(client);
    }
  }
};
function connectSelection(mc, selection2, client) {
  if (!selection2)
    return;
  let entry = mc.filterGroups?.get(selection2);
  if (!entry) {
    const activate = (clause) => activateSelection(mc, selection2, clause);
    const value = () => updateSelection(mc, selection2);
    selection2.addEventListener("activate", activate);
    selection2.addEventListener("value", value);
    entry = {
      selection: selection2,
      clients: /* @__PURE__ */ new Set(),
      disconnect() {
        selection2.removeEventListener("activate", activate);
        selection2.removeEventListener("value", value);
      }
    };
    mc.filterGroups?.set(selection2, entry);
  }
  entry.clients.add(client);
}
function activateSelection(mc, selection2, clause) {
  const { preaggregator, filterGroups } = mc;
  const { clients } = filterGroups.get(selection2);
  for (const client of clients) {
    if (client.enabled) {
      preaggregator.request(client, selection2, clause);
    }
  }
}
function updateSelection(mc, selection2) {
  const { preaggregator, filterGroups } = mc;
  const { clients } = filterGroups.get(selection2);
  const { active } = selection2;
  return Promise.allSettled(Array.from(clients, (client) => {
    if (!client.enabled)
      return client.requestQuery();
    const info = preaggregator.request(client, selection2, active);
    const filter3 = info ? null : selection2.predicate(client);
    if (info?.skip || !info && !filter3)
      return;
    const query = info?.query(active.predicate) ?? client.query(filter3);
    return mc.updateClient(client, query);
  }));
}

// ../../mosaic/core/dist/src/util/AsyncDispatch.js
var AsyncDispatch = class {
  _callbacks;
  /**
   * Create a new asynchronous dispatcher instance.
   */
  constructor() {
    this._callbacks = /* @__PURE__ */ new Map();
  }
  /**
   * Add an event listener callback for the provided event type.
   * @param type The event type.
   * @param callback The event handler
   *  callback function to add. If the callback has already been
   *  added for the event type, this method has no effect.
   */
  addEventListener(type2, callback) {
    if (!this._callbacks.has(type2)) {
      this._callbacks.set(type2, {
        callbacks: /* @__PURE__ */ new Set(),
        pending: null,
        queue: new DispatchQueue()
      });
    }
    const entry = this._callbacks.get(type2);
    entry.callbacks.add(callback);
  }
  /**
   * Remove an event listener callback for the provided event type.
   * @param type The event type.
   * @param callback The event handler
   *  callback function to remove.
   */
  removeEventListener(type2, callback) {
    const entry = this._callbacks.get(type2);
    if (entry) {
      entry.callbacks.delete(callback);
    }
  }
  /**
   * Lifecycle method that returns the event value to emit.
   * This default implementation simply returns the input value as-is.
   * Subclasses may override this method to implement custom transformations
   * prior to emitting an event value to all listeners.
   * @param type The event type.
   * @param value The event value.
   * @returns The (possibly transformed) event value to emit.
   */
  willEmit(type2, value) {
    return value;
  }
  /**
   * Lifecycle method that returns a filter function for updating the
   * queue of unemitted event values prior to enqueueing a new value.
   * This default implementation simply returns null, indicating that
   * unknown other unemitted event values should be dropped (that is, all
   * queued events are filtered).
   * @param type The event type.
   * @param value The new event value that will be enqueued.
   * @returns A dispatch queue filter
   *  function, or null if all unemitted event values should be filtered.
   */
  emitQueueFilter(_type, _value) {
    return null;
  }
  /**
   * Cancel all unemitted event values for the given event type.
   * @param type The event type.
   */
  cancel(type2) {
    const entry = this._callbacks.get(type2);
    entry?.queue.clear();
  }
  /**
   * Returns a promise that resolves when unknown pending updates complete for
   * the event of the given type currently being processed. The Promise will
   * resolve immediately if the queue for the given event type is empty.
   * @param type The event type to wait for.
   * @returns A pending event promise.
   */
  async pending(type2) {
    await this._callbacks.get(type2)?.pending;
  }
  /**
   * Emit an event value to listeners for the given event type.
   * If a previous emit has not yet resolved, the event value
   * will be queued to be emitted later.
   * The actual event value given to listeners will be the result
   * of passing the input value through the emitValue() method.
   * @param type The event type.
   * @param value The event value.
   */
  emit(type2, value) {
    const entry = this._callbacks.get(type2) || {};
    if (entry.pending) {
      entry.queue.enqueue(value, this.emitQueueFilter(type2, value));
    } else {
      const event = this.willEmit(type2, value);
      const { callbacks, queue } = entry;
      if (callbacks?.size) {
        const callbackValues = Array.from(callbacks, (cb) => cb(event));
        entry.pending = Promise.allSettled(callbackValues).then(() => {
          entry.pending = null;
          if (!queue.isEmpty()) {
            this.emit(type2, queue.dequeue());
          }
        });
      }
    }
  }
};
var DispatchQueue = class {
  next = null;
  /**
   * Create a new dispatch queue instance.
   */
  constructor() {
    this.clear();
  }
  /**
   * Clear the queue state of all event values.
   */
  clear() {
    this.next = null;
  }
  /**
   * Indicate if the queue is empty.
   * @returns True if queue is empty, false otherwise.
   */
  isEmpty() {
    return !this.next;
  }
  /**
   * Add a new value to the queue, and optionally filter the
   * current queue content in response.
   * @param value The value to add.
   * @param filter An optional filter
   *  function to apply to existing queue content. If unspecified
   *  or falsy, all previously queued values are removed. Otherwise,
   *  the provided function is applied to all queue entries. The
   *  entry is retained if the filter function returns a truthy value,
   *  otherwise the entry is removed.
   */
  enqueue(value, filter3) {
    const tail = { value };
    if (filter3 && this.next) {
      let curr = this;
      while (curr.next) {
        if (filter3(curr.next.value)) {
          curr = curr.next;
        } else {
          curr.next = curr.next.next;
        }
      }
      curr.next = tail;
    } else {
      this.next = tail;
    }
  }
  /**
   * Remove and return the next queued event value.
   * @returns The next event value in the queue.
   */
  dequeue() {
    const { next } = this;
    this.next = next?.next || null;
    return next?.value;
  }
};

// ../../mosaic/core/dist/src/util/distinct.js
function distinct(a2, b) {
  return a2 === b ? false : a2 instanceof Date && b instanceof Date ? +a2 !== +b : Array.isArray(a2) && Array.isArray(b) ? distinctArray(a2, b) : true;
}
function distinctArray(a2, b) {
  if (a2.length !== b.length)
    return true;
  for (let i = 0; i < a2.length; ++i) {
    if (a2[i] !== b[i])
      return true;
  }
  return false;
}

// ../../mosaic/core/dist/src/Param.js
function isParam(x3) {
  return x3 instanceof Param;
}
var Param = class _Param extends AsyncDispatch {
  _value;
  /**
   * Create a new Param instance.
   * @param value The initial value of the Param.
   */
  constructor(value) {
    super();
    this._value = value;
  }
  /**
   * Create a new Param instance with the given initial value.
   * @param value The initial value of the Param.
   * @returns The new Param instance.
   */
  static value(value) {
    return new _Param(value);
  }
  /**
   * Create a new Param instance over an array of initial values,
   * which may contain nested Params.
   * @param values The initial values of the Param.
   * @returns The new Param instance.
   */
  static array(values2) {
    if (values2.some((v2) => isParam(v2))) {
      const p = new _Param();
      const update = () => {
        p.update(values2.map((v2) => isParam(v2) ? v2.value : v2));
      };
      update();
      values2.forEach((v2) => isParam(v2) ? v2.addEventListener("value", update) : 0);
      return p;
    }
    return new _Param(values2);
  }
  /**
   * The current value of the Param.
   */
  get value() {
    return this._value;
  }
  /**
   * Update the Param value
   * @param value The new value of the Param.
   * @param options The update options.
   * @param options.force A boolean flag indicating if the Param
   *  should emit a 'value' event even if the internal value is unchanged.
   * @returns This Param instance.
   */
  update(value, { force } = {}) {
    const shouldEmit = distinct(this._value, value) || force;
    if (shouldEmit) {
      this.emit("value", value);
    } else {
      this.cancel("value");
    }
    return this;
  }
  /**
   * Upon value-typed updates, sets the current value to the input value
   * immediately prior to the event value being emitted to listeners.
   * @param type The event type.
   * @param value The input event value.
   * @returns The input event value.
   */
  willEmit(type2, value) {
    if (type2 === "value") {
      this._value = value;
    }
    return value;
  }
};

// ../../mosaic/core/dist/src/Selection.js
function isSelection(x3) {
  return x3 instanceof Selection;
}
function create(options, include) {
  return new Selection(new SelectionResolver(options), include ? [include].flat() : void 0);
}
var Selection = class _Selection extends Param {
  _resolved;
  _resolver;
  _relay;
  /**
   * Create a new Selection instance with an
   * intersect (conjunction) resolution strategy.
   * @param options The selection options.
   * @returns The new Selection instance.
   */
  static intersect({ cross: cross3 = false, empty: empty4 = false, include = [] } = {}) {
    return create({ cross: cross3, empty: empty4 }, include);
  }
  /**
   * Create a new Selection instance with a
   * union (disjunction) resolution strategy.
   * @param options The selection options.
   * @returns The new Selection instance.
   */
  static union({ cross: cross3 = false, empty: empty4 = false, include = [] } = {}) {
    return create({ cross: cross3, empty: empty4, union: true }, include);
  }
  /**
   * Create a new Selection instance with a singular resolution strategy
   * that keeps only the most recent selection clause.
   * @param options The selection options.
   * @returns The new Selection instance.
   */
  static single({ cross: cross3 = false, empty: empty4 = false, include = [] } = {}) {
    return create({ cross: cross3, empty: empty4, single: true }, include);
  }
  /**
   * Create a new Selection instance with a
   * cross-filtered intersect resolution strategy.
   * @param options The selection options.
   * @returns The new Selection instance.
   */
  static crossfilter({ empty: empty4 = false, include = [] } = {}) {
    return create({ cross: true, empty: empty4 }, include);
  }
  /**
   * Create a new Selection instance.
   * @param resolver The selection resolution
   *  strategy to apply.
   * @param include Upstream selections whose clauses
   * should be included as part of this selection. Any clauses published
   * to these upstream selections will be relayed to this selection.
   */
  constructor(resolver = new SelectionResolver(), include = []) {
    super([]);
    this._resolved = this._value;
    this._resolver = resolver;
    this._relay = /* @__PURE__ */ new Set();
    if (Array.isArray(include)) {
      for (const sel of include) {
        sel._relay.add(this);
      }
    }
  }
  /**
   * Create a cloned copy of this Selection instance.
   * @returns A clone of this selection.
   */
  clone() {
    const s2 = new _Selection(this._resolver);
    s2._value = s2._resolved = this._value;
    return s2;
  }
  /**
   * Create a clone of this Selection with clauses corresponding
   * to the provided source removed.
   * @param source The clause source to remove.
   * @returns A cloned and updated Selection.
   */
  remove(source) {
    const s2 = this.clone();
    s2._value = s2._resolved = s2._resolver.resolve(this._resolved, { source });
    s2._value.active = { source };
    return s2;
  }
  /**
   * The selection clause resolver.
   */
  get resolver() {
    return this._resolver;
  }
  /**
   * Indicate if this selection has a single resolution strategy.
   */
  get single() {
    return this._resolver.single;
  }
  /**
   * The current array of selection clauses.
   */
  get clauses() {
    return super.value;
  }
  /**
   * The current active (most recently updated) selection clause.
   */
  get active() {
    return this.clauses.active;
  }
  /**
   * The value corresponding to the current active selection clause.
   * This method ensures compatibility where a normal Param is expected.
   */
  // @ts-expect-error return type differs from Param parent class
  get value() {
    return this.active?.value;
  }
  /**
   * The value corresponding to a given source. Returns undefined if
   * this selection does not include a clause from this source.
   * @param source The clause source to look up the value for.
   */
  valueFor(source) {
    return this.clauses.find((c4) => c4.source === source)?.value;
  }
  /**
   * Emit an activate event with the given selection clause.
   * @param clause The clause representing the potential activation.
   */
  activate(clause) {
    this.emit("activate", clause);
    this._relay.forEach((sel) => sel.activate(clause));
  }
  /**
   * Update the selection with a new selection clause.
   * @param clause The selection clause to add.
   * @returns This Selection instance.
   */
  // @ts-expect-error selection and param use differing value types
  update(clause) {
    this._resolved = this._resolver.resolve(this._resolved, clause, true);
    this._resolved.active = clause;
    this._relay.forEach((sel) => sel.update(clause));
    return super.update(this._resolved);
  }
  /**
   * Reset the selection state by removing all provided clauses. If no clause
   * array is provided as an argument, all current clauses are removed. The
   * reset method (if defined) is invoked on all corresponding clause sources.
   * The reset is relayed to downstream selections that include this selection.
   * @param clauses The clauses to remove. If unspecified, all current clauses are removed.
   * @returns This selection instance.
   */
  reset(clauses) {
    clauses ??= this._resolved;
    clauses.forEach((c4) => c4.source?.reset?.());
    this._resolved = this._resolved.filter((c4) => clauses.includes(c4));
    this._relay.forEach((sel) => sel.reset(clauses));
    return super.update(this._resolved = []);
  }
  /**
   * Upon value-typed updates, sets the current clause list to the
   * input value and returns the active clause value.
   * @param type The event type.
   * @param value The input event value.
   * @returns For value-typed events, returns the active clause
   *  values. Otherwise returns the input event value as-is.
   */
  // @ts-expect-error selection and param use differing value types
  willEmit(type2, value) {
    if (type2 === "value") {
      this._value = value;
      return this.value;
    }
    return value;
  }
  /**
   * Upon value-typed updates, returns a dispatch queue filter function.
   * The return value depends on the selection resolution strategy.
   * @param type The event type.
   * @param value The new event value that will be enqueued.
   * @returns A dispatch queue filter function. For non-value events,
   *  returns a function that always returns null (no filtering).
   */
  // @ts-expect-error selection and param use differing value types
  emitQueueFilter(type2, value) {
    return type2 === "value" ? this._resolver.queueFilter(value) : null;
  }
  /**
   * Indicates if a selection clause should not be applied to a given client.
   * The return value depends on the selection resolution strategy.
   * @param client The client to test. If null or undefined, return false.
   * @param clause The selection clause.
   * @returns True if the client should be skipped, false otherwise.
   */
  skip(client, clause) {
    return this._resolver.skip(client, clause);
  }
  /**
   * Return a selection query predicate for the given client.
   * @param client The client whose data may be filtered. If null or undefined, return a predicate with all clauses.
   * @param noSkip Disable skipping of active
   *  cross-filtered sources. If set true, the source of the active
   *  clause in a cross-filtered selection will not be skipped.
   * @returns The query predicate for filtering client data,
   *  based on the current state of this selection.
   */
  predicate(client = void 0, noSkip = false) {
    const { clauses } = this;
    const active = noSkip ? null : clauses.active;
    return this._resolver.predicate(clauses, active, client);
  }
};
var SelectionResolver = class {
  union;
  cross;
  single;
  empty;
  /**
   * Create a new selection resolved instance.
   * @param options The resolution strategy options.
   * @param options.union Boolean flag to indicate a union strategy.
   *  If false, an intersection strategy is used.
   * @param options.cross Boolean flag to indicate cross-filtering.
   * @param options.single Boolean flag to indicate single clauses only.
   * @param options.empty Boolean flag indicating if a lack
   *  of clauses should correspond to an empty selection with no records. This
   *  setting determines the default selection state.
   */
  constructor({ union: union2, cross: cross3, single, empty: empty4 } = {}) {
    this.union = !!union2;
    this.cross = !!cross3;
    this.single = !!single;
    this.empty = !!empty4;
  }
  /**
   * Resolve a list of selection clauses according to the resolution strategy.
   * @param clauseList An array of selection clauses.
   * @param clause A new selection clause to add.
   * @returns An updated array of selection clauses.
   */
  resolve(clauseList2, clause, reset = false) {
    const { source, predicate } = clause;
    const filtered = clauseList2.filter((c4) => source !== c4.source);
    const clauses = this.single ? [] : filtered;
    if (this.single && reset)
      filtered.forEach((c4) => c4.source?.reset?.());
    if (predicate)
      clauses.push(clause);
    return clauses;
  }
  /**
   * Indicates if a selection clause should not be applied to a given client.
   * The return value depends on the resolution strategy.
   * @param client The client to test. If null or undefined, return false.
   * @param clause The selection clause.
   * @returns True if the client should be skipped, false otherwise.
   */
  skip(client, clause) {
    if (client == null) {
      return false;
    }
    return Boolean(this.cross && clause?.clients?.has(client));
  }
  /**
   * Return a selection query predicate for the given client.
   * @param clauseList An array of selection clauses.
   * @param active The current active selection clause.
   * @param client The client whose data may be filtered. If null or undefined, return all clauses.
   * @returns The query predicate for filtering client data,
   *  based on the current state of this selection.
   */
  predicate(clauseList2, active, client) {
    const { empty: empty4, union: union2 } = this;
    if (empty4 && !clauseList2.length) {
      return [literal(false)];
    }
    if (this.skip(client, active))
      return void 0;
    const predicates = clauseList2.filter((clause) => !this.skip(client, clause)).map((clause) => clause.predicate);
    return union2 && predicates.length > 1 ? or(predicates) : predicates;
  }
  /**
   * Returns a filter function for queued selection updates.
   * @param value The new event value that will be enqueued.
   * @returns A dispatch queue filter
   *  function, or null if all unemitted event values should be filtered.
   */
  queueFilter(value) {
    if (this.cross) {
      const source = value.active?.source;
      return (value2) => value2.active?.source !== source;
    }
    return null;
  }
};

// ../../mosaic/core/dist/src/SelectionClause.js
function clausePoint(field3, value, { source, clients = isMosaicClient(source) ? /* @__PURE__ */ new Set([source]) : void 0 }) {
  const predicate = value !== void 0 ? isIn(field3, [literal(value)]) : null;
  return {
    meta: { type: "point" },
    source,
    clients,
    value,
    predicate
  };
}
function clausePoints(fields, value, { source, clients = isMosaicClient(source) ? /* @__PURE__ */ new Set([source]) : void 0 }) {
  let predicate = null;
  if (value?.length) {
    const clauses = value.length && fields.length === 1 ? [isIn(fields[0], value.map((v2) => literal(v2[0])))] : value.map((v2) => and(v2.map((_, i) => isNotDistinct(fields[i], literal(_)))));
    predicate = value.length === 0 ? literal(false) : clauses.length > 1 ? or(clauses) : clauses[0];
  }
  return {
    meta: { type: "point" },
    source,
    clients,
    value,
    predicate
  };
}
function clauseInterval(field3, value, { source, clients = isMosaicClient(source) ? /* @__PURE__ */ new Set([source]) : void 0, bin: bin3, scale: scale3, pixelSize = 1 }) {
  const predicate = value != null ? isBetween(field3, value) : null;
  const meta = {
    type: "interval",
    scales: scale3 && [scale3],
    bin: bin3,
    pixelSize
  };
  return { meta, source, clients, value, predicate };
}
function clauseIntervals(fields, value, { source, clients = isMosaicClient(source) ? /* @__PURE__ */ new Set([source]) : void 0, bin: bin3, scales: scales2 = [], pixelSize = 1 }) {
  const predicate = value != null ? and(fields.map((f, i) => isBetween(f, value[i]))) : null;
  const meta = {
    type: "interval",
    scales: scales2,
    bin: bin3,
    pixelSize
  };
  return { meta, source, clients, value, predicate };
}
var identity2 = (x3) => x3;
var MATCH_METHODS = { contains, prefix, suffix, regexp: regexp_matches };
function clauseMatch(field3, value, { source, clients = void 0, method = "contains", caseSensitive = false }) {
  const fn2 = MATCH_METHODS[method];
  const transform3 = caseSensitive ? identity2 : lower;
  const predicate = value ? fn2(transform3(field3), transform3(literal(value))) : null;
  const meta = { type: "match", method };
  return { meta, source, clients, value, predicate };
}
function clauseList(field3, value, { source, clients = isMosaicClient(source) ? /* @__PURE__ */ new Set([source]) : void 0, listMatch = "any" }) {
  const listFn = listMatch === "all" ? listHasAll : listHasAny;
  const predicate = value !== void 0 ? listFn(field3, literal(value)) : null;
  return { source, clients, value, predicate };
}

// ../../mosaic/core/dist/src/util/is-arrow-table.js
function isArrowTable(values2) {
  return typeof values2?.getChild === "function";
}

// ../../mosaic/core/dist/src/util/synchronizer.js
var Synchronizer = class {
  _set;
  _done;
  _promise;
  /**
   * Create a new synchronizer instance.
   */
  constructor() {
    this._set = /* @__PURE__ */ new Set();
    this._done = () => {
    };
    this._promise = new Promise((resolve) => this._done = resolve);
  }
  /**
   * Mark an item as pending.
   * @param item An item to synchronize on.
   */
  pending(item) {
    this._set.add(item);
  }
  /**
   * Mark a pending item as ready, indicating it is
   * ready for a synchronized update.
   * @param item An item to synchronize on.
   * @returns True if the synchronizer is ready to
   *  resolve, false otherwise.
   */
  ready(item) {
    this._set.delete(item);
    return this._set.size === 0;
  }
  /**
   * Resolve the current synchronization cycle, causing the synchronize
   * promise to resolve and thereby trigger downstream updates.
   */
  resolve() {
    this._promise = new Promise((resolve) => {
      this._done();
      this._done = resolve;
    });
  }
  /**
   * The promise for the current synchronization cycle.
   * @returns The synchronization promise.
   */
  get promise() {
    return this._promise;
  }
};

// ../../mosaic/core/dist/src/util/to-data-columns.js
function toDataColumns(data) {
  if (isArrowTable(data)) {
    return arrowToColumns(data);
  } else if (Array.isArray(data)) {
    return arrayToColumns(data);
  } else {
    throw new Error("Unrecognized data format.");
  }
}
function arrowToColumns(data) {
  const { numRows } = data;
  return { numRows, columns: data.toColumns() };
}
function arrayToColumns(data) {
  const numRows = data.length;
  if (typeof data[0] === "object") {
    const names = numRows ? Object.keys(data[0]) : [];
    const columns = {};
    if (names.length > 0) {
      names.forEach((name2) => {
        columns[name2] = data.map((d) => d[name2]);
      });
    }
    return { numRows, columns };
  } else {
    return { numRows, values: data };
  }
}

// ../../mosaic/core/dist/src/util/js-type.js
function jsType(type2) {
  switch (type2) {
    case "BIGINT":
    case "HUGEINT":
    case "INTEGER":
    case "SMALLINT":
    case "TINYINT":
    case "UBIGINT":
    case "UINTEGER":
    case "USMALLINT":
    case "UTINYINT":
    // integers
    case "DOUBLE":
    case "FLOAT":
    case "REAL":
      return "number";
    case "DATE":
    case "TIMESTAMP":
    case "TIMESTAMPTZ":
    case "TIMESTAMP WITH TIME ZONE":
    case "TIME":
    case "TIMESTAMP_NS":
      return "date";
    case "BOOLEAN":
      return "boolean";
    case "VARCHAR":
    case "UUID":
    case "JSON":
      return "string";
    case "ARRAY":
    case "LIST":
      return "array";
    case "BLOB":
    case "STRUCT":
    case "MAP":
    case "GEOMETRY":
      return "object";
    default:
      if (type2.startsWith("ENUM")) {
        return "string";
      } else if (type2.startsWith("DECIMAL")) {
        return "number";
      } else if (type2.startsWith("STRUCT") || type2.startsWith("MAP")) {
        return "object";
      } else if (type2.endsWith("]")) {
        return "array";
      }
      throw new Error(`Unsupported type: ${type2}`);
  }
}

// ../../mosaic/core/dist/src/util/field-info.js
var Count = "count";
var Nulls = "nulls";
var Max = "max";
var Min = "min";
var Distinct = "distinct";
var statMap = {
  [Count]: count,
  [Distinct]: (column3) => count(column3).distinct(),
  [Max]: max,
  [Min]: min,
  [Nulls]: (column3) => count().where(isNull(column3))
};
function summarize({ table: table3, column: column3, stats }) {
  return Query.from(table3).select(Array.from(stats, (s2) => ({ [s2]: statMap[s2](column3) })));
}
async function queryFieldInfo(mc, fields) {
  if (fields.length === 1 && fields[0].column === "*") {
    return getTableInfo(mc, fields[0].table);
  } else {
    return (await Promise.all(fields.map((f) => getFieldInfo(mc, f)))).filter((x3) => x3 !== void 0);
  }
}
async function getFieldInfo(mc, { table: table3, column: column3, stats }) {
  const q = Query.from({ source: table3 }).select({ column: column3 }).groupby(isNode(column3) && isAggregateExpression(column3) ? sql`ALL` : []);
  const [desc2] = Array.from(await mc.query(Query.describe(q)));
  const info = {
    table: table3,
    column: `${column3}`,
    sqlType: desc2.column_type,
    type: jsType(desc2.column_type),
    nullable: desc2.null === "YES"
  };
  if (!stats?.length)
    return info;
  const [result] = await mc.query(summarize({ table: table3, column: column3, stats }), { persist: true });
  return Object.assign(info, result);
}
async function getTableInfo(mc, table3) {
  const result = Array.from(await mc.query(`DESCRIBE ${asTableRef(table3)}`));
  return result.map((desc2) => ({
    table: table3,
    column: desc2.column_name,
    sqlType: desc2.column_type,
    type: jsType(desc2.column_type),
    nullable: desc2.null === "YES"
  }));
}

// ../vgplot/src/api.js
var api_exports = {};
__export(api_exports, {
  Fixed: () => Fixed,
  Param: () => Param,
  Query: () => Query,
  Selection: () => Selection,
  align: () => align2,
  and: () => and,
  area: () => area2,
  areaX: () => areaX2,
  areaY: () => areaY2,
  argmax: () => argmax,
  argmin: () => argmin,
  ariaDescription: () => ariaDescription,
  ariaLabel: () => ariaLabel,
  arrayAgg: () => arrayAgg,
  arrow: () => arrow2,
  aspectRatio: () => aspectRatio,
  avg: () => avg,
  axis: () => axis2,
  axisFx: () => axisFx2,
  axisFy: () => axisFy2,
  axisX: () => axisX2,
  axisY: () => axisY2,
  barX: () => barX2,
  barY: () => barY2,
  bin: () => bin2,
  cast: () => cast,
  cell: () => cell2,
  cellX: () => cellX2,
  cellY: () => cellY2,
  centroid: () => centroid,
  centroidX: () => centroidX,
  centroidY: () => centroidY,
  circle: () => circle2,
  clip: () => clip,
  colorBase: () => colorBase,
  colorClamp: () => colorClamp,
  colorConstant: () => colorConstant2,
  colorDomain: () => colorDomain,
  colorExponent: () => colorExponent,
  colorInterpolate: () => colorInterpolate,
  colorLabel: () => colorLabel,
  colorLegend: () => colorLegend,
  colorN: () => colorN,
  colorNice: () => colorNice,
  colorPercent: () => colorPercent,
  colorPivot: () => colorPivot,
  colorRange: () => colorRange,
  colorReverse: () => colorReverse,
  colorScale: () => colorScale2,
  colorScheme: () => colorScheme2,
  colorSymmetric: () => colorSymmetric,
  colorTickFormat: () => colorTickFormat,
  colorZero: () => colorZero,
  column: () => column,
  contour: () => contour2,
  coordinator: () => coordinator,
  corr: () => corr,
  count: () => count,
  covarPop: () => covarPop,
  covariance: () => covariance,
  createSchema: () => createSchema,
  createTable: () => createTable2,
  cume_dist: () => cume_dist,
  dateDay: () => dateDay2,
  dateMonth: () => dateMonth,
  dateMonthDay: () => dateMonthDay,
  days: () => days,
  delaunayLink: () => delaunayLink2,
  delaunayMesh: () => delaunayMesh2,
  denseLine: () => denseLine,
  dense_rank: () => dense_rank,
  density: () => density2,
  densityX: () => densityX,
  densityY: () => densityY,
  dot: () => dot2,
  dotX: () => dotX2,
  dotY: () => dotY2,
  entropy: () => entropy,
  eq: () => eq,
  errorbarX: () => errorbarX,
  errorbarY: () => errorbarY,
  facetGrid: () => facetGrid,
  facetLabel: () => facetLabel,
  facetMargin: () => facetMargin,
  facetMarginBottom: () => facetMarginBottom,
  facetMarginLeft: () => facetMarginLeft,
  facetMarginRight: () => facetMarginRight,
  facetMarginTop: () => facetMarginTop,
  first: () => first,
  first_value: () => first_value,
  float32: () => float322,
  float64: () => float642,
  frame: () => frame3,
  frameGroups: () => frameGroups,
  frameRange: () => frameRange,
  frameRows: () => frameRows,
  from: () => from,
  fxAlign: () => fxAlign,
  fxAriaDescription: () => fxAriaDescription,
  fxAriaLabel: () => fxAriaLabel,
  fxAxis: () => fxAxis,
  fxDomain: () => fxDomain,
  fxFontVariant: () => fxFontVariant,
  fxGrid: () => fxGrid,
  fxInset: () => fxInset,
  fxInsetLeft: () => fxInsetLeft,
  fxInsetRight: () => fxInsetRight,
  fxLabel: () => fxLabel,
  fxLabelAnchor: () => fxLabelAnchor,
  fxLabelOffset: () => fxLabelOffset,
  fxLine: () => fxLine,
  fxPadding: () => fxPadding,
  fxPaddingInner: () => fxPaddingInner,
  fxPaddingOuter: () => fxPaddingOuter,
  fxRange: () => fxRange,
  fxReverse: () => fxReverse,
  fxRound: () => fxRound,
  fxTickFormat: () => fxTickFormat,
  fxTickPadding: () => fxTickPadding,
  fxTickRotate: () => fxTickRotate,
  fxTickSize: () => fxTickSize,
  fxTickSpacing: () => fxTickSpacing,
  fxTicks: () => fxTicks,
  fyAlign: () => fyAlign,
  fyAriaDescription: () => fyAriaDescription,
  fyAriaLabel: () => fyAriaLabel,
  fyAxis: () => fyAxis,
  fyDomain: () => fyDomain,
  fyFontVariant: () => fyFontVariant,
  fyGrid: () => fyGrid,
  fyInset: () => fyInset,
  fyInsetBottom: () => fyInsetBottom,
  fyInsetTop: () => fyInsetTop,
  fyLabel: () => fyLabel,
  fyLabelAnchor: () => fyLabelAnchor,
  fyLabelOffset: () => fyLabelOffset,
  fyLine: () => fyLine,
  fyPadding: () => fyPadding,
  fyPaddingInner: () => fyPaddingInner,
  fyPaddingOuter: () => fyPaddingOuter,
  fyRange: () => fyRange,
  fyReverse: () => fyReverse,
  fyRound: () => fyRound,
  fyTickFormat: () => fyTickFormat,
  fyTickPadding: () => fyTickPadding,
  fyTickRotate: () => fyTickRotate,
  fyTickSize: () => fyTickSize,
  fyTickSpacing: () => fyTickSpacing,
  fyTicks: () => fyTicks,
  geo: () => geo2,
  geojson: () => geojson,
  geomean: () => geomean,
  graticule: () => graticule3,
  grid: () => grid,
  gridFx: () => gridFx2,
  gridFy: () => gridFy2,
  gridX: () => gridX2,
  gridY: () => gridY2,
  gt: () => gt,
  gte: () => gte,
  hconcat: () => hconcat,
  heatmap: () => heatmap,
  height: () => height,
  hexagon: () => hexagon2,
  hexbin: () => hexbin2,
  hexgrid: () => hexgrid2,
  highlight: () => highlight,
  hours: () => hours,
  hspace: () => hspace,
  hull: () => hull2,
  image: () => image2,
  inset: () => inset,
  int32: () => int322,
  interval: () => interval2,
  intervalX: () => intervalX,
  intervalXY: () => intervalXY,
  intervalY: () => intervalY,
  isBetween: () => isBetween,
  isDistinct: () => isDistinct,
  isNotBetween: () => isNotBetween,
  isNotDistinct: () => isNotDistinct,
  isNotNull: () => isNotNull,
  isNull: () => isNull,
  kurtosis: () => kurtosis,
  lag: () => lag,
  last: () => last,
  last_value: () => last_value,
  lead: () => lead,
  lengthBase: () => lengthBase,
  lengthClamp: () => lengthClamp,
  lengthConstant: () => lengthConstant,
  lengthDomain: () => lengthDomain,
  lengthExponent: () => lengthExponent,
  lengthNice: () => lengthNice,
  lengthPercent: () => lengthPercent,
  lengthRange: () => lengthRange,
  lengthScale: () => lengthScale,
  lengthZero: () => lengthZero,
  line: () => line2,
  lineX: () => lineX2,
  lineY: () => lineY2,
  link: () => link3,
  literal: () => literal,
  loadCSV: () => loadCSV,
  loadExtension: () => loadExtension,
  loadJSON: () => loadJSON,
  loadObjects: () => loadObjects,
  loadParquet: () => loadParquet,
  loadSpatial: () => loadSpatial,
  lt: () => lt,
  lte: () => lte,
  mad: () => mad,
  margin: () => margin,
  marginBottom: () => marginBottom,
  marginLeft: () => marginLeft,
  marginRight: () => marginRight,
  marginTop: () => marginTop,
  margins: () => margins,
  max: () => max,
  median: () => median,
  menu: () => menu2,
  microseconds: () => microseconds,
  milliseconds: () => milliseconds,
  min: () => min,
  minutes: () => minutes,
  mode: () => mode,
  months: () => months,
  name: () => name,
  nearest: () => nearest,
  nearestX: () => nearestX,
  nearestY: () => nearestY,
  neq: () => neq,
  not: () => not,
  nth_value: () => nth_value,
  ntile: () => ntile,
  opacityBase: () => opacityBase,
  opacityClamp: () => opacityClamp,
  opacityConstant: () => opacityConstant,
  opacityDomain: () => opacityDomain,
  opacityExponent: () => opacityExponent,
  opacityLabel: () => opacityLabel,
  opacityLegend: () => opacityLegend,
  opacityNice: () => opacityNice,
  opacityPercent: () => opacityPercent,
  opacityRange: () => opacityRange,
  opacityReverse: () => opacityReverse,
  opacityScale: () => opacityScale,
  opacityTickFormat: () => opacityTickFormat,
  opacityZero: () => opacityZero,
  or: () => or,
  padding: () => padding,
  pan: () => pan,
  panX: () => panX,
  panY: () => panY,
  panZoom: () => panZoom,
  panZoomX: () => panZoomX,
  panZoomY: () => panZoomY,
  percent_rank: () => percent_rank,
  plot: () => plot2,
  product: () => product,
  projectionClip: () => projectionClip,
  projectionDomain: () => projectionDomain,
  projectionInset: () => projectionInset,
  projectionInsetBottom: () => projectionInsetBottom,
  projectionInsetLeft: () => projectionInsetLeft,
  projectionInsetRight: () => projectionInsetRight,
  projectionInsetTop: () => projectionInsetTop,
  projectionParallels: () => projectionParallels,
  projectionPrecision: () => projectionPrecision,
  projectionRotate: () => projectionRotate,
  projectionType: () => projectionType,
  quantile: () => quantile,
  rBase: () => rBase,
  rClamp: () => rClamp,
  rConstant: () => rConstant,
  rDomain: () => rDomain,
  rExponent: () => rExponent,
  rLabel: () => rLabel,
  rNice: () => rNice,
  rPercent: () => rPercent,
  rRange: () => rRange,
  rScale: () => rScale,
  rZero: () => rZero,
  rank: () => rank,
  raster: () => raster2,
  rasterTile: () => rasterTile,
  rect: () => rect2,
  rectX: () => rectX2,
  rectY: () => rectY2,
  region: () => region,
  regressionY: () => regressionY,
  row_number: () => row_number,
  ruleX: () => ruleX2,
  ruleY: () => ruleY2,
  search: () => search2,
  seconds: () => seconds,
  skewness: () => skewness,
  slider: () => slider2,
  sphere: () => sphere3,
  spike: () => spike2,
  sql: () => sql,
  stddev: () => stddev,
  stddevPop: () => stddevPop,
  stringAgg: () => stringAgg,
  style: () => style,
  sum: () => sum,
  symbolDomain: () => symbolDomain,
  symbolLegend: () => symbolLegend,
  symbolRange: () => symbolRange,
  symbolScale: () => symbolScale,
  table: () => table2,
  text: () => text2,
  textX: () => textX2,
  textY: () => textY2,
  tickX: () => tickX2,
  tickY: () => tickY2,
  toggle: () => toggle,
  toggleColor: () => toggleColor,
  toggleX: () => toggleX,
  toggleY: () => toggleY,
  toggleZ: () => toggleZ,
  varPop: () => varPop,
  variance: () => variance,
  vconcat: () => vconcat,
  vector: () => vector2,
  vectorX: () => vectorX2,
  vectorY: () => vectorY2,
  voronoi: () => voronoi2,
  voronoiMesh: () => voronoiMesh2,
  vspace: () => vspace,
  waffleX: () => waffleX2,
  waffleY: () => waffleY2,
  width: () => width,
  xAlign: () => xAlign,
  xAriaDescription: () => xAriaDescription,
  xAriaLabel: () => xAriaLabel,
  xAxis: () => xAxis,
  xBase: () => xBase,
  xClamp: () => xClamp,
  xConstant: () => xConstant,
  xDomain: () => xDomain,
  xExponent: () => xExponent,
  xFontVariant: () => xFontVariant,
  xGrid: () => xGrid,
  xInset: () => xInset,
  xInsetLeft: () => xInsetLeft,
  xInsetRight: () => xInsetRight,
  xLabel: () => xLabel,
  xLabelAnchor: () => xLabelAnchor,
  xLabelArrow: () => xLabelArrow,
  xLabelOffset: () => xLabelOffset,
  xLine: () => xLine,
  xNice: () => xNice,
  xPadding: () => xPadding,
  xPaddingInner: () => xPaddingInner,
  xPaddingOuter: () => xPaddingOuter,
  xPercent: () => xPercent,
  xRange: () => xRange,
  xReverse: () => xReverse,
  xRound: () => xRound,
  xScale: () => xScale,
  xTickFormat: () => xTickFormat,
  xTickPadding: () => xTickPadding,
  xTickRotate: () => xTickRotate,
  xTickSize: () => xTickSize,
  xTickSpacing: () => xTickSpacing,
  xTicks: () => xTicks,
  xZero: () => xZero,
  xyDomain: () => xyDomain,
  yAlign: () => yAlign,
  yAriaDescription: () => yAriaDescription,
  yAriaLabel: () => yAriaLabel,
  yAxis: () => yAxis,
  yBase: () => yBase,
  yClamp: () => yClamp,
  yConstant: () => yConstant,
  yDomain: () => yDomain,
  yExponent: () => yExponent,
  yFontVariant: () => yFontVariant,
  yGrid: () => yGrid,
  yInset: () => yInset,
  yInsetBottom: () => yInsetBottom,
  yInsetTop: () => yInsetTop,
  yLabel: () => yLabel,
  yLabelAnchor: () => yLabelAnchor,
  yLabelArrow: () => yLabelArrow,
  yLabelOffset: () => yLabelOffset,
  yLine: () => yLine,
  yNice: () => yNice,
  yPadding: () => yPadding,
  yPaddingInner: () => yPaddingInner,
  yPaddingOuter: () => yPaddingOuter,
  yPercent: () => yPercent,
  yRange: () => yRange,
  yReverse: () => yReverse,
  yRound: () => yRound,
  yScale: () => yScale,
  yTickFormat: () => yTickFormat,
  yTickPadding: () => yTickPadding,
  yTickRotate: () => yTickRotate,
  yTickSize: () => yTickSize,
  yTickSpacing: () => yTickSpacing,
  yTicks: () => yTicks,
  yZero: () => yZero,
  years: () => years
});

// ../plot/src/symbols.js
var Fixed = Symbol("Fixed");
var Transient = Symbol("Transient");
var Transform = Symbol("Transform");

// ../../../node_modules/@observablehq/plot/src/index.js
var src_exports = {};
__export(src_exports, {
  Area: () => Area,
  Arrow: () => Arrow,
  BarX: () => BarX,
  BarY: () => BarY,
  Cell: () => Cell,
  Contour: () => Contour,
  Density: () => Density,
  Dot: () => Dot,
  Frame: () => Frame,
  Geo: () => Geo,
  Hexgrid: () => Hexgrid,
  Image: () => Image,
  Line: () => Line,
  Link: () => Link,
  Mark: () => Mark,
  Raster: () => Raster,
  Rect: () => Rect,
  RuleX: () => RuleX,
  RuleY: () => RuleY,
  Text: () => Text,
  TickX: () => TickX,
  TickY: () => TickY,
  Tip: () => Tip,
  Vector: () => Vector,
  WaffleX: () => WaffleX,
  WaffleY: () => WaffleY,
  area: () => area,
  areaX: () => areaX,
  areaY: () => areaY,
  arrow: () => arrow,
  auto: () => auto,
  autoSpec: () => autoSpec,
  axisFx: () => axisFx,
  axisFy: () => axisFy,
  axisX: () => axisX,
  axisY: () => axisY,
  barX: () => barX,
  barY: () => barY,
  bin: () => bin,
  binX: () => binX,
  binY: () => binY,
  bollinger: () => bollinger,
  bollingerX: () => bollingerX,
  bollingerY: () => bollingerY,
  boxX: () => boxX,
  boxY: () => boxY,
  cell: () => cell,
  cellX: () => cellX,
  cellY: () => cellY,
  centroid: () => centroid2,
  circle: () => circle,
  cluster: () => cluster,
  column: () => column2,
  contour: () => contour,
  crosshair: () => crosshair,
  crosshairX: () => crosshairX,
  crosshairY: () => crosshairY,
  delaunayLink: () => delaunayLink,
  delaunayMesh: () => delaunayMesh,
  density: () => density,
  differenceX: () => differenceX,
  differenceY: () => differenceY,
  dodgeX: () => dodgeX,
  dodgeY: () => dodgeY,
  dot: () => dot,
  dotX: () => dotX,
  dotY: () => dotY,
  filter: () => filter2,
  find: () => find2,
  formatIsoDate: () => formatIsoDate,
  formatMonth: () => formatMonth,
  formatNumber: () => formatNumber,
  formatWeekday: () => formatWeekday,
  frame: () => frame2,
  geo: () => geo,
  geoCentroid: () => geoCentroid,
  graticule: () => graticule2,
  gridFx: () => gridFx,
  gridFy: () => gridFy,
  gridX: () => gridX,
  gridY: () => gridY,
  group: () => group2,
  groupX: () => groupX,
  groupY: () => groupY,
  groupZ: () => groupZ,
  hexagon: () => hexagon,
  hexbin: () => hexbin,
  hexgrid: () => hexgrid,
  hull: () => hull,
  identity: () => identity8,
  image: () => image,
  indexOf: () => indexOf,
  initializer: () => initializer,
  interpolateNearest: () => interpolateNearest,
  interpolateNone: () => interpolateNone,
  interpolatorBarycentric: () => interpolatorBarycentric,
  interpolatorRandomWalk: () => interpolatorRandomWalk,
  legend: () => legend,
  line: () => line,
  lineX: () => lineX,
  lineY: () => lineY,
  linearRegressionX: () => linearRegressionX,
  linearRegressionY: () => linearRegressionY,
  link: () => link2,
  map: () => map4,
  mapX: () => mapX,
  mapY: () => mapY,
  marks: () => marks,
  normalize: () => normalize3,
  normalizeX: () => normalizeX,
  normalizeY: () => normalizeY,
  numberInterval: () => numberInterval,
  plot: () => plot,
  pointer: () => pointer,
  pointerX: () => pointerX,
  pointerY: () => pointerY,
  raster: () => raster,
  rect: () => rect,
  rectX: () => rectX,
  rectY: () => rectY,
  reverse: () => reverse2,
  ruleX: () => ruleX,
  ruleY: () => ruleY,
  scale: () => scale2,
  select: () => select,
  selectFirst: () => selectFirst,
  selectLast: () => selectLast,
  selectMaxX: () => selectMaxX,
  selectMaxY: () => selectMaxY,
  selectMinX: () => selectMinX,
  selectMinY: () => selectMinY,
  shiftX: () => shiftX,
  shiftY: () => shiftY,
  shuffle: () => shuffle,
  sort: () => sort2,
  sphere: () => sphere2,
  spike: () => spike,
  stackX: () => stackX,
  stackX1: () => stackX1,
  stackX2: () => stackX2,
  stackY: () => stackY,
  stackY1: () => stackY1,
  stackY2: () => stackY2,
  text: () => text,
  textX: () => textX,
  textY: () => textY,
  tickX: () => tickX,
  tickY: () => tickY,
  timeInterval: () => timeInterval3,
  tip: () => tip,
  transform: () => basic,
  tree: () => tree,
  treeLink: () => treeLink,
  treeNode: () => treeNode,
  utcInterval: () => utcInterval,
  valueof: () => valueof,
  vector: () => vector,
  vectorX: () => vectorX,
  vectorY: () => vectorY,
  voronoi: () => voronoi,
  voronoiMesh: () => voronoiMesh,
  waffleX: () => waffleX,
  waffleY: () => waffleY,
  window: () => window2,
  windowX: () => windowX,
  windowY: () => windowY
});

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

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

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

// ../../../node_modules/d3-array/src/number.js
function number(x3) {
  return x3 === null ? NaN : +x3;
}
function* numbers(values2, valueof2) {
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value != null && (value = +value) >= value) {
        yield value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (value = +value) >= value) {
        yield value;
      }
    }
  }
}

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

// ../../../node_modules/d3-array/src/blur.js
var blur2 = Blur2(blurf);
var blurImage = Blur2(blurfImage);
function Blur2(blur3) {
  return function(data, rx, ry = rx) {
    if (!((rx = +rx) >= 0)) throw new RangeError("invalid rx");
    if (!((ry = +ry) >= 0)) throw new RangeError("invalid ry");
    let { data: values2, width: width2, height: height2 } = data;
    if (!((width2 = Math.floor(width2)) >= 0)) throw new RangeError("invalid width");
    if (!((height2 = Math.floor(height2 !== void 0 ? height2 : values2.length / width2)) >= 0)) throw new RangeError("invalid height");
    if (!width2 || !height2 || !rx && !ry) return data;
    const blurx = rx && blur3(rx);
    const blury = ry && blur3(ry);
    const temp = values2.slice();
    if (blurx && blury) {
      blurh(blurx, temp, values2, width2, height2);
      blurh(blurx, values2, temp, width2, height2);
      blurh(blurx, temp, values2, width2, height2);
      blurv(blury, values2, temp, width2, height2);
      blurv(blury, temp, values2, width2, height2);
      blurv(blury, values2, temp, width2, height2);
    } else if (blurx) {
      blurh(blurx, values2, temp, width2, height2);
      blurh(blurx, temp, values2, width2, height2);
      blurh(blurx, values2, temp, width2, height2);
    } else if (blury) {
      blurv(blury, values2, temp, width2, height2);
      blurv(blury, temp, values2, width2, height2);
      blurv(blury, values2, temp, width2, height2);
    }
    return data;
  };
}
function blurh(blur3, T, S, w, h) {
  for (let y3 = 0, n = w * h; y3 < n; ) {
    blur3(T, S, y3, y3 += w, 1);
  }
}
function blurv(blur3, T, S, w, h) {
  for (let x3 = 0, n = w * h; x3 < w; ++x3) {
    blur3(T, S, x3, x3 + n, w);
  }
}
function blurfImage(radius2) {
  const blur3 = blurf(radius2);
  return (T, S, start2, stop, step) => {
    start2 <<= 2, stop <<= 2, step <<= 2;
    blur3(T, S, start2 + 0, stop + 0, step);
    blur3(T, S, start2 + 1, stop + 1, step);
    blur3(T, S, start2 + 2, stop + 2, step);
    blur3(T, S, start2 + 3, stop + 3, step);
  };
}
function blurf(radius2) {
  const radius0 = Math.floor(radius2);
  if (radius0 === radius2) return bluri(radius2);
  const t = radius2 - radius0;
  const w = 2 * radius2 + 1;
  return (T, S, start2, stop, step) => {
    if (!((stop -= step) >= start2)) return;
    let sum4 = radius0 * S[start2];
    const s0 = step * radius0;
    const s1 = s0 + step;
    for (let i = start2, j = start2 + s0; i < j; i += step) {
      sum4 += S[Math.min(stop, i)];
    }
    for (let i = start2, j = stop; i <= j; i += step) {
      sum4 += S[Math.min(stop, i + s0)];
      T[i] = (sum4 + t * (S[Math.max(start2, i - s1)] + S[Math.min(stop, i + s1)])) / w;
      sum4 -= S[Math.max(start2, i - s0)];
    }
  };
}
function bluri(radius2) {
  const w = 2 * radius2 + 1;
  return (T, S, start2, stop, step) => {
    if (!((stop -= step) >= start2)) return;
    let sum4 = radius2 * S[start2];
    const s2 = step * radius2;
    for (let i = start2, j = start2 + s2; i < j; i += step) {
      sum4 += S[Math.min(stop, i)];
    }
    for (let i = start2, j = stop; i <= j; i += step) {
      sum4 += S[Math.min(stop, i + s2)];
      T[i] = sum4 / w;
      sum4 -= S[Math.max(start2, i - s2)];
    }
  };
}

// ../../../node_modules/d3-array/src/count.js
function count2(values2, valueof2) {
  let count4 = 0;
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value != null && (value = +value) >= value) {
        ++count4;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (value = +value) >= value) {
        ++count4;
      }
    }
  }
  return count4;
}

// ../../../node_modules/d3-array/src/cross.js
function length2(array4) {
  return array4.length | 0;
}
function empty(length4) {
  return !(length4 > 0);
}
function arrayify(values2) {
  return typeof values2 !== "object" || "length" in values2 ? values2 : Array.from(values2);
}
function reducer(reduce) {
  return (values2) => reduce(...values2);
}
function cross(...values2) {
  const reduce = typeof values2[values2.length - 1] === "function" && reducer(values2.pop());
  values2 = values2.map(arrayify);
  const lengths = values2.map(length2);
  const j = values2.length - 1;
  const index2 = new Array(j + 1).fill(0);
  const product2 = [];
  if (j < 0 || lengths.some(empty)) return product2;
  while (true) {
    product2.push(index2.map((j2, i2) => values2[i2][j2]));
    let i = j;
    while (++index2[i] === lengths[i]) {
      if (i === 0) return reduce ? product2.map(reduce) : product2;
      index2[i--] = 0;
    }
  }
}

// ../../../node_modules/d3-array/src/cumsum.js
function cumsum(values2, valueof2) {
  var sum4 = 0, index2 = 0;
  return Float64Array.from(values2, valueof2 === void 0 ? (v2) => sum4 += +v2 || 0 : (v2) => sum4 += +valueof2(v2, index2++, values2) || 0);
}

// ../../../node_modules/d3-array/src/variance.js
function variance2(values2, valueof2) {
  let count4 = 0;
  let delta;
  let mean2 = 0;
  let sum4 = 0;
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value != null && (value = +value) >= value) {
        delta = value - mean2;
        mean2 += delta / ++count4;
        sum4 += delta * (value - mean2);
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (value = +value) >= value) {
        delta = value - mean2;
        mean2 += delta / ++count4;
        sum4 += delta * (value - mean2);
      }
    }
  }
  if (count4 > 1) return sum4 / (count4 - 1);
}

// ../../../node_modules/d3-array/src/deviation.js
function deviation(values2, valueof2) {
  const v2 = variance2(values2, valueof2);
  return v2 ? Math.sqrt(v2) : v2;
}

// ../../../node_modules/d3-array/src/extent.js
function extent(values2, valueof2) {
  let min5;
  let max4;
  if (valueof2 === void 0) {
    for (const value of values2) {
      if (value != null) {
        if (min5 === void 0) {
          if (value >= value) min5 = max4 = value;
        } else {
          if (min5 > value) min5 = value;
          if (max4 < value) max4 = value;
        }
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null) {
        if (min5 === void 0) {
          if (value >= value) min5 = max4 = value;
        } else {
          if (min5 > value) min5 = value;
          if (max4 < value) max4 = value;
        }
      }
    }
  }
  return [min5, max4];
}

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

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

// ../../../node_modules/d3-array/src/identity.js
function identity3(x3) {
  return x3;
}

// ../../../node_modules/d3-array/src/group.js
function group(values2, ...keys) {
  return nest(values2, identity3, identity3, keys);
}
function rollup(values2, reduce, ...keys) {
  return nest(values2, identity3, reduce, keys);
}
function rollups(values2, reduce, ...keys) {
  return nest(values2, Array.from, reduce, keys);
}
function nest(values2, map5, reduce, keys) {
  return (function regroup(values3, i) {
    if (i >= keys.length) return reduce(values3);
    const groups2 = new InternMap();
    const keyof3 = keys[i++];
    let index2 = -1;
    for (const value of values3) {
      const key = keyof3(value, ++index2, values3);
      const group3 = groups2.get(key);
      if (group3) group3.push(value);
      else groups2.set(key, [value]);
    }
    for (const [key, values4] of groups2) {
      groups2.set(key, regroup(values4, i));
    }
    return map5(groups2);
  })(values2, 0);
}

// ../../../node_modules/d3-array/src/permute.js
function permute(source, keys) {
  return Array.from(keys, (key) => source[key]);
}

// ../../../node_modules/d3-array/src/sort.js
function sort(values2, ...F) {
  if (typeof values2[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");
  values2 = Array.from(values2);
  let [f] = F;
  if (f && f.length !== 2 || F.length > 1) {
    const index2 = Uint32Array.from(values2, (d, i) => i);
    if (F.length > 1) {
      F = F.map((f2) => values2.map(f2));
      index2.sort((i, j) => {
        for (const f2 of F) {
          const c4 = ascendingDefined(f2[i], f2[j]);
          if (c4) return c4;
        }
      });
    } else {
      f = values2.map(f);
      index2.sort((i, j) => ascendingDefined(f[i], f[j]));
    }
    return permute(values2, index2);
  }
  return values2.sort(compareDefined(f));
}
function compareDefined(compare = ascending) {
  if (compare === ascending) return ascendingDefined;
  if (typeof compare !== "function") throw new TypeError("compare is not a function");
  return (a2, b) => {
    const x3 = compare(a2, b);
    if (x3 || x3 === 0) return x3;
    return (compare(b, b) === 0) - (compare(a2, a2) === 0);
  };
}
function ascendingDefined(a2, b) {
  return (a2 == null || !(a2 >= a2)) - (b == null || !(b >= b)) || (a2 < b ? -1 : a2 > b ? 1 : 0);
}

// ../../../node_modules/d3-array/src/groupSort.js
function groupSort(values2, reduce, key) {
  return (reduce.length !== 2 ? sort(rollup(values2, reduce, key), (([ak, av], [bk, bv]) => ascending(av, bv) || ascending(ak, bk))) : sort(group(values2, key), (([ak, av], [bk, bv]) => reduce(av, bv) || ascending(ak, bk)))).map(([key2]) => key2);
}

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

// ../../../node_modules/d3-array/src/nice.js
function nice(start2, stop, count4) {
  let prestep;
  while (true) {
    const step = tickIncrement(start2, stop, count4);
    if (step === prestep || step === 0 || !isFinite(step)) {
      return [start2, stop];
    } else if (step > 0) {
      start2 = Math.floor(start2 / step) * step;
      stop = Math.ceil(stop / step) * step;
    } else if (step < 0) {
      start2 = Math.ceil(start2 * step) / step;
      stop = Math.floor(stop * step) / step;
    }
    prestep = step;
  }
}

// ../../../node_modules/d3-array/src/threshold/sturges.js
function thresholdSturges(values2) {
  return Math.max(1, Math.ceil(Math.log(count2(values2)) / Math.LN2) + 1);
}

// ../../../node_modules/d3-array/src/max.js
function max2(values2, valueof2) {
  let max4;
  if (valueof2 === void 0) {
    for (const value of values2) {
      if (value != null && (max4 < value || max4 === void 0 && value >= value)) {
        max4 = value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (max4 < value || max4 === void 0 && value >= value)) {
        max4 = value;
      }
    }
  }
  return max4;
}

// ../../../node_modules/d3-array/src/maxIndex.js
function maxIndex(values2, valueof2) {
  let max4;
  let maxIndex2 = -1;
  let index2 = -1;
  if (valueof2 === void 0) {
    for (const value of values2) {
      ++index2;
      if (value != null && (max4 < value || max4 === void 0 && value >= value)) {
        max4 = value, maxIndex2 = index2;
      }
    }
  } else {
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (max4 < value || max4 === void 0 && value >= value)) {
        max4 = value, maxIndex2 = index2;
      }
    }
  }
  return maxIndex2;
}

// ../../../node_modules/d3-array/src/min.js
function min2(values2, valueof2) {
  let min5;
  if (valueof2 === void 0) {
    for (const value of values2) {
      if (value != null && (min5 > value || min5 === void 0 && value >= value)) {
        min5 = value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (min5 > value || min5 === void 0 && value >= value)) {
        min5 = value;
      }
    }
  }
  return min5;
}

// ../../../node_modules/d3-array/src/minIndex.js
function minIndex(values2, valueof2) {
  let min5;
  let minIndex2 = -1;
  let index2 = -1;
  if (valueof2 === void 0) {
    for (const value of values2) {
      ++index2;
      if (value != null && (min5 > value || min5 === void 0 && value >= value)) {
        min5 = value, minIndex2 = index2;
      }
    }
  } else {
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (min5 > value || min5 === void 0 && value >= value)) {
        min5 = value, minIndex2 = index2;
      }
    }
  }
  return minIndex2;
}

// ../../../node_modules/d3-array/src/quickselect.js
function quickselect(array4, k2, left2 = 0, right2 = Infinity, compare) {
  k2 = Math.floor(k2);
  left2 = Math.floor(Math.max(0, left2));
  right2 = Math.floor(Math.min(array4.length - 1, right2));
  if (!(left2 <= k2 && k2 <= right2)) return array4;
  compare = compare === void 0 ? ascendingDefined : compareDefined(compare);
  while (right2 > left2) {
    if (right2 - left2 > 600) {
      const n = right2 - left2 + 1;
      const m = k2 - left2 + 1;
      const z = Math.log(n);
      const s2 = 0.5 * Math.exp(2 * z / 3);
      const sd = 0.5 * Math.sqrt(z * s2 * (n - s2) / n) * (m - n / 2 < 0 ? -1 : 1);
      const newLeft = Math.max(left2, Math.floor(k2 - m * s2 / n + sd));
      const newRight = Math.min(right2, Math.floor(k2 + (n - m) * s2 / n + sd));
      quickselect(array4, k2, newLeft, newRight, compare);
    }
    const t = array4[k2];
    let i = left2;
    let j = right2;
    swap(array4, left2, k2);
    if (compare(array4[right2], t) > 0) swap(array4, left2, right2);
    while (i < j) {
      swap(array4, i, j), ++i, --j;
      while (compare(array4[i], t) < 0) ++i;
      while (compare(array4[j], t) > 0) --j;
    }
    if (compare(array4[left2], t) === 0) swap(array4, left2, j);
    else ++j, swap(array4, j, right2);
    if (j <= k2) left2 = j + 1;
    if (k2 <= j) right2 = j - 1;
  }
  return array4;
}
function swap(array4, i, j) {
  const t = array4[i];
  array4[i] = array4[j];
  array4[j] = t;
}

// ../../../node_modules/d3-array/src/greatest.js
function greatest2(values2, compare = ascending) {
  let max4;
  let defined2 = false;
  if (compare.length === 1) {
    let maxValue;
    for (const element of values2) {
      const value = compare(element);
      if (defined2 ? ascending(value, maxValue) > 0 : ascending(value, value) === 0) {
        max4 = element;
        maxValue = value;
        defined2 = true;
      }
    }
  } else {
    for (const value of values2) {
      if (defined2 ? compare(value, max4) > 0 : compare(value, value) === 0) {
        max4 = value;
        defined2 = true;
      }
    }
  }
  return max4;
}

// ../../../node_modules/d3-array/src/quantile.js
function quantile2(values2, p, valueof2) {
  values2 = Float64Array.from(numbers(values2, valueof2));
  if (!(n = values2.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return min2(values2);
  if (p >= 1) return max2(values2);
  var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = max2(quickselect(values2, i0).subarray(0, i0 + 1)), value1 = min2(values2.subarray(i0 + 1));
  return value0 + (value1 - value0) * (i - i0);
}
function quantileSorted(values2, p, valueof2 = number) {
  if (!(n = values2.length) || isNaN(p = +p)) return;
  if (p <= 0 || n < 2) return +valueof2(values2[0], 0, values2);
  if (p >= 1) return +valueof2(values2[n - 1], n - 1, values2);
  var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof2(values2[i0], i0, values2), value1 = +valueof2(values2[i0 + 1], i0 + 1, values2);
  return value0 + (value1 - value0) * (i - i0);
}

// ../../../node_modules/d3-array/src/threshold/freedmanDiaconis.js
function thresholdFreedmanDiaconis(values2, min5, max4) {
  const c4 = count2(values2), d = quantile2(values2, 0.75) - quantile2(values2, 0.25);
  return c4 && d ? Math.ceil((max4 - min5) / (2 * d * Math.pow(c4, -1 / 3))) : 1;
}

// ../../../node_modules/d3-array/src/threshold/scott.js
function thresholdScott(values2, min5, max4) {
  const c4 = count2(values2), d = deviation(values2);
  return c4 && d ? Math.ceil((max4 - min5) * Math.cbrt(c4) / (3.49 * d)) : 1;
}

// ../../../node_modules/d3-array/src/mean.js
function mean(values2, valueof2) {
  let count4 = 0;
  let sum4 = 0;
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value != null && (value = +value) >= value) {
        ++count4, sum4 += value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && (value = +value) >= value) {
        ++count4, sum4 += value;
      }
    }
  }
  if (count4) return sum4 / count4;
}

// ../../../node_modules/d3-array/src/median.js
function median2(values2, valueof2) {
  return quantile2(values2, 0.5, valueof2);
}

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

// ../../../node_modules/d3-array/src/mode.js
function mode2(values2, valueof2) {
  const counts = new InternMap();
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value != null && value >= value) {
        counts.set(value, (counts.get(value) || 0) + 1);
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if ((value = valueof2(value, ++index2, values2)) != null && value >= value) {
        counts.set(value, (counts.get(value) || 0) + 1);
      }
    }
  }
  let modeValue;
  let modeCount = 0;
  for (const [value, count4] of counts) {
    if (count4 > modeCount) {
      modeCount = count4;
      modeValue = value;
    }
  }
  return modeValue;
}

// ../../../node_modules/d3-array/src/pairs.js
function pairs2(values2, pairof = pair) {
  const pairs3 = [];
  let previous;
  let first3 = false;
  for (const value of values2) {
    if (first3) pairs3.push(pairof(previous, value));
    previous = value;
    first3 = true;
  }
  return pairs3;
}
function pair(a2, b) {
  return [a2, b];
}

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

// ../../../node_modules/d3-array/src/rank.js
function rank2(values2, valueof2 = ascending) {
  if (typeof values2[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");
  let V = Array.from(values2);
  const R = new Float64Array(V.length);
  if (valueof2.length !== 2) V = V.map(valueof2), valueof2 = ascending;
  const compareIndex = (i, j) => valueof2(V[i], V[j]);
  let k2, r;
  values2 = Uint32Array.from(V, (_, i) => i);
  values2.sort(valueof2 === ascending ? (i, j) => ascendingDefined(V[i], V[j]) : compareDefined(compareIndex));
  values2.forEach((j, i) => {
    const c4 = compareIndex(j, k2 === void 0 ? j : k2);
    if (c4 >= 0) {
      if (k2 === void 0 || c4 > 0) k2 = j, r = i;
      R[j] = r;
    } else {
      R[j] = NaN;
    }
  });
  return R;
}

// ../../../node_modules/d3-array/src/least.js
function least2(values2, compare = ascending) {
  let min5;
  let defined2 = false;
  if (compare.length === 1) {
    let minValue;
    for (const element of values2) {
      const value = compare(element);
      if (defined2 ? ascending(value, minValue) < 0 : ascending(value, value) === 0) {
        min5 = element;
        minValue = value;
        defined2 = true;
      }
    }
  } else {
    for (const value of values2) {
      if (defined2 ? compare(value, min5) < 0 : compare(value, value) === 0) {
        min5 = value;
        defined2 = true;
      }
    }
  }
  return min5;
}

// ../../../node_modules/d3-array/src/sum.js
function sum2(values2, valueof2) {
  let sum4 = 0;
  if (valueof2 === void 0) {
    for (let value of values2) {
      if (value = +value) {
        sum4 += value;
      }
    }
  } else {
    let index2 = -1;
    for (let value of values2) {
      if (value = +valueof2(value, ++index2, values2)) {
        sum4 += value;
      }
    }
  }
  return sum4;
}

// ../../../node_modules/d3-array/src/reverse.js
function reverse(values2) {
  if (typeof values2[Symbol.iterator] !== "function") throw new TypeError("values is not iterable");
  return Array.from(values2).reverse();
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ../../../node_modules/d3-selection/src/sourceEvent.js
function sourceEvent_default(event) {
  let sourceEvent;
  while (sourceEvent = event.sourceEvent) event = sourceEvent;
  return event;
}

// ../../../node_modules/d3-selection/src/pointer.js
function pointer_default(event, node) {
  event = sourceEvent_default(event);
  if (node === void 0) node = event.currentTarget;
  if (node) {
    var svg = node.ownerSVGElement || node;
    if (svg.createSVGPoint) {
      var point6 = svg.createSVGPoint();
      point6.x = event.clientX, point6.y = event.clientY;
      point6 = point6.matrixTransform(node.getScreenCTM().inverse());
      return [point6.x, point6.y];
    }
    if (node.getBoundingClientRect) {
      var rect3 = node.getBoundingClientRect();
      return [event.clientX - rect3.left - node.clientLeft, event.clientY - rect3.top - node.clientTop];
    }
  }
  return [event.pageX, event.pageY];
}

// ../../../node_modules/d3-drag/src/noevent.js
var nonpassivecapture = { capture: true, passive: false };
function noevent_default(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
}

// ../../../node_modules/d3-drag/src/nodrag.js
function nodrag_default(view) {
  var root2 = view.document.documentElement, selection2 = select_default2(view).on("dragstart.drag", noevent_default, nonpassivecapture);
  if ("onselectstart" in root2) {
    selection2.on("selectstart.drag", noevent_default, nonpassivecapture);
  } else {
    root2.__noselect = root2.style.MozUserSelect;
    root2.style.MozUserSelect = "none";
  }
}
function yesdrag(view, noclick) {
  var root2 = view.document.documentElement, selection2 = select_default2(view).on("dragstart.drag", null);
  if (noclick) {
    selection2.on("click.drag", noevent_default, nonpassivecapture);
    setTimeout(function() {
      selection2.on("click.drag", null);
    }, 0);
  }
  if ("onselectstart" in root2) {
    selection2.on("selectstart.drag", null);
  } else {
    root2.style.MozUserSelect = root2.__noselect;
    delete root2.__noselect;
  }
}

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

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

// ../../../node_modules/d3-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 t0 = 4 / 29;
var t1 = 6 / 29;
var t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1;
function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) return hcl2lab(o);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y3 = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x3, z;
  if (r === g && g === b) x3 = z = y3;
  else {
    x3 = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y3 - 16, 500 * (x3 - y3), 200 * (y3 - z), o.opacity);
}
function lab(l, a2, b, opacity2) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a2, b, opacity2 == null ? 1 : opacity2);
}
function Lab(l, a2, b, opacity2) {
  this.l = +l;
  this.a = +a2;
  this.b = +b;
  this.opacity = +opacity2;
}
define_default(Lab, lab, extend(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 y3 = (this.l + 16) / 116, x3 = isNaN(this.a) ? y3 : y3 + this.a / 500, z = isNaN(this.b) ? y3 : y3 - this.b / 200;
    x3 = Xn * lab2xyz(x3);
    y3 = Yn * lab2xyz(y3);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb(3.1338561 * x3 - 1.6168667 * y3 - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x3 + 1.9161415 * y3 + 0.033454 * z),
      lrgb2rgb(0.0719453 * x3 - 0.2289914 * y3 + 1.4052427 * z),
      this.opacity
    );
  }
}));
function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}
function lrgb2rgb(x3) {
  return 255 * (x3 <= 31308e-7 ? 12.92 * x3 : 1.055 * Math.pow(x3, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x3) {
  return (x3 /= 255) <= 0.04045 ? x3 / 12.92 : Math.pow((x3 + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * degrees;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c4, l, opacity2) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c4, l, opacity2 == null ? 1 : opacity2);
}
function Hcl(h, c4, l, opacity2) {
  this.h = +h;
  this.c = +c4;
  this.l = +l;
  this.opacity = +opacity2;
}
function hcl2lab(o) {
  if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
  var h = o.h * radians;
  return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define_default(Hcl, hcl, extend(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(o) {
  if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k2 = (E * (g - l) - C * bl) / D, s2 = Math.sqrt(k2 * k2 + bl * bl) / (E * l * (1 - l)), h = s2 ? Math.atan2(k2, bl) * degrees - 120 : NaN;
  return new Cubehelix(h < 0 ? h + 360 : h, s2, l, o.opacity);
}
function cubehelix(h, s2, l, opacity2) {
  return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s2, l, opacity2 == null ? 1 : opacity2);
}
function Cubehelix(h, s2, l, opacity2) {
  this.h = +h;
  this.s = +s2;
  this.l = +l;
  this.opacity = +opacity2;
}
define_default(Cubehelix, cubehelix, extend(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 h = isNaN(this.h) ? 0 : (this.h + 120) * radians, l = +this.l, a2 = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh2 = Math.cos(h), sinh2 = Math.sin(h);
    return new Rgb(
      255 * (l + a2 * (A * cosh2 + B * sinh2)),
      255 * (l + a2 * (C * cosh2 + D * sinh2)),
      255 * (l + a2 * (E * cosh2)),
      this.opacity
    );
  }
}));

// ../../../node_modules/d3-interpolate/src/basis.js
function basis(t13, v0, v1, v2, 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) * v2 + t32 * v3) / 6;
}
function basis_default(values2) {
  var n = values2.length - 1;
  return function(t) {
    var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values2[i], v2 = values2[i + 1], v0 = i > 0 ? values2[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values2[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

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

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

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

// ../../../node_modules/d3-interpolate/src/rgb.js
var rgb_default = (function rgbGamma(y3) {
  var color3 = gamma(y3);
  function rgb2(start2, end) {
    var r = color3((start2 = rgb(start2)).r, (end = rgb(end)).r), g = color3(start2.g, end.g), b = color3(start2.b, end.b), opacity2 = nogamma(start2.opacity, end.opacity);
    return function(t) {
      start2.r = r(t);
      start2.g = g(t);
      start2.b = b(t);
      start2.opacity = opacity2(t);
      return start2 + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
})(1);
function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color3;
    for (i = 0; i < n; ++i) {
      color3 = rgb(colors[i]);
      r[i] = color3.r || 0;
      g[i] = color3.g || 0;
      b[i] = color3.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color3.opacity = 1;
    return function(t) {
      color3.r = r(t);
      color3.g = g(t);
      color3.b = b(t);
      return color3 + "";
    };
  };
}
var rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

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

// ../../../node_modules/d3-interpolate/src/array.js
function genericArray(a2, b) {
  var nb = b ? b.length : 0, na = a2 ? Math.min(nb, a2.length) : 0, x3 = new Array(na), c4 = new Array(nb), i;
  for (i = 0; i < na; ++i) x3[i] = value_default(a2[i], b[i]);
  for (; i < nb; ++i) c4[i] = b[i];
  return function(t) {
    for (i = 0; i < na; ++i) c4[i] = x3[i](t);
    return c4;
  };
}

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

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

// ../../../node_modules/d3-interpolate/src/object.js
function object_default(a2, b) {
  var i = {}, c4 = {}, k2;
  if (a2 === null || typeof a2 !== "object") a2 = {};
  if (b === null || typeof b !== "object") b = {};
  for (k2 in b) {
    if (k2 in a2) {
      i[k2] = value_default(a2[k2], b[k2]);
    } else {
      c4[k2] = b[k2];
    }
  }
  return function(t) {
    for (k2 in i) c4[k2] = i[k2](t);
    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 zero2(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t) {
    return b(t) + "";
  };
}
function string_default(a2, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s2 = [], q = [];
  a2 = a2 + "", b = b + "";
  while ((am = reA.exec(a2)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s2[i]) s2[i] += bs;
      else s2[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s2[i]) s2[i] += bm;
      else s2[++i] = bm;
    } else {
      s2[++i] = null;
      q.push({ i, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s2[i]) s2[i] += bs;
    else s2[++i] = bs;
  }
  return s2.length < 2 ? q[0] ? one(q[0].x) : zero2(b) : (b = q.length, function(t) {
    for (var i2 = 0, o; i2 < b; ++i2) s2[(o = q[i2]).i] = o.x(t);
    return s2.join("");
  });
}

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

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

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

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

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

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

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

// ../../../node_modules/d3-interpolate/src/lab.js
function lab2(start2, end) {
  var l = nogamma((start2 = lab(start2)).l, (end = lab(end)).l), a2 = nogamma(start2.a, end.a), b = nogamma(start2.b, end.b), opacity2 = nogamma(start2.opacity, end.opacity);
  return function(t) {
    start2.l = l(t);
    start2.a = a2(t);
    start2.b = b(t);
    start2.opacity = opacity2(t);
    return start2 + "";
  };
}

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

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

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

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

// ../../../node_modules/d3-timer/src/timer.js
var frame = 0;
var timeout = 0;
var interval3 = 0;
var pokeDelay = 1e3;
var taskHead;
var taskTail;
var clockLast = 0;
var clockNow = 0;
var clockSkew = 0;
var clock = typeof performance === "object" && performance.now ? performance : Date;
var setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) {
  setTimeout(f, 17);
};
function 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 t = new Timer();
  t.restart(callback, delay, time3);
  return t;
}
function timerFlush() {
  now();
  ++frame;
  var t = taskHead, e;
  while (t) {
    if ((e = clockNow - t._time) >= 0) t._call.call(void 0, e);
    t = t._next;
  }
  --frame;
}
function wake() {
  clockNow = (clockLast = clock.now()) + clockSkew;
  frame = timeout = 0;
  try {
    timerFlush();
  } finally {
    frame = 0;
    nap();
    clockNow = 0;
  }
}
function poke() {
  var now2 = clock.now(), delay = now2 - clockLast;
  if (delay > pokeDelay) clockSkew -= delay, clockLast = now2;
}
function nap() {
  var t03, t13 = taskHead, t22, time3 = Infinity;
  while (t13) {
    if (t13._call) {
      if (time3 > t13._time) time3 = t13._time;
      t03 = t13, t13 = t13._next;
    } else {
      t22 = t13._next, t13._next = null;
      t13 = t03 ? t03._next = t22 : taskHead = t22;
    }
  }
  taskTail = t03;
  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 (interval3) interval3 = clearInterval(interval3);
  } else {
    if (!interval3) clockLast = clock.now(), interval3 = setInterval(poke, pokeDelay);
    frame = 1, setFrame(wake);
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ../../../node_modules/d3-transition/src/transition/selectAll.js
function selectAll_default2(select2) {
  var name2 = this._name, id2 = this._id;
  if (typeof select2 !== "function") select2 = selectorAll_default(select2);
  for (var groups2 = this._groups, m = groups2.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group3 = groups2[j], n = group3.length, node, i = 0; i < n; ++i) {
      if (node = group3[i]) {
        for (var children2 = select2.call(node, node.__data__, i, group3), child, inherit3 = get2(node, id2), k2 = 0, l = children2.length; k2 < l; ++k2) {
          if (child = children2[k2]) {
            schedule_default(child, name2, id2, k2, children2, inherit3);
          }
        }
        subgroups.push(children2);
        parents.push(node);
      }
    }
  }
  return new Transition(subgroups, parents, name2, id2);
}

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

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

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

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

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

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

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

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

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

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

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

// ../../../node_modules/d3-brush/src/constant.js
var constant_default3 = (x3) => () => x3;

// ../../../node_modules/d3-brush/src/event.js
function BrushEvent(type2, {
  sourceEvent,
  target,
  selection: selection2,
  mode: mode3,
  dispatch: dispatch2
}) {
  Object.defineProperties(this, {
    type: { value: type2, enumerable: true, configurable: true },
    sourceEvent: { value: sourceEvent, enumerable: true, configurable: true },
    target: { value: target, enumerable: true, configurable: true },
    selection: { value: selection2, enumerable: true, configurable: true },
    mode: { value: mode3, enumerable: true, configurable: true },
    _: { value: dispatch2 }
  });
}

// ../../../node_modules/d3-brush/src/noevent.js
function nopropagation(event) {
  event.stopImmediatePropagation();
}
function noevent_default2(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
}

// ../../../node_modules/d3-brush/src/brush.js
var MODE_DRAG = { name: "drag" };
var MODE_SPACE = { name: "space" };
var MODE_HANDLE = { name: "handle" };
var MODE_CENTER = { name: "center" };
var { abs: abs2, max: max3, min: min3 } = Math;
function number1(e) {
  return [+e[0], +e[1]];
}
function number22(e) {
  return [number1(e[0]), number1(e[1])];
}
var X = {
  name: "x",
  handles: ["w", "e"].map(type),
  input: function(x3, e) {
    return x3 == null ? null : [[+x3[0], e[0][1]], [+x3[1], e[1][1]]];
  },
  output: function(xy) {
    return xy && [xy[0][0], xy[1][0]];
  }
};
var Y = {
  name: "y",
  handles: ["n", "s"].map(type),
  input: function(y3, e) {
    return y3 == null ? null : [[e[0][0], +y3[0]], [e[1][0], +y3[1]]];
  },
  output: function(xy) {
    return xy && [xy[0][1], xy[1][1]];
  }
};
var XY = {
  name: "xy",
  handles: ["n", "w", "e", "s", "nw", "ne", "sw", "se"].map(type),
  input: function(xy) {
    return xy == null ? null : number22(xy);
  },
  output: function(xy) {
    return xy;
  }
};
var cursors = {
  overlay: "crosshair",
  selection: "move",
  n: "ns-resize",
  e: "ew-resize",
  s: "ns-resize",
  w: "ew-resize",
  nw: "nwse-resize",
  ne: "nesw-resize",
  se: "nwse-resize",
  sw: "nesw-resize"
};
var flipX = {
  e: "w",
  w: "e",
  nw: "ne",
  ne: "nw",
  se: "sw",
  sw: "se"
};
var flipY = {
  n: "s",
  s: "n",
  nw: "sw",
  ne: "se",
  se: "ne",
  sw: "nw"
};
var signsX = {
  overlay: 1,
  selection: 1,
  n: null,
  e: 1,
  s: null,
  w: -1,
  nw: -1,
  ne: 1,
  se: 1,
  sw: -1
};
var signsY = {
  overlay: 1,
  selection: 1,
  n: -1,
  e: null,
  s: 1,
  w: null,
  nw: -1,
  ne: -1,
  se: 1,
  sw: 1
};
function type(t) {
  return { type: t };
}
function defaultFilter(event) {
  return !event.ctrlKey && !event.button;
}
function defaultExtent() {
  var svg = this.ownerSVGElement || this;
  if (svg.hasAttribute("viewBox")) {
    svg = svg.viewBox.baseVal;
    return [[svg.x, svg.y], [svg.x + svg.width, svg.y + svg.height]];
  }
  return [[0, 0], [svg.width.baseVal.value, svg.height.baseVal.value]];
}
function defaultTouchable() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function local(node) {
  while (!node.__brush) if (!(node = node.parentNode)) return;
  return node.__brush;
}
function empty3(extent4) {
  return extent4[0][0] === extent4[1][0] || extent4[0][1] === extent4[1][1];
}
function brushX() {
  return brush(X);
}
function brushY() {
  return brush(Y);
}
function brush_default() {
  return brush(XY);
}
function brush(dim) {
  var extent4 = defaultExtent, filter3 = defaultFilter, touchable = defaultTouchable, keys = true, listeners = dispatch_default("start", "brush", "end"), handleSize = 6, touchending;
  function brush3(group3) {
    var overlay = group3.property("__brush", initialize).selectAll(".overlay").data([type("overlay")]);
    overlay.enter().append("rect").attr("class", "overlay").attr("pointer-events", "all").attr("cursor", cursors.overlay).merge(overlay).each(function() {
      var extent5 = local(this).extent;
      select_default2(this).attr("x", extent5[0][0]).attr("y", extent5[0][1]).attr("width", extent5[1][0] - extent5[0][0]).attr("height", extent5[1][1] - extent5[0][1]);
    });
    group3.selectAll(".selection").data([type("selection")]).enter().append("rect").attr("class", "selection").attr("cursor", cursors.selection).attr("fill", "#777").attr("fill-opacity", 0.3).attr("stroke", "#fff").attr("shape-rendering", "crispEdges");
    var handle = group3.selectAll(".handle").data(dim.handles, function(d) {
      return d.type;
    });
    handle.exit().remove();
    handle.enter().append("rect").attr("class", function(d) {
      return "handle handle--" + d.type;
    }).attr("cursor", function(d) {
      return cursors[d.type];
    });
    group3.each(redraw).attr("fill", "none").attr("pointer-events", "all").on("mousedown.brush", started).filter(touchable).on("touchstart.brush", started).on("touchmove.brush", touchmoved).on("touchend.brush touchcancel.brush", touchended).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  brush3.move = function(group3, selection2, event) {
    if (group3.tween) {
      group3.on("start.brush", function(event2) {
        emitter(this, arguments).beforestart().start(event2);
      }).on("interrupt.brush end.brush", function(event2) {
        emitter(this, arguments).end(event2);
      }).tween("brush", function() {
        var that = this, state = that.__brush, emit = emitter(that, arguments), selection0 = state.selection, selection1 = dim.input(typeof selection2 === "function" ? selection2.apply(this, arguments) : selection2, state.extent), i = value_default(selection0, selection1);
        function tween(t) {
          state.selection = t === 1 && selection1 === null ? null : i(t);
          redraw.call(that);
          emit.brush();
        }
        return selection0 !== null && selection1 !== null ? tween : tween(1);
      });
    } else {
      group3.each(function() {
        var that = this, args = arguments, state = that.__brush, selection1 = dim.input(typeof selection2 === "function" ? selection2.apply(that, args) : selection2, state.extent), emit = emitter(that, args).beforestart();
        interrupt_default(that);
        state.selection = selection1 === null ? null : selection1;
        redraw.call(that);
        emit.start(event).brush(event).end(event);
      });
    }
  };
  brush3.clear = function(group3, event) {
    brush3.move(group3, null, event);
  };
  function redraw() {
    var group3 = select_default2(this), selection2 = local(this).selection;
    if (selection2) {
      group3.selectAll(".selection").style("display", null).attr("x", selection2[0][0]).attr("y", selection2[0][1]).attr("width", selection2[1][0] - selection2[0][0]).attr("height", selection2[1][1] - selection2[0][1]);
      group3.selectAll(".handle").style("display", null).attr("x", function(d) {
        return d.type[d.type.length - 1] === "e" ? selection2[1][0] - handleSize / 2 : selection2[0][0] - handleSize / 2;
      }).attr("y", function(d) {
        return d.type[0] === "s" ? selection2[1][1] - handleSize / 2 : selection2[0][1] - handleSize / 2;
      }).attr("width", function(d) {
        return d.type === "n" || d.type === "s" ? selection2[1][0] - selection2[0][0] + handleSize : handleSize;
      }).attr("height", function(d) {
        return d.type === "e" || d.type === "w" ? selection2[1][1] - selection2[0][1] + handleSize : handleSize;
      });
    } else {
      group3.selectAll(".selection,.handle").style("display", "none").attr("x", null).attr("y", null).attr("width", null).attr("height", null);
    }
  }
  function emitter(that, args, clean) {
    var emit = that.__brush.emitter;
    return emit && (!clean || !emit.clean) ? emit : new Emitter(that, args, clean);
  }
  function Emitter(that, args, clean) {
    this.that = that;
    this.args = args;
    this.state = that.__brush;
    this.active = 0;
    this.clean = clean;
  }
  Emitter.prototype = {
    beforestart: function() {
      if (++this.active === 1) this.state.emitter = this, this.starting = true;
      return this;
    },
    start: function(event, mode3) {
      if (this.starting) this.starting = false, this.emit("start", event, mode3);
      else this.emit("brush", event);
      return this;
    },
    brush: function(event, mode3) {
      this.emit("brush", event, mode3);
      return this;
    },
    end: function(event, mode3) {
      if (--this.active === 0) delete this.state.emitter, this.emit("end", event, mode3);
      return this;
    },
    emit: function(type2, event, mode3) {
      var d = select_default2(this.that).datum();
      listeners.call(
        type2,
        this.that,
        new BrushEvent(type2, {
          sourceEvent: event,
          target: brush3,
          selection: dim.output(this.state.selection),
          mode: mode3,
          dispatch: listeners
        }),
        d
      );
    }
  };
  function started(event) {
    if (touchending && !event.touches) return;
    if (!filter3.apply(this, arguments)) return;
    var that = this, type2 = event.target.__data__.type, mode3 = (keys && event.metaKey ? type2 = "overlay" : type2) === "selection" ? MODE_DRAG : keys && event.altKey ? MODE_CENTER : MODE_HANDLE, signX = dim === Y ? null : signsX[type2], signY = dim === X ? null : signsY[type2], state = local(that), extent5 = state.extent, selection2 = state.selection, W = extent5[0][0], w0, w1, N = extent5[0][1], n0, n1, E2 = extent5[1][0], e0, e1, S = extent5[1][1], s0, s1, dx = 0, dy = 0, moving, shifting = signX && signY && keys && event.shiftKey, lockX, lockY, points2 = Array.from(event.touches || [event], (t) => {
      const i = t.identifier;
      t = pointer_default(t, that);
      t.point0 = t.slice();
      t.identifier = i;
      return t;
    });
    interrupt_default(that);
    var emit = emitter(that, arguments, true).beforestart();
    if (type2 === "overlay") {
      if (selection2) moving = true;
      const pts = [points2[0], points2[1] || points2[0]];
      state.selection = selection2 = [[
        w0 = dim === Y ? W : min3(pts[0][0], pts[1][0]),
        n0 = dim === X ? N : min3(pts[0][1], pts[1][1])
      ], [
        e0 = dim === Y ? E2 : max3(pts[0][0], pts[1][0]),
        s0 = dim === X ? S : max3(pts[0][1], pts[1][1])
      ]];
      if (points2.length > 1) move(event);
    } else {
      w0 = selection2[0][0];
      n0 = selection2[0][1];
      e0 = selection2[1][0];
      s0 = selection2[1][1];
    }
    w1 = w0;
    n1 = n0;
    e1 = e0;
    s1 = s0;
    var group3 = select_default2(that).attr("pointer-events", "none");
    var overlay = group3.selectAll(".overlay").attr("cursor", cursors[type2]);
    if (event.touches) {
      emit.moved = moved;
      emit.ended = ended;
    } else {
      var view = select_default2(event.view).on("mousemove.brush", moved, true).on("mouseup.brush", ended, true);
      if (keys) view.on("keydown.brush", keydowned, true).on("keyup.brush", keyupped, true);
      nodrag_default(event.view);
    }
    redraw.call(that);
    emit.start(event, mode3.name);
    function moved(event2) {
      for (const p of event2.changedTouches || [event2]) {
        for (const d of points2)
          if (d.identifier === p.identifier) d.cur = pointer_default(p, that);
      }
      if (shifting && !lockX && !lockY && points2.length === 1) {
        const point6 = points2[0];
        if (abs2(point6.cur[0] - point6[0]) > abs2(point6.cur[1] - point6[1]))
          lockY = true;
        else
          lockX = true;
      }
      for (const point6 of points2)
        if (point6.cur) point6[0] = point6.cur[0], point6[1] = point6.cur[1];
      moving = true;
      noevent_default2(event2);
      move(event2);
    }
    function move(event2) {
      const point6 = points2[0], point0 = point6.point0;
      var t;
      dx = point6[0] - point0[0];
      dy = point6[1] - point0[1];
      switch (mode3) {
        case MODE_SPACE:
        case MODE_DRAG: {
          if (signX) dx = max3(W - w0, min3(E2 - e0, dx)), w1 = w0 + dx, e1 = e0 + dx;
          if (signY) dy = max3(N - n0, min3(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy;
          break;
        }
        case MODE_HANDLE: {
          if (points2[1]) {
            if (signX) w1 = max3(W, min3(E2, points2[0][0])), e1 = max3(W, min3(E2, points2[1][0])), signX = 1;
            if (signY) n1 = max3(N, min3(S, points2[0][1])), s1 = max3(N, min3(S, points2[1][1])), signY = 1;
          } else {
            if (signX < 0) dx = max3(W - w0, min3(E2 - w0, dx)), w1 = w0 + dx, e1 = e0;
            else if (signX > 0) dx = max3(W - e0, min3(E2 - e0, dx)), w1 = w0, e1 = e0 + dx;
            if (signY < 0) dy = max3(N - n0, min3(S - n0, dy)), n1 = n0 + dy, s1 = s0;
            else if (signY > 0) dy = max3(N - s0, min3(S - s0, dy)), n1 = n0, s1 = s0 + dy;
          }
          break;
        }
        case MODE_CENTER: {
          if (signX) w1 = max3(W, min3(E2, w0 - dx * signX)), e1 = max3(W, min3(E2, e0 + dx * signX));
          if (signY) n1 = max3(N, min3(S, n0 - dy * signY)), s1 = max3(N, min3(S, s0 + dy * signY));
          break;
        }
      }
      if (e1 < w1) {
        signX *= -1;
        t = w0, w0 = e0, e0 = t;
        t = w1, w1 = e1, e1 = t;
        if (type2 in flipX) overlay.attr("cursor", cursors[type2 = flipX[type2]]);
      }
      if (s1 < n1) {
        signY *= -1;
        t = n0, n0 = s0, s0 = t;
        t = n1, n1 = s1, s1 = t;
        if (type2 in flipY) overlay.attr("cursor", cursors[type2 = flipY[type2]]);
      }
      if (state.selection) selection2 = state.selection;
      if (lockX) w1 = selection2[0][0], e1 = selection2[1][0];
      if (lockY) n1 = selection2[0][1], s1 = selection2[1][1];
      if (selection2[0][0] !== w1 || selection2[0][1] !== n1 || selection2[1][0] !== e1 || selection2[1][1] !== s1) {
        state.selection = [[w1, n1], [e1, s1]];
        redraw.call(that);
        emit.brush(event2, mode3.name);
      }
    }
    function ended(event2) {
      nopropagation(event2);
      if (event2.touches) {
        if (event2.touches.length) return;
        if (touchending) clearTimeout(touchending);
        touchending = setTimeout(function() {
          touchending = null;
        }, 500);
      } else {
        yesdrag(event2.view, moving);
        view.on("keydown.brush keyup.brush mousemove.brush mouseup.brush", null);
      }
      group3.attr("pointer-events", "all");
      overlay.attr("cursor", cursors.overlay);
      if (state.selection) selection2 = state.selection;
      if (empty3(selection2)) state.selection = null, redraw.call(that);
      emit.end(event2, mode3.name);
    }
    function keydowned(event2) {
      switch (event2.keyCode) {
        case 16: {
          shifting = signX && signY;
          break;
        }
        case 18: {
          if (mode3 === MODE_HANDLE) {
            if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
            if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
            mode3 = MODE_CENTER;
            move(event2);
          }
          break;
        }
        case 32: {
          if (mode3 === MODE_HANDLE || mode3 === MODE_CENTER) {
            if (signX < 0) e0 = e1 - dx;
            else if (signX > 0) w0 = w1 - dx;
            if (signY < 0) s0 = s1 - dy;
            else if (signY > 0) n0 = n1 - dy;
            mode3 = MODE_SPACE;
            overlay.attr("cursor", cursors.selection);
            move(event2);
          }
          break;
        }
        default:
          return;
      }
      noevent_default2(event2);
    }
    function keyupped(event2) {
      switch (event2.keyCode) {
        case 16: {
          if (shifting) {
            lockX = lockY = shifting = false;
            move(event2);
          }
          break;
        }
        case 18: {
          if (mode3 === MODE_CENTER) {
            if (signX < 0) e0 = e1;
            else if (signX > 0) w0 = w1;
            if (signY < 0) s0 = s1;
            else if (signY > 0) n0 = n1;
            mode3 = MODE_HANDLE;
            move(event2);
          }
          break;
        }
        case 32: {
          if (mode3 === MODE_SPACE) {
            if (event2.altKey) {
              if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;
              if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;
              mode3 = MODE_CENTER;
            } else {
              if (signX < 0) e0 = e1;
              else if (signX > 0) w0 = w1;
              if (signY < 0) s0 = s1;
              else if (signY > 0) n0 = n1;
              mode3 = MODE_HANDLE;
            }
            overlay.attr("cursor", cursors[type2]);
            move(event2);
          }
          break;
        }
        default:
          return;
      }
      noevent_default2(event2);
    }
  }
  function touchmoved(event) {
    emitter(this, arguments).moved(event);
  }
  function touchended(event) {
    emitter(this, arguments).ended(event);
  }
  function initialize() {
    var state = this.__brush || { selection: null };
    state.extent = number22(extent4.apply(this, arguments));
    state.dim = dim;
    return state;
  }
  brush3.extent = function(_) {
    return arguments.length ? (extent4 = typeof _ === "function" ? _ : constant_default3(number22(_)), brush3) : extent4;
  };
  brush3.filter = function(_) {
    return arguments.length ? (filter3 = typeof _ === "function" ? _ : constant_default3(!!_), brush3) : filter3;
  };
  brush3.touchable = function(_) {
    return arguments.length ? (touchable = typeof _ === "function" ? _ : constant_default3(!!_), brush3) : touchable;
  };
  brush3.handleSize = function(_) {
    return arguments.length ? (handleSize = +_, brush3) : handleSize;
  };
  brush3.keyModifiers = function(_) {
    return arguments.length ? (keys = !!_, brush3) : keys;
  };
  brush3.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? brush3 : value;
  };
  return brush3;
}

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

// ../../../node_modules/d3-contour/src/array.js
var array2 = Array.prototype;
var slice = array2.slice;

// ../../../node_modules/d3-contour/src/ascending.js
function ascending_default(a2, b) {
  return a2 - b;
}

// ../../../node_modules/d3-contour/src/area.js
function area_default(ring) {
  var i = 0, n = ring.length, area3 = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
  while (++i < n) area3 += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
  return area3;
}

// ../../../node_modules/d3-contour/src/constant.js
var constant_default4 = (x3) => () => x3;

// ../../../node_modules/d3-contour/src/contains.js
function contains_default(ring, hole) {
  var i = -1, n = hole.length, c4;
  while (++i < n) if (c4 = ringContains(ring, hole[i])) return c4;
  return 0;
}
function ringContains(ring, point6) {
  var x3 = point6[0], y3 = point6[1], contains2 = -1;
  for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
    var pi5 = ring[i], xi = pi5[0], yi = pi5[1], pj = ring[j], xj = pj[0], yj = pj[1];
    if (segmentContains(pi5, pj, point6)) return 0;
    if (yi > y3 !== yj > y3 && x3 < (xj - xi) * (y3 - yi) / (yj - yi) + xi) contains2 = -contains2;
  }
  return contains2;
}
function segmentContains(a2, b, c4) {
  var i;
  return collinear(a2, b, c4) && within(a2[i = +(a2[0] === b[0])], c4[i], b[i]);
}
function collinear(a2, b, c4) {
  return (b[0] - a2[0]) * (c4[1] - a2[1]) === (c4[0] - a2[0]) * (b[1] - a2[1]);
}
function within(p, q, r) {
  return p <= q && q <= r || r <= q && q <= p;
}

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

// ../../../node_modules/d3-contour/src/contours.js
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_default() {
  var dx = 1, dy = 1, threshold2 = thresholdSturges, smooth = smoothLinear;
  function contours(values2) {
    var tz = threshold2(values2);
    if (!Array.isArray(tz)) {
      const e = extent(values2, finite);
      tz = ticks(...nice(e[0], e[1], tz), tz);
      while (tz[tz.length - 1] >= e[1]) tz.pop();
      while (tz[1] < e[0]) tz.shift();
    } else {
      tz = tz.slice().sort(ascending_default);
    }
    return tz.map((value) => contour3(values2, value));
  }
  function contour3(values2, value) {
    const v2 = value == null ? NaN : +value;
    if (isNaN(v2)) throw new Error(`invalid value: ${value}`);
    var polygons = [], holes = [];
    isorings(values2, v2, function(ring) {
      smooth(ring, values2, v2);
      if (area_default(ring) > 0) polygons.push([ring]);
      else holes.push(ring);
    });
    holes.forEach(function(hole) {
      for (var i = 0, n = polygons.length, polygon; i < n; ++i) {
        if (contains_default((polygon = polygons[i])[0], hole) !== -1) {
          polygon.push(hole);
          return;
        }
      }
    });
    return {
      type: "MultiPolygon",
      value,
      coordinates: polygons
    };
  }
  function isorings(values2, value, callback) {
    var fragmentByStart = new Array(), fragmentByEnd = new Array(), x3, y3, t03, t13, t22, t32;
    x3 = y3 = -1;
    t13 = above(values2[0], value);
    cases[t13 << 1].forEach(stitch);
    while (++x3 < dx - 1) {
      t03 = t13, t13 = above(values2[x3 + 1], value);
      cases[t03 | t13 << 1].forEach(stitch);
    }
    cases[t13 << 0].forEach(stitch);
    while (++y3 < dy - 1) {
      x3 = -1;
      t13 = above(values2[y3 * dx + dx], value);
      t22 = above(values2[y3 * dx], value);
      cases[t13 << 1 | t22 << 2].forEach(stitch);
      while (++x3 < dx - 1) {
        t03 = t13, t13 = above(values2[y3 * dx + dx + x3 + 1], value);
        t32 = t22, t22 = above(values2[y3 * dx + x3 + 1], value);
        cases[t03 | t13 << 1 | t22 << 2 | t32 << 3].forEach(stitch);
      }
      cases[t13 | t22 << 3].forEach(stitch);
    }
    x3 = -1;
    t22 = values2[y3 * dx] >= value;
    cases[t22 << 2].forEach(stitch);
    while (++x3 < dx - 1) {
      t32 = t22, t22 = above(values2[y3 * dx + x3 + 1], value);
      cases[t22 << 2 | t32 << 3].forEach(stitch);
    }
    cases[t22 << 3].forEach(stitch);
    function stitch(line3) {
      var start2 = [line3[0][0] + x3, line3[0][1] + y3], end = [line3[1][0] + x3, line3[1][1] + y3], startIndex = index2(start2), endIndex = index2(end), f, g;
      if (f = fragmentByEnd[startIndex]) {
        if (g = fragmentByStart[endIndex]) {
          delete fragmentByEnd[f.end];
          delete fragmentByStart[g.start];
          if (f === g) {
            f.ring.push(end);
            callback(f.ring);
          } else {
            fragmentByStart[f.start] = fragmentByEnd[g.end] = { start: f.start, end: g.end, ring: f.ring.concat(g.ring) };
          }
        } else {
          delete fragmentByEnd[f.end];
          f.ring.push(end);
          fragmentByEnd[f.end = endIndex] = f;
        }
      } else if (f = fragmentByStart[endIndex]) {
        if (g = fragmentByEnd[startIndex]) {
          delete fragmentByStart[f.start];
          delete fragmentByEnd[g.end];
          if (f === g) {
            f.ring.push(end);
            callback(f.ring);
          } else {
            fragmentByStart[g.start] = fragmentByEnd[f.end] = { start: g.start, end: f.end, ring: g.ring.concat(f.ring) };
          }
        } else {
          delete fragmentByStart[f.start];
          f.ring.unshift(start2);
          fragmentByStart[f.start = startIndex] = f;
        }
      } else {
        fragmentByStart[startIndex] = fragmentByEnd[endIndex] = { start: startIndex, end: endIndex, ring: [start2, end] };
      }
    }
  }
  function index2(point6) {
    return point6[0] * 2 + point6[1] * (dx + 1) * 4;
  }
  function smoothLinear(ring, values2, value) {
    ring.forEach(function(point6) {
      var x3 = point6[0], y3 = point6[1], xt = x3 | 0, yt = y3 | 0, v1 = valid(values2[yt * dx + xt]);
      if (x3 > 0 && x3 < dx && xt === x3) {
        point6[0] = smooth1(x3, valid(values2[yt * dx + xt - 1]), v1, value);
      }
      if (y3 > 0 && y3 < dy && yt === y3) {
        point6[1] = smooth1(y3, valid(values2[(yt - 1) * dx + xt]), v1, value);
      }
    });
  }
  contours.contour = contour3;
  contours.size = function(_) {
    if (!arguments.length) return [dx, dy];
    var _0 = Math.floor(_[0]), _1 = Math.floor(_[1]);
    if (!(_0 >= 0 && _1 >= 0)) throw new Error("invalid size");
    return dx = _0, dy = _1, contours;
  };
  contours.thresholds = function(_) {
    return arguments.length ? (threshold2 = typeof _ === "function" ? _ : Array.isArray(_) ? constant_default4(slice.call(_)) : constant_default4(_), contours) : threshold2;
  };
  contours.smooth = function(_) {
    return arguments.length ? (smooth = _ ? smoothLinear : noop_default, contours) : smooth === smoothLinear;
  };
  return contours;
}
function finite(x3) {
  return isFinite(x3) ? x3 : NaN;
}
function above(x3, value) {
  return x3 == null ? false : +x3 >= value;
}
function valid(v2) {
  return v2 == null || isNaN(v2 = +v2) ? -Infinity : v2;
}
function smooth1(x3, v0, v1, value) {
  const a2 = value - v0;
  const b = v1 - v0;
  const d = isFinite(a2) || isFinite(b) ? a2 / b : Math.sign(a2) / Math.sign(b);
  return isNaN(d) ? x3 : x3 + d - 0.5;
}

// ../../../node_modules/d3-contour/src/density.js
function defaultX(d) {
  return d[0];
}
function defaultY(d) {
  return d[1];
}
function defaultWeight() {
  return 1;
}
function density_default() {
  var x3 = defaultX, y3 = defaultY, weight = defaultWeight, dx = 960, dy = 500, r = 20, k2 = 2, o = r * 3, n = dx + o * 2 >> k2, m = dy + o * 2 >> k2, threshold2 = constant_default4(20);
  function grid2(data) {
    var values2 = new Float32Array(n * m), pow2k = Math.pow(2, -k2), i = -1;
    for (const d of data) {
      var xi = (x3(d, ++i, data) + o) * pow2k, yi = (y3(d, i, data) + o) * pow2k, wi = +weight(d, i, data);
      if (wi && xi >= 0 && xi < n && yi >= 0 && yi < m) {
        var x06 = Math.floor(xi), y06 = Math.floor(yi), xt = xi - x06 - 0.5, yt = yi - y06 - 0.5;
        values2[x06 + y06 * n] += (1 - xt) * (1 - yt) * wi;
        values2[x06 + 1 + y06 * n] += xt * (1 - yt) * wi;
        values2[x06 + 1 + (y06 + 1) * n] += xt * yt * wi;
        values2[x06 + (y06 + 1) * n] += (1 - xt) * yt * wi;
      }
    }
    blur2({ data: values2, width: n, height: m }, r * pow2k);
    return values2;
  }
  function density3(data) {
    var values2 = grid2(data), tz = threshold2(values2), pow4k = Math.pow(2, 2 * k2);
    if (!Array.isArray(tz)) {
      tz = ticks(Number.MIN_VALUE, max2(values2) / pow4k, tz);
    }
    return contours_default().size([n, m]).thresholds(tz.map((d) => d * pow4k))(values2).map((c4, i) => (c4.value = +tz[i], transform3(c4)));
  }
  density3.contours = function(data) {
    var values2 = grid2(data), contours = contours_default().size([n, m]), pow4k = Math.pow(2, 2 * k2), contour3 = (value) => {
      value = +value;
      var c4 = transform3(contours.contour(values2, value * pow4k));
      c4.value = value;
      return c4;
    };
    Object.defineProperty(contour3, "max", { get: () => max2(values2) / pow4k });
    return contour3;
  };
  function transform3(geometry) {
    geometry.coordinates.forEach(transformPolygon);
    return geometry;
  }
  function transformPolygon(coordinates) {
    coordinates.forEach(transformRing);
  }
  function transformRing(coordinates) {
    coordinates.forEach(transformPoint);
  }
  function transformPoint(coordinates) {
    coordinates[0] = coordinates[0] * Math.pow(2, k2) - o;
    coordinates[1] = coordinates[1] * Math.pow(2, k2) - o;
  }
  function resize() {
    o = r * 3;
    n = dx + o * 2 >> k2;
    m = dy + o * 2 >> k2;
    return density3;
  }
  density3.x = function(_) {
    return arguments.length ? (x3 = typeof _ === "function" ? _ : constant_default4(+_), density3) : x3;
  };
  density3.y = function(_) {
    return arguments.length ? (y3 = typeof _ === "function" ? _ : constant_default4(+_), density3) : y3;
  };
  density3.weight = function(_) {
    return arguments.length ? (weight = typeof _ === "function" ? _ : constant_default4(+_), density3) : weight;
  };
  density3.size = function(_) {
    if (!arguments.length) return [dx, dy];
    var _0 = +_[0], _1 = +_[1];
    if (!(_0 >= 0 && _1 >= 0)) throw new Error("invalid size");
    return dx = _0, dy = _1, resize();
  };
  density3.cellSize = function(_) {
    if (!arguments.length) return 1 << k2;
    if (!((_ = +_) >= 1)) throw new Error("invalid cell size");
    return k2 = Math.floor(Math.log(_) / Math.LN2), resize();
  };
  density3.thresholds = function(_) {
    return arguments.length ? (threshold2 = typeof _ === "function" ? _ : Array.isArray(_) ? constant_default4(slice.call(_)) : constant_default4(_), density3) : threshold2;
  };
  density3.bandwidth = function(_) {
    if (!arguments.length) return Math.sqrt(r * (r + 1));
    if (!((_ = +_) >= 0)) throw new Error("invalid bandwidth");
    return r = (Math.sqrt(4 * _ * _ + 1) - 1) / 2, resize();
  };
  return density3;
}

// ../../../node_modules/robust-predicates/esm/util.js
var epsilon4 = 11102230246251565e-32;
var splitter = 134217729;
var resulterrbound = (3 + 8 * epsilon4) * epsilon4;
function sum3(elen, e, flen, f, h) {
  let Q, Qnew, hh, bvirt;
  let enow = e[0];
  let fnow = f[0];
  let eindex = 0;
  let findex = 0;
  if (fnow > enow === fnow > -enow) {
    Q = enow;
    enow = e[++eindex];
  } else {
    Q = fnow;
    fnow = f[++findex];
  }
  let hindex = 0;
  if (eindex < elen && findex < flen) {
    if (fnow > enow === fnow > -enow) {
      Qnew = enow + Q;
      hh = Q - (Qnew - enow);
      enow = e[++eindex];
    } else {
      Qnew = fnow + Q;
      hh = Q - (Qnew - fnow);
      fnow = f[++findex];
    }
    Q = Qnew;
    if (hh !== 0) {
      h[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 = e[++eindex];
      } else {
        Qnew = Q + fnow;
        bvirt = Qnew - Q;
        hh = Q - (Qnew - bvirt) + (fnow - bvirt);
        fnow = f[++findex];
      }
      Q = Qnew;
      if (hh !== 0) {
        h[hindex++] = hh;
      }
    }
  }
  while (eindex < elen) {
    Qnew = Q + enow;
    bvirt = Qnew - Q;
    hh = Q - (Qnew - bvirt) + (enow - bvirt);
    enow = e[++eindex];
    Q = Qnew;
    if (hh !== 0) {
      h[hindex++] = hh;
    }
  }
  while (findex < flen) {
    Qnew = Q + fnow;
    bvirt = Qnew - Q;
    hh = Q - (Qnew - bvirt) + (fnow - bvirt);
    fnow = f[++findex];
    Q = Qnew;
    if (hh !== 0) {
      h[hindex++] = hh;
    }
  }
  if (Q !== 0 || hindex === 0) {
    h[hindex++] = Q;
  }
  return hindex;
}
function estimate(elen, e) {
  let Q = e[0];
  for (let i = 1; i < elen; i++) Q += e[i];
  return Q;
}
function vec(n) {
  return new Float64Array(n);
}

// ../../../node_modules/robust-predicates/esm/orient2d.js
var ccwerrboundA = (3 + 16 * epsilon4) * epsilon4;
var ccwerrboundB = (2 + 12 * epsilon4) * epsilon4;
var ccwerrboundC = (9 + 64 * epsilon4) * epsilon4 * epsilon4;
var B2 = vec(4);
var C1 = vec(8);
var C2 = 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, t03, u33;
  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;
  t03 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
  _i = s0 - t03;
  bvirt = s0 - _i;
  B2[0] = s0 - (_i + bvirt) + (bvirt - t03);
  _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);
  u33 = _j + _i;
  bvirt = u33 - _j;
  B2[2] = _j - (u33 - bvirt) + (_i - bvirt);
  B2[3] = u33;
  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;
  t03 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
  _i = s0 - t03;
  bvirt = s0 - _i;
  u[0] = s0 - (_i + bvirt) + (bvirt - t03);
  _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);
  u33 = _j + _i;
  bvirt = u33 - _j;
  u[2] = _j - (u33 - bvirt) + (_i - bvirt);
  u[3] = u33;
  const C1len = sum3(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;
  t03 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
  _i = s0 - t03;
  bvirt = s0 - _i;
  u[0] = s0 - (_i + bvirt) + (bvirt - t03);
  _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);
  u33 = _j + _i;
  bvirt = u33 - _j;
  u[2] = _j - (u33 - bvirt) + (_i - bvirt);
  u[3] = u33;
  const C2len = sum3(C1len, C1, 4, u, C2);
  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;
  t03 = alo * blo - (t13 - ahi * bhi - alo * bhi - ahi * blo);
  _i = s0 - t03;
  bvirt = s0 - _i;
  u[0] = s0 - (_i + bvirt) + (bvirt - t03);
  _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);
  u33 = _j + _i;
  bvirt = u33 - _j;
  u[2] = _j - (u33 - bvirt) + (_i - bvirt);
  u[3] = u33;
  const Dlen = sum3(C2len, C2, 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 * epsilon4) * epsilon4;
var o3derrboundB = (3 + 28 * epsilon4) * epsilon4;
var o3derrboundC = (26 + 288 * epsilon4) * epsilon4 * epsilon4;
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 * epsilon4) * epsilon4;
var iccerrboundB = (4 + 48 * epsilon4) * epsilon4;
var iccerrboundC = (44 + 576 * epsilon4) * epsilon4 * epsilon4;
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 * epsilon4) * epsilon4;
var isperrboundB = (5 + 72 * epsilon4) * epsilon4;
var isperrboundC = (71 + 1408 * epsilon4) * epsilon4 * epsilon4;
var ab3 = vec(4);
var bc3 = vec(4);
var cd = vec(4);
var de = vec(4);
var ea = 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 EPSILON = Math.pow(2, -52);
var EDGE_STACK = new Uint32Array(512);
var Delaunator = class _Delaunator {
  static from(points2, getX = defaultGetX, getY = defaultGetY) {
    const n = points2.length;
    const coords = new Float64Array(n * 2);
    for (let i = 0; i < n; i++) {
      const p = points2[i];
      coords[2 * i] = getX(p);
      coords[2 * i + 1] = getY(p);
    }
    return new _Delaunator(coords);
  }
  constructor(coords) {
    const n = coords.length >> 1;
    if (n > 0 && typeof coords[0] !== "number") throw new Error("Expected coords to contain numbers.");
    this.coords = coords;
    const maxTriangles = Math.max(2 * n - 5, 0);
    this._triangles = new Uint32Array(maxTriangles * 3);
    this._halfedges = new Int32Array(maxTriangles * 3);
    this._hashSize = Math.ceil(Math.sqrt(n));
    this._hullPrev = new Uint32Array(n);
    this._hullNext = new Uint32Array(n);
    this._hullTri = new Uint32Array(n);
    this._hullHash = new Int32Array(this._hashSize);
    this._ids = new Uint32Array(n);
    this._dists = new Float64Array(n);
    this.update();
  }
  update() {
    const { coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash } = this;
    const n = coords.length >> 1;
    let minX = Infinity;
    let minY = Infinity;
    let maxX = -Infinity;
    let maxY2 = -Infinity;
    for (let i = 0; i < n; i++) {
      const x3 = coords[2 * i];
      const y3 = coords[2 * i + 1];
      if (x3 < minX) minX = x3;
      if (y3 < minY) minY = y3;
      if (x3 > maxX) maxX = x3;
      if (y3 > maxY2) maxY2 = y3;
      this._ids[i] = i;
    }
    const cx = (minX + maxX) / 2;
    const cy = (minY + maxY2) / 2;
    let i0, i1, i2;
    for (let i = 0, minDist = Infinity; i < n; i++) {
      const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
      if (d < minDist) {
        i0 = i;
        minDist = d;
      }
    }
    const i0x = coords[2 * i0];
    const i0y = coords[2 * i0 + 1];
    for (let i = 0, minDist = Infinity; i < n; i++) {
      if (i === i0) continue;
      const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
      if (d < minDist && d > 0) {
        i1 = i;
        minDist = d;
      }
    }
    let i1x = coords[2 * i1];
    let i1y = coords[2 * i1 + 1];
    let minRadius = Infinity;
    for (let i = 0; i < n; i++) {
      if (i === i0 || i === i1) continue;
      const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
      if (r < minRadius) {
        i2 = i;
        minRadius = r;
      }
    }
    let i2x = coords[2 * i2];
    let i2y = coords[2 * i2 + 1];
    if (minRadius === Infinity) {
      for (let i = 0; i < n; i++) {
        this._dists[i] = coords[2 * i] - coords[0] || coords[2 * i + 1] - coords[1];
      }
      quicksort(this._ids, this._dists, 0, n - 1);
      const hull3 = new Uint32Array(n);
      let j = 0;
      for (let i = 0, d0 = -Infinity; i < n; i++) {
        const id2 = this._ids[i];
        const d = this._dists[id2];
        if (d > d0) {
          hull3[j++] = id2;
          d0 = d;
        }
      }
      this.hull = hull3.subarray(0, j);
      this.triangles = new Uint32Array(0);
      this.halfedges = new Uint32Array(0);
      return;
    }
    if (orient2d(i0x, i0y, i1x, i1y, i2x, i2y) < 0) {
      const i = i1;
      const x3 = i1x;
      const y3 = i1y;
      i1 = i2;
      i1x = i2x;
      i1y = i2y;
      i2 = i;
      i2x = x3;
      i2y = y3;
    }
    const center2 = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
    this._cx = center2.x;
    this._cy = center2.y;
    for (let i = 0; i < n; i++) {
      this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center2.x, center2.y);
    }
    quicksort(this._ids, this._dists, 0, n - 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 i = this._ids[k2];
      const x3 = coords[2 * i];
      const y3 = coords[2 * i + 1];
      if (k2 > 0 && Math.abs(x3 - xp) <= EPSILON && Math.abs(y3 - yp) <= EPSILON) continue;
      xp = x3;
      yp = y3;
      if (i === i0 || i === i1 || i === i2) continue;
      let start2 = 0;
      for (let j = 0, key = this._hashKey(x3, y3); j < this._hashSize; j++) {
        start2 = hullHash[(key + j) % this._hashSize];
        if (start2 !== -1 && start2 !== hullNext[start2]) break;
      }
      start2 = hullPrev[start2];
      let e = start2, q;
      while (q = hullNext[e], orient2d(x3, y3, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]) >= 0) {
        e = q;
        if (e === start2) {
          e = -1;
          break;
        }
      }
      if (e === -1) continue;
      let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);
      hullTri[i] = this._legalize(t + 2);
      hullTri[e] = t;
      hullSize++;
      let n2 = hullNext[e];
      while (q = hullNext[n2], orient2d(x3, y3, coords[2 * n2], coords[2 * n2 + 1], coords[2 * q], coords[2 * q + 1]) < 0) {
        t = this._addTriangle(n2, i, q, hullTri[i], -1, hullTri[n2]);
        hullTri[i] = this._legalize(t + 2);
        hullNext[n2] = n2;
        hullSize--;
        n2 = q;
      }
      if (e === start2) {
        while (q = hullPrev[e], orient2d(x3, y3, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]) < 0) {
          t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
          this._legalize(t + 2);
          hullTri[q] = t;
          hullNext[e] = e;
          hullSize--;
          e = q;
        }
      }
      this._hullStart = hullPrev[i] = e;
      hullNext[e] = hullPrev[n2] = i;
      hullNext[i] = n2;
      hullHash[this._hashKey(x3, y3)] = i;
      hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
    }
    this.hull = new Uint32Array(hullSize);
    for (let i = 0, e = this._hullStart; i < hullSize; i++) {
      this.hull[i] = e;
      e = hullNext[e];
    }
    this.triangles = this._triangles.subarray(0, this.trianglesLen);
    this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
  }
  _hashKey(x3, y3) {
    return Math.floor(pseudoAngle(x3 - this._cx, y3 - this._cy) * this._hashSize) % this._hashSize;
  }
  _legalize(a2) {
    const { _triangles: triangles, _halfedges: halfedges, coords } = this;
    let i = 0;
    let ar = 0;
    while (true) {
      const b = halfedges[a2];
      const a0 = a2 - a2 % 3;
      ar = a0 + (a2 + 2) % 3;
      if (b === -1) {
        if (i === 0) break;
        a2 = EDGE_STACK[--i];
        continue;
      }
      const b0 = b - b % 3;
      const al = a0 + (a2 + 1) % 3;
      const bl = b0 + (b + 2) % 3;
      const p0 = triangles[ar];
      const pr = triangles[a2];
      const pl = triangles[al];
      const p1 = triangles[bl];
      const illegal = inCircle(
        coords[2 * p0],
        coords[2 * p0 + 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[a2] = p1;
        triangles[b] = p0;
        const hbl = halfedges[bl];
        if (hbl === -1) {
          let e = this._hullStart;
          do {
            if (this._hullTri[e] === bl) {
              this._hullTri[e] = a2;
              break;
            }
            e = this._hullPrev[e];
          } while (e !== this._hullStart);
        }
        this._link(a2, hbl);
        this._link(b, halfedges[ar]);
        this._link(ar, bl);
        const br = b0 + (b + 1) % 3;
        if (i < EDGE_STACK.length) {
          EDGE_STACK[i++] = br;
        }
      } else {
        if (i === 0) break;
        a2 = EDGE_STACK[--i];
      }
    }
    return ar;
  }
  _link(a2, b) {
    this._halfedges[a2] = b;
    if (b !== -1) this._halfedges[b] = a2;
  }
  // add a new triangle given vertex indices and adjacent half-edge ids
  _addTriangle(i0, i1, i2, a2, b, c4) {
    const t = this.trianglesLen;
    this._triangles[t] = i0;
    this._triangles[t + 1] = i1;
    this._triangles[t + 2] = i2;
    this._link(t, a2);
    this._link(t + 1, b);
    this._link(t + 2, c4);
    this.trianglesLen += 3;
    return t;
  }
};
function pseudoAngle(dx, dy) {
  const p = dx / (Math.abs(dx) + Math.abs(dy));
  return (dy > 0 ? 3 - p : 1 + p) / 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, px, py) {
  const dx = ax - px;
  const dy = ay - py;
  const ex = bx - px;
  const ey = by - py;
  const fx = cx - px;
  const fy = cy - py;
  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 bl = dx * dx + dy * dy;
  const cl = ex * ex + ey * ey;
  const d = 0.5 / (dx * ey - dy * ex);
  const x3 = (ey * bl - dy * cl) * d;
  const y3 = (dx * cl - ex * bl) * d;
  return x3 * x3 + y3 * y3;
}
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 bl = dx * dx + dy * dy;
  const cl = ex * ex + ey * ey;
  const d = 0.5 / (dx * ey - dy * ex);
  const x3 = ax + (ey * bl - dy * cl) * d;
  const y3 = ay + (dx * cl - ex * bl) * d;
  return { x: x3, y: y3 };
}
function quicksort(ids, dists, left2, right2) {
  if (right2 - left2 <= 20) {
    for (let i = left2 + 1; i <= right2; i++) {
      const temp = ids[i];
      const tempDist = dists[temp];
      let j = i - 1;
      while (j >= left2 && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
      ids[j + 1] = temp;
    }
  } else {
    const median3 = left2 + right2 >> 1;
    let i = left2 + 1;
    let j = right2;
    swap2(ids, median3, i);
    if (dists[ids[left2]] > dists[ids[right2]]) swap2(ids, left2, right2);
    if (dists[ids[i]] > dists[ids[right2]]) swap2(ids, i, right2);
    if (dists[ids[left2]] > dists[ids[i]]) swap2(ids, left2, i);
    const temp = ids[i];
    const tempDist = dists[temp];
    while (true) {
      do
        i++;
      while (dists[ids[i]] < tempDist);
      do
        j--;
      while (dists[ids[j]] > tempDist);
      if (j < i) break;
      swap2(ids, i, j);
    }
    ids[left2 + 1] = ids[j];
    ids[j] = temp;
    if (right2 - i + 1 >= j - left2) {
      quicksort(ids, dists, i, right2);
      quicksort(ids, dists, left2, j - 1);
    } else {
      quicksort(ids, dists, left2, j - 1);
      quicksort(ids, dists, i, right2);
    }
  }
}
function swap2(arr, i, j) {
  const tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
}
function defaultGetX(p) {
  return p[0];
}
function defaultGetY(p) {
  return p[1];
}

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

// ../../../node_modules/d3-delaunay/src/polygon.js
var Polygon = class {
  constructor() {
    this._ = [];
  }
  moveTo(x3, y3) {
    this._.push([x3, y3]);
  }
  closePath() {
    this._.push(this._[0].slice());
  }
  lineTo(x3, y3) {
    this._.push([x3, y3]);
  }
  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: hull3, triangles }, vectors } = this;
    let bx, by;
    const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
    for (let i = 0, j = 0, n = triangles.length, x3, y3; i < n; i += 3, j += 2) {
      const t13 = triangles[i] * 2;
      const t22 = triangles[i + 1] * 2;
      const t32 = triangles[i + 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 i2 of hull3) bx += points2[i2 * 2], by += points2[i2 * 2 + 1];
          bx /= hull3.length, by /= hull3.length;
        }
        const a2 = 1e9 * Math.sign((bx - x13) * ey - (by - y13) * ex);
        x3 = (x13 + x32) / 2 - a2 * ey;
        y3 = (y13 + y32) / 2 + a2 * ex;
      } else {
        const d = 1 / ab4;
        const bl = dx * dx + dy * dy;
        const cl = ex * ex + ey * ey;
        x3 = x13 + (ey * bl - dy * cl) * d;
        y3 = y13 + (dx * cl - ex * bl) * d;
      }
      circumcenters[j] = x3;
      circumcenters[j + 1] = y3;
    }
    let h = hull3[hull3.length - 1];
    let p0, p1 = h * 4;
    let x06, x12 = points2[2 * h];
    let y06, y12 = points2[2 * h + 1];
    vectors.fill(0);
    for (let i = 0; i < hull3.length; ++i) {
      h = hull3[i];
      p0 = p1, x06 = x12, y06 = y12;
      p1 = h * 4, x12 = points2[2 * h], y12 = points2[2 * h + 1];
      vectors[p0 + 2] = vectors[p1] = y06 - y12;
      vectors[p0 + 3] = vectors[p1 + 1] = x12 - x06;
    }
  }
  render(context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    const { delaunay: { halfedges, inedges, hull: hull3 }, circumcenters, vectors } = this;
    if (hull3.length <= 1) return null;
    for (let i = 0, n = halfedges.length; i < n; ++i) {
      const j = halfedges[i];
      if (j < i) continue;
      const ti = Math.floor(i / 3) * 2;
      const tj = Math.floor(j / 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, context);
    }
    let h0, h1 = hull3[hull3.length - 1];
    for (let i = 0; i < hull3.length; ++i) {
      h0 = h1, h1 = hull3[i];
      const t = Math.floor(inedges[h1] / 3) * 2;
      const x3 = circumcenters[t];
      const y3 = circumcenters[t + 1];
      const v2 = h0 * 4;
      const p = this._project(x3, y3, vectors[v2 + 2], vectors[v2 + 3]);
      if (p) this._renderSegment(x3, y3, p[0], p[1], context);
    }
    return buffer2 && buffer2.value();
  }
  renderBounds(context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);
    return buffer2 && buffer2.value();
  }
  renderCell(i, context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    const points2 = this._clip(i);
    if (points2 === null || !points2.length) return;
    context.moveTo(points2[0], points2[1]);
    let n = points2.length;
    while (points2[0] === points2[n - 2] && points2[1] === points2[n - 1] && n > 1) n -= 2;
    for (let i2 = 2; i2 < n; i2 += 2) {
      if (points2[i2] !== points2[i2 - 2] || points2[i2 + 1] !== points2[i2 - 1])
        context.lineTo(points2[i2], points2[i2 + 1]);
    }
    context.closePath();
    return buffer2 && buffer2.value();
  }
  *cellPolygons() {
    const { delaunay: { points: points2 } } = this;
    for (let i = 0, n = points2.length / 2; i < n; ++i) {
      const cell3 = this.cellPolygon(i);
      if (cell3) cell3.index = i, yield cell3;
    }
  }
  cellPolygon(i) {
    const polygon = new Polygon();
    this.renderCell(i, polygon);
    return polygon.value();
  }
  _renderSegment(x06, y06, x12, y12, context) {
    let S;
    const c0 = this._regioncode(x06, y06);
    const c1 = this._regioncode(x12, y12);
    if (c0 === 0 && c1 === 0) {
      context.moveTo(x06, y06);
      context.lineTo(x12, y12);
    } else if (S = this._clipSegment(x06, y06, x12, y12, c0, c1)) {
      context.moveTo(S[0], S[1]);
      context.lineTo(S[2], S[3]);
    }
  }
  contains(i, x3, y3) {
    if ((x3 = +x3, x3 !== x3) || (y3 = +y3, y3 !== y3)) return false;
    return this.delaunay._step(i, x3, y3) === i;
  }
  *neighbors(i) {
    const ci = this._clip(i);
    if (ci) for (const j of this.delaunay.neighbors(i)) {
      const cj = this._clip(j);
      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 j;
            break loop;
          }
        }
      }
    }
  }
  _cell(i) {
    const { circumcenters, delaunay: { inedges, halfedges, triangles } } = this;
    const e0 = inedges[i];
    if (e0 === -1) return null;
    const points2 = [];
    let e = e0;
    do {
      const t = Math.floor(e / 3);
      points2.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) break;
      e = halfedges[e];
    } while (e !== e0 && e !== -1);
    return points2;
  }
  _clip(i) {
    if (i === 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(i);
    if (points2 === null) return null;
    const { vectors: V } = this;
    const v2 = i * 4;
    return this._simplify(V[v2] || V[v2 + 1] ? this._clipInfinite(i, points2, V[v2], V[v2 + 1], V[v2 + 2], V[v2 + 3]) : this._clipFinite(i, points2));
  }
  _clipFinite(i, points2) {
    const n = points2.length;
    let P = null;
    let x06, y06, x12 = points2[n - 2], y12 = points2[n - 1];
    let c0, c1 = this._regioncode(x12, y12);
    let e0, e1 = 0;
    for (let j = 0; j < n; j += 2) {
      x06 = x12, y06 = y12, x12 = points2[j], y12 = points2[j + 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(i, 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(i, 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(i, e0, e1, P, P.length);
    } else if (this.contains(i, (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 x3, y3, c4 = c0 || c1;
      if (c4 & 8) x3 = x06 + (x12 - x06) * (this.ymax - y06) / (y12 - y06), y3 = this.ymax;
      else if (c4 & 4) x3 = x06 + (x12 - x06) * (this.ymin - y06) / (y12 - y06), y3 = this.ymin;
      else if (c4 & 2) y3 = y06 + (y12 - y06) * (this.xmax - x06) / (x12 - x06), x3 = this.xmax;
      else y3 = y06 + (y12 - y06) * (this.xmin - x06) / (x12 - x06), x3 = this.xmin;
      if (c0) x06 = x3, y06 = y3, c0 = this._regioncode(x06, y06);
      else x12 = x3, y12 = y3, c1 = this._regioncode(x12, y12);
    }
  }
  _clipInfinite(i, points2, vx0, vy0, vxn, vyn) {
    let P = Array.from(points2), p;
    if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);
    if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);
    if (P = this._clipFinite(i, P)) {
      for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {
        c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);
        if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;
      }
    } else if (this.contains(i, (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(i, e0, e1, P, j) {
    while (e0 !== e1) {
      let x3, y3;
      switch (e0) {
        case 5:
          e0 = 4;
          continue;
        // top-left
        case 4:
          e0 = 6, x3 = this.xmax, y3 = this.ymin;
          break;
        // top
        case 6:
          e0 = 2;
          continue;
        // top-right
        case 2:
          e0 = 10, x3 = this.xmax, y3 = this.ymax;
          break;
        // right
        case 10:
          e0 = 8;
          continue;
        // bottom-right
        case 8:
          e0 = 9, x3 = this.xmin, y3 = this.ymax;
          break;
        // bottom
        case 9:
          e0 = 1;
          continue;
        // bottom-left
        case 1:
          e0 = 5, x3 = this.xmin, y3 = this.ymin;
          break;
      }
      if ((P[j] !== x3 || P[j + 1] !== y3) && this.contains(i, x3, y3)) {
        P.splice(j, 0, x3, y3), j += 2;
      }
    }
    return j;
  }
  _project(x06, y06, vx, vy) {
    let t = Infinity, c4, x3, y3;
    if (vy < 0) {
      if (y06 <= this.ymin) return null;
      if ((c4 = (this.ymin - y06) / vy) < t) y3 = this.ymin, x3 = x06 + (t = c4) * vx;
    } else if (vy > 0) {
      if (y06 >= this.ymax) return null;
      if ((c4 = (this.ymax - y06) / vy) < t) y3 = this.ymax, x3 = x06 + (t = c4) * vx;
    }
    if (vx > 0) {
      if (x06 >= this.xmax) return null;
      if ((c4 = (this.xmax - x06) / vx) < t) x3 = this.xmax, y3 = y06 + (t = c4) * vy;
    } else if (vx < 0) {
      if (x06 <= this.xmin) return null;
      if ((c4 = (this.xmin - x06) / vx) < t) x3 = this.xmin, y3 = y06 + (t = c4) * vy;
    }
    return [x3, y3];
  }
  _edgecode(x3, y3) {
    return (x3 === this.xmin ? 1 : x3 === this.xmax ? 2 : 0) | (y3 === this.ymin ? 4 : y3 === this.ymax ? 8 : 0);
  }
  _regioncode(x3, y3) {
    return (x3 < this.xmin ? 1 : x3 > this.xmax ? 2 : 0) | (y3 < this.ymin ? 4 : y3 > this.ymax ? 8 : 0);
  }
  _simplify(P) {
    if (P && P.length > 4) {
      for (let i = 0; i < P.length; i += 2) {
        const j = (i + 2) % P.length, k2 = (i + 4) % P.length;
        if (P[i] === P[j] && P[j] === P[k2] || P[i + 1] === P[j + 1] && P[j + 1] === P[k2 + 1]) {
          P.splice(j, 2), i -= 2;
        }
      }
      if (!P.length) P = null;
    }
    return P;
  }
};

// ../../../node_modules/d3-delaunay/src/delaunay.js
var tau2 = 2 * Math.PI;
var pow2 = Math.pow;
function pointX(p) {
  return p[0];
}
function pointY(p) {
  return p[1];
}
function collinear2(d) {
  const { triangles, coords } = d;
  for (let i = 0; i < triangles.length; i += 3) {
    const a2 = 2 * triangles[i], b = 2 * triangles[i + 1], c4 = 2 * triangles[i + 2], cross3 = (coords[c4] - coords[a2]) * (coords[b + 1] - coords[a2 + 1]) - (coords[b] - coords[a2]) * (coords[c4 + 1] - coords[a2 + 1]);
    if (cross3 > 1e-10) return false;
  }
  return true;
}
function jitter(x3, y3, r) {
  return [x3 + Math.sin(x3 + y3) * r, y3 + Math.cos(x3 - y3) * r];
}
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 d = this._delaunator, points2 = this.points;
    if (d.hull && d.hull.length > 2 && collinear2(d)) {
      this.collinear = Int32Array.from({ length: points2.length / 2 }, (_, i) => i).sort((i, j) => points2[2 * i] - points2[2 * j] || points2[2 * i + 1] - points2[2 * j + 1]);
      const e = this.collinear[0], f = this.collinear[this.collinear.length - 1], bounds = [points2[2 * e], points2[2 * e + 1], points2[2 * f], points2[2 * f + 1]], r = 1e-8 * Math.hypot(bounds[3] - bounds[1], bounds[2] - bounds[0]);
      for (let i = 0, n = points2.length / 2; i < n; ++i) {
        const p = jitter(points2[2 * i], points2[2 * i + 1], r);
        points2[2 * i] = p[0];
        points2[2 * i + 1] = p[1];
      }
      this._delaunator = new Delaunator(points2);
    } else {
      delete this.collinear;
    }
    const halfedges = this.halfedges = this._delaunator.halfedges;
    const hull3 = 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 e = 0, n = halfedges.length; e < n; ++e) {
      const p = triangles[e % 3 === 2 ? e - 2 : e + 1];
      if (halfedges[e] === -1 || inedges[p] === -1) inedges[p] = e;
    }
    for (let i = 0, n = hull3.length; i < n; ++i) {
      hullIndex[hull3[i]] = i;
    }
    if (hull3.length <= 2 && hull3.length > 0) {
      this.triangles = new Int32Array(3).fill(-1);
      this.halfedges = new Int32Array(3).fill(-1);
      this.triangles[0] = hull3[0];
      inedges[hull3[0]] = 1;
      if (hull3.length === 2) {
        inedges[hull3[1]] = 0;
        this.triangles[1] = hull3[1];
        this.triangles[2] = hull3[1];
      }
    }
  }
  voronoi(bounds) {
    return new Voronoi(this, bounds);
  }
  *neighbors(i) {
    const { inedges, hull: hull3, _hullIndex, halfedges, triangles, collinear: collinear3 } = this;
    if (collinear3) {
      const l = collinear3.indexOf(i);
      if (l > 0) yield collinear3[l - 1];
      if (l < collinear3.length - 1) yield collinear3[l + 1];
      return;
    }
    const e0 = inedges[i];
    if (e0 === -1) return;
    let e = e0, p0 = -1;
    do {
      yield p0 = triangles[e];
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) return;
      e = halfedges[e];
      if (e === -1) {
        const p = hull3[(_hullIndex[i] + 1) % hull3.length];
        if (p !== p0) yield p;
        return;
      }
    } while (e !== e0);
  }
  find(x3, y3, i = 0) {
    if ((x3 = +x3, x3 !== x3) || (y3 = +y3, y3 !== y3)) return -1;
    const i0 = i;
    let c4;
    while ((c4 = this._step(i, x3, y3)) >= 0 && c4 !== i && c4 !== i0) i = c4;
    return c4;
  }
  _step(i, x3, y3) {
    const { inedges, hull: hull3, _hullIndex, halfedges, triangles, points: points2 } = this;
    if (inedges[i] === -1 || !points2.length) return (i + 1) % (points2.length >> 1);
    let c4 = i;
    let dc = pow2(x3 - points2[i * 2], 2) + pow2(y3 - points2[i * 2 + 1], 2);
    const e0 = inedges[i];
    let e = e0;
    do {
      let t = triangles[e];
      const dt = pow2(x3 - points2[t * 2], 2) + pow2(y3 - points2[t * 2 + 1], 2);
      if (dt < dc) dc = dt, c4 = t;
      e = e % 3 === 2 ? e - 2 : e + 1;
      if (triangles[e] !== i) break;
      e = halfedges[e];
      if (e === -1) {
        e = hull3[(_hullIndex[i] + 1) % hull3.length];
        if (e !== t) {
          if (pow2(x3 - points2[e * 2], 2) + pow2(y3 - points2[e * 2 + 1], 2) < dc) return e;
        }
        break;
      }
    } while (e !== e0);
    return c4;
  }
  render(context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    const { points: points2, halfedges, triangles } = this;
    for (let i = 0, n = halfedges.length; i < n; ++i) {
      const j = halfedges[i];
      if (j < i) continue;
      const ti = triangles[i] * 2;
      const tj = triangles[j] * 2;
      context.moveTo(points2[ti], points2[ti + 1]);
      context.lineTo(points2[tj], points2[tj + 1]);
    }
    this.renderHull(context);
    return buffer2 && buffer2.value();
  }
  renderPoints(context, r) {
    if (r === void 0 && (!context || typeof context.moveTo !== "function")) r = context, context = null;
    r = r == void 0 ? 2 : +r;
    const buffer2 = context == null ? context = new Path2() : void 0;
    const { points: points2 } = this;
    for (let i = 0, n = points2.length; i < n; i += 2) {
      const x3 = points2[i], y3 = points2[i + 1];
      context.moveTo(x3 + r, y3);
      context.arc(x3, y3, r, 0, tau2);
    }
    return buffer2 && buffer2.value();
  }
  renderHull(context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    const { hull: hull3, points: points2 } = this;
    const h = hull3[0] * 2, n = hull3.length;
    context.moveTo(points2[h], points2[h + 1]);
    for (let i = 1; i < n; ++i) {
      const h2 = 2 * hull3[i];
      context.lineTo(points2[h2], points2[h2 + 1]);
    }
    context.closePath();
    return buffer2 && buffer2.value();
  }
  hullPolygon() {
    const polygon = new Polygon();
    this.renderHull(polygon);
    return polygon.value();
  }
  renderTriangle(i, context) {
    const buffer2 = context == null ? context = new Path2() : void 0;
    const { points: points2, triangles } = this;
    const t03 = triangles[i *= 3] * 2;
    const t13 = triangles[i + 1] * 2;
    const t22 = triangles[i + 2] * 2;
    context.moveTo(points2[t03], points2[t03 + 1]);
    context.lineTo(points2[t13], points2[t13 + 1]);
    context.lineTo(points2[t22], points2[t22 + 1]);
    context.closePath();
    return buffer2 && buffer2.value();
  }
  *trianglePolygons() {
    const { triangles } = this;
    for (let i = 0, n = triangles.length / 3; i < n; ++i) {
      yield this.trianglePolygon(i);
    }
  }
  trianglePolygon(i) {
    const polygon = new Polygon();
    this.renderTriangle(i, polygon);
    return polygon.value();
  }
};
function flatArray(points2, fx, fy, that) {
  const n = points2.length;
  const array4 = new Float64Array(n * 2);
  for (let i = 0; i < n; ++i) {
    const p = points2[i];
    array4[i * 2] = fx.call(that, p, i, points2);
    array4[i * 2 + 1] = fy.call(that, p, i, points2);
  }
  return array4;
}
function* flatIterable(points2, fx, fy, that) {
  let i = 0;
  for (const p of points2) {
    yield fx.call(that, p, i, points2);
    yield fy.call(that, p, i, points2);
    ++i;
  }
}

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

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

// ../../../node_modules/d3-format/src/formatGroup.js
function formatGroup_default(grouping, thousands) {
  return function(value, width2) {
    var i = value.length, t = [], j = 0, g = grouping[0], length4 = 0;
    while (i > 0 && g > 0) {
      if (length4 + g + 1 > width2) g = Math.max(1, width2 - length4);
      t.push(value.substring(i -= g, i + g));
      if ((length4 += g + 1) > width2) break;
      g = grouping[j = (j + 1) % grouping.length];
    }
    return t.reverse().join(thousands);
  };
}

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

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

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

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

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

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

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

// ../../../node_modules/d3-format/src/locale.js
var map2 = Array.prototype.map;
var prefixes = ["y", "z", "a", "f", "p", "n", "\xB5", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"];
function locale_default(locale3) {
  var group3 = locale3.grouping === void 0 || locale3.thousands === void 0 ? identity_default2 : formatGroup_default(map2.call(locale3.grouping, Number), locale3.thousands + ""), currencyPrefix = locale3.currency === void 0 ? "" : locale3.currency[0] + "", currencySuffix = locale3.currency === void 0 ? "" : locale3.currency[1] + "", decimal2 = locale3.decimal === void 0 ? "." : locale3.decimal + "", numerals = locale3.numerals === void 0 ? identity_default2 : formatNumerals_default(map2.call(locale3.numerals, String)), percent = locale3.percent === void 0 ? "%" : locale3.percent + "", minus = locale3.minus === void 0 ? "\u2212" : locale3.minus + "", nan = locale3.nan === void 0 ? "NaN" : locale3.nan + "";
  function newFormat(specifier) {
    specifier = formatSpecifier(specifier);
    var fill = specifier.fill, align3 = specifier.align, sign4 = specifier.sign, symbol2 = specifier.symbol, zero3 = specifier.zero, width2 = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type2 = specifier.type;
    if (type2 === "n") comma = true, type2 = "g";
    else if (!formatTypes_default[type2]) precision === void 0 && (precision = 12), trim = true, type2 = "g";
    if (zero3 || fill === "0" && align3 === "=") zero3 = true, fill = "0", align3 = "=";
    var prefix2 = symbol2 === "$" ? currencyPrefix : symbol2 === "#" && /[boxX]/.test(type2) ? "0" + type2.toLowerCase() : "", suffix2 = symbol2 === "$" ? currencySuffix : /[%p]/.test(type2) ? percent : "";
    var formatType = formatTypes_default[type2], maybeSuffix = /[defgprs%]/.test(type2);
    precision = precision === void 0 ? 6 : /[gprs]/.test(type2) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision));
    function format3(value) {
      var valuePrefix = prefix2, valueSuffix = suffix2, i, n, c4;
      if (type2 === "c") {
        valueSuffix = formatType(value) + valueSuffix;
        value = "";
      } else {
        value = +value;
        var valueNegative = value < 0 || 1 / value < 0;
        value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
        if (trim) value = formatTrim_default(value);
        if (valueNegative && +value === 0 && sign4 !== "+") valueNegative = false;
        valuePrefix = (valueNegative ? sign4 === "(" ? sign4 : minus : sign4 === "-" || sign4 === "(" ? "" : sign4) + valuePrefix;
        valueSuffix = (type2 === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign4 === "(" ? ")" : "");
        if (maybeSuffix) {
          i = -1, n = value.length;
          while (++i < n) {
            if (c4 = value.charCodeAt(i), 48 > c4 || c4 > 57) {
              valueSuffix = (c4 === 46 ? decimal2 + value.slice(i + 1) : value.slice(i)) + valueSuffix;
              value = value.slice(0, i);
              break;
            }
          }
        }
      }
      if (comma && !zero3) value = group3(value, Infinity);
      var length4 = valuePrefix.length + value.length + valueSuffix.length, padding2 = length4 < width2 ? new Array(width2 - length4 + 1).join(fill) : "";
      if (comma && zero3) value = group3(padding2 + value, padding2.length ? width2 - valueSuffix.length : Infinity), padding2 = "";
      switch (align3) {
        case "<":
          value = valuePrefix + value + valueSuffix + padding2;
          break;
        case "=":
          value = valuePrefix + padding2 + value + valueSuffix;
          break;
        case "^":
          value = padding2.slice(0, length4 = padding2.length >> 1) + valuePrefix + value + valueSuffix + padding2.slice(length4);
          break;
        default:
          value = padding2 + valuePrefix + value + valueSuffix;
          break;
      }
      return numerals(value);
    }
    format3.toString = function() {
      return specifier + "";
    };
    return format3;
  }
  function formatPrefix2(specifier, value) {
    var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent_default(value) / 3))) * 3, k2 = Math.pow(10, -e), prefix2 = prefixes[8 + e / 3];
    return function(value2) {
      return f(k2 * value2) + prefix2;
    };
  }
  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(definition) {
  locale = locale_default(definition);
  format = locale.format;
  formatPrefix = locale.formatPrefix;
  return locale;
}

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

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

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

// ../../../node_modules/d3-geo/src/math.js
var epsilon6 = 1e-6;
var epsilon22 = 1e-12;
var pi2 = Math.PI;
var halfPi = pi2 / 2;
var quarterPi = pi2 / 4;
var tau3 = pi2 * 2;
var degrees3 = 180 / pi2;
var radians2 = pi2 / 180;
var abs3 = Math.abs;
var atan = Math.atan;
var atan2 = Math.atan2;
var cos = Math.cos;
var ceil2 = Math.ceil;
var exp2 = Math.exp;
var hypot = Math.hypot;
var log2 = Math.log;
var pow3 = Math.pow;
var sin = Math.sin;
var sign2 = Math.sign || function(x3) {
  return x3 > 0 ? 1 : x3 < 0 ? -1 : 0;
};
var sqrt2 = Math.sqrt;
var tan = Math.tan;
function acos(x3) {
  return x3 > 1 ? 0 : x3 < -1 ? pi2 : Math.acos(x3);
}
function asin(x3) {
  return x3 > 1 ? halfPi : x3 < -1 ? -halfPi : Math.asin(x3);
}

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

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

// ../../../node_modules/d3-geo/src/cartesian.js
function spherical(cartesian2) {
  return [atan2(cartesian2[1], cartesian2[0]), asin(cartesian2[2])];
}
function cartesian(spherical2) {
  var lambda = spherical2[0], phi = spherical2[1], cosPhi = cos(phi);
  return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
}
function cartesianDot(a2, b) {
  return a2[0] * b[0] + a2[1] * b[1] + a2[2] * b[2];
}
function cartesianCross(a2, b) {
  return [a2[1] * b[2] - a2[2] * b[1], a2[2] * b[0] - a2[0] * b[2], a2[0] * b[1] - a2[1] * b[0]];
}
function cartesianAddInPlace(a2, b) {
  a2[0] += b[0], a2[1] += b[1], a2[2] += b[2];
}
function cartesianScale(vector3, k2) {
  return [vector3[0] * k2, vector3[1] * k2, vector3[2] * k2];
}
function cartesianNormalizeInPlace(d) {
  var l = sqrt2(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
  d[0] /= l, d[1] /= l, d[2] /= l;
}

// ../../../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 lambda00;
var phi00;
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, phi) {
  lambda *= radians2, phi *= radians2;
  var cosPhi = cos(phi);
  centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));
}
function centroidPointCartesian(x3, y3, z) {
  ++W0;
  X0 += (x3 - X0) / W0;
  Y0 += (y3 - Y0) / W0;
  Z0 += (z - Z0) / W0;
}
function centroidLineStart() {
  centroidStream.point = centroidLinePointFirst;
}
function centroidLinePointFirst(lambda, phi) {
  lambda *= radians2, phi *= radians2;
  var cosPhi = cos(phi);
  x0 = cosPhi * cos(lambda);
  y0 = cosPhi * sin(lambda);
  z0 = sin(phi);
  centroidStream.point = centroidLinePoint;
  centroidPointCartesian(x0, y0, z0);
}
function centroidLinePoint(lambda, phi) {
  lambda *= radians2, phi *= radians2;
  var cosPhi = cos(phi), x3 = cosPhi * cos(lambda), y3 = cosPhi * sin(lambda), z = sin(phi), w = atan2(sqrt2((w = y0 * z - z0 * y3) * w + (w = z0 * x3 - x0 * z) * w + (w = x0 * y3 - y0 * x3) * w), x0 * x3 + y0 * y3 + z0 * z);
  W1 += w;
  X1 += w * (x0 + (x0 = x3));
  Y1 += w * (y0 + (y0 = y3));
  Z1 += w * (z0 + (z0 = z));
  centroidPointCartesian(x0, y0, z0);
}
function centroidLineEnd() {
  centroidStream.point = centroidPoint;
}
function centroidRingStart() {
  centroidStream.point = centroidRingPointFirst;
}
function centroidRingEnd() {
  centroidRingPoint(lambda00, phi00);
  centroidStream.point = centroidPoint;
}
function centroidRingPointFirst(lambda, phi) {
  lambda00 = lambda, phi00 = phi;
  lambda *= radians2, phi *= radians2;
  centroidStream.point = centroidRingPoint;
  var cosPhi = cos(phi);
  x0 = cosPhi * cos(lambda);
  y0 = cosPhi * sin(lambda);
  z0 = sin(phi);
  centroidPointCartesian(x0, y0, z0);
}
function centroidRingPoint(lambda, phi) {
  lambda *= radians2, phi *= radians2;
  var cosPhi = cos(phi), x3 = cosPhi * cos(lambda), y3 = cosPhi * sin(lambda), z = sin(phi), cx = y0 * z - z0 * y3, cy = z0 * x3 - x0 * z, cz = x0 * y3 - y0 * x3, m = hypot(cx, cy, cz), w = asin(m), v2 = m && -w / m;
  X2.add(v2 * cx);
  Y2.add(v2 * cy);
  Z2.add(v2 * cz);
  W1 += w;
  X1 += w * (x0 + (x0 = x3));
  Y1 += w * (y0 + (y0 = y3));
  Z1 += w * (z0 + (z0 = z));
  centroidPointCartesian(x0, y0, z0);
}
function centroid_default(object) {
  W0 = W1 = X0 = Y0 = Z0 = X1 = Y1 = Z1 = 0;
  X2 = new Adder();
  Y2 = new Adder();
  Z2 = new Adder();
  stream_default(object, centroidStream);
  var x3 = +X2, y3 = +Y2, z = +Z2, m = hypot(x3, y3, z);
  if (m < epsilon22) {
    x3 = X1, y3 = Y1, z = Z1;
    if (W1 < epsilon6) x3 = X0, y3 = Y0, z = Z0;
    m = hypot(x3, y3, z);
    if (m < epsilon22) return [NaN, NaN];
  }
  return [atan2(y3, x3) * degrees3, asin(z / m) * degrees3];
}

// ../../../node_modules/d3-geo/src/compose.js
function compose_default(a2, b) {
  function compose(x3, y3) {
    return x3 = a2(x3, y3), b(x3[0], x3[1]);
  }
  if (a2.invert && b.invert) compose.invert = function(x3, y3) {
    return x3 = b.invert(x3, y3), x3 && a2.invert(x3[0], x3[1]);
  };
  return compose;
}

// ../../../node_modules/d3-geo/src/rotation.js
function rotationIdentity(lambda, phi) {
  if (abs3(lambda) > pi2) lambda -= Math.round(lambda / tau3) * tau3;
  return [lambda, phi];
}
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, phi) {
    lambda += deltaLambda;
    if (abs3(lambda) > pi2) lambda -= Math.round(lambda / tau3) * tau3;
    return [lambda, phi];
  };
}
function rotationLambda(deltaLambda) {
  var rotation = forwardRotationLambda(deltaLambda);
  rotation.invert = forwardRotationLambda(-deltaLambda);
  return rotation;
}
function rotationPhiGamma(deltaPhi, deltaGamma) {
  var cosDeltaPhi = cos(deltaPhi), sinDeltaPhi = sin(deltaPhi), cosDeltaGamma = cos(deltaGamma), sinDeltaGamma = sin(deltaGamma);
  function rotation(lambda, phi) {
    var cosPhi = cos(phi), x3 = cos(lambda) * cosPhi, y3 = sin(lambda) * cosPhi, z = sin(phi), k2 = z * cosDeltaPhi + x3 * sinDeltaPhi;
    return [
      atan2(y3 * cosDeltaGamma - k2 * sinDeltaGamma, x3 * cosDeltaPhi - z * sinDeltaPhi),
      asin(k2 * cosDeltaGamma + y3 * sinDeltaGamma)
    ];
  }
  rotation.invert = function(lambda, phi) {
    var cosPhi = cos(phi), x3 = cos(lambda) * cosPhi, y3 = sin(lambda) * cosPhi, z = sin(phi), k2 = z * cosDeltaGamma - y3 * sinDeltaGamma;
    return [
      atan2(y3 * cosDeltaGamma + z * sinDeltaGamma, x3 * cosDeltaPhi + k2 * sinDeltaPhi),
      asin(k2 * cosDeltaPhi - x3 * sinDeltaPhi)
    ];
  };
  return rotation;
}
function rotation_default(rotate) {
  rotate = rotateRadians(rotate[0] * radians2, rotate[1] * radians2, rotate.length > 2 ? rotate[2] * radians2 : 0);
  function forward(coordinates) {
    coordinates = rotate(coordinates[0] * radians2, coordinates[1] * radians2);
    return coordinates[0] *= degrees3, coordinates[1] *= degrees3, coordinates;
  }
  forward.invert = function(coordinates) {
    coordinates = rotate.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(stream, radius2, delta, direction, t03, t13) {
  if (!delta) return;
  var cosRadius = cos(radius2), sinRadius = sin(radius2), step = direction * delta;
  if (t03 == null) {
    t03 = radius2 + direction * tau3;
    t13 = radius2 - step / 2;
  } else {
    t03 = circleRadius(cosRadius, t03);
    t13 = circleRadius(cosRadius, t13);
    if (direction > 0 ? t03 < t13 : t03 > t13) t03 += direction * tau3;
  }
  for (var point6, t = t03; direction > 0 ? t > t13 : t < t13; t -= step) {
    point6 = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);
    stream.point(point6[0], point6[1]);
  }
}
function circleRadius(cosRadius, point6) {
  point6 = cartesian(point6), point6[0] -= cosRadius;
  cartesianNormalizeInPlace(point6);
  var radius2 = acos(-point6[1]);
  return ((-point6[2] < 0 ? -radius2 : radius2) + tau3 - epsilon6) % tau3;
}

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

// ../../../node_modules/d3-geo/src/pointEqual.js
function pointEqual_default(a2, b) {
  return abs3(a2[0] - b[0]) < epsilon6 && abs3(a2[1] - b[1]) < epsilon6;
}

// ../../../node_modules/d3-geo/src/clip/rejoin.js
function Intersection(point6, points2, other, entry) {
  this.x = point6;
  this.z = points2;
  this.o = other;
  this.e = entry;
  this.v = false;
  this.n = this.p = null;
}
function rejoin_default(segments, compareIntersection2, startInside, interpolate, stream) {
  var subject = [], clip2 = [], i, n;
  segments.forEach(function(segment) {
    if ((n2 = segment.length - 1) <= 0) return;
    var n2, p0 = segment[0], p1 = segment[n2], x3;
    if (pointEqual_default(p0, p1)) {
      if (!p0[2] && !p1[2]) {
        stream.lineStart();
        for (i = 0; i < n2; ++i) stream.point((p0 = segment[i])[0], p0[1]);
        stream.lineEnd();
        return;
      }
      p1[0] += 2 * epsilon6;
    }
    subject.push(x3 = new Intersection(p0, segment, null, true));
    clip2.push(x3.o = new Intersection(p0, null, x3, false));
    subject.push(x3 = new Intersection(p1, segment, null, false));
    clip2.push(x3.o = new Intersection(p1, null, x3, true));
  });
  if (!subject.length) return;
  clip2.sort(compareIntersection2);
  link(subject);
  link(clip2);
  for (i = 0, n = clip2.length; i < n; ++i) {
    clip2[i].e = startInside = !startInside;
  }
  var start2 = subject[0], points2, point6;
  while (1) {
    var current = start2, isSubject = true;
    while (current.v) if ((current = current.n) === start2) return;
    points2 = current.z;
    stream.lineStart();
    do {
      current.v = current.o.v = true;
      if (current.e) {
        if (isSubject) {
          for (i = 0, n = points2.length; i < n; ++i) stream.point((point6 = points2[i])[0], point6[1]);
        } else {
          interpolate(current.x, current.n.x, 1, stream);
        }
        current = current.n;
      } else {
        if (isSubject) {
          points2 = current.p.z;
          for (i = points2.length - 1; i >= 0; --i) stream.point((point6 = points2[i])[0], point6[1]);
        } else {
          interpolate(current.x, current.p.x, -1, stream);
        }
        current = current.p;
      }
      current = current.o;
      points2 = current.z;
      isSubject = !isSubject;
    } while (!current.v);
    stream.lineEnd();
  }
}
function link(array4) {
  if (!(n = array4.length)) return;
  var n, i = 0, a2 = array4[0], b;
  while (++i < n) {
    a2.n = b = array4[i];
    b.p = a2;
    a2 = b;
  }
  a2.n = b = array4[0];
  b.p = a2;
}

// ../../../node_modules/d3-geo/src/polygonContains.js
function longitude(point6) {
  return abs3(point6[0]) <= pi2 ? point6[0] : sign2(point6[0]) * ((abs3(point6[0]) + pi2) % tau3 - pi2);
}
function polygonContains_default(polygon, point6) {
  var lambda = longitude(point6), phi = point6[1], sinPhi = sin(phi), normal = [sin(lambda), -cos(lambda), 0], angle = 0, winding = 0;
  var sum4 = new Adder();
  if (sinPhi === 1) phi = halfPi + epsilon6;
  else if (sinPhi === -1) phi = -halfPi - epsilon6;
  for (var i = 0, n = polygon.length; i < n; ++i) {
    if (!(m = (ring = polygon[i]).length)) continue;
    var ring, m, point0 = ring[m - 1], lambda0 = longitude(point0), phi0 = point0[1] / 2 + quarterPi, sinPhi0 = sin(phi0), cosPhi0 = cos(phi0);
    for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {
      var point1 = ring[j], lambda1 = longitude(point1), phi1 = point1[1] / 2 + quarterPi, sinPhi1 = sin(phi1), cosPhi1 = cos(phi1), delta = lambda1 - lambda0, sign4 = delta >= 0 ? 1 : -1, absDelta = sign4 * delta, antimeridian = absDelta > pi2, k2 = sinPhi0 * sinPhi1;
      sum4.add(atan2(k2 * sign4 * sin(absDelta), cosPhi0 * cosPhi1 + k2 * cos(absDelta)));
      angle += antimeridian ? delta + sign4 * tau3 : delta;
      if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
        var arc = cartesianCross(cartesian(point0), cartesian(point1));
        cartesianNormalizeInPlace(arc);
        var intersection = cartesianCross(normal, arc);
        cartesianNormalizeInPlace(intersection);
        var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
        if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {
          winding += antimeridian ^ delta >= 0 ? 1 : -1;
        }
      }
    }
  }
  return (angle < -epsilon6 || angle < epsilon6 && sum4 < -epsilon22) ^ winding & 1;
}

// ../../../node_modules/d3-geo/src/clip/index.js
function clip_default(pointVisible, clipLine, interpolate, start2) {
  return function(sink) {
    var line3 = clipLine(sink), ringBuffer = buffer_default(), ringSink = clipLine(ringBuffer), polygonStarted = false, polygon, segments, ring;
    var clip2 = {
      point: point6,
      lineStart,
      lineEnd,
      polygonStart: function() {
        clip2.point = pointRing;
        clip2.lineStart = ringStart;
        clip2.lineEnd = ringEnd;
        segments = [];
        polygon = [];
      },
      polygonEnd: function() {
        clip2.point = point6;
        clip2.lineStart = lineStart;
        clip2.lineEnd = lineEnd;
        segments = merge(segments);
        var startInside = polygonContains_default(polygon, start2);
        if (segments.length) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          rejoin_default(segments, compareIntersection, startInside, interpolate, sink);
        } else if (startInside) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          interpolate(null, null, 1, sink);
          sink.lineEnd();
        }
        if (polygonStarted) sink.polygonEnd(), polygonStarted = false;
        segments = polygon = null;
      },
      sphere: function() {
        sink.polygonStart();
        sink.lineStart();
        interpolate(null, null, 1, sink);
        sink.lineEnd();
        sink.polygonEnd();
      }
    };
    function point6(lambda, phi) {
      if (pointVisible(lambda, phi)) sink.point(lambda, phi);
    }
    function pointLine(lambda, phi) {
      line3.point(lambda, phi);
    }
    function lineStart() {
      clip2.point = pointLine;
      line3.lineStart();
    }
    function lineEnd() {
      clip2.point = point6;
      line3.lineEnd();
    }
    function pointRing(lambda, phi) {
      ring.push([lambda, phi]);
      ringSink.point(lambda, phi);
    }
    function ringStart() {
      ringSink.lineStart();
      ring = [];
    }
    function ringEnd() {
      pointRing(ring[0][0], ring[0][1]);
      ringSink.lineEnd();
      var clean = ringSink.clean(), ringSegments = ringBuffer.result(), i, n = ringSegments.length, m, segment, point7;
      ring.pop();
      polygon.push(ring);
      ring = null;
      if (!n) return;
      if (clean & 1) {
        segment = ringSegments[0];
        if ((m = segment.length - 1) > 0) {
          if (!polygonStarted) sink.polygonStart(), polygonStarted = true;
          sink.lineStart();
          for (i = 0; i < m; ++i) sink.point((point7 = segment[i])[0], point7[1]);
          sink.lineEnd();
        }
        return;
      }
      if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
      segments.push(ringSegments.filter(validSegment));
    }
    return clip2;
  };
}
function validSegment(segment) {
  return segment.length > 1;
}
function compareIntersection(a2, b) {
  return ((a2 = a2.x)[0] < 0 ? a2[1] - halfPi - epsilon6 : halfPi - a2[1]) - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon6 : halfPi - b[1]);
}

// ../../../node_modules/d3-geo/src/clip/antimeridian.js
var antimeridian_default = clip_default(
  function() {
    return true;
  },
  clipAntimeridianLine,
  clipAntimeridianInterpolate,
  [-pi2, -halfPi]
);
function clipAntimeridianLine(stream) {
  var lambda0 = NaN, phi0 = NaN, sign0 = NaN, clean;
  return {
    lineStart: function() {
      stream.lineStart();
      clean = 1;
    },
    point: function(lambda1, phi1) {
      var sign1 = lambda1 > 0 ? pi2 : -pi2, delta = abs3(lambda1 - lambda0);
      if (abs3(delta - pi2) < epsilon6) {
        stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        stream.point(lambda1, phi0);
        clean = 0;
      } else if (sign0 !== sign1 && delta >= pi2) {
        if (abs3(lambda0 - sign0) < epsilon6) lambda0 -= sign0 * epsilon6;
        if (abs3(lambda1 - sign1) < epsilon6) lambda1 -= sign1 * epsilon6;
        phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);
        stream.point(sign0, phi0);
        stream.lineEnd();
        stream.lineStart();
        stream.point(sign1, phi0);
        clean = 0;
      }
      stream.point(lambda0 = lambda1, phi0 = phi1);
      sign0 = sign1;
    },
    lineEnd: function() {
      stream.lineEnd();
      lambda0 = phi0 = NaN;
    },
    clean: function() {
      return 2 - clean;
    }
  };
}
function clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {
  var cosPhi0, cosPhi1, sinLambda0Lambda1 = sin(lambda0 - lambda1);
  return abs3(sinLambda0Lambda1) > epsilon6 ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1) - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0)) / (cosPhi0 * cosPhi1 * sinLambda0Lambda1)) : (phi0 + phi1) / 2;
}
function clipAntimeridianInterpolate(from2, to, direction, stream) {
  var phi;
  if (from2 == null) {
    phi = direction * halfPi;
    stream.point(-pi2, phi);
    stream.point(0, phi);
    stream.point(pi2, phi);
    stream.point(pi2, 0);
    stream.point(pi2, -phi);
    stream.point(0, -phi);
    stream.point(-pi2, -phi);
    stream.point(-pi2, 0);
    stream.point(-pi2, phi);
  } else if (abs3(from2[0] - to[0]) > epsilon6) {
    var lambda = from2[0] < to[0] ? pi2 : -pi2;
    phi = direction * lambda / 2;
    stream.point(-lambda, phi);
    stream.point(0, phi);
    stream.point(lambda, phi);
  } else {
    stream.point(to[0], to[1]);
  }
}

// ../../../node_modules/d3-geo/src/clip/circle.js
function circle_default(radius2) {
  var cr = cos(radius2), delta = 2 * radians2, smallRadius = cr > 0, notHemisphere = abs3(cr) > epsilon6;
  function interpolate(from2, to, direction, stream) {
    circleStream(stream, radius2, delta, direction, from2, to);
  }
  function visible(lambda, phi) {
    return cos(lambda) * cos(phi) > cr;
  }
  function clipLine(stream) {
    var point0, c0, v0, v00, clean;
    return {
      lineStart: function() {
        v00 = v0 = false;
        clean = 1;
      },
      point: function(lambda, phi) {
        var point1 = [lambda, phi], point22, v2 = visible(lambda, phi), c4 = smallRadius ? v2 ? 0 : code(lambda, phi) : v2 ? code(lambda + (lambda < 0 ? pi2 : -pi2), phi) : 0;
        if (!point0 && (v00 = v0 = v2)) stream.lineStart();
        if (v2 !== v0) {
          point22 = intersect2(point0, point1);
          if (!point22 || pointEqual_default(point0, point22) || pointEqual_default(point1, point22))
            point1[2] = 1;
        }
        if (v2 !== v0) {
          clean = 0;
          if (v2) {
            stream.lineStart();
            point22 = intersect2(point1, point0);
            stream.point(point22[0], point22[1]);
          } else {
            point22 = intersect2(point0, point1);
            stream.point(point22[0], point22[1], 2);
            stream.lineEnd();
          }
          point0 = point22;
        } else if (notHemisphere && point0 && smallRadius ^ v2) {
          var t;
          if (!(c4 & c0) && (t = intersect2(point1, point0, true))) {
            clean = 0;
            if (smallRadius) {
              stream.lineStart();
              stream.point(t[0][0], t[0][1]);
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
            } else {
              stream.point(t[1][0], t[1][1]);
              stream.lineEnd();
              stream.lineStart();
              stream.point(t[0][0], t[0][1], 3);
            }
          }
        }
        if (v2 && (!point0 || !pointEqual_default(point0, point1))) {
          stream.point(point1[0], point1[1]);
        }
        point0 = point1, v0 = v2, c0 = c4;
      },
      lineEnd: function() {
        if (v0) stream.lineEnd();
        point0 = null;
      },
      // Rejoin first and last segments if there were intersections and the first
      // and last points were visible.
      clean: function() {
        return clean | (v00 && v0) << 1;
      }
    };
  }
  function intersect2(a2, b, two) {
    var pa = cartesian(a2), pb = cartesian(b);
    var n1 = [1, 0, 0], n2 = cartesianCross(pa, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
    if (!determinant) return !two && a2;
    var c1 = cr * n2n2 / determinant, c22 = -cr * n1n2 / determinant, n1xn2 = cartesianCross(n1, n2), A5 = cartesianScale(n1, c1), B3 = cartesianScale(n2, c22);
    cartesianAddInPlace(A5, B3);
    var u4 = n1xn2, w = cartesianDot(A5, u4), uu = cartesianDot(u4, u4), t22 = w * w - uu * (cartesianDot(A5, A5) - 1);
    if (t22 < 0) return;
    var t = sqrt2(t22), q = cartesianScale(u4, (-w - t) / uu);
    cartesianAddInPlace(q, A5);
    q = spherical(q);
    if (!two) return q;
    var lambda0 = a2[0], lambda1 = b[0], phi0 = a2[1], phi1 = b[1], z;
    if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;
    var delta2 = lambda1 - lambda0, polar = abs3(delta2 - pi2) < epsilon6, meridian = polar || delta2 < epsilon6;
    if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;
    if (meridian ? polar ? phi0 + phi1 > 0 ^ q[1] < (abs3(q[0] - lambda0) < epsilon6 ? phi0 : phi1) : phi0 <= q[1] && q[1] <= phi1 : delta2 > pi2 ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
      var q1 = cartesianScale(u4, (-w + t) / uu);
      cartesianAddInPlace(q1, A5);
      return [q, spherical(q1)];
    }
  }
  function code(lambda, phi) {
    var r = smallRadius ? radius2 : pi2 - radius2, code2 = 0;
    if (lambda < -r) code2 |= 1;
    else if (lambda > r) code2 |= 2;
    if (phi < -r) code2 |= 4;
    else if (phi > r) code2 |= 8;
    return code2;
  }
  return clip_default(visible, clipLine, interpolate, smallRadius ? [0, -radius2] : [-pi2, radius2 - pi2]);
}

// ../../../node_modules/d3-geo/src/clip/line.js
function line_default(a2, b, x06, y06, x12, y12) {
  var ax = a2[0], ay = a2[1], bx = b[0], by = b[1], t03 = 0, t13 = 1, dx = bx - ax, dy = by - ay, r;
  r = x06 - ax;
  if (!dx && r > 0) return;
  r /= dx;
  if (dx < 0) {
    if (r < t03) return;
    if (r < t13) t13 = r;
  } else if (dx > 0) {
    if (r > t13) return;
    if (r > t03) t03 = r;
  }
  r = x12 - ax;
  if (!dx && r < 0) return;
  r /= dx;
  if (dx < 0) {
    if (r > t13) return;
    if (r > t03) t03 = r;
  } else if (dx > 0) {
    if (r < t03) return;
    if (r < t13) t13 = r;
  }
  r = y06 - ay;
  if (!dy && r > 0) return;
  r /= dy;
  if (dy < 0) {
    if (r < t03) return;
    if (r < t13) t13 = r;
  } else if (dy > 0) {
    if (r > t13) return;
    if (r > t03) t03 = r;
  }
  r = y12 - ay;
  if (!dy && r < 0) return;
  r /= dy;
  if (dy < 0) {
    if (r > t13) return;
    if (r > t03) t03 = r;
  } else if (dy > 0) {
    if (r < t03) return;
    if (r < t13) t13 = r;
  }
  if (t03 > 0) a2[0] = ax + t03 * dx, a2[1] = ay + t03 * dy;
  if (t13 < 1) b[0] = ax + t13 * dx, b[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(x3, y3) {
    return x06 <= x3 && x3 <= x12 && y06 <= y3 && y3 <= y12;
  }
  function interpolate(from2, to, direction, stream) {
    var a2 = 0, a1 = 0;
    if (from2 == null || (a2 = corner(from2, direction)) !== (a1 = corner(to, direction)) || comparePoint(from2, to) < 0 ^ direction > 0) {
      do
        stream.point(a2 === 0 || a2 === 3 ? x06 : x12, a2 > 1 ? y12 : y06);
      while ((a2 = (a2 + direction + 4) % 4) !== a1);
    } else {
      stream.point(to[0], to[1]);
    }
  }
  function corner(p, direction) {
    return abs3(p[0] - x06) < epsilon6 ? direction > 0 ? 0 : 3 : abs3(p[0] - x12) < epsilon6 ? direction > 0 ? 2 : 1 : abs3(p[1] - y06) < epsilon6 ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
  }
  function compareIntersection2(a2, b) {
    return comparePoint(a2.x, b.x);
  }
  function comparePoint(a2, b) {
    var ca3 = corner(a2, 1), cb = corner(b, 1);
    return ca3 !== cb ? ca3 - cb : ca3 === 0 ? b[1] - a2[1] : ca3 === 1 ? a2[0] - b[0] : ca3 === 2 ? a2[1] - b[1] : b[0] - a2[0];
  }
  return function(stream) {
    var activeStream = stream, bufferStream = buffer_default(), segments, polygon, ring, x__, y__, v__, x_, y_, v_, first3, clean;
    var clipStream = {
      point: point6,
      lineStart,
      lineEnd,
      polygonStart,
      polygonEnd
    };
    function point6(x3, y3) {
      if (visible(x3, y3)) activeStream.point(x3, y3);
    }
    function polygonInside() {
      var winding = 0;
      for (var i = 0, n = polygon.length; i < n; ++i) {
        for (var ring2 = polygon[i], j = 1, m = ring2.length, point7 = ring2[0], a0, a1, b0 = point7[0], b1 = point7[1]; j < m; ++j) {
          a0 = b0, a1 = b1, point7 = ring2[j], b0 = point7[0], b1 = point7[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, segments = [], polygon = [], clean = true;
    }
    function polygonEnd() {
      var startInside = polygonInside(), cleanInside = clean && startInside, visible2 = (segments = merge(segments)).length;
      if (cleanInside || visible2) {
        stream.polygonStart();
        if (cleanInside) {
          stream.lineStart();
          interpolate(null, null, 1, stream);
          stream.lineEnd();
        }
        if (visible2) {
          rejoin_default(segments, compareIntersection2, startInside, interpolate, stream);
        }
        stream.polygonEnd();
      }
      activeStream = stream, segments = polygon = ring = null;
    }
    function lineStart() {
      clipStream.point = linePoint;
      if (polygon) polygon.push(ring = []);
      first3 = true;
      v_ = false;
      x_ = y_ = NaN;
    }
    function lineEnd() {
      if (segments) {
        linePoint(x__, y__);
        if (v__ && v_) bufferStream.rejoin();
        segments.push(bufferStream.result());
      }
      clipStream.point = point6;
      if (v_) activeStream.lineEnd();
    }
    function linePoint(x3, y3) {
      var v2 = visible(x3, y3);
      if (polygon) ring.push([x3, y3]);
      if (first3) {
        x__ = x3, y__ = y3, v__ = v2;
        first3 = false;
        if (v2) {
          activeStream.lineStart();
          activeStream.point(x3, y3);
        }
      } else {
        if (v2 && v_) activeStream.point(x3, y3);
        else {
          var a2 = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))], b = [x3 = Math.max(clipMin, Math.min(clipMax, x3)), y3 = Math.max(clipMin, Math.min(clipMax, y3))];
          if (line_default(a2, b, x06, y06, x12, y12)) {
            if (!v_) {
              activeStream.lineStart();
              activeStream.point(a2[0], a2[1]);
            }
            activeStream.point(b[0], b[1]);
            if (!v2) activeStream.lineEnd();
            clean = false;
          } else if (v2) {
            activeStream.lineStart();
            activeStream.point(x3, y3);
            clean = false;
          }
        }
      }
      x_ = x3, y_ = y3, v_ = v2;
    }
    return clipStream;
  };
}

// ../../../node_modules/d3-geo/src/graticule.js
function graticuleX(y06, y12, dy) {
  var y3 = range(y06, y12 - epsilon6, dy).concat(y12);
  return function(x3) {
    return y3.map(function(y4) {
      return [x3, y4];
    });
  };
}
function graticuleY(x06, x12, dx) {
  var x3 = range(x06, x12 - epsilon6, dx).concat(x12);
  return function(y3) {
    return x3.map(function(x4) {
      return [x4, y3];
    });
  };
}
function graticule() {
  var x12, x06, X13, X03, y12, y06, Y13, Y03, dx = 10, dy = dx, DX = 90, DY = 360, x3, y3, X3, Y3, precision = 2.5;
  function graticule4() {
    return { type: "MultiLineString", coordinates: lines() };
  }
  function lines() {
    return range(ceil2(X03 / DX) * DX, X13, DX).map(X3).concat(range(ceil2(Y03 / DY) * DY, Y13, DY).map(Y3)).concat(range(ceil2(x06 / dx) * dx, x12, dx).filter(function(x4) {
      return abs3(x4 % DX) > epsilon6;
    }).map(x3)).concat(range(ceil2(y06 / dy) * dy, y12, dy).filter(function(y4) {
      return abs3(y4 % DY) > epsilon6;
    }).map(y3));
  }
  graticule4.lines = function() {
    return lines().map(function(coordinates) {
      return { type: "LineString", coordinates };
    });
  };
  graticule4.outline = function() {
    return {
      type: "Polygon",
      coordinates: [
        X3(X03).concat(
          Y3(Y13).slice(1),
          X3(X13).reverse().slice(1),
          Y3(Y03).reverse().slice(1)
        )
      ]
    };
  };
  graticule4.extent = function(_) {
    if (!arguments.length) return graticule4.extentMinor();
    return graticule4.extentMajor(_).extentMinor(_);
  };
  graticule4.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 graticule4.precision(precision);
  };
  graticule4.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 graticule4.precision(precision);
  };
  graticule4.step = function(_) {
    if (!arguments.length) return graticule4.stepMinor();
    return graticule4.stepMajor(_).stepMinor(_);
  };
  graticule4.stepMajor = function(_) {
    if (!arguments.length) return [DX, DY];
    DX = +_[0], DY = +_[1];
    return graticule4;
  };
  graticule4.stepMinor = function(_) {
    if (!arguments.length) return [dx, dy];
    dx = +_[0], dy = +_[1];
    return graticule4;
  };
  graticule4.precision = function(_) {
    if (!arguments.length) return precision;
    precision = +_;
    x3 = graticuleX(y06, y12, 90);
    y3 = graticuleY(x06, x12, precision);
    X3 = graticuleX(Y03, Y13, 90);
    Y3 = graticuleY(X03, X13, precision);
    return graticule4;
  };
  return graticule4.extentMajor([[-180, -90 + epsilon6], [180, 90 - epsilon6]]).extentMinor([[-180, -80 - epsilon6], [180, 80 + epsilon6]]);
}
function graticule10() {
  return graticule()();
}

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

// ../../../node_modules/d3-geo/src/path/area.js
var areaSum = new Adder();
var areaRingSum = new Adder();
var x00;
var y00;
var x02;
var y02;
var areaStream = {
  point: noop2,
  lineStart: noop2,
  lineEnd: noop2,
  polygonStart: function() {
    areaStream.lineStart = areaRingStart;
    areaStream.lineEnd = areaRingEnd;
  },
  polygonEnd: function() {
    areaStream.lineStart = areaStream.lineEnd = areaStream.point = noop2;
    areaSum.add(abs3(areaRingSum));
    areaRingSum = new Adder();
  },
  result: function() {
    var area3 = areaSum / 2;
    areaSum = new Adder();
    return area3;
  }
};
function areaRingStart() {
  areaStream.point = areaPointFirst;
}
function areaPointFirst(x3, y3) {
  areaStream.point = areaPoint;
  x00 = x02 = x3, y00 = y02 = y3;
}
function areaPoint(x3, y3) {
  areaRingSum.add(y02 * x3 - x02 * y3);
  x02 = x3, y02 = y3;
}
function areaRingEnd() {
  areaPoint(x00, y00);
}
var area_default2 = areaStream;

// ../../../node_modules/d3-geo/src/path/bounds.js
var x03 = Infinity;
var y03 = x03;
var x1 = -x03;
var y1 = x1;
var boundsStream = {
  point: boundsPoint,
  lineStart: noop2,
  lineEnd: noop2,
  polygonStart: noop2,
  polygonEnd: noop2,
  result: function() {
    var bounds = [[x03, y03], [x1, y1]];
    x1 = y1 = -(y03 = x03 = Infinity);
    return bounds;
  }
};
function boundsPoint(x3, y3) {
  if (x3 < x03) x03 = x3;
  if (x3 > x1) x1 = x3;
  if (y3 < y03) y03 = y3;
  if (y3 > y1) y1 = y3;
}
var bounds_default = boundsStream;

// ../../../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 centroid3 = 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 centroid3;
  }
};
function centroidPoint2(x3, y3) {
  X02 += x3;
  Y02 += y3;
  ++Z02;
}
function centroidLineStart2() {
  centroidStream2.point = centroidPointFirstLine;
}
function centroidPointFirstLine(x3, y3) {
  centroidStream2.point = centroidPointLine;
  centroidPoint2(x04 = x3, y04 = y3);
}
function centroidPointLine(x3, y3) {
  var dx = x3 - x04, dy = y3 - y04, z = sqrt2(dx * dx + dy * dy);
  X12 += z * (x04 + x3) / 2;
  Y12 += z * (y04 + y3) / 2;
  Z12 += z;
  centroidPoint2(x04 = x3, y04 = y3);
}
function centroidLineEnd2() {
  centroidStream2.point = centroidPoint2;
}
function centroidRingStart2() {
  centroidStream2.point = centroidPointFirstRing;
}
function centroidRingEnd2() {
  centroidPointRing(x002, y002);
}
function centroidPointFirstRing(x3, y3) {
  centroidStream2.point = centroidPointRing;
  centroidPoint2(x002 = x04 = x3, y002 = y04 = y3);
}
function centroidPointRing(x3, y3) {
  var dx = x3 - x04, dy = y3 - y04, z = sqrt2(dx * dx + dy * dy);
  X12 += z * (x04 + x3) / 2;
  Y12 += z * (y04 + y3) / 2;
  Z12 += z;
  z = y04 * x3 - x04 * y3;
  X22 += z * (x04 + x3);
  Y22 += z * (y04 + y3);
  Z22 += z * 3;
  centroidPoint2(x04 = x3, y04 = y3);
}
var centroid_default2 = centroidStream2;

// ../../../node_modules/d3-geo/src/path/context.js
function PathContext(context) {
  this._context = context;
}
PathContext.prototype = {
  _radius: 4.5,
  pointRadius: function(_) {
    return this._radius = _, this;
  },
  polygonStart: function() {
    this._line = 0;
  },
  polygonEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line === 0) this._context.closePath();
    this._point = NaN;
  },
  point: function(x3, y3) {
    switch (this._point) {
      case 0: {
        this._context.moveTo(x3, y3);
        this._point = 1;
        break;
      }
      case 1: {
        this._context.lineTo(x3, y3);
        break;
      }
      default: {
        this._context.moveTo(x3 + this._radius, y3);
        this._context.arc(x3, y3, 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 length4 = +lengthSum;
    lengthSum = new Adder();
    return length4;
  }
};
function lengthPointFirst(x3, y3) {
  lengthStream.point = lengthPoint;
  x003 = x05 = x3, y003 = y05 = y3;
}
function lengthPoint(x3, y3) {
  x05 -= x3, y05 -= y3;
  lengthSum.add(sqrt2(x05 * x05 + y05 * y05));
  x05 = x3, y05 = y3;
}
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(x3, y3) {
    switch (this._point) {
      case 0: {
        this._append`M${x3},${y3}`;
        this._point = 1;
        break;
      }
      case 1: {
        this._append`L${x3},${y3}`;
        break;
      }
      default: {
        this._append`M${x3},${y3}`;
        if (this._radius !== cacheRadius || this._append !== cacheAppend) {
          const r = this._radius;
          const s2 = this._;
          this._ = "";
          this._append`m0,${r}a${r},${r} 0 1,1 0,${-2 * r}a${r},${r} 0 1,1 0,${2 * r}z`;
          cacheRadius = r;
          cacheAppend = this._append;
          cacheCircle = this._;
          this._ = s2;
        }
        this._ += cacheCircle;
        break;
      }
    }
  }
  result() {
    const result = this._;
    this._ = "";
    return result.length ? result : null;
  }
};
function append2(strings) {
  let i = 1;
  this._ += strings[0];
  for (const j = strings.length; i < j; ++i) {
    this._ += arguments[i] + strings[i];
  }
}
function appendRound2(digits) {
  const d = Math.floor(digits);
  if (!(d >= 0)) throw new RangeError(`invalid digits: ${digits}`);
  if (d > 15) return append2;
  if (d !== cacheDigits) {
    const k2 = 10 ** d;
    cacheDigits = d;
    cacheAppend = function append3(strings) {
      let i = 1;
      this._ += strings[0];
      for (const j = strings.length; i < j; ++i) {
        this._ += Math.round(arguments[i] * k2) / k2 + strings[i];
      }
    };
  }
  return cacheAppend;
}

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

// ../../../node_modules/d3-geo/src/transform.js
function transform_default(methods) {
  return {
    stream: transformer(methods)
  };
}
function transformer(methods) {
  return function(stream) {
    var s2 = new TransformStream();
    for (var key in methods) s2[key] = methods[key];
    s2.stream = stream;
    return s2;
  };
}
function TransformStream() {
}
TransformStream.prototype = {
  constructor: TransformStream,
  point: function(x3, y3) {
    this.stream.point(x3, y3);
  },
  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, object) {
  var clip2 = projection3.clipExtent && projection3.clipExtent();
  projection3.scale(150).translate([0, 0]);
  if (clip2 != null) projection3.clipExtent(null);
  stream_default(object, projection3.stream(bounds_default));
  fitBounds(bounds_default.result());
  if (clip2 != null) projection3.clipExtent(clip2);
  return projection3;
}
function fitExtent(projection3, extent4, object) {
  return fit(projection3, function(b) {
    var w = extent4[1][0] - extent4[0][0], h = extent4[1][1] - extent4[0][1], k2 = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])), x3 = +extent4[0][0] + (w - k2 * (b[1][0] + b[0][0])) / 2, y3 = +extent4[0][1] + (h - k2 * (b[1][1] + b[0][1])) / 2;
    projection3.scale(150 * k2).translate([x3, y3]);
  }, object);
}
function fitSize(projection3, size, object) {
  return fitExtent(projection3, [[0, 0], size], object);
}
function fitWidth(projection3, width2, object) {
  return fit(projection3, function(b) {
    var w = +width2, k2 = w / (b[1][0] - b[0][0]), x3 = (w - k2 * (b[1][0] + b[0][0])) / 2, y3 = -k2 * b[0][1];
    projection3.scale(150 * k2).translate([x3, y3]);
  }, object);
}
function fitHeight(projection3, height2, object) {
  return fit(projection3, function(b) {
    var h = +height2, k2 = h / (b[1][1] - b[0][1]), x3 = -k2 * b[0][0], y3 = (h - k2 * (b[1][1] + b[0][1])) / 2;
    projection3.scale(150 * k2).translate([x3, y3]);
  }, object);
}

// ../../../node_modules/d3-geo/src/projection/resample.js
var maxDepth = 16;
var cosMinDistance = cos(30 * radians2);
function resample_default(project2, delta2) {
  return +delta2 ? resample(project2, delta2) : resampleNone(project2);
}
function resampleNone(project2) {
  return transformer({
    point: function(x3, y3) {
      x3 = project2(x3, y3);
      this.stream.point(x3[0], x3[1]);
    }
  });
}
function resample(project2, delta2) {
  function resampleLineTo(x06, y06, lambda0, a0, b0, c0, x12, y12, lambda1, a1, b1, c1, depth, stream) {
    var dx = x12 - x06, dy = y12 - y06, d2 = dx * dx + dy * dy;
    if (d2 > 4 * delta2 && depth--) {
      var a2 = a0 + a1, b = b0 + b1, c4 = c0 + c1, m = sqrt2(a2 * a2 + b * b + c4 * c4), phi2 = asin(c4 /= m), lambda2 = abs3(abs3(c4) - 1) < epsilon6 || abs3(lambda0 - lambda1) < epsilon6 ? (lambda0 + lambda1) / 2 : atan2(b, a2), p = project2(lambda2, phi2), x22 = p[0], y22 = p[1], dx2 = x22 - x06, dy2 = y22 - y06, dz = dy * dx2 - dx * dy2;
      if (dz * dz / d2 > delta2 || abs3((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
        resampleLineTo(x06, y06, lambda0, a0, b0, c0, x22, y22, lambda2, a2 /= m, b /= m, c4, depth, stream);
        stream.point(x22, y22);
        resampleLineTo(x22, y22, lambda2, a2, b, c4, x12, y12, lambda1, a1, b1, c1, depth, stream);
      }
    }
  }
  return function(stream) {
    var lambda002, x004, y004, a00, b00, c00, lambda0, x06, y06, a0, b0, c0;
    var resampleStream = {
      point: point6,
      lineStart,
      lineEnd,
      polygonStart: function() {
        stream.polygonStart();
        resampleStream.lineStart = ringStart;
      },
      polygonEnd: function() {
        stream.polygonEnd();
        resampleStream.lineStart = lineStart;
      }
    };
    function point6(x3, y3) {
      x3 = project2(x3, y3);
      stream.point(x3[0], x3[1]);
    }
    function lineStart() {
      x06 = NaN;
      resampleStream.point = linePoint;
      stream.lineStart();
    }
    function linePoint(lambda, phi) {
      var c4 = cartesian([lambda, phi]), p = project2(lambda, phi);
      resampleLineTo(x06, y06, lambda0, a0, b0, c0, x06 = p[0], y06 = p[1], lambda0 = lambda, a0 = c4[0], b0 = c4[1], c0 = c4[2], maxDepth, stream);
      stream.point(x06, y06);
    }
    function lineEnd() {
      resampleStream.point = point6;
      stream.lineEnd();
    }
    function ringStart() {
      lineStart();
      resampleStream.point = ringPoint;
      resampleStream.lineEnd = ringEnd;
    }
    function ringPoint(lambda, phi) {
      linePoint(lambda002 = lambda, phi), x004 = x06, y004 = y06, a00 = a0, b00 = b0, c00 = c0;
      resampleStream.point = linePoint;
    }
    function ringEnd() {
      resampleLineTo(x06, y06, lambda0, a0, b0, c0, x004, y004, lambda002, a00, b00, c00, maxDepth, stream);
      resampleStream.lineEnd = lineEnd;
      lineEnd();
    }
    return resampleStream;
  };
}

// ../../../node_modules/d3-geo/src/projection/index.js
var transformRadians = transformer({
  point: function(x3, y3) {
    this.stream.point(x3 * radians2, y3 * radians2);
  }
});
function transformRotate(rotate) {
  return transformer({
    point: function(x3, y3) {
      var r = rotate(x3, y3);
      return this.stream.point(r[0], r[1]);
    }
  });
}
function scaleTranslate(k2, dx, dy, sx, sy) {
  function transform3(x3, y3) {
    x3 *= sx;
    y3 *= sy;
    return [dx + k2 * x3, dy - k2 * y3];
  }
  transform3.invert = function(x3, y3) {
    return [(x3 - dx) / k2 * sx, (dy - y3) / k2 * sy];
  };
  return transform3;
}
function scaleTranslateRotate(k2, dx, dy, sx, sy, alpha) {
  if (!alpha) return scaleTranslate(k2, dx, dy, sx, sy);
  var cosAlpha = cos(alpha), sinAlpha = sin(alpha), a2 = cosAlpha * k2, b = sinAlpha * k2, ai = cosAlpha / k2, bi = sinAlpha / k2, ci = (sinAlpha * dy - cosAlpha * dx) / k2, fi = (sinAlpha * dx + cosAlpha * dy) / k2;
  function transform3(x3, y3) {
    x3 *= sx;
    y3 *= sy;
    return [a2 * x3 - b * y3 + dx, dy - b * x3 - a2 * y3];
  }
  transform3.invert = function(x3, y3) {
    return [sx * (ai * x3 - bi * y3 + ci), sy * (fi - bi * x3 - ai * y3)];
  };
  return transform3;
}
function projection(project2) {
  return projectionMutator(function() {
    return project2;
  })();
}
function projectionMutator(projectAt) {
  var project2, k2 = 150, x3 = 480, y3 = 250, lambda = 0, phi = 0, deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, 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, cache, cacheStream;
  function projection3(point6) {
    return projectRotateTransform(point6[0] * radians2, point6[1] * radians2);
  }
  function invert2(point6) {
    point6 = projectRotateTransform.invert(point6[0], point6[1]);
    return point6 && [point6[0] * degrees3, point6[1] * degrees3];
  }
  projection3.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));
  };
  projection3.preclip = function(_) {
    return arguments.length ? (preclip = _, theta = void 0, reset()) : preclip;
  };
  projection3.postclip = function(_) {
    return arguments.length ? (postclip = _, x06 = y06 = x12 = y12 = null, reset()) : postclip;
  };
  projection3.clipAngle = function(_) {
    return arguments.length ? (preclip = +_ ? circle_default(theta = _ * radians2) : (theta = null, antimeridian_default), reset()) : 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]), reset()) : x06 == null ? null : [[x06, y06], [x12, y12]];
  };
  projection3.scale = function(_) {
    return arguments.length ? (k2 = +_, recenter()) : k2;
  };
  projection3.translate = function(_) {
    return arguments.length ? (x3 = +_[0], y3 = +_[1], recenter()) : [x3, y3];
  };
  projection3.center = function(_) {
    return arguments.length ? (lambda = _[0] % 360 * radians2, phi = _[1] % 360 * radians2, recenter()) : [lambda * degrees3, phi * 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 = _ * _), reset()) : sqrt2(delta2);
  };
  projection3.fitExtent = function(extent4, object) {
    return fitExtent(projection3, extent4, object);
  };
  projection3.fitSize = function(size, object) {
    return fitSize(projection3, size, object);
  };
  projection3.fitWidth = function(width2, object) {
    return fitWidth(projection3, width2, object);
  };
  projection3.fitHeight = function(height2, object) {
    return fitHeight(projection3, height2, object);
  };
  function recenter() {
    var center2 = scaleTranslateRotate(k2, 0, 0, sx, sy, alpha).apply(null, project2(lambda, phi)), transform3 = scaleTranslateRotate(k2, x3 - center2[0], y3 - center2[1], sx, sy, alpha);
    rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);
    projectTransform = compose_default(project2, transform3);
    projectRotateTransform = compose_default(rotate, projectTransform);
    projectResample = resample_default(projectTransform, delta2);
    return reset();
  }
  function reset() {
    cache = cacheStream = null;
    return projection3;
  }
  return function() {
    project2 = projectAt.apply(this, arguments);
    projection3.invert = project2.invert && invert2;
    return recenter();
  };
}

// ../../../node_modules/d3-geo/src/projection/conic.js
function conicProjection(projectAt) {
  var phi0 = 0, phi1 = pi2 / 3, m = projectionMutator(projectAt), p = m(phi0, phi1);
  p.parallels = function(_) {
    return arguments.length ? m(phi0 = _[0] * radians2, phi1 = _[1] * radians2) : [phi0 * degrees3, phi1 * degrees3];
  };
  return p;
}

// ../../../node_modules/d3-geo/src/projection/cylindricalEqualArea.js
function cylindricalEqualAreaRaw(phi0) {
  var cosPhi0 = cos(phi0);
  function forward(lambda, phi) {
    return [lambda * cosPhi0, sin(phi) / cosPhi0];
  }
  forward.invert = function(x3, y3) {
    return [x3 / cosPhi0, asin(y3 * cosPhi0)];
  };
  return forward;
}

// ../../../node_modules/d3-geo/src/projection/conicEqualArea.js
function conicEqualAreaRaw(y06, y12) {
  var sy0 = sin(y06), n = (sy0 + sin(y12)) / 2;
  if (abs3(n) < epsilon6) return cylindricalEqualAreaRaw(y06);
  var c4 = 1 + sy0 * (2 * n - sy0), r0 = sqrt2(c4) / n;
  function project2(x3, y3) {
    var r = sqrt2(c4 - 2 * n * sin(y3)) / n;
    return [r * sin(x3 *= n), r0 - r * cos(x3)];
  }
  project2.invert = function(x3, y3) {
    var r0y = r0 - y3, l = atan2(x3, abs3(r0y)) * sign2(r0y);
    if (r0y * n < 0)
      l -= pi2 * sign2(x3) * sign2(r0y);
    return [l / n, asin((c4 - (x3 * x3 + r0y * r0y) * n * n) / (2 * n))];
  };
  return project2;
}
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 n = streams.length;
  return {
    point: function(x3, y3) {
      var i = -1;
      while (++i < n) streams[i].point(x3, y3);
    },
    sphere: function() {
      var i = -1;
      while (++i < n) streams[i].sphere();
    },
    lineStart: function() {
      var i = -1;
      while (++i < n) streams[i].lineStart();
    },
    lineEnd: function() {
      var i = -1;
      while (++i < n) streams[i].lineEnd();
    },
    polygonStart: function() {
      var i = -1;
      while (++i < n) streams[i].polygonStart();
    },
    polygonEnd: function() {
      var i = -1;
      while (++i < n) streams[i].polygonEnd();
    }
  };
}
function albersUsa_default() {
  var cache, 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, point6, pointStream = { point: function(x3, y3) {
    point6 = [x3, y3];
  } };
  function albersUsa(coordinates) {
    var x3 = coordinates[0], y3 = coordinates[1];
    return point6 = null, (lower48Point.point(x3, y3), point6) || (alaskaPoint.point(x3, y3), point6) || (hawaiiPoint.point(x3, y3), point6);
  }
  albersUsa.invert = function(coordinates) {
    var k2 = lower48.scale(), t = lower48.translate(), x3 = (coordinates[0] - t[0]) / k2, y3 = (coordinates[1] - t[1]) / k2;
    return (y3 >= 0.12 && y3 < 0.234 && x3 >= -0.425 && x3 < -0.214 ? alaska : y3 >= 0.166 && y3 < 0.234 && x3 >= -0.214 && x3 < -0.115 ? hawaii : lower48).invert(coordinates);
  };
  albersUsa.stream = function(stream) {
    return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);
  };
  albersUsa.precision = function(_) {
    if (!arguments.length) return lower48.precision();
    lower48.precision(_), alaska.precision(_), hawaii.precision(_);
    return reset();
  };
  albersUsa.scale = function(_) {
    if (!arguments.length) return lower48.scale();
    lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);
    return albersUsa.translate(lower48.translate());
  };
  albersUsa.translate = function(_) {
    if (!arguments.length) return lower48.translate();
    var k2 = lower48.scale(), x3 = +_[0], y3 = +_[1];
    lower48Point = lower48.translate(_).clipExtent([[x3 - 0.455 * k2, y3 - 0.238 * k2], [x3 + 0.455 * k2, y3 + 0.238 * k2]]).stream(pointStream);
    alaskaPoint = alaska.translate([x3 - 0.307 * k2, y3 + 0.201 * k2]).clipExtent([[x3 - 0.425 * k2 + epsilon6, y3 + 0.12 * k2 + epsilon6], [x3 - 0.214 * k2 - epsilon6, y3 + 0.234 * k2 - epsilon6]]).stream(pointStream);
    hawaiiPoint = hawaii.translate([x3 - 0.205 * k2, y3 + 0.212 * k2]).clipExtent([[x3 - 0.214 * k2 + epsilon6, y3 + 0.166 * k2 + epsilon6], [x3 - 0.115 * k2 - epsilon6, y3 + 0.234 * k2 - epsilon6]]).stream(pointStream);
    return reset();
  };
  albersUsa.fitExtent = function(extent4, object) {
    return fitExtent(albersUsa, extent4, object);
  };
  albersUsa.fitSize = function(size, object) {
    return fitSize(albersUsa, size, object);
  };
  albersUsa.fitWidth = function(width2, object) {
    return fitWidth(albersUsa, width2, object);
  };
  albersUsa.fitHeight = function(height2, object) {
    return fitHeight(albersUsa, height2, object);
  };
  function reset() {
    cache = cacheStream = null;
    return albersUsa;
  }
  return albersUsa.scale(1070);
}

// ../../../node_modules/d3-geo/src/projection/azimuthal.js
function azimuthalRaw(scale3) {
  return function(x3, y3) {
    var cx = cos(x3), cy = cos(y3), k2 = scale3(cx * cy);
    if (k2 === Infinity) return [2, 0];
    return [
      k2 * cy * sin(x3),
      k2 * sin(y3)
    ];
  };
}
function azimuthalInvert(angle) {
  return function(x3, y3) {
    var z = sqrt2(x3 * x3 + y3 * y3), c4 = angle(z), sc = sin(c4), cc2 = cos(c4);
    return [
      atan2(x3 * sc, z * cc2),
      asin(z && y3 * sc / z)
    ];
  };
}

// ../../../node_modules/d3-geo/src/projection/azimuthalEqualArea.js
var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
  return sqrt2(2 / (1 + cxcy));
});
azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
  return 2 * asin(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 = acos(c4)) && c4 / sin(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, phi) {
  return [lambda, log2(tan((halfPi + phi) / 2))];
}
mercatorRaw.invert = function(x3, y3) {
  return [x3, 2 * atan(exp2(y3)) - halfPi];
};
function mercator_default() {
  return mercatorProjection(mercatorRaw).scale(961 / tau3);
}
function mercatorProjection(project2) {
  var m = projection(project2), center2 = m.center, scale3 = m.scale, translate = m.translate, clipExtent = m.clipExtent, x06 = null, y06, x12, y12;
  m.scale = function(_) {
    return arguments.length ? (scale3(_), reclip()) : scale3();
  };
  m.translate = function(_) {
    return arguments.length ? (translate(_), reclip()) : translate();
  };
  m.center = function(_) {
    return arguments.length ? (center2(_), reclip()) : center2();
  };
  m.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 = pi2 * scale3(), t = m(rotation_default(m.rotate()).invert([0, 0]));
    return clipExtent(x06 == null ? [[t[0] - k2, t[1] - k2], [t[0] + k2, t[1] + k2]] : project2 === mercatorRaw ? [[Math.max(t[0] - k2, x06), y06], [Math.min(t[0] + k2, x12), y12]] : [[x06, Math.max(t[1] - k2, y06)], [x12, Math.min(t[1] + k2, y12)]]);
  }
  return reclip();
}

// ../../../node_modules/d3-geo/src/projection/conicConformal.js
function tany(y3) {
  return tan((halfPi + y3) / 2);
}
function conicConformalRaw(y06, y12) {
  var cy0 = cos(y06), n = y06 === y12 ? sin(y06) : log2(cy0 / cos(y12)) / log2(tany(y12) / tany(y06)), f = cy0 * pow3(tany(y06), n) / n;
  if (!n) return mercatorRaw;
  function project2(x3, y3) {
    if (f > 0) {
      if (y3 < -halfPi + epsilon6) y3 = -halfPi + epsilon6;
    } else {
      if (y3 > halfPi - epsilon6) y3 = halfPi - epsilon6;
    }
    var r = f / pow3(tany(y3), n);
    return [r * sin(n * x3), f - r * cos(n * x3)];
  }
  project2.invert = function(x3, y3) {
    var fy = f - y3, r = sign2(n) * sqrt2(x3 * x3 + fy * fy), l = atan2(x3, abs3(fy)) * sign2(fy);
    if (fy * n < 0)
      l -= pi2 * sign2(x3) * sign2(fy);
    return [l / n, 2 * atan(pow3(f / r, 1 / n)) - halfPi];
  };
  return project2;
}
function conicConformal_default() {
  return conicProjection(conicConformalRaw).scale(109.5).parallels([30, 30]);
}

// ../../../node_modules/d3-geo/src/projection/equirectangular.js
function equirectangularRaw(lambda, phi) {
  return [lambda, phi];
}
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 = cos(y06), n = y06 === y12 ? sin(y06) : (cy0 - cos(y12)) / (y12 - y06), g = cy0 / n + y06;
  if (abs3(n) < epsilon6) return equirectangularRaw;
  function project2(x3, y3) {
    var gy = g - y3, nx = n * x3;
    return [gy * sin(nx), g - gy * cos(nx)];
  }
  project2.invert = function(x3, y3) {
    var gy = g - y3, l = atan2(x3, abs3(gy)) * sign2(gy);
    if (gy * n < 0)
      l -= pi2 * sign2(x3) * sign2(gy);
    return [l / n, g - sign2(n) * sqrt2(x3 * x3 + gy * gy)];
  };
  return project2;
}
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 = sqrt2(3) / 2;
var iterations = 12;
function equalEarthRaw(lambda, phi) {
  var l = asin(M * sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;
  return [
    lambda * cos(l) / (M * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2))),
    l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2))
  ];
}
equalEarthRaw.invert = function(x3, y3) {
  var l = y3, l2 = l * l, l6 = l2 * l2 * l2;
  for (var i = 0, delta, fy, fpy; i < iterations; ++i) {
    fy = l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2)) - y3;
    fpy = A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2);
    l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;
    if (abs3(delta) < epsilon22) break;
  }
  return [
    M * x3 * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2)) / cos(l),
    asin(sin(l) / M)
  ];
};
function equalEarth_default() {
  return projection(equalEarthRaw).scale(177.158);
}

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

// ../../../node_modules/d3-geo/src/projection/orthographic.js
function orthographicRaw(x3, y3) {
  return [cos(y3) * sin(x3), sin(y3)];
}
orthographicRaw.invert = azimuthalInvert(asin);
function orthographic_default() {
  return projection(orthographicRaw).scale(249.5).clipAngle(90 + epsilon6);
}

// ../../../node_modules/d3-geo/src/projection/stereographic.js
function stereographicRaw(x3, y3) {
  var cy = cos(y3), k2 = 1 + cos(x3) * cy;
  return [cy * sin(x3) / k2, sin(y3) / 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, phi) {
  return [log2(tan((halfPi + phi) / 2)), -lambda];
}
transverseMercatorRaw.invert = function(x3, y3) {
  return [-y3, 2 * atan(exp2(x3)) - halfPi];
};
function transverseMercator_default() {
  var m = mercatorProjection(transverseMercatorRaw), center2 = m.center, rotate = m.rotate;
  m.center = function(_) {
    return arguments.length ? center2([-_[1], _[0]]) : (_ = center2(), [_[1], -_[0]]);
  };
  m.rotate = function(_) {
    return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);
  };
  return rotate([0, 0, 90]).scale(159.155);
}

// ../../../node_modules/d3-hierarchy/src/cluster.js
function defaultSeparation(a2, b) {
  return a2.parent === b.parent ? 1 : 2;
}
function meanX(children2) {
  return children2.reduce(meanXReduce, 0) / children2.length;
}
function meanXReduce(x3, c4) {
  return x3 + c4.x;
}
function maxY(children2) {
  return 1 + children2.reduce(maxYReduce, 0);
}
function maxYReduce(y3, c4) {
  return Math.max(y3, c4.y);
}
function leafLeft(node) {
  var children2;
  while (children2 = node.children) node = children2[0];
  return node;
}
function leafRight(node) {
  var children2;
  while (children2 = node.children) node = children2[children2.length - 1];
  return node;
}
function cluster_default() {
  var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = false;
  function cluster2(root2) {
    var previousNode, x3 = 0;
    root2.eachAfter(function(node) {
      var children2 = node.children;
      if (children2) {
        node.x = meanX(children2);
        node.y = maxY(children2);
      } else {
        node.x = previousNode ? x3 += separation(node, previousNode) : 0;
        node.y = 0;
        previousNode = node;
      }
    });
    var left2 = leafLeft(root2), right2 = leafRight(root2), x06 = left2.x - separation(left2, right2) / 2, x12 = right2.x + separation(right2, left2) / 2;
    return root2.eachAfter(nodeSize ? function(node) {
      node.x = (node.x - root2.x) * dx;
      node.y = (root2.y - node.y) * dy;
    } : function(node) {
      node.x = (node.x - x06) / (x12 - x06) * dx;
      node.y = (1 - (root2.y ? node.y / root2.y : 1)) * dy;
    });
  }
  cluster2.separation = function(x3) {
    return arguments.length ? (separation = x3, cluster2) : separation;
  };
  cluster2.size = function(x3) {
    return arguments.length ? (nodeSize = false, dx = +x3[0], dy = +x3[1], cluster2) : nodeSize ? null : [dx, dy];
  };
  cluster2.nodeSize = function(x3) {
    return arguments.length ? (nodeSize = true, dx = +x3[0], dy = +x3[1], cluster2) : nodeSize ? [dx, dy] : null;
  };
  return cluster2;
}

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

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

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

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

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

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

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

// ../../../node_modules/d3-hierarchy/src/hierarchy/path.js
function path_default2(end) {
  var start2 = this, ancestor = leastCommonAncestor(start2, end), nodes = [start2];
  while (start2 !== ancestor) {
    start2 = start2.parent;
    nodes.push(start2);
  }
  var k2 = nodes.length;
  while (end !== ancestor) {
    nodes.splice(k2, 0, end);
    end = end.parent;
  }
  return nodes;
}
function leastCommonAncestor(a2, b) {
  if (a2 === b) return a2;
  var aNodes = a2.ancestors(), bNodes = b.ancestors(), c4 = null;
  a2 = aNodes.pop();
  b = bNodes.pop();
  while (a2 === b) {
    c4 = a2;
    a2 = aNodes.pop();
    b = 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 root2 = this, links = [];
  root2.each(function(node) {
    if (node !== root2) {
      links.push({ source: node.parent, target: node });
    }
  });
  return links;
}

// ../../../node_modules/d3-hierarchy/src/hierarchy/iterator.js
function* iterator_default2() {
  var node = this, current, next = [node], children2, i, n;
  do {
    current = next.reverse(), next = [];
    while (node = current.pop()) {
      yield node;
      if (children2 = node.children) {
        for (i = 0, n = children2.length; i < n; ++i) {
          next.push(children2[i]);
        }
      }
    }
  } while (next.length);
}

// ../../../node_modules/d3-hierarchy/src/hierarchy/index.js
function hierarchy(data, children2) {
  if (data instanceof Map) {
    data = [void 0, data];
    if (children2 === void 0) children2 = mapChildren;
  } else if (children2 === void 0) {
    children2 = objectChildren;
  }
  var root2 = new Node(data), node, nodes = [root2], child, childs, i, n;
  while (node = nodes.pop()) {
    if ((childs = children2(node.data)) && (n = (childs = Array.from(childs)).length)) {
      node.children = childs;
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = childs[i] = new Node(childs[i]));
        child.parent = node;
        child.depth = node.depth + 1;
      }
    }
  }
  return root2.eachBefore(computeHeight);
}
function node_copy() {
  return hierarchy(this).eachBefore(copyData);
}
function objectChildren(d) {
  return d.children;
}
function mapChildren(d) {
  return Array.isArray(d) ? d[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(data) {
  this.data = data;
  this.depth = this.height = 0;
  this.parent = null;
}
Node.prototype = hierarchy.prototype = {
  constructor: Node,
  count: count_default,
  each: each_default2,
  eachAfter: eachAfter_default,
  eachBefore: eachBefore_default,
  find: find_default,
  sum: sum_default,
  sort: sort_default2,
  path: path_default2,
  ancestors: ancestors_default,
  descendants: descendants_default,
  leaves: leaves_default,
  links: links_default,
  copy: node_copy,
  [Symbol.iterator]: iterator_default2
};

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

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

// ../../../node_modules/d3-hierarchy/src/tree.js
function defaultSeparation2(a2, b) {
  return a2.parent === b.parent ? 1 : 2;
}
function nextLeft(v2) {
  var children2 = v2.children;
  return children2 ? children2[0] : v2.t;
}
function nextRight(v2) {
  var children2 = v2.children;
  return children2 ? children2[children2.length - 1] : v2.t;
}
function moveSubtree(wm, wp, shift) {
  var change = shift / (wp.i - wm.i);
  wp.c -= change;
  wp.s += shift;
  wm.c += change;
  wp.z += shift;
  wp.m += shift;
}
function executeShifts(v2) {
  var shift = 0, change = 0, children2 = v2.children, i = children2.length, w;
  while (--i >= 0) {
    w = children2[i];
    w.z += shift;
    w.m += shift;
    shift += w.s + (change += w.c);
  }
}
function nextAncestor(vim, v2, ancestor) {
  return vim.a.parent === v2.parent ? vim.a : ancestor;
}
function TreeNode(node, i) {
  this._ = node;
  this.parent = null;
  this.children = null;
  this.A = null;
  this.a = this;
  this.z = 0;
  this.m = 0;
  this.c = 0;
  this.s = 0;
  this.t = null;
  this.i = i;
}
TreeNode.prototype = Object.create(Node.prototype);
function treeRoot(root2) {
  var tree2 = new TreeNode(root2, 0), node, nodes = [tree2], child, children2, i, n;
  while (node = nodes.pop()) {
    if (children2 = node._.children) {
      node.children = new Array(n = children2.length);
      for (i = n - 1; i >= 0; --i) {
        nodes.push(child = node.children[i] = new TreeNode(children2[i], i));
        child.parent = node;
      }
    }
  }
  (tree2.parent = new TreeNode(null, 0)).children = [tree2];
  return tree2;
}
function tree_default() {
  var separation = defaultSeparation2, dx = 1, dy = 1, nodeSize = null;
  function tree2(root2) {
    var t = treeRoot(root2);
    t.eachAfter(firstWalk), t.parent.m = -t.z;
    t.eachBefore(secondWalk);
    if (nodeSize) root2.eachBefore(sizeNode);
    else {
      var left2 = root2, right2 = root2, bottom2 = root2;
      root2.eachBefore(function(node) {
        if (node.x < left2.x) left2 = node;
        if (node.x > right2.x) right2 = node;
        if (node.depth > bottom2.depth) bottom2 = node;
      });
      var s2 = left2 === right2 ? 1 : separation(left2, right2) / 2, tx = s2 - left2.x, kx2 = dx / (right2.x + s2 + tx), ky2 = dy / (bottom2.depth || 1);
      root2.eachBefore(function(node) {
        node.x = (node.x + tx) * kx2;
        node.y = node.depth * ky2;
      });
    }
    return root2;
  }
  function firstWalk(v2) {
    var children2 = v2.children, siblings = v2.parent.children, w = v2.i ? siblings[v2.i - 1] : null;
    if (children2) {
      executeShifts(v2);
      var midpoint = (children2[0].z + children2[children2.length - 1].z) / 2;
      if (w) {
        v2.z = w.z + separation(v2._, w._);
        v2.m = v2.z - midpoint;
      } else {
        v2.z = midpoint;
      }
    } else if (w) {
      v2.z = w.z + separation(v2._, w._);
    }
    v2.parent.A = apportion(v2, w, v2.parent.A || siblings[0]);
  }
  function secondWalk(v2) {
    v2._.x = v2.z + v2.parent.m;
    v2.m += v2.parent.m;
  }
  function apportion(v2, w, ancestor) {
    if (w) {
      var vip = v2, vop = v2, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
      while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
        vom = nextLeft(vom);
        vop = nextRight(vop);
        vop.a = v2;
        shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
        if (shift > 0) {
          moveSubtree(nextAncestor(vim, v2, ancestor), v2, 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 = v2;
      }
    }
    return ancestor;
  }
  function sizeNode(node) {
    node.x *= dx;
    node.y = node.depth * dy;
  }
  tree2.separation = function(x3) {
    return arguments.length ? (separation = x3, tree2) : separation;
  };
  tree2.size = function(x3) {
    return arguments.length ? (nodeSize = false, dx = +x3[0], dy = +x3[1], tree2) : nodeSize ? null : [dx, dy];
  };
  tree2.nodeSize = function(x3) {
    return arguments.length ? (nodeSize = true, dx = +x3[0], dy = +x3[1], tree2) : nodeSize ? [dx, dy] : null;
  };
  return tree2;
}

// ../../../node_modules/d3-random/src/lcg.js
var mul2 = 1664525;
var inc = 1013904223;
var eps = 1 / 4294967296;
function lcg(seed = Math.random()) {
  let state = (0 <= seed && seed < 1 ? seed / eps : Math.abs(seed)) | 0;
  return () => (state = mul2 * state + inc | 0, eps * (state >>> 0));
}

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

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

// ../../../node_modules/d3-scale/src/band.js
function band() {
  var scale3 = ordinal().unknown(void 0), domain = scale3.domain, ordinalRange2 = scale3.range, r0 = 0, r1 = 1, step, bandwidth, round3 = false, paddingInner = 0, paddingOuter = 0, align3 = 0.5;
  delete scale3.unknown;
  function rescale() {
    var n = domain().length, reverse3 = r1 < r0, start2 = reverse3 ? r1 : r0, stop = reverse3 ? r0 : r1;
    step = (stop - start2) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round3) step = Math.floor(step);
    start2 += (stop - start2 - step * (n - paddingInner)) * align3;
    bandwidth = step * (1 - paddingInner);
    if (round3) start2 = Math.round(start2), bandwidth = Math.round(bandwidth);
    var values2 = range(n).map(function(i) {
      return start2 + step * i;
    });
    return ordinalRange2(reverse3 ? values2.reverse() : values2);
  }
  scale3.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };
  scale3.range = function(_) {
    return arguments.length ? ([r0, r1] = _, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale3.rangeRound = function(_) {
    return [r0, r1] = _, r0 = +r0, r1 = +r1, round3 = true, rescale();
  };
  scale3.bandwidth = function() {
    return bandwidth;
  };
  scale3.step = function() {
    return step;
  };
  scale3.round = function(_) {
    return arguments.length ? (round3 = !!_, rescale()) : round3;
  };
  scale3.padding = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
  };
  scale3.paddingInner = function(_) {
    return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
  };
  scale3.paddingOuter = function(_) {
    return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
  };
  scale3.align = function(_) {
    return arguments.length ? (align3 = Math.max(0, Math.min(1, _)), rescale()) : align3;
  };
  scale3.copy = function() {
    return band(domain(), [r0, r1]).round(round3).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align3);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale3) {
  var copy4 = scale3.copy;
  scale3.padding = scale3.paddingOuter;
  delete scale3.paddingInner;
  delete scale3.paddingOuter;
  scale3.copy = function() {
    return pointish(copy4());
  };
  return scale3;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}

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

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

// ../../../node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity5(x3) {
  return x3;
}
function normalize2(a2, b) {
  return (b -= a2 = +a2) ? function(x3) {
    return (x3 - a2) / b;
  } : constants(isNaN(b) ? NaN : 0.5);
}
function clamper(a2, b) {
  var t;
  if (a2 > b) t = a2, a2 = b, b = t;
  return function(x3) {
    return Math.max(a2, Math.min(b, x3));
  };
}
function bimap(domain, range3, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range3[0], r1 = range3[1];
  if (d1 < d0) d0 = normalize2(d1, d0), r0 = interpolate(r1, r0);
  else d0 = normalize2(d0, d1), r0 = interpolate(r0, r1);
  return function(x3) {
    return r0(d0(x3));
  };
}
function polymap(domain, range3, interpolate) {
  var j = Math.min(domain.length, range3.length) - 1, d = new Array(j), r = new Array(j), i = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range3 = range3.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize2(domain[i], domain[i + 1]);
    r[i] = interpolate(range3[i], range3[i + 1]);
  }
  return function(x3) {
    var i2 = bisect_default(domain, x3, 1, j) - 1;
    return r[i2](d[i2](x3));
  };
}
function copy(source, target) {
  return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer2() {
  var domain = unit, range3 = unit, interpolate = value_default, transform3, untransform, unknown, clamp = identity5, piecewise2, output, input3;
  function rescale() {
    var n = Math.min(domain.length, range3.length);
    if (clamp !== identity5) clamp = clamper(domain[0], domain[n - 1]);
    piecewise2 = n > 2 ? polymap : bimap;
    output = input3 = null;
    return scale3;
  }
  function scale3(x3) {
    return x3 == null || isNaN(x3 = +x3) ? unknown : (output || (output = piecewise2(domain.map(transform3), range3, interpolate)))(transform3(clamp(x3)));
  }
  scale3.invert = function(y3) {
    return clamp(untransform((input3 || (input3 = piecewise2(range3, domain.map(transform3), number_default)))(y3)));
  };
  scale3.domain = function(_) {
    return arguments.length ? (domain = Array.from(_, number3), rescale()) : domain.slice();
  };
  scale3.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), rescale()) : range3.slice();
  };
  scale3.rangeRound = function(_) {
    return range3 = Array.from(_), interpolate = round_default, rescale();
  };
  scale3.clamp = function(_) {
    return arguments.length ? (clamp = _ ? true : identity5, rescale()) : clamp !== identity5;
  };
  scale3.interpolate = function(_) {
    return arguments.length ? (interpolate = _, rescale()) : interpolate;
  };
  scale3.unknown = function(_) {
    return arguments.length ? (unknown = _, scale3) : unknown;
  };
  return function(t, u4) {
    transform3 = t, untransform = u4;
    return rescale();
  };
}
function continuous() {
  return transformer2()(identity5, identity5);
}

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

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

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

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

// ../../../node_modules/d3-scale/src/log.js
function transformLog(x3) {
  return Math.log(x3);
}
function transformExp(x3) {
  return Math.exp(x3);
}
function transformLogn(x3) {
  return -Math.log(-x3);
}
function transformExpn(x3) {
  return -Math.exp(-x3);
}
function pow10(x3) {
  return isFinite(x3) ? +("1e" + x3) : x3 < 0 ? 0 : x3;
}
function powp(base) {
  return base === 10 ? pow10 : base === Math.E ? Math.exp : (x3) => Math.pow(base, x3);
}
function logp(base) {
  return base === Math.E ? Math.log : base === 10 && Math.log10 || base === 2 && Math.log2 || (base = Math.log(base), (x3) => Math.log(x3) / base);
}
function reflect(f) {
  return (x3, k2) => -f(-x3, k2);
}
function loggish(transform3) {
  const scale3 = transform3(transformLog, transformExp);
  const domain = scale3.domain;
  let base = 10;
  let logs;
  let pows;
  function rescale() {
    logs = logp(base), pows = powp(base);
    if (domain()[0] < 0) {
      logs = reflect(logs), pows = reflect(pows);
      transform3(transformLogn, transformExpn);
    } else {
      transform3(transformLog, transformExp);
    }
    return scale3;
  }
  scale3.base = function(_) {
    return arguments.length ? (base = +_, rescale()) : base;
  };
  scale3.domain = function(_) {
    return arguments.length ? (domain(_), rescale()) : domain();
  };
  scale3.ticks = (count4) => {
    const d = domain();
    let u4 = d[0];
    let v2 = d[d.length - 1];
    const r = v2 < u4;
    if (r) [u4, v2] = [v2, u4];
    let i = logs(u4);
    let j = logs(v2);
    let k2;
    let t;
    const n = count4 == null ? 10 : +count4;
    let z = [];
    if (!(base % 1) && j - i < n) {
      i = Math.floor(i), j = Math.ceil(j);
      if (u4 > 0) for (; i <= j; ++i) {
        for (k2 = 1; k2 < base; ++k2) {
          t = i < 0 ? k2 / pows(-i) : k2 * pows(i);
          if (t < u4) continue;
          if (t > v2) break;
          z.push(t);
        }
      }
      else for (; i <= j; ++i) {
        for (k2 = base - 1; k2 >= 1; --k2) {
          t = i > 0 ? k2 / pows(-i) : k2 * pows(i);
          if (t < u4) continue;
          if (t > v2) break;
          z.push(t);
        }
      }
      if (z.length * 2 < n) z = ticks(u4, v2, n);
    } else {
      z = ticks(i, j, Math.min(j - i, n)).map(pows);
    }
    return r ? z.reverse() : z;
  };
  scale3.tickFormat = (count4, specifier) => {
    if (count4 == null) count4 = 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 (count4 === Infinity) return specifier;
    const k2 = Math.max(1, base * count4 / scale3.ticks().length);
    return (d) => {
      let i = d / pows(Math.round(logs(d)));
      if (i * base < base - 0.5) i *= base;
      return i <= k2 ? specifier(d) : "";
    };
  };
  scale3.nice = () => {
    return domain(nice2(domain(), {
      floor: (x3) => pows(Math.floor(logs(x3))),
      ceil: (x3) => pows(Math.ceil(logs(x3)))
    }));
  };
  return scale3;
}
function log3() {
  const scale3 = loggish(transformer2()).domain([1, 10]);
  scale3.copy = () => copy(scale3, log3()).base(scale3.base());
  initRange.apply(scale3, arguments);
  return scale3;
}

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

// ../../../node_modules/d3-scale/src/pow.js
function transformPow(exponent) {
  return function(x3) {
    return x3 < 0 ? -Math.pow(-x3, exponent) : Math.pow(x3, exponent);
  };
}
function transformSqrt(x3) {
  return x3 < 0 ? -Math.sqrt(-x3) : Math.sqrt(x3);
}
function transformSquare(x3) {
  return x3 < 0 ? -x3 * x3 : x3 * x3;
}
function powish(transform3) {
  var scale3 = transform3(identity5, identity5), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform3(identity5, identity5) : exponent === 0.5 ? transform3(transformSqrt, transformSquare) : transform3(transformPow(exponent), transformPow(1 / exponent));
  }
  scale3.exponent = function(_) {
    return arguments.length ? (exponent = +_, rescale()) : exponent;
  };
  return linearish(scale3);
}
function pow4() {
  var scale3 = powish(transformer2());
  scale3.copy = function() {
    return copy(scale3, pow4()).exponent(scale3.exponent());
  };
  initRange.apply(scale3, arguments);
  return scale3;
}

// ../../../node_modules/d3-scale/src/quantile.js
function quantile3() {
  var domain = [], range3 = [], thresholds = [], unknown;
  function rescale() {
    var i = 0, n = Math.max(1, range3.length);
    thresholds = new Array(n - 1);
    while (++i < n) thresholds[i - 1] = quantileSorted(domain, i / n);
    return scale3;
  }
  function scale3(x3) {
    return x3 == null || isNaN(x3 = +x3) ? unknown : range3[bisect_default(thresholds, x3)];
  }
  scale3.invertExtent = function(y3) {
    var i = range3.indexOf(y3);
    return i < 0 ? [NaN, NaN] : [
      i > 0 ? thresholds[i - 1] : domain[0],
      i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
    ];
  };
  scale3.domain = function(_) {
    if (!arguments.length) return domain.slice();
    domain = [];
    for (let d of _) if (d != null && !isNaN(d = +d)) domain.push(d);
    domain.sort(ascending);
    return rescale();
  };
  scale3.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), rescale()) : range3.slice();
  };
  scale3.unknown = function(_) {
    return arguments.length ? (unknown = _, scale3) : unknown;
  };
  scale3.quantiles = function() {
    return thresholds.slice();
  };
  scale3.copy = function() {
    return quantile3().domain(domain).range(range3).unknown(unknown);
  };
  return initRange.apply(scale3, arguments);
}

// ../../../node_modules/d3-scale/src/threshold.js
function threshold() {
  var domain = [0.5], range3 = [0, 1], unknown, n = 1;
  function scale3(x3) {
    return x3 != null && x3 <= x3 ? range3[bisect_default(domain, x3, 0, n)] : unknown;
  }
  scale3.domain = function(_) {
    return arguments.length ? (domain = Array.from(_), n = Math.min(domain.length, range3.length - 1), scale3) : domain.slice();
  };
  scale3.range = function(_) {
    return arguments.length ? (range3 = Array.from(_), n = Math.min(domain.length, range3.length - 1), scale3) : range3.slice();
  };
  scale3.invertExtent = function(y3) {
    var i = range3.indexOf(y3);
    return [domain[i - 1], domain[i]];
  };
  scale3.unknown = function(_) {
    return arguments.length ? (unknown = _, scale3) : unknown;
  };
  scale3.copy = function() {
    return threshold().domain(domain).range(range3).unknown(unknown);
  };
  return initRange.apply(scale3, arguments);
}

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

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

// ../../../node_modules/d3-time/src/duration.js
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;

// ../../../node_modules/d3-time/src/second.js
var second = timeInterval2((date3) => {
  date3.setTime(date3 - date3.getMilliseconds());
}, (date3, step) => {
  date3.setTime(+date3 + step * durationSecond2);
}, (start2, end) => {
  return (end - start2) / durationSecond2;
}, (date3) => {
  return date3.getUTCSeconds();
});
var seconds2 = second.range;

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

// ../../../node_modules/d3-time/src/hour.js
var timeHour = timeInterval2((date3) => {
  date3.setTime(date3 - date3.getMilliseconds() - date3.getSeconds() * durationSecond2 - date3.getMinutes() * durationMinute2);
}, (date3, step) => {
  date3.setTime(+date3 + step * durationHour2);
}, (start2, end) => {
  return (end - start2) / durationHour2;
}, (date3) => {
  return date3.getHours();
});
var timeHours = timeHour.range;
var utcHour = timeInterval2((date3) => {
  date3.setUTCMinutes(0, 0, 0);
}, (date3, step) => {
  date3.setTime(+date3 + step * durationHour2);
}, (start2, end) => {
  return (end - start2) / durationHour2;
}, (date3) => {
  return date3.getUTCHours();
});
var utcHours = utcHour.range;

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

// ../../../node_modules/d3-time/src/week.js
function timeWeekday(i) {
  return timeInterval2((date3) => {
    date3.setDate(date3.getDate() - (date3.getDay() + 7 - i) % 7);
    date3.setHours(0, 0, 0, 0);
  }, (date3, step) => {
    date3.setDate(date3.getDate() + step * 7);
  }, (start2, end) => {
    return (end - start2 - (end.getTimezoneOffset() - start2.getTimezoneOffset()) * durationMinute2) / durationWeek2;
  });
}
var timeSunday = timeWeekday(0);
var timeMonday = timeWeekday(1);
var timeTuesday = timeWeekday(2);
var timeWednesday = timeWeekday(3);
var timeThursday = timeWeekday(4);
var timeFriday = timeWeekday(5);
var timeSaturday = timeWeekday(6);
var timeSundays = timeSunday.range;
var timeMondays = timeMonday.range;
var timeTuesdays = timeTuesday.range;
var timeWednesdays = timeWednesday.range;
var timeThursdays = timeThursday.range;
var timeFridays = timeFriday.range;
var timeSaturdays = timeSaturday.range;
function utcWeekday(i) {
  return timeInterval2((date3) => {
    date3.setUTCDate(date3.getUTCDate() - (date3.getUTCDay() + 7 - i) % 7);
    date3.setUTCHours(0, 0, 0, 0);
  }, (date3, step) => {
    date3.setUTCDate(date3.getUTCDate() + step * 7);
  }, (start2, end) => {
    return (end - start2) / durationWeek2;
  });
}
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 = timeInterval2((date3) => {
  date3.setDate(1);
  date3.setHours(0, 0, 0, 0);
}, (date3, step) => {
  date3.setMonth(date3.getMonth() + step);
}, (start2, end) => {
  return end.getMonth() - start2.getMonth() + (end.getFullYear() - start2.getFullYear()) * 12;
}, (date3) => {
  return date3.getMonth();
});
var timeMonths = timeMonth.range;
var utcMonth = timeInterval2((date3) => {
  date3.setUTCDate(1);
  date3.setUTCHours(0, 0, 0, 0);
}, (date3, step) => {
  date3.setUTCMonth(date3.getUTCMonth() + step);
}, (start2, end) => {
  return end.getUTCMonth() - start2.getUTCMonth() + (end.getUTCFullYear() - start2.getUTCFullYear()) * 12;
}, (date3) => {
  return date3.getUTCMonth();
});
var utcMonths = utcMonth.range;

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

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

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

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

// ../../../node_modules/d3-scale/src/time.js
function date2(t) {
  return new Date(t);
}
function number4(t) {
  return t instanceof Date ? +t : +/* @__PURE__ */ new Date(+t);
}
function calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second3, format3) {
  var scale3 = continuous(), invert2 = scale3.invert, domain = scale3.domain;
  var formatMillisecond = format3(".%L"), formatSecond = format3(":%S"), formatMinute = format3("%I:%M"), formatHour = format3("%I %p"), formatDay = format3("%a %d"), formatWeek = format3("%b %d"), formatMonth2 = format3("%B"), formatYear4 = format3("%Y");
  function tickFormat2(date3) {
    return (second3(date3) < date3 ? formatMillisecond : minute(date3) < date3 ? formatSecond : hour(date3) < date3 ? formatMinute : day(date3) < date3 ? formatHour : month(date3) < date3 ? week(date3) < date3 ? formatDay : formatWeek : year(date3) < date3 ? formatMonth2 : formatYear4)(date3);
  }
  scale3.invert = function(y3) {
    return new Date(invert2(y3));
  };
  scale3.domain = function(_) {
    return arguments.length ? domain(Array.from(_, number4)) : domain().map(date2);
  };
  scale3.ticks = function(interval4) {
    var d = domain();
    return ticks2(d[0], d[d.length - 1], interval4 == null ? 10 : interval4);
  };
  scale3.tickFormat = function(count4, specifier) {
    return specifier == null ? tickFormat2 : format3(specifier);
  };
  scale3.nice = function(interval4) {
    var d = domain();
    if (!interval4 || typeof interval4.range !== "function") interval4 = tickInterval(d[0], d[d.length - 1], interval4 == null ? 10 : interval4);
    return interval4 ? domain(nice2(d, interval4)) : scale3;
  };
  scale3.copy = function() {
    return copy(scale3, calendar(ticks2, tickInterval, year, month, week, day, hour, minute, second3, format3));
  };
  return scale3;
}
function time2() {
  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 copy2(source, target) {
  return target.domain(source.domain()).interpolator(source.interpolator()).clamp(source.clamp()).unknown(source.unknown());
}

// ../../../node_modules/d3-scale/src/diverging.js
function transformer3() {
  var x06 = 0, x12 = 0.5, x22 = 1, s2 = 1, t03, t13, t22, k10, k21, interpolator = identity5, transform3, clamp = false, unknown;
  function scale3(x3) {
    return isNaN(x3 = +x3) ? unknown : (x3 = 0.5 + ((x3 = +transform3(x3)) - t13) * (s2 * x3 < s2 * t13 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x3)) : x3));
  }
  scale3.domain = function(_) {
    return arguments.length ? ([x06, x12, x22] = _, t03 = transform3(x06 = +x06), t13 = transform3(x12 = +x12), t22 = transform3(x22 = +x22), k10 = t03 === t13 ? 0 : 0.5 / (t13 - t03), k21 = t13 === t22 ? 0 : 0.5 / (t22 - t13), s2 = t13 < t03 ? -1 : 1, scale3) : [x06, x12, x22];
  };
  scale3.clamp = function(_) {
    return arguments.length ? (clamp = !!_, scale3) : clamp;
  };
  scale3.interpolator = function(_) {
    return arguments.length ? (interpolator = _, scale3) : interpolator;
  };
  function range3(interpolate) {
    return function(_) {
      var r0, r1, r2;
      return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate, [r0, r1, r2]), scale3) : [interpolator(0), interpolator(0.5), interpolator(1)];
    };
  }
  scale3.range = range3(value_default);
  scale3.rangeRound = range3(round_default);
  scale3.unknown = function(_) {
    return arguments.length ? (unknown = _, scale3) : unknown;
  };
  return function(t) {
    transform3 = t, t03 = t(x06), t13 = t(x12), t22 = t(x22), k10 = t03 === t13 ? 0 : 0.5 / (t13 - t03), k21 = t13 === t22 ? 0 : 0.5 / (t22 - t13), s2 = t13 < t03 ? -1 : 1;
    return scale3;
  };
}
function diverging() {
  var scale3 = linearish(transformer3()(identity5));
  scale3.copy = function() {
    return copy2(scale3, diverging());
  };
  return initInterpolator.apply(scale3, arguments);
}
function divergingLog() {
  var scale3 = loggish(transformer3()).domain([0.1, 1, 10]);
  scale3.copy = function() {
    return copy2(scale3, divergingLog()).base(scale3.base());
  };
  return initInterpolator.apply(scale3, arguments);
}
function divergingSymlog() {
  var scale3 = symlogish(transformer3());
  scale3.copy = function() {
    return copy2(scale3, divergingSymlog()).constant(scale3.constant());
  };
  return initInterpolator.apply(scale3, arguments);
}
function divergingPow() {
  var scale3 = powish(transformer3());
  scale3.copy = function() {
    return copy2(scale3, divergingPow()).exponent(scale3.exponent());
  };
  return initInterpolator.apply(scale3, arguments);
}

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

// ../../../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/d3-scale-chromatic/src/categorical/Tableau10.js
var Tableau10_default = colors_default("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab");

// ../../../node_modules/d3-scale-chromatic/src/ramp.js
var ramp_default = (scheme28) => rgbBasis(scheme28[scheme28.length - 1]);

// ../../../node_modules/d3-scale-chromatic/src/diverging/BrBG.js
var scheme = new Array(3).concat(
  "d8b365f5f5f55ab4ac",
  "a6611adfc27d80cdc1018571",
  "a6611adfc27df5f5f580cdc1018571",
  "8c510ad8b365f6e8c3c7eae55ab4ac01665e",
  "8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e",
  "8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e",
  "8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e",
  "5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30",
  "5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30"
).map(colors_default);
var BrBG_default = ramp_default(scheme);

// ../../../node_modules/d3-scale-chromatic/src/diverging/PRGn.js
var scheme2 = new Array(3).concat(
  "af8dc3f7f7f77fbf7b",
  "7b3294c2a5cfa6dba0008837",
  "7b3294c2a5cff7f7f7a6dba0008837",
  "762a83af8dc3e7d4e8d9f0d37fbf7b1b7837",
  "762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837",
  "762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837",
  "762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837",
  "40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b",
  "40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b"
).map(colors_default);
var PRGn_default = ramp_default(scheme2);

// ../../../node_modules/d3-scale-chromatic/src/diverging/PiYG.js
var scheme3 = new Array(3).concat(
  "e9a3c9f7f7f7a1d76a",
  "d01c8bf1b6dab8e1864dac26",
  "d01c8bf1b6daf7f7f7b8e1864dac26",
  "c51b7de9a3c9fde0efe6f5d0a1d76a4d9221",
  "c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221",
  "c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221",
  "c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221",
  "8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419",
  "8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419"
).map(colors_default);
var PiYG_default = ramp_default(scheme3);

// ../../../node_modules/d3-scale-chromatic/src/diverging/PuOr.js
var scheme4 = new Array(3).concat(
  "998ec3f7f7f7f1a340",
  "5e3c99b2abd2fdb863e66101",
  "5e3c99b2abd2f7f7f7fdb863e66101",
  "542788998ec3d8daebfee0b6f1a340b35806",
  "542788998ec3d8daebf7f7f7fee0b6f1a340b35806",
  "5427888073acb2abd2d8daebfee0b6fdb863e08214b35806",
  "5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806",
  "2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08",
  "2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08"
).map(colors_default);
var PuOr_default = ramp_default(scheme4);

// ../../../node_modules/d3-scale-chromatic/src/diverging/RdBu.js
var scheme5 = new Array(3).concat(
  "ef8a62f7f7f767a9cf",
  "ca0020f4a58292c5de0571b0",
  "ca0020f4a582f7f7f792c5de0571b0",
  "b2182bef8a62fddbc7d1e5f067a9cf2166ac",
  "b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac",
  "b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac",
  "b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac",
  "67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061",
  "67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061"
).map(colors_default);
var RdBu_default = ramp_default(scheme5);

// ../../../node_modules/d3-scale-chromatic/src/diverging/RdGy.js
var scheme6 = new Array(3).concat(
  "ef8a62ffffff999999",
  "ca0020f4a582bababa404040",
  "ca0020f4a582ffffffbababa404040",
  "b2182bef8a62fddbc7e0e0e09999994d4d4d",
  "b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d",
  "b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d",
  "b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d",
  "67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a",
  "67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a"
).map(colors_default);
var RdGy_default = ramp_default(scheme6);

// ../../../node_modules/d3-scale-chromatic/src/diverging/RdYlBu.js
var scheme7 = new Array(3).concat(
  "fc8d59ffffbf91bfdb",
  "d7191cfdae61abd9e92c7bb6",
  "d7191cfdae61ffffbfabd9e92c7bb6",
  "d73027fc8d59fee090e0f3f891bfdb4575b4",
  "d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4",
  "d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4",
  "d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4",
  "a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695",
  "a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695"
).map(colors_default);
var RdYlBu_default = ramp_default(scheme7);

// ../../../node_modules/d3-scale-chromatic/src/diverging/RdYlGn.js
var scheme8 = new Array(3).concat(
  "fc8d59ffffbf91cf60",
  "d7191cfdae61a6d96a1a9641",
  "d7191cfdae61ffffbfa6d96a1a9641",
  "d73027fc8d59fee08bd9ef8b91cf601a9850",
  "d73027fc8d59fee08bffffbfd9ef8b91cf601a9850",
  "d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850",
  "d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850",
  "a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837",
  "a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837"
).map(colors_default);
var RdYlGn_default = ramp_default(scheme8);

// ../../../node_modules/d3-scale-chromatic/src/diverging/Spectral.js
var scheme9 = new Array(3).concat(
  "fc8d59ffffbf99d594",
  "d7191cfdae61abdda42b83ba",
  "d7191cfdae61ffffbfabdda42b83ba",
  "d53e4ffc8d59fee08be6f59899d5943288bd",
  "d53e4ffc8d59fee08bffffbfe6f59899d5943288bd",
  "d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd",
  "d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd",
  "9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2",
  "9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2"
).map(colors_default);
var Spectral_default = ramp_default(scheme9);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/BuGn.js
var scheme10 = new Array(3).concat(
  "e5f5f999d8c92ca25f",
  "edf8fbb2e2e266c2a4238b45",
  "edf8fbb2e2e266c2a42ca25f006d2c",
  "edf8fbccece699d8c966c2a42ca25f006d2c",
  "edf8fbccece699d8c966c2a441ae76238b45005824",
  "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824",
  "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b"
).map(colors_default);
var BuGn_default = ramp_default(scheme10);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/BuPu.js
var scheme11 = new Array(3).concat(
  "e0ecf49ebcda8856a7",
  "edf8fbb3cde38c96c688419d",
  "edf8fbb3cde38c96c68856a7810f7c",
  "edf8fbbfd3e69ebcda8c96c68856a7810f7c",
  "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b",
  "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b",
  "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b"
).map(colors_default);
var BuPu_default = ramp_default(scheme11);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/GnBu.js
var scheme12 = new Array(3).concat(
  "e0f3dba8ddb543a2ca",
  "f0f9e8bae4bc7bccc42b8cbe",
  "f0f9e8bae4bc7bccc443a2ca0868ac",
  "f0f9e8ccebc5a8ddb57bccc443a2ca0868ac",
  "f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e",
  "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e",
  "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081"
).map(colors_default);
var GnBu_default = ramp_default(scheme12);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/OrRd.js
var scheme13 = new Array(3).concat(
  "fee8c8fdbb84e34a33",
  "fef0d9fdcc8afc8d59d7301f",
  "fef0d9fdcc8afc8d59e34a33b30000",
  "fef0d9fdd49efdbb84fc8d59e34a33b30000",
  "fef0d9fdd49efdbb84fc8d59ef6548d7301f990000",
  "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000",
  "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000"
).map(colors_default);
var OrRd_default = ramp_default(scheme13);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/PuBuGn.js
var scheme14 = new Array(3).concat(
  "ece2f0a6bddb1c9099",
  "f6eff7bdc9e167a9cf02818a",
  "f6eff7bdc9e167a9cf1c9099016c59",
  "f6eff7d0d1e6a6bddb67a9cf1c9099016c59",
  "f6eff7d0d1e6a6bddb67a9cf3690c002818a016450",
  "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450",
  "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636"
).map(colors_default);
var PuBuGn_default = ramp_default(scheme14);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/PuBu.js
var scheme15 = new Array(3).concat(
  "ece7f2a6bddb2b8cbe",
  "f1eef6bdc9e174a9cf0570b0",
  "f1eef6bdc9e174a9cf2b8cbe045a8d",
  "f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d",
  "f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b",
  "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b",
  "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858"
).map(colors_default);
var PuBu_default = ramp_default(scheme15);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/PuRd.js
var scheme16 = new Array(3).concat(
  "e7e1efc994c7dd1c77",
  "f1eef6d7b5d8df65b0ce1256",
  "f1eef6d7b5d8df65b0dd1c77980043",
  "f1eef6d4b9dac994c7df65b0dd1c77980043",
  "f1eef6d4b9dac994c7df65b0e7298ace125691003f",
  "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f",
  "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f"
).map(colors_default);
var PuRd_default = ramp_default(scheme16);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/RdPu.js
var scheme17 = new Array(3).concat(
  "fde0ddfa9fb5c51b8a",
  "feebe2fbb4b9f768a1ae017e",
  "feebe2fbb4b9f768a1c51b8a7a0177",
  "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177",
  "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177",
  "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177",
  "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a"
).map(colors_default);
var RdPu_default = ramp_default(scheme17);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/YlGnBu.js
var scheme18 = new Array(3).concat(
  "edf8b17fcdbb2c7fb8",
  "ffffcca1dab441b6c4225ea8",
  "ffffcca1dab441b6c42c7fb8253494",
  "ffffccc7e9b47fcdbb41b6c42c7fb8253494",
  "ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84",
  "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84",
  "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58"
).map(colors_default);
var YlGnBu_default = ramp_default(scheme18);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/YlGn.js
var scheme19 = new Array(3).concat(
  "f7fcb9addd8e31a354",
  "ffffccc2e69978c679238443",
  "ffffccc2e69978c67931a354006837",
  "ffffccd9f0a3addd8e78c67931a354006837",
  "ffffccd9f0a3addd8e78c67941ab5d238443005a32",
  "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32",
  "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529"
).map(colors_default);
var YlGn_default = ramp_default(scheme19);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/YlOrBr.js
var scheme20 = new Array(3).concat(
  "fff7bcfec44fd95f0e",
  "ffffd4fed98efe9929cc4c02",
  "ffffd4fed98efe9929d95f0e993404",
  "ffffd4fee391fec44ffe9929d95f0e993404",
  "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04",
  "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04",
  "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506"
).map(colors_default);
var YlOrBr_default = ramp_default(scheme20);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/YlOrRd.js
var scheme21 = new Array(3).concat(
  "ffeda0feb24cf03b20",
  "ffffb2fecc5cfd8d3ce31a1c",
  "ffffb2fecc5cfd8d3cf03b20bd0026",
  "ffffb2fed976feb24cfd8d3cf03b20bd0026",
  "ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026",
  "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026",
  "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026"
).map(colors_default);
var YlOrRd_default = ramp_default(scheme21);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Blues.js
var scheme22 = new Array(3).concat(
  "deebf79ecae13182bd",
  "eff3ffbdd7e76baed62171b5",
  "eff3ffbdd7e76baed63182bd08519c",
  "eff3ffc6dbef9ecae16baed63182bd08519c",
  "eff3ffc6dbef9ecae16baed64292c62171b5084594",
  "f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594",
  "f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b"
).map(colors_default);
var Blues_default = ramp_default(scheme22);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Greens.js
var scheme23 = new Array(3).concat(
  "e5f5e0a1d99b31a354",
  "edf8e9bae4b374c476238b45",
  "edf8e9bae4b374c47631a354006d2c",
  "edf8e9c7e9c0a1d99b74c47631a354006d2c",
  "edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32",
  "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32",
  "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b"
).map(colors_default);
var Greens_default = ramp_default(scheme23);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Greys.js
var scheme24 = new Array(3).concat(
  "f0f0f0bdbdbd636363",
  "f7f7f7cccccc969696525252",
  "f7f7f7cccccc969696636363252525",
  "f7f7f7d9d9d9bdbdbd969696636363252525",
  "f7f7f7d9d9d9bdbdbd969696737373525252252525",
  "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525",
  "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000"
).map(colors_default);
var Greys_default = ramp_default(scheme24);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Purples.js
var scheme25 = new Array(3).concat(
  "efedf5bcbddc756bb1",
  "f2f0f7cbc9e29e9ac86a51a3",
  "f2f0f7cbc9e29e9ac8756bb154278f",
  "f2f0f7dadaebbcbddc9e9ac8756bb154278f",
  "f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486",
  "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486",
  "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d"
).map(colors_default);
var Purples_default = ramp_default(scheme25);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Reds.js
var scheme26 = new Array(3).concat(
  "fee0d2fc9272de2d26",
  "fee5d9fcae91fb6a4acb181d",
  "fee5d9fcae91fb6a4ade2d26a50f15",
  "fee5d9fcbba1fc9272fb6a4ade2d26a50f15",
  "fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d",
  "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d",
  "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d"
).map(colors_default);
var Reds_default = ramp_default(scheme26);

// ../../../node_modules/d3-scale-chromatic/src/sequential-single/Oranges.js
var scheme27 = new Array(3).concat(
  "fee6cefdae6be6550d",
  "feeddefdbe85fd8d3cd94701",
  "feeddefdbe85fd8d3ce6550da63603",
  "feeddefdd0a2fdae6bfd8d3ce6550da63603",
  "feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04",
  "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04",
  "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704"
).map(colors_default);
var Oranges_default = ramp_default(scheme27);

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/cividis.js
function cividis_default(t) {
  t = Math.max(0, Math.min(1, t));
  return "rgb(" + Math.max(0, Math.min(255, Math.round(-4.54 - t * (35.34 - t * (2381.73 - t * (6402.7 - t * (7024.72 - t * 2710.57))))))) + ", " + Math.max(0, Math.min(255, Math.round(32.49 + t * (170.73 + t * (52.82 - t * (131.46 - t * (176.58 - t * 67.37))))))) + ", " + Math.max(0, Math.min(255, Math.round(81.24 + t * (442.36 - t * (2482.43 - t * (6167.24 - t * (6614.94 - t * 2475.67))))))) + ")";
}

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/cubehelix.js
var cubehelix_default2 = cubehelixLong(cubehelix(300, 0.5, 0), cubehelix(-240, 0.5, 1));

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/rainbow.js
var warm = cubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.5, 0.8));
var cool = cubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.5, 0.8));
var c = cubehelix();
function rainbow_default(t) {
  if (t < 0 || t > 1) t -= Math.floor(t);
  var ts = Math.abs(t - 0.5);
  c.h = 360 * t - 100;
  c.s = 1.5 - 1.5 * ts;
  c.l = 0.8 - 0.9 * ts;
  return c + "";
}

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/sinebow.js
var c2 = rgb();
var pi_1_3 = Math.PI / 3;
var pi_2_3 = Math.PI * 2 / 3;
function sinebow_default(t) {
  var x3;
  t = (0.5 - t) * Math.PI;
  c2.r = 255 * (x3 = Math.sin(t)) * x3;
  c2.g = 255 * (x3 = Math.sin(t + pi_1_3)) * x3;
  c2.b = 255 * (x3 = Math.sin(t + pi_2_3)) * x3;
  return c2 + "";
}

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/turbo.js
function turbo_default(t) {
  t = Math.max(0, Math.min(1, t));
  return "rgb(" + Math.max(0, Math.min(255, Math.round(34.61 + t * (1172.33 - t * (10793.56 - t * (33300.12 - t * (38394.49 - t * 14825.05))))))) + ", " + Math.max(0, Math.min(255, Math.round(23.31 + t * (557.33 + t * (1225.33 - t * (3574.96 - t * (1073.77 + t * 707.56))))))) + ", " + Math.max(0, Math.min(255, Math.round(27.2 + t * (3211.1 - t * (15327.97 - t * (27814 - t * (22569.18 - t * 6838.66))))))) + ")";
}

// ../../../node_modules/d3-scale-chromatic/src/sequential-multi/viridis.js
function ramp(range3) {
  var n = range3.length;
  return function(t) {
    return range3[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
  };
}
var viridis_default = ramp(colors_default("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));
var magma = ramp(colors_default("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf"));
var inferno = ramp(colors_default("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4"));
var plasma = ramp(colors_default("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));

// ../../../node_modules/d3-shape/src/constant.js
function constant_default5(x3) {
  return function constant2() {
    return x3;
  };
}

// ../../../node_modules/d3-shape/src/math.js
var cos2 = Math.cos;
var min4 = Math.min;
var sin2 = Math.sin;
var sqrt4 = Math.sqrt;
var epsilon7 = 1e-12;
var pi3 = Math.PI;
var halfPi2 = pi3 / 2;
var tau4 = 2 * pi3;

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

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

// ../../../node_modules/d3-shape/src/curve/linear.js
function Linear(context) {
  this._context = context;
}
Linear.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x3, y3) : this._context.moveTo(x3, y3);
        break;
      case 1:
        this._point = 2;
      // falls through
      default:
        this._context.lineTo(x3, y3);
        break;
    }
  }
};
function linear_default(context) {
  return new Linear(context);
}

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

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

// ../../../node_modules/d3-shape/src/area.js
function area_default3(x06, y06, y12) {
  var x12 = null, defined2 = constant_default5(true), context = null, curve = linear_default, output = null, path2 = withPath(area3);
  x06 = typeof x06 === "function" ? x06 : x06 === void 0 ? x2 : constant_default5(+x06);
  y06 = typeof y06 === "function" ? y06 : y06 === void 0 ? constant_default5(0) : constant_default5(+y06);
  y12 = typeof y12 === "function" ? y12 : y12 === void 0 ? y2 : constant_default5(+y12);
  function area3(data) {
    var i, j, k2, n = (data = array_default(data)).length, d, defined0 = false, buffer2, x0z = new Array(n), y0z = new Array(n);
    if (context == null) output = curve(buffer2 = path2());
    for (i = 0; i <= n; ++i) {
      if (!(i < n && defined2(d = data[i], i, data)) === defined0) {
        if (defined0 = !defined0) {
          j = i;
          output.areaStart();
          output.lineStart();
        } else {
          output.lineEnd();
          output.lineStart();
          for (k2 = i - 1; k2 >= j; --k2) {
            output.point(x0z[k2], y0z[k2]);
          }
          output.lineEnd();
          output.areaEnd();
        }
      }
      if (defined0) {
        x0z[i] = +x06(d, i, data), y0z[i] = +y06(d, i, data);
        output.point(x12 ? +x12(d, i, data) : x0z[i], y12 ? +y12(d, i, data) : y0z[i]);
      }
    }
    if (buffer2) return output = null, buffer2 + "" || null;
  }
  function arealine() {
    return line_default2().defined(defined2).curve(curve).context(context);
  }
  area3.x = function(_) {
    return arguments.length ? (x06 = typeof _ === "function" ? _ : constant_default5(+_), x12 = null, area3) : x06;
  };
  area3.x0 = function(_) {
    return arguments.length ? (x06 = typeof _ === "function" ? _ : constant_default5(+_), area3) : x06;
  };
  area3.x1 = function(_) {
    return arguments.length ? (x12 = _ == null ? null : typeof _ === "function" ? _ : constant_default5(+_), area3) : x12;
  };
  area3.y = function(_) {
    return arguments.length ? (y06 = typeof _ === "function" ? _ : constant_default5(+_), y12 = null, area3) : y06;
  };
  area3.y0 = function(_) {
    return arguments.length ? (y06 = typeof _ === "function" ? _ : constant_default5(+_), area3) : y06;
  };
  area3.y1 = function(_) {
    return arguments.length ? (y12 = _ == null ? null : typeof _ === "function" ? _ : constant_default5(+_), area3) : y12;
  };
  area3.lineX0 = area3.lineY0 = function() {
    return arealine().x(x06).y(y06);
  };
  area3.lineY1 = function() {
    return arealine().x(x06).y(y12);
  };
  area3.lineX1 = function() {
    return arealine().x(x12).y(y06);
  };
  area3.defined = function(_) {
    return arguments.length ? (defined2 = typeof _ === "function" ? _ : constant_default5(!!_), area3) : defined2;
  };
  area3.curve = function(_) {
    return arguments.length ? (curve = _, context != null && (output = curve(context)), area3) : curve;
  };
  area3.context = function(_) {
    return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area3) : context;
  };
  return area3;
}

// ../../../node_modules/d3-shape/src/curve/bump.js
var Bump = class {
  constructor(context, x3) {
    this._context = context;
    this._x = x3;
  }
  areaStart() {
    this._line = 0;
  }
  areaEnd() {
    this._line = NaN;
  }
  lineStart() {
    this._point = 0;
  }
  lineEnd() {
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  }
  point(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0: {
        this._point = 1;
        if (this._line) this._context.lineTo(x3, y3);
        else this._context.moveTo(x3, y3);
        break;
      }
      case 1:
        this._point = 2;
      // falls through
      default: {
        if (this._x) this._context.bezierCurveTo(this._x0 = (this._x0 + x3) / 2, this._y0, this._x0, y3, x3, y3);
        else this._context.bezierCurveTo(this._x0, this._y0 = (this._y0 + y3) / 2, x3, this._y0, x3, y3);
        break;
      }
    }
    this._x0 = x3, this._y0 = y3;
  }
};
function bumpX(context) {
  return new Bump(context, true);
}
function bumpY(context) {
  return new Bump(context, false);
}

// ../../../node_modules/d3-shape/src/symbol/asterisk.js
var sqrt32 = sqrt4(3);
var asterisk_default = {
  draw(context, size) {
    const r = sqrt4(size + min4(size / 28, 0.75)) * 0.59436;
    const t = r / 2;
    const u4 = t * sqrt32;
    context.moveTo(0, r);
    context.lineTo(0, -r);
    context.moveTo(-u4, -t);
    context.lineTo(u4, t);
    context.moveTo(-u4, t);
    context.lineTo(u4, -t);
  }
};

// ../../../node_modules/d3-shape/src/symbol/circle.js
var circle_default2 = {
  draw(context, size) {
    const r = sqrt4(size / pi3);
    context.moveTo(r, 0);
    context.arc(0, 0, r, 0, tau4);
  }
};

// ../../../node_modules/d3-shape/src/symbol/cross.js
var cross_default = {
  draw(context, size) {
    const r = sqrt4(size / 5) / 2;
    context.moveTo(-3 * r, -r);
    context.lineTo(-r, -r);
    context.lineTo(-r, -3 * r);
    context.lineTo(r, -3 * r);
    context.lineTo(r, -r);
    context.lineTo(3 * r, -r);
    context.lineTo(3 * r, r);
    context.lineTo(r, r);
    context.lineTo(r, 3 * r);
    context.lineTo(-r, 3 * r);
    context.lineTo(-r, r);
    context.lineTo(-3 * r, r);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/diamond.js
var tan30 = sqrt4(1 / 3);
var tan30_2 = tan30 * 2;
var diamond_default = {
  draw(context, size) {
    const y3 = sqrt4(size / tan30_2);
    const x3 = y3 * tan30;
    context.moveTo(0, -y3);
    context.lineTo(x3, 0);
    context.lineTo(0, y3);
    context.lineTo(-x3, 0);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/diamond2.js
var diamond2_default = {
  draw(context, size) {
    const r = sqrt4(size) * 0.62625;
    context.moveTo(0, -r);
    context.lineTo(r, 0);
    context.lineTo(0, r);
    context.lineTo(-r, 0);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/plus.js
var plus_default = {
  draw(context, size) {
    const r = sqrt4(size - min4(size / 7, 2)) * 0.87559;
    context.moveTo(-r, 0);
    context.lineTo(r, 0);
    context.moveTo(0, r);
    context.lineTo(0, -r);
  }
};

// ../../../node_modules/d3-shape/src/symbol/square.js
var square_default = {
  draw(context, size) {
    const w = sqrt4(size);
    const x3 = -w / 2;
    context.rect(x3, x3, w, w);
  }
};

// ../../../node_modules/d3-shape/src/symbol/square2.js
var square2_default = {
  draw(context, size) {
    const r = sqrt4(size) * 0.4431;
    context.moveTo(r, r);
    context.lineTo(r, -r);
    context.lineTo(-r, -r);
    context.lineTo(-r, r);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/star.js
var ka = 0.8908130915292852;
var kr = sin2(pi3 / 10) / sin2(7 * pi3 / 10);
var kx = sin2(tau4 / 10) * kr;
var ky = -cos2(tau4 / 10) * kr;
var star_default = {
  draw(context, size) {
    const r = sqrt4(size * ka);
    const x3 = kx * r;
    const y3 = ky * r;
    context.moveTo(0, -r);
    context.lineTo(x3, y3);
    for (let i = 1; i < 5; ++i) {
      const a2 = tau4 * i / 5;
      const c4 = cos2(a2);
      const s2 = sin2(a2);
      context.lineTo(s2 * r, -c4 * r);
      context.lineTo(c4 * x3 - s2 * y3, s2 * x3 + c4 * y3);
    }
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/triangle.js
var sqrt33 = sqrt4(3);
var triangle_default = {
  draw(context, size) {
    const y3 = -sqrt4(size / (sqrt33 * 3));
    context.moveTo(0, y3 * 2);
    context.lineTo(-sqrt33 * y3, -y3);
    context.lineTo(sqrt33 * y3, -y3);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/triangle2.js
var sqrt34 = sqrt4(3);
var triangle2_default = {
  draw(context, size) {
    const s2 = sqrt4(size) * 0.6824;
    const t = s2 / 2;
    const u4 = s2 * sqrt34 / 2;
    context.moveTo(0, -s2);
    context.lineTo(u4, t);
    context.lineTo(-u4, t);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/wye.js
var c3 = -0.5;
var s = sqrt4(3) / 2;
var k = 1 / sqrt4(12);
var a = (k / 2 + 1) * 3;
var wye_default = {
  draw(context, size) {
    const r = sqrt4(size / a);
    const x06 = r / 2, y06 = r * k;
    const x12 = x06, y12 = r * k + r;
    const x22 = -x12, y22 = y12;
    context.moveTo(x06, y06);
    context.lineTo(x12, y12);
    context.lineTo(x22, y22);
    context.lineTo(c3 * x06 - s * y06, s * x06 + c3 * y06);
    context.lineTo(c3 * x12 - s * y12, s * x12 + c3 * y12);
    context.lineTo(c3 * x22 - s * y22, s * x22 + c3 * y22);
    context.lineTo(c3 * x06 + s * y06, c3 * y06 - s * x06);
    context.lineTo(c3 * x12 + s * y12, c3 * y12 - s * x12);
    context.lineTo(c3 * x22 + s * y22, c3 * y22 - s * x22);
    context.closePath();
  }
};

// ../../../node_modules/d3-shape/src/symbol/times.js
var times_default = {
  draw(context, size) {
    const r = sqrt4(size - min4(size / 6, 1.7)) * 0.6189;
    context.moveTo(-r, -r);
    context.lineTo(r, r);
    context.moveTo(-r, r);
    context.lineTo(r, -r);
  }
};

// ../../../node_modules/d3-shape/src/symbol.js
var symbolsFill = [
  circle_default2,
  cross_default,
  diamond_default,
  square_default,
  star_default,
  triangle_default,
  wye_default
];
var symbolsStroke = [
  circle_default2,
  plus_default,
  times_default,
  triangle2_default,
  asterisk_default,
  square2_default,
  diamond2_default
];

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

// ../../../node_modules/d3-shape/src/curve/basis.js
function point2(that, x3, y3) {
  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 + x3) / 6,
    (that._y0 + 4 * that._y1 + y3) / 6
  );
}
function Basis(context) {
  this._context = context;
}
Basis.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 3:
        point2(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(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x3, y3) : this._context.moveTo(x3, y3);
        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:
        point2(this, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = x3;
    this._y0 = this._y1, this._y1 = y3;
  }
};
function basis_default2(context) {
  return new Basis(context);
}

// ../../../node_modules/d3-shape/src/curve/basisClosed.js
function BasisClosed(context) {
  this._context = context;
}
BasisClosed.prototype = {
  areaStart: noop_default2,
  areaEnd: noop_default2,
  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(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._x2 = x3, this._y2 = y3;
        break;
      case 1:
        this._point = 2;
        this._x3 = x3, this._y3 = y3;
        break;
      case 2:
        this._point = 3;
        this._x4 = x3, this._y4 = y3;
        this._context.moveTo((this._x0 + 4 * this._x1 + x3) / 6, (this._y0 + 4 * this._y1 + y3) / 6);
        break;
      default:
        point2(this, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = x3;
    this._y0 = this._y1, this._y1 = y3;
  }
};
function basisClosed_default2(context) {
  return new BasisClosed(context);
}

// ../../../node_modules/d3-shape/src/curve/basisOpen.js
function BasisOpen(context) {
  this._context = context;
}
BasisOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x3, y3) {
    x3 = +x3, y3 = +y3;
    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 + x3) / 6, y06 = (this._y0 + 4 * this._y1 + y3) / 6;
        this._line ? this._context.lineTo(x06, y06) : this._context.moveTo(x06, y06);
        break;
      case 3:
        this._point = 4;
      // falls through
      default:
        point2(this, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = x3;
    this._y0 = this._y1, this._y1 = y3;
  }
};
function basisOpen_default(context) {
  return new BasisOpen(context);
}

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

// ../../../node_modules/d3-shape/src/curve/cardinal.js
function point3(that, x3, y3) {
  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 - x3),
    that._y2 + that._k * (that._y1 - y3),
    that._x2,
    that._y2
  );
}
function Cardinal(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}
Cardinal.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2:
        this._context.lineTo(this._x2, this._y2);
        break;
      case 3:
        point3(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(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x3, y3) : this._context.moveTo(x3, y3);
        break;
      case 1:
        this._point = 2;
        this._x1 = x3, this._y1 = y3;
        break;
      case 2:
        this._point = 3;
      // falls through
      default:
        point3(this, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var cardinal_default = (function custom2(tension) {
  function cardinal(context) {
    return new Cardinal(context, tension);
  }
  cardinal.tension = function(tension2) {
    return custom2(+tension2);
  };
  return cardinal;
})(0);

// ../../../node_modules/d3-shape/src/curve/cardinalClosed.js
function CardinalClosed(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}
CardinalClosed.prototype = {
  areaStart: noop_default2,
  areaEnd: noop_default2,
  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(x3, y3) {
    x3 = +x3, y3 = +y3;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._x3 = x3, this._y3 = y3;
        break;
      case 1:
        this._point = 2;
        this._context.moveTo(this._x4 = x3, this._y4 = y3);
        break;
      case 2:
        this._point = 3;
        this._x5 = x3, this._y5 = y3;
        break;
      default:
        point3(this, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var cardinalClosed_default = (function custom3(tension) {
  function cardinal(context) {
    return new CardinalClosed(context, tension);
  }
  cardinal.tension = function(tension2) {
    return custom3(+tension2);
  };
  return cardinal;
})(0);

// ../../../node_modules/d3-shape/src/curve/cardinalOpen.js
function CardinalOpen(context, tension) {
  this._context = context;
  this._k = (1 - tension) / 6;
}
CardinalOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x3, y3) {
    x3 = +x3, y3 = +y3;
    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, x3, y3);
        break;
    }
    this._x0 = this._x1, this._x1 = this._x2, this._x2 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var cardinalOpen_default = (function custom4(tension) {
  function cardinal(context) {
    return new CardinalOpen(context, tension);
  }
  cardinal.tension = function(tension2) {
    return custom4(+tension2);
  };
  return cardinal;
})(0);

// ../../../node_modules/d3-shape/src/curve/catmullRom.js
function point4(that, x3, y3) {
  var x12 = that._x1, y12 = that._y1, x22 = that._x2, y22 = that._y2;
  if (that._l01_a > epsilon7) {
    var a2 = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a, n = 3 * that._l01_a * (that._l01_a + that._l12_a);
    x12 = (x12 * a2 - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;
    y12 = (y12 * a2 - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
  }
  if (that._l23_a > epsilon7) {
    var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a, m = 3 * that._l23_a * (that._l23_a + that._l12_a);
    x22 = (x22 * b + that._x1 * that._l23_2a - x3 * that._l12_2a) / m;
    y22 = (y22 * b + that._y1 * that._l23_2a - y3 * that._l12_2a) / m;
  }
  that._context.bezierCurveTo(x12, y12, x22, y22, that._x2, that._y2);
}
function CatmullRom(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}
CatmullRom.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2:
        this._context.lineTo(this._x2, this._y2);
        break;
      case 3:
        this.point(this._x2, this._y2);
        break;
    }
    if (this._line || this._line !== 0 && this._point === 1) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x3, y3) {
    x3 = +x3, y3 = +y3;
    if (this._point) {
      var x23 = this._x2 - x3, y23 = this._y2 - y3;
      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(x3, y3) : this._context.moveTo(x3, y3);
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
      // falls through
      default:
        point4(this, x3, y3);
        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 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var catmullRom_default = (function custom5(alpha) {
  function catmullRom(context) {
    return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
  }
  catmullRom.alpha = function(alpha2) {
    return custom5(+alpha2);
  };
  return catmullRom;
})(0.5);

// ../../../node_modules/d3-shape/src/curve/catmullRomClosed.js
function CatmullRomClosed(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}
CatmullRomClosed.prototype = {
  areaStart: noop_default2,
  areaEnd: noop_default2,
  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(x3, y3) {
    x3 = +x3, y3 = +y3;
    if (this._point) {
      var x23 = this._x2 - x3, y23 = this._y2 - y3;
      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 = x3, this._y3 = y3;
        break;
      case 1:
        this._point = 2;
        this._context.moveTo(this._x4 = x3, this._y4 = y3);
        break;
      case 2:
        this._point = 3;
        this._x5 = x3, this._y5 = y3;
        break;
      default:
        point4(this, x3, y3);
        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 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var catmullRomClosed_default = (function custom6(alpha) {
  function catmullRom(context) {
    return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);
  }
  catmullRom.alpha = function(alpha2) {
    return custom6(+alpha2);
  };
  return catmullRom;
})(0.5);

// ../../../node_modules/d3-shape/src/curve/catmullRomOpen.js
function CatmullRomOpen(context, alpha) {
  this._context = context;
  this._alpha = alpha;
}
CatmullRomOpen.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN;
    this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
  },
  lineEnd: function() {
    if (this._line || this._line !== 0 && this._point === 3) this._context.closePath();
    this._line = 1 - this._line;
  },
  point: function(x3, y3) {
    x3 = +x3, y3 = +y3;
    if (this._point) {
      var x23 = this._x2 - x3, y23 = this._y2 - y3;
      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:
        point4(this, x3, y3);
        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 = x3;
    this._y0 = this._y1, this._y1 = this._y2, this._y2 = y3;
  }
};
var catmullRomOpen_default = (function custom7(alpha) {
  function catmullRom(context) {
    return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);
  }
  catmullRom.alpha = function(alpha2) {
    return custom7(+alpha2);
  };
  return catmullRom;
})(0.5);

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

// ../../../node_modules/d3-shape/src/curve/monotone.js
function sign3(x3) {
  return x3 < 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), p = (s0 * h1 + s1 * h0) / (h0 + h1);
  return (sign3(s0) + sign3(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
}
function slope2(that, t) {
  var h = that._x1 - that._x0;
  return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
function point5(that, t03, 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 * t03, x12 - dx, y12 - dx * t13, x12, y12);
}
function MonotoneX(context) {
  this._context = context;
}
MonotoneX.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN;
    this._point = 0;
  },
  lineEnd: function() {
    switch (this._point) {
      case 2:
        this._context.lineTo(this._x1, this._y1);
        break;
      case 3:
        point5(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(x3, y3) {
    var t13 = NaN;
    x3 = +x3, y3 = +y3;
    if (x3 === this._x1 && y3 === this._y1) return;
    switch (this._point) {
      case 0:
        this._point = 1;
        this._line ? this._context.lineTo(x3, y3) : this._context.moveTo(x3, y3);
        break;
      case 1:
        this._point = 2;
        break;
      case 2:
        this._point = 3;
        point5(this, slope2(this, t13 = slope3(this, x3, y3)), t13);
        break;
      default:
        point5(this, this._t0, t13 = slope3(this, x3, y3));
        break;
    }
    this._x0 = this._x1, this._x1 = x3;
    this._y0 = this._y1, this._y1 = y3;
    this._t0 = t13;
  }
};
function MonotoneY(context) {
  this._context = new ReflectContext(context);
}
(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x3, y3) {
  MonotoneX.prototype.point.call(this, y3, x3);
};
function ReflectContext(context) {
  this._context = context;
}
ReflectContext.prototype = {
  moveTo: function(x3, y3) {
    this._context.moveTo(y3, x3);
  },
  closePath: function() {
    this._context.closePath();
  },
  lineTo: function(x3, y3) {
    this._context.lineTo(y3, x3);
  },
  bezierCurveTo: function(x12, y12, x22, y22, x3, y3) {
    this._context.bezierCurveTo(y12, x12, y22, x22, y3, x3);
  }
};
function monotoneX(context) {
  return new MonotoneX(context);
}
function monotoneY(context) {
  return new MonotoneY(context);
}

// ../../../node_modules/d3-shape/src/curve/natural.js
function Natural(context) {
  this._context = context;
}
Natural.prototype = {
  areaStart: function() {
    this._line = 0;
  },
  areaEnd: function() {
    this._line = NaN;
  },
  lineStart: function() {
    this._x = [];
    this._y = [];
  },
  lineEnd: function() {
    var x3 = this._x, y3 = this._y, n = x3.length;
    if (n) {
      this._line ? this._context.lineTo(x3[0], y3[0]) : this._context.moveTo(x3[0], y3[0]);
      if (n === 2) {
        this._context.lineTo(x3[1], y3[1]);
      } else {
        var px = controlPoints(x3), py = controlPoints(y3);
        for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {
          this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x3[i1], y3[i1]);
        }
      }
    }
    if (this._line || this._line !== 0 && n === 1) this._context.closePath();
    this._line = 1 - this._line;
    this._x = this._y = null;
  },
  point: function(x3, y3) {
    this._x.push(+x3);
    this._y.push(+y3);
  }
};
function controlPoints(x3) {
  var i, n = x3.length - 1, m, a2 = new Array(n), b = new Array(n), r = new Array(n);
  a2[0] = 0, b[0] = 2, r[0] = x3[0] + 2 * x3[1];
  for (i = 1; i < n - 1; ++i) a2[i] = 1, b[i] = 4, r[i] = 4 * x3[i] + 2 * x3[i + 1];
  a2[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x3[n - 1] + x3[n];
  for (i = 1; i < n; ++i) m = a2[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
  a2[n - 1] = r[n - 1] / b[n - 1];
  for (i = n - 2; i >= 0; --i) a2[i] = (r[i] - a2[i + 1]) / b[i];
  b[n - 1] = (x3[n] + a2[n - 1]) / 2;
  for (i = 0; i < n - 1; ++i) b[i] = 2 * x3[i + 1] - a2[i + 1];
  return [a2, b];
}
function natural_default(context) {
  return new Natural(context);
}

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

// ../../../node_modules/d3-zoom/src/constant.js
var constant_default6 = (x3) => () => x3;

// ../../../node_modules/d3-zoom/src/event.js
function ZoomEvent(type2, {
  sourceEvent,
  target,
  transform: transform3,
  dispatch: dispatch2
}) {
  Object.defineProperties(this, {
    type: { value: type2, enumerable: true, configurable: true },
    sourceEvent: { value: sourceEvent, enumerable: true, configurable: true },
    target: { value: target, enumerable: true, configurable: true },
    transform: { value: transform3, enumerable: true, configurable: true },
    _: { value: dispatch2 }
  });
}

// ../../../node_modules/d3-zoom/src/transform.js
function Transform2(k2, x3, y3) {
  this.k = k2;
  this.x = x3;
  this.y = y3;
}
Transform2.prototype = {
  constructor: Transform2,
  scale: function(k2) {
    return k2 === 1 ? this : new Transform2(this.k * k2, this.x, this.y);
  },
  translate: function(x3, y3) {
    return x3 === 0 & y3 === 0 ? this : new Transform2(this.k, this.x + this.k * x3, this.y + this.k * y3);
  },
  apply: function(point6) {
    return [point6[0] * this.k + this.x, point6[1] * this.k + this.y];
  },
  applyX: function(x3) {
    return x3 * this.k + this.x;
  },
  applyY: function(y3) {
    return y3 * this.k + this.y;
  },
  invert: function(location) {
    return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];
  },
  invertX: function(x3) {
    return (x3 - this.x) / this.k;
  },
  invertY: function(y3) {
    return (y3 - this.y) / this.k;
  },
  rescaleX: function(x3) {
    return x3.copy().domain(x3.range().map(this.invertX, this).map(x3.invert, x3));
  },
  rescaleY: function(y3) {
    return y3.copy().domain(y3.range().map(this.invertY, this).map(y3.invert, y3));
  },
  toString: function() {
    return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
  }
};
var identity7 = new Transform2(1, 0, 0);
transform.prototype = Transform2.prototype;
function transform(node) {
  while (!node.__zoom) if (!(node = node.parentNode)) return identity7;
  return node.__zoom;
}

// ../../../node_modules/d3-zoom/src/noevent.js
function nopropagation2(event) {
  event.stopImmediatePropagation();
}
function noevent_default3(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
}

// ../../../node_modules/d3-zoom/src/zoom.js
function defaultFilter2(event) {
  return (!event.ctrlKey || event.type === "wheel") && !event.button;
}
function defaultExtent2() {
  var e = this;
  if (e instanceof SVGElement) {
    e = e.ownerSVGElement || e;
    if (e.hasAttribute("viewBox")) {
      e = e.viewBox.baseVal;
      return [[e.x, e.y], [e.x + e.width, e.y + e.height]];
    }
    return [[0, 0], [e.width.baseVal.value, e.height.baseVal.value]];
  }
  return [[0, 0], [e.clientWidth, e.clientHeight]];
}
function defaultTransform() {
  return this.__zoom || identity7;
}
function defaultWheelDelta(event) {
  return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 2e-3) * (event.ctrlKey ? 10 : 1);
}
function defaultTouchable2() {
  return navigator.maxTouchPoints || "ontouchstart" in this;
}
function defaultConstrain(transform3, extent4, translateExtent) {
  var dx0 = transform3.invertX(extent4[0][0]) - translateExtent[0][0], dx1 = transform3.invertX(extent4[1][0]) - translateExtent[1][0], dy0 = transform3.invertY(extent4[0][1]) - translateExtent[0][1], dy1 = transform3.invertY(extent4[1][1]) - translateExtent[1][1];
  return transform3.translate(
    dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),
    dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)
  );
}
function zoom_default2() {
  var filter3 = defaultFilter2, extent4 = defaultExtent2, constrain = defaultConstrain, wheelDelta = defaultWheelDelta, touchable = defaultTouchable2, scaleExtent = [0, Infinity], translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]], duration2 = 250, interpolate = zoom_default, listeners = dispatch_default("start", "zoom", "end"), touchstarting, touchfirst, touchending, touchDelay = 500, wheelDelay = 150, clickDistance2 = 0, tapDistance = 10;
  function zoom2(selection2) {
    selection2.property("__zoom", defaultTransform).on("wheel.zoom", wheeled, { passive: false }).on("mousedown.zoom", mousedowned).on("dblclick.zoom", dblclicked).filter(touchable).on("touchstart.zoom", touchstarted).on("touchmove.zoom", touchmoved).on("touchend.zoom touchcancel.zoom", touchended).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
  }
  zoom2.transform = function(collection, transform3, point6, event) {
    var selection2 = collection.selection ? collection.selection() : collection;
    selection2.property("__zoom", defaultTransform);
    if (collection !== selection2) {
      schedule(collection, transform3, point6, event);
    } else {
      selection2.interrupt().each(function() {
        gesture(this, arguments).event(event).start().zoom(null, typeof transform3 === "function" ? transform3.apply(this, arguments) : transform3).end();
      });
    }
  };
  zoom2.scaleBy = function(selection2, k2, p, event) {
    zoom2.scaleTo(selection2, function() {
      var k0 = this.__zoom.k, k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return k0 * k1;
    }, p, event);
  };
  zoom2.scaleTo = function(selection2, k2, p, event) {
    zoom2.transform(selection2, function() {
      var e = extent4.apply(this, arguments), t03 = this.__zoom, p0 = p == null ? centroid3(e) : typeof p === "function" ? p.apply(this, arguments) : p, p1 = t03.invert(p0), k1 = typeof k2 === "function" ? k2.apply(this, arguments) : k2;
      return constrain(translate(scale3(t03, k1), p0, p1), e, translateExtent);
    }, p, event);
  };
  zoom2.translateBy = function(selection2, x3, y3, event) {
    zoom2.transform(selection2, function() {
      return constrain(this.__zoom.translate(
        typeof x3 === "function" ? x3.apply(this, arguments) : x3,
        typeof y3 === "function" ? y3.apply(this, arguments) : y3
      ), extent4.apply(this, arguments), translateExtent);
    }, null, event);
  };
  zoom2.translateTo = function(selection2, x3, y3, p, event) {
    zoom2.transform(selection2, function() {
      var e = extent4.apply(this, arguments), t = this.__zoom, p0 = p == null ? centroid3(e) : typeof p === "function" ? p.apply(this, arguments) : p;
      return constrain(identity7.translate(p0[0], p0[1]).scale(t.k).translate(
        typeof x3 === "function" ? -x3.apply(this, arguments) : -x3,
        typeof y3 === "function" ? -y3.apply(this, arguments) : -y3
      ), e, translateExtent);
    }, p, event);
  };
  function scale3(transform3, k2) {
    k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k2));
    return k2 === transform3.k ? transform3 : new Transform2(k2, transform3.x, transform3.y);
  }
  function translate(transform3, p0, p1) {
    var x3 = p0[0] - p1[0] * transform3.k, y3 = p0[1] - p1[1] * transform3.k;
    return x3 === transform3.x && y3 === transform3.y ? transform3 : new Transform2(transform3.k, x3, y3);
  }
  function centroid3(extent5) {
    return [(+extent5[0][0] + +extent5[1][0]) / 2, (+extent5[0][1] + +extent5[1][1]) / 2];
  }
  function schedule(transition2, transform3, point6, event) {
    transition2.on("start.zoom", function() {
      gesture(this, arguments).event(event).start();
    }).on("interrupt.zoom end.zoom", function() {
      gesture(this, arguments).event(event).end();
    }).tween("zoom", function() {
      var that = this, args = arguments, g = gesture(that, args).event(event), e = extent4.apply(that, args), p = point6 == null ? centroid3(e) : typeof point6 === "function" ? point6.apply(that, args) : point6, w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]), a2 = that.__zoom, b = typeof transform3 === "function" ? transform3.apply(that, args) : transform3, i = interpolate(a2.invert(p).concat(w / a2.k), b.invert(p).concat(w / b.k));
      return function(t) {
        if (t === 1) t = b;
        else {
          var l = i(t), k2 = w / l[2];
          t = new Transform2(k2, p[0] - l[0] * k2, p[1] - l[1] * k2);
        }
        g.zoom(null, t);
      };
    });
  }
  function gesture(that, args, clean) {
    return !clean && that.__zooming || new Gesture(that, args);
  }
  function Gesture(that, args) {
    this.that = that;
    this.args = args;
    this.active = 0;
    this.sourceEvent = null;
    this.extent = extent4.apply(that, args);
    this.taps = 0;
  }
  Gesture.prototype = {
    event: function(event) {
      if (event) this.sourceEvent = event;
      return this;
    },
    start: function() {
      if (++this.active === 1) {
        this.that.__zooming = this;
        this.emit("start");
      }
      return this;
    },
    zoom: function(key, transform3) {
      if (this.mouse && key !== "mouse") this.mouse[1] = transform3.invert(this.mouse[0]);
      if (this.touch0 && key !== "touch") this.touch0[1] = transform3.invert(this.touch0[0]);
      if (this.touch1 && key !== "touch") this.touch1[1] = transform3.invert(this.touch1[0]);
      this.that.__zoom = transform3;
      this.emit("zoom");
      return this;
    },
    end: function() {
      if (--this.active === 0) {
        delete this.that.__zooming;
        this.emit("end");
      }
      return this;
    },
    emit: function(type2) {
      var d = select_default2(this.that).datum();
      listeners.call(
        type2,
        this.that,
        new ZoomEvent(type2, {
          sourceEvent: this.sourceEvent,
          target: zoom2,
          type: type2,
          transform: this.that.__zoom,
          dispatch: listeners
        }),
        d
      );
    }
  };
  function wheeled(event, ...args) {
    if (!filter3.apply(this, arguments)) return;
    var g = gesture(this, args).event(event), t = this.__zoom, k2 = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t.k * Math.pow(2, wheelDelta.apply(this, arguments)))), p = pointer_default(event);
    if (g.wheel) {
      if (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) {
        g.mouse[1] = t.invert(g.mouse[0] = p);
      }
      clearTimeout(g.wheel);
    } else if (t.k === k2) return;
    else {
      g.mouse = [p, t.invert(p)];
      interrupt_default(this);
      g.start();
    }
    noevent_default3(event);
    g.wheel = setTimeout(wheelidled, wheelDelay);
    g.zoom("mouse", constrain(translate(scale3(t, k2), g.mouse[0], g.mouse[1]), g.extent, translateExtent));
    function wheelidled() {
      g.wheel = null;
      g.end();
    }
  }
  function mousedowned(event, ...args) {
    if (touchending || !filter3.apply(this, arguments)) return;
    var currentTarget = event.currentTarget, g = gesture(this, args, true).event(event), v2 = select_default2(event.view).on("mousemove.zoom", mousemoved, true).on("mouseup.zoom", mouseupped, true), p = pointer_default(event, currentTarget), x06 = event.clientX, y06 = event.clientY;
    nodrag_default(event.view);
    nopropagation2(event);
    g.mouse = [p, this.__zoom.invert(p)];
    interrupt_default(this);
    g.start();
    function mousemoved(event2) {
      noevent_default3(event2);
      if (!g.moved) {
        var dx = event2.clientX - x06, dy = event2.clientY - y06;
        g.moved = dx * dx + dy * dy > clickDistance2;
      }
      g.event(event2).zoom("mouse", constrain(translate(g.that.__zoom, g.mouse[0] = pointer_default(event2, currentTarget), g.mouse[1]), g.extent, translateExtent));
    }
    function mouseupped(event2) {
      v2.on("mousemove.zoom mouseup.zoom", null);
      yesdrag(event2.view, g.moved);
      noevent_default3(event2);
      g.event(event2).end();
    }
  }
  function dblclicked(event, ...args) {
    if (!filter3.apply(this, arguments)) return;
    var t03 = this.__zoom, p0 = pointer_default(event.changedTouches ? event.changedTouches[0] : event, this), p1 = t03.invert(p0), k1 = t03.k * (event.shiftKey ? 0.5 : 2), t13 = constrain(translate(scale3(t03, k1), p0, p1), extent4.apply(this, args), translateExtent);
    noevent_default3(event);
    if (duration2 > 0) select_default2(this).transition().duration(duration2).call(schedule, t13, p0, event);
    else select_default2(this).call(zoom2.transform, t13, p0, event);
  }
  function touchstarted(event, ...args) {
    if (!filter3.apply(this, arguments)) return;
    var touches = event.touches, n = touches.length, g = gesture(this, args, event.changedTouches.length === n).event(event), started, i, t, p;
    nopropagation2(event);
    for (i = 0; i < n; ++i) {
      t = touches[i], p = pointer_default(t, this);
      p = [p, this.__zoom.invert(p), t.identifier];
      if (!g.touch0) g.touch0 = p, started = true, g.taps = 1 + !!touchstarting;
      else if (!g.touch1 && g.touch0[2] !== p[2]) g.touch1 = p, g.taps = 0;
    }
    if (touchstarting) touchstarting = clearTimeout(touchstarting);
    if (started) {
      if (g.taps < 2) touchfirst = p[0], touchstarting = setTimeout(function() {
        touchstarting = null;
      }, touchDelay);
      interrupt_default(this);
      g.start();
    }
  }
  function touchmoved(event, ...args) {
    if (!this.__zooming) return;
    var g = gesture(this, args).event(event), touches = event.changedTouches, n = touches.length, i, t, p, l;
    noevent_default3(event);
    for (i = 0; i < n; ++i) {
      t = touches[i], p = pointer_default(t, this);
      if (g.touch0 && g.touch0[2] === t.identifier) g.touch0[0] = p;
      else if (g.touch1 && g.touch1[2] === t.identifier) g.touch1[0] = p;
    }
    t = g.that.__zoom;
    if (g.touch1) {
      var p0 = g.touch0[0], l0 = g.touch0[1], p1 = g.touch1[0], l1 = g.touch1[1], dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
      t = scale3(t, Math.sqrt(dp / dl));
      p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
      l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];
    } else if (g.touch0) p = g.touch0[0], l = g.touch0[1];
    else return;
    g.zoom("touch", constrain(translate(t, p, l), g.extent, translateExtent));
  }
  function touchended(event, ...args) {
    if (!this.__zooming) return;
    var g = gesture(this, args).event(event), touches = event.changedTouches, n = touches.length, i, t;
    nopropagation2(event);
    if (touchending) clearTimeout(touchending);
    touchending = setTimeout(function() {
      touchending = null;
    }, touchDelay);
    for (i = 0; i < n; ++i) {
      t = touches[i];
      if (g.touch0 && g.touch0[2] === t.identifier) delete g.touch0;
      else if (g.touch1 && g.touch1[2] === t.identifier) delete g.touch1;
    }
    if (g.touch1 && !g.touch0) g.touch0 = g.touch1, delete g.touch1;
    if (g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);
    else {
      g.end();
      if (g.taps === 2) {
        t = pointer_default(t, this);
        if (Math.hypot(touchfirst[0] - t[0], touchfirst[1] - t[1]) < tapDistance) {
          var p = select_default2(this).on("dblclick.zoom");
          if (p) p.apply(this, arguments);
        }
      }
    }
  }
  zoom2.wheelDelta = function(_) {
    return arguments.length ? (wheelDelta = typeof _ === "function" ? _ : constant_default6(+_), zoom2) : wheelDelta;
  };
  zoom2.filter = function(_) {
    return arguments.length ? (filter3 = typeof _ === "function" ? _ : constant_default6(!!_), zoom2) : filter3;
  };
  zoom2.touchable = function(_) {
    return arguments.length ? (touchable = typeof _ === "function" ? _ : constant_default6(!!_), zoom2) : touchable;
  };
  zoom2.extent = function(_) {
    return arguments.length ? (extent4 = typeof _ === "function" ? _ : constant_default6([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), zoom2) : extent4;
  };
  zoom2.scaleExtent = function(_) {
    return arguments.length ? (scaleExtent[0] = +_[0], scaleExtent[1] = +_[1], zoom2) : [scaleExtent[0], scaleExtent[1]];
  };
  zoom2.translateExtent = function(_) {
    return arguments.length ? (translateExtent[0][0] = +_[0][0], translateExtent[1][0] = +_[1][0], translateExtent[0][1] = +_[0][1], translateExtent[1][1] = +_[1][1], zoom2) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];
  };
  zoom2.constrain = function(_) {
    return arguments.length ? (constrain = _, zoom2) : constrain;
  };
  zoom2.duration = function(_) {
    return arguments.length ? (duration2 = +_, zoom2) : duration2;
  };
  zoom2.interpolate = function(_) {
    return arguments.length ? (interpolate = _, zoom2) : interpolate;
  };
  zoom2.on = function() {
    var value = listeners.on.apply(listeners, arguments);
    return value === listeners ? zoom2 : value;
  };
  zoom2.clickDistance = function(_) {
    return arguments.length ? (clickDistance2 = (_ = +_) * _, zoom2) : Math.sqrt(clickDistance2);
  };
  zoom2.tapDistance = function(_) {
    return arguments.length ? (tapDistance = +_, zoom2) : tapDistance;
  };
  return zoom2;
}

// ../../../node_modules/@observablehq/plot/src/defined.js
function defined(x3) {
  return x3 != null && !Number.isNaN(x3);
}
function ascendingDefined2(a2, b) {
  return +defined(b) - +defined(a2) || ascending(a2, b);
}
function descendingDefined(a2, b) {
  return +defined(b) - +defined(a2) || descending(a2, b);
}
function nonempty(x3) {
  return x3 != null && `${x3}` !== "";
}
function finite2(x3) {
  return isFinite(x3) ? x3 : NaN;
}
function positive(x3) {
  return x3 > 0 && isFinite(x3) ? x3 : NaN;
}
function negative(x3) {
  return x3 < 0 && isFinite(x3) ? x3 : NaN;
}

// ../../../node_modules/isoformat/src/format.js
function format2(date3, fallback) {
  if (!(date3 instanceof Date)) date3 = /* @__PURE__ */ new Date(+date3);
  if (isNaN(date3)) return typeof fallback === "function" ? fallback(date3) : fallback;
  const hours2 = date3.getUTCHours();
  const minutes2 = date3.getUTCMinutes();
  const seconds3 = date3.getUTCSeconds();
  const milliseconds3 = date3.getUTCMilliseconds();
  return `${formatYear2(date3.getUTCFullYear(), 4)}-${pad2(date3.getUTCMonth() + 1, 2)}-${pad2(date3.getUTCDate(), 2)}${hours2 || minutes2 || seconds3 || milliseconds3 ? `T${pad2(hours2, 2)}:${pad2(minutes2, 2)}${seconds3 || milliseconds3 ? `:${pad2(seconds3, 2)}${milliseconds3 ? `.${pad2(milliseconds3, 3)}` : ``}` : ``}Z` : ``}`;
}
function formatYear2(year) {
  return year < 0 ? `-${pad2(-year, 6)}` : year > 9999 ? `+${pad2(year, 6)}` : pad2(year, 4);
}
function pad2(value, width2) {
  return `${value}`.padStart(width2, "0");
}

// ../../../node_modules/isoformat/src/parse.js
var re2 = /^(?:[-+]\d{2})?\d{4}(?:-\d{2}(?:-\d{2})?)?(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d{3})?)?(?:Z|[-+]\d{2}:?\d{2})?)?$/;
function parse(string2, fallback) {
  if (!re2.test(string2 += "")) return typeof fallback === "function" ? fallback(string2) : fallback;
  return new Date(string2);
}

// ../../../node_modules/@observablehq/plot/src/order.js
function orderof(values2) {
  if (values2 == null) return;
  const first3 = values2[0];
  const last2 = values2[values2.length - 1];
  return descending(first3, last2);
}

// ../../../node_modules/@observablehq/plot/src/time.js
var durationSecond3 = 1e3;
var durationMinute3 = durationSecond3 * 60;
var durationHour3 = durationMinute3 * 60;
var durationDay3 = durationHour3 * 24;
var durationWeek3 = durationDay3 * 7;
var durationMonth3 = durationDay3 * 30;
var durationYear3 = durationDay3 * 365;
var tickIntervals = [
  ["millisecond", 1],
  ["2 milliseconds", 2],
  ["5 milliseconds", 5],
  ["10 milliseconds", 10],
  ["20 milliseconds", 20],
  ["50 milliseconds", 50],
  ["100 milliseconds", 100],
  ["200 milliseconds", 200],
  ["500 milliseconds", 500],
  ["second", durationSecond3],
  ["5 seconds", 5 * durationSecond3],
  ["15 seconds", 15 * durationSecond3],
  ["30 seconds", 30 * durationSecond3],
  ["minute", durationMinute3],
  ["5 minutes", 5 * durationMinute3],
  ["15 minutes", 15 * durationMinute3],
  ["30 minutes", 30 * durationMinute3],
  ["hour", durationHour3],
  ["3 hours", 3 * durationHour3],
  ["6 hours", 6 * durationHour3],
  ["12 hours", 12 * durationHour3],
  ["day", durationDay3],
  ["2 days", 2 * durationDay3],
  ["week", durationWeek3],
  ["2 weeks", 2 * durationWeek3],
  // https://github.com/d3/d3-time/issues/46
  ["month", durationMonth3],
  ["3 months", 3 * durationMonth3],
  ["6 months", 6 * durationMonth3],
  // https://github.com/d3/d3-time/issues/46
  ["year", durationYear3],
  ["2 years", 2 * durationYear3],
  ["5 years", 5 * durationYear3],
  ["10 years", 10 * durationYear3],
  ["20 years", 20 * durationYear3],
  ["50 years", 50 * durationYear3],
  ["100 years", 100 * durationYear3]
  // TODO generalize to longer time scales
];
var durations = /* @__PURE__ */ new Map([
  ["second", durationSecond3],
  ["minute", durationMinute3],
  ["hour", durationHour3],
  ["day", durationDay3],
  ["monday", durationWeek3],
  ["tuesday", durationWeek3],
  ["wednesday", durationWeek3],
  ["thursday", durationWeek3],
  ["friday", durationWeek3],
  ["saturday", durationWeek3],
  ["sunday", durationWeek3],
  ["week", durationWeek3],
  ["month", durationMonth3],
  ["year", durationYear3]
]);
var timeIntervals = /* @__PURE__ */ new Map([
  ["second", second],
  ["minute", timeMinute],
  ["hour", timeHour],
  ["day", timeDay],
  // https://github.com/d3/d3-time/issues/62
  ["monday", timeMonday],
  ["tuesday", timeTuesday],
  ["wednesday", timeWednesday],
  ["thursday", timeThursday],
  ["friday", timeFriday],
  ["saturday", timeSaturday],
  ["sunday", timeSunday],
  ["week", timeSunday],
  ["month", timeMonth],
  ["year", timeYear]
]);
var utcIntervals = /* @__PURE__ */ new Map([
  ["second", second],
  ["minute", utcMinute],
  ["hour", utcHour],
  ["day", unixDay],
  ["monday", utcMonday],
  ["tuesday", utcTuesday],
  ["wednesday", utcWednesday],
  ["thursday", utcThursday],
  ["friday", utcFriday],
  ["saturday", utcSaturday],
  ["sunday", utcSunday],
  ["week", utcSunday],
  ["month", utcMonth],
  ["year", utcYear]
]);
var intervalDuration = Symbol("intervalDuration");
var intervalType = Symbol("intervalType");
for (const [name2, interval4] of timeIntervals) {
  interval4[intervalDuration] = durations.get(name2);
  interval4[intervalType] = "time";
}
for (const [name2, interval4] of utcIntervals) {
  interval4[intervalDuration] = durations.get(name2);
  interval4[intervalType] = "utc";
}
var utcFormatIntervals = [
  ["year", utcYear, "utc"],
  ["month", utcMonth, "utc"],
  ["day", unixDay, "utc", 6 * durationMonth3],
  ["hour", utcHour, "utc", 3 * durationDay3],
  ["minute", utcMinute, "utc", 6 * durationHour3],
  ["second", second, "utc", 30 * durationMinute3]
];
var timeFormatIntervals = [
  ["year", timeYear, "time"],
  ["month", timeMonth, "time"],
  ["day", timeDay, "time", 6 * durationMonth3],
  ["hour", timeHour, "time", 3 * durationDay3],
  ["minute", timeMinute, "time", 6 * durationHour3],
  ["second", second, "time", 30 * durationMinute3]
];
var formatIntervals = [
  utcFormatIntervals[0],
  timeFormatIntervals[0],
  utcFormatIntervals[1],
  timeFormatIntervals[1],
  utcFormatIntervals[2],
  timeFormatIntervals[2],
  // Below day, local time typically has an hourly offset from UTC and hence the
  // two are aligned and indistinguishable; therefore, we only consider UTC, and
  // we don’t consider these if the domain only has a single value.
  ...utcFormatIntervals.slice(3)
];
function parseTimeInterval(input3) {
  let name2 = `${input3}`.toLowerCase();
  if (name2.endsWith("s")) name2 = name2.slice(0, -1);
  let period = 1;
  const match = /^(?:(\d+)\s+)/.exec(name2);
  if (match) {
    name2 = name2.slice(match[0].length);
    period = +match[1];
  }
  switch (name2) {
    case "quarter":
      name2 = "month";
      period *= 3;
      break;
    case "half":
      name2 = "month";
      period *= 6;
      break;
  }
  let interval4 = utcIntervals.get(name2);
  if (!interval4) throw new Error(`unknown interval: ${input3}`);
  if (period > 1 && !interval4.every) throw new Error(`non-periodic interval: ${name2}`);
  return [name2, period];
}
function timeInterval3(input3) {
  return asInterval(parseTimeInterval(input3), "time");
}
function utcInterval(input3) {
  return asInterval(parseTimeInterval(input3), "utc");
}
function asInterval([name2, period], type2) {
  let interval4 = (type2 === "time" ? timeIntervals : utcIntervals).get(name2);
  if (period > 1) {
    interval4 = interval4.every(period);
    interval4[intervalDuration] = durations.get(name2) * period;
    interval4[intervalType] = type2;
  }
  return interval4;
}
function generalizeTimeInterval(interval4, n) {
  if (!(n > 1)) return;
  const duration2 = interval4[intervalDuration];
  if (!tickIntervals.some(([, d]) => d === duration2)) return;
  if (duration2 % durationDay3 === 0 && durationDay3 < duration2 && duration2 < durationMonth3) return;
  const [i] = tickIntervals[bisector(([, step]) => Math.log(step)).center(tickIntervals, Math.log(duration2 * n))];
  return (interval4[intervalType] === "time" ? timeInterval3 : utcInterval)(i);
}
function formatTimeInterval(name2, type2, anchor) {
  const format3 = type2 === "time" ? timeFormat : utcFormat;
  if (anchor == null) {
    return format3(
      name2 === "year" ? "%Y" : name2 === "month" ? "%Y-%m" : name2 === "day" ? "%Y-%m-%d" : name2 === "hour" || name2 === "minute" ? "%Y-%m-%dT%H:%M" : name2 === "second" ? "%Y-%m-%dT%H:%M:%S" : "%Y-%m-%dT%H:%M:%S.%L"
    );
  }
  const template2 = getTimeTemplate(anchor);
  switch (name2) {
    case "millisecond":
      return formatConditional(format3(".%L"), format3(":%M:%S"), template2);
    case "second":
      return formatConditional(format3(":%S"), format3("%-I:%M"), template2);
    case "minute":
      return formatConditional(format3("%-I:%M"), format3("%p"), template2);
    case "hour":
      return formatConditional(format3("%-I %p"), format3("%b %-d"), template2);
    case "day":
      return formatConditional(format3("%-d"), format3("%b"), template2);
    case "month":
      return formatConditional(format3("%b"), format3("%Y"), template2);
    case "year":
      return format3("%Y");
  }
  throw new Error("unable to format time ticks");
}
function getTimeTemplate(anchor) {
  return anchor === "left" || anchor === "right" ? (f1, f2) => `
${f1}
${f2}` : anchor === "top" ? (f1, f2) => `${f2}
${f1}` : (f1, f2) => `${f1}
${f2}`;
}
function getFormatIntervals(type2) {
  return type2 === "time" ? timeFormatIntervals : type2 === "utc" ? utcFormatIntervals : formatIntervals;
}
function inferTimeFormat(type2, dates, anchor) {
  const step = max2(pairs2(dates, (a2, b) => Math.abs(b - a2)));
  if (step < 1e3) return formatTimeInterval("millisecond", "utc", anchor);
  for (const [name2, interval4, intervalType2, maxStep] of getFormatIntervals(type2)) {
    if (step > maxStep) break;
    if (name2 === "hour" && !step) break;
    if (dates.every((d) => interval4.floor(d) >= d)) return formatTimeInterval(name2, intervalType2, anchor);
  }
}
function formatConditional(format1, format22, template2) {
  return (x3, i, X3) => {
    const f1 = format1(x3, i);
    const f2 = format22(x3, i);
    const j = i - orderof(X3);
    return i !== j && X3[j] !== void 0 && f2 === format22(X3[j], j) ? f1 : template2(f1, f2);
  };
}

// ../../../node_modules/@observablehq/plot/src/options.js
var TypedArray2 = Object.getPrototypeOf(Uint8Array);
var objectToString = Object.prototype.toString;
function isArray3(value) {
  return value instanceof Array || value instanceof TypedArray2;
}
function isNumberArray2(value) {
  return value instanceof TypedArray2 && !isBigIntArray(value);
}
function isNumberType(type2) {
  return type2?.prototype instanceof TypedArray2 && !isBigIntType(type2);
}
function isBigIntArray(value) {
  return value instanceof BigInt64Array || value instanceof BigUint64Array;
}
function isBigIntType(type2) {
  return type2 === BigInt64Array || type2 === BigUint64Array;
}
var reindex = Symbol("reindex");
function valueof(data, value, type2) {
  const valueType = typeof value;
  return valueType === "string" ? isArrowTable2(data) ? maybeTypedArrowify(data.getChild(value), type2) : maybeTypedMap(data, field2(value), type2) : valueType === "function" ? maybeTypedMap(data, value, type2) : valueType === "number" || value instanceof Date || valueType === "boolean" ? map3(data, constant(value), type2) : typeof value?.transform === "function" ? maybeTypedArrayify(value.transform(data), type2) : maybeTake(maybeTypedArrayify(value, type2), data?.[reindex]);
}
function maybeTake(values2, index2) {
  return values2 != null && index2 ? take(values2, index2) : values2;
}
function maybeTypedMap(data, f, type2) {
  return map3(data, isNumberType(type2) ? (d, i) => coerceNumber(f(d, i)) : f, type2);
}
function maybeTypedArrayify(data, type2) {
  return type2 === void 0 ? arrayify2(data) : isArrowVector(data) ? maybeTypedArrowify(data, type2) : data instanceof type2 ? data : type2.from(data, isNumberType(type2) && !isNumberArray2(data) ? coerceNumber : void 0);
}
function maybeTypedArrowify(vector3, type2) {
  return vector3 == null ? vector3 : (type2 === void 0 || type2 === Array) && isArrowDateType(vector3.type) ? coerceDates(vectorToArray(vector3)) : maybeTypedArrayify(vectorToArray(vector3), type2);
}
function vectorToArray(vector3) {
  return vector3.nullCount ? vector3.toJSON() : vector3.toArray();
}
var singleton = [null];
var field2 = (name2) => (d) => {
  const v2 = d[name2];
  return v2 === void 0 && d.type === "Feature" ? d.properties?.[name2] : v2;
};
var indexOf = { transform: range2 };
var identity8 = { transform: (d) => d };
var one2 = () => 1;
var yes = () => true;
var string = (x3) => x3 == null ? x3 : `${x3}`;
var number5 = (x3) => x3 == null ? x3 : +x3;
var first2 = (x3) => x3 ? x3[0] : void 0;
var second2 = (x3) => x3 ? x3[1] : void 0;
var third = (x3) => x3 ? x3[2] : void 0;
var constant = (x3) => () => x3;
function percentile(reduce) {
  const p = +`${reduce}`.slice(1) / 100;
  return (I, f) => quantile2(I, p, f);
}
function coerceNumbers(values2) {
  return isNumberArray2(values2) ? values2 : map3(values2, coerceNumber, Float64Array);
}
function coerceNumber(x3) {
  return x3 == null ? NaN : Number(x3);
}
function coerceDates(values2) {
  return map3(values2, coerceDate);
}
function coerceDate(x3) {
  return x3 instanceof Date && !isNaN(x3) ? x3 : typeof x3 === "string" ? parse(x3) : x3 == null || isNaN(x3 = Number(x3)) ? void 0 : new Date(x3);
}
function maybeColorChannel(value, defaultValue) {
  if (value === void 0) value = defaultValue;
  return value === null ? [void 0, "none"] : isColor(value) ? [void 0, value] : [value, void 0];
}
function maybeNumberChannel(value, defaultValue) {
  if (value === void 0) value = defaultValue;
  return value === null || typeof value === "number" ? [void 0, value] : [value, void 0];
}
function maybeKeyword(input3, name2, allowed) {
  if (input3 != null) return keyword(input3, name2, allowed);
}
function keyword(input3, name2, allowed) {
  const i = `${input3}`.toLowerCase();
  if (!allowed.includes(i)) throw new Error(`invalid ${name2}: ${input3}`);
  return i;
}
function dataify(data) {
  return isArrowTable2(data) ? data : arrayify2(data);
}
function arrayify2(values2) {
  if (values2 == null || isArray3(values2)) return values2;
  if (isArrowVector(values2)) return maybeTypedArrowify(values2);
  if (isGeoJSON(values2)) {
    switch (values2.type) {
      case "FeatureCollection":
        return values2.features;
      case "GeometryCollection":
        return values2.geometries;
      default:
        return [values2];
    }
  }
  return Array.from(values2);
}
function isGeoJSON(x3) {
  switch (x3?.type) {
    case "FeatureCollection":
    case "GeometryCollection":
    case "Feature":
    case "LineString":
    case "MultiLineString":
    case "MultiPoint":
    case "MultiPolygon":
    case "Point":
    case "Polygon":
    case "Sphere":
      return true;
    default:
      return false;
  }
}
function map3(values2, f, type2 = Array) {
  return values2 == null ? values2 : values2 instanceof type2 ? values2.map(f) : type2.from(values2, f);
}
function slice3(values2, type2 = Array) {
  return values2 instanceof type2 ? values2.slice() : type2.from(values2);
}
function hasX({ x: x3, x1: x12, x2: x22 }) {
  return x3 !== void 0 || x12 !== void 0 || x22 !== void 0;
}
function hasY({ y: y3, y1: y12, y2: y22 }) {
  return y3 !== void 0 || y12 !== void 0 || y22 !== void 0;
}
function hasXY(options) {
  return hasX(options) || hasY(options) || options.interval !== void 0;
}
function isObject(option) {
  return option?.toString === objectToString;
}
function isScaleOptions(option) {
  return isObject(option) && (option.type !== void 0 || option.domain !== void 0);
}
function isOptions(option) {
  return isObject(option) && typeof option.transform !== "function";
}
function isDomainSort(sort3) {
  return isOptions(sort3) && sort3.value === void 0 && sort3.channel === void 0;
}
function maybeZero(x3, x12, x22, x32 = identity8) {
  if (x12 === void 0 && x22 === void 0) {
    x12 = 0, x22 = x3 === void 0 ? x32 : x3;
  } else if (x12 === void 0) {
    x12 = x3 === void 0 ? 0 : x3;
  } else if (x22 === void 0) {
    x22 = x3 === void 0 ? 0 : x3;
  }
  return [x12, x22];
}
function maybeTuple(x3, y3) {
  return x3 === void 0 && y3 === void 0 ? [first2, second2] : [x3, y3];
}
function maybeZ({ z, fill, stroke } = {}) {
  if (z === void 0) [z] = maybeColorChannel(fill);
  if (z === void 0) [z] = maybeColorChannel(stroke);
  return z;
}
function lengthof(data) {
  return isArray3(data) ? data.length : data?.numRows;
}
function range2(data) {
  const n = lengthof(data);
  const r = new Uint32Array(n);
  for (let i = 0; i < n; ++i) r[i] = i;
  return r;
}
function take(values2, index2) {
  return isArray3(values2) ? map3(index2, (i) => values2[i], values2.constructor) : map3(index2, (i) => values2.at(i));
}
function taker(f) {
  return f.length === 1 ? (index2, values2) => f(take(values2, index2)) : f;
}
function subarray(I, i, j) {
  return I.subarray ? I.subarray(i, j) : I.slice(i, j);
}
function keyof2(value) {
  return value !== null && typeof value === "object" ? value.valueOf() : value;
}
function maybeInput(key, options) {
  if (options[key] !== void 0) return options[key];
  switch (key) {
    case "x1":
    case "x2":
      key = "x";
      break;
    case "y1":
    case "y2":
      key = "y";
      break;
  }
  return options[key];
}
function column2(source) {
  let value;
  return [
    {
      transform: () => value,
      label: labelof(source)
    },
    (v2) => value = v2
  ];
}
function maybeColumn(source) {
  return source == null ? [source] : column2(source);
}
function labelof(value, defaultValue) {
  return typeof value === "string" ? value : value && value.label !== void 0 ? value.label : defaultValue;
}
function mid(x12, x22) {
  return {
    transform(data) {
      const X13 = x12.transform(data);
      const X23 = x22.transform(data);
      return isTemporal(X13) || isTemporal(X23) ? map3(X13, (_, i) => new Date((+X13[i] + +X23[i]) / 2)) : map3(X13, (_, i) => (+X13[i] + +X23[i]) / 2, Float64Array);
    },
    label: x12.label
  };
}
function maybeApplyInterval(V, scale3) {
  const t = maybeIntervalTransform(scale3?.interval, scale3?.type);
  return t ? map3(V, t) : V;
}
function maybeIntervalTransform(interval4, type2) {
  const i = maybeInterval(interval4, type2);
  return i && ((v2) => defined(v2) ? i.floor(v2) : v2);
}
function maybeInterval(interval4, type2) {
  if (interval4 == null) return;
  if (typeof interval4 === "number") return numberInterval(interval4);
  if (typeof interval4 === "string") return (type2 === "time" ? timeInterval3 : utcInterval)(interval4);
  if (typeof interval4.floor !== "function") throw new Error("invalid interval; missing floor method");
  if (typeof interval4.offset !== "function") throw new Error("invalid interval; missing offset method");
  return interval4;
}
function numberInterval(interval4) {
  interval4 = +interval4;
  if (0 < interval4 && interval4 < 1 && Number.isInteger(1 / interval4)) interval4 = -1 / interval4;
  const n = Math.abs(interval4);
  return interval4 < 0 ? {
    floor: (d) => Math.floor(d * n) / n,
    offset: (d, s2 = 1) => (d * n + Math.floor(s2)) / n,
    range: (lo, hi) => range(Math.ceil(lo * n), hi * n).map((x3) => x3 / n)
  } : {
    floor: (d) => Math.floor(d / n) * n,
    offset: (d, s2 = 1) => d + n * Math.floor(s2),
    range: (lo, hi) => range(Math.ceil(lo / n), hi / n).map((x3) => x3 * n)
  };
}
function maybeRangeInterval(interval4, type2) {
  interval4 = maybeInterval(interval4, type2);
  if (interval4 && typeof interval4.range !== "function") throw new Error("invalid interval: missing range method");
  return interval4;
}
function maybeNiceInterval(interval4, type2) {
  interval4 = maybeRangeInterval(interval4, type2);
  if (interval4 && typeof interval4.ceil !== "function") throw new Error("invalid interval: missing ceil method");
  return interval4;
}
function isTimeInterval(t) {
  return isInterval(t) && typeof t?.floor === "function" && t.floor() instanceof Date;
}
function isInterval(t) {
  return typeof t?.range === "function";
}
function maybeValue(value) {
  return value === void 0 || isOptions(value) ? value : { value };
}
function numberChannel(source) {
  return source == null ? null : {
    transform: (data) => valueof(data, source, Float64Array),
    label: labelof(source)
  };
}
function isTuples(data) {
  if (!isIterable2(data)) return false;
  for (const d of data) {
    if (d == null) continue;
    return typeof d === "object" && "0" in d && "1" in d;
  }
}
function isIterable2(value) {
  return value && typeof value[Symbol.iterator] === "function";
}
function isTextual(values2) {
  for (const value of values2) {
    if (value == null) continue;
    return typeof value !== "object" || value instanceof Date;
  }
}
function isOrdinal(values2) {
  for (const value of values2) {
    if (value == null) continue;
    const type2 = typeof value;
    return type2 === "string" || type2 === "boolean";
  }
}
function isTemporal(values2) {
  for (const value of values2) {
    if (value == null) continue;
    return value instanceof Date;
  }
}
function isTemporalString(values2) {
  for (const value of values2) {
    if (value == null) continue;
    return typeof value === "string" && isNaN(value) && parse(value);
  }
}
function isNumericString(values2) {
  for (const value of values2) {
    if (value == null) continue;
    if (typeof value !== "string") return false;
    if (!value.trim()) continue;
    return !isNaN(value);
  }
}
function isNumeric(values2) {
  for (const value of values2) {
    if (value == null) continue;
    return typeof value === "number";
  }
}
function isEvery(values2, is) {
  let every;
  for (const value of values2) {
    if (value == null) continue;
    if (!is(value)) return false;
    every = true;
  }
  return every;
}
var namedColors = new Set("none,currentcolor,transparent,aliceblue,antiquewhite,aqua,aquamarine,azure,beige,bisque,black,blanchedalmond,blue,blueviolet,brown,burlywood,cadetblue,chartreuse,chocolate,coral,cornflowerblue,cornsilk,crimson,cyan,darkblue,darkcyan,darkgoldenrod,darkgray,darkgreen,darkgrey,darkkhaki,darkmagenta,darkolivegreen,darkorange,darkorchid,darkred,darksalmon,darkseagreen,darkslateblue,darkslategray,darkslategrey,darkturquoise,darkviolet,deeppink,deepskyblue,dimgray,dimgrey,dodgerblue,firebrick,floralwhite,forestgreen,fuchsia,gainsboro,ghostwhite,gold,goldenrod,gray,green,greenyellow,grey,honeydew,hotpink,indianred,indigo,ivory,khaki,lavender,lavenderblush,lawngreen,lemonchiffon,lightblue,lightcoral,lightcyan,lightgoldenrodyellow,lightgray,lightgreen,lightgrey,lightpink,lightsalmon,lightseagreen,lightskyblue,lightslategray,lightslategrey,lightsteelblue,lightyellow,lime,limegreen,linen,magenta,maroon,mediumaquamarine,mediumblue,mediumorchid,mediumpurple,mediumseagreen,mediumslateblue,mediumspringgreen,mediumturquoise,mediumvioletred,midnightblue,mintcream,mistyrose,moccasin,navajowhite,navy,oldlace,olive,olivedrab,orange,orangered,orchid,palegoldenrod,palegreen,paleturquoise,palevioletred,papayawhip,peachpuff,peru,pink,plum,powderblue,purple,rebeccapurple,red,rosybrown,royalblue,saddlebrown,salmon,sandybrown,seagreen,seashell,sienna,silver,skyblue,slateblue,slategray,slategrey,snow,springgreen,steelblue,tan,teal,thistle,tomato,turquoise,violet,wheat,white,whitesmoke,yellow".split(","));
function isColor(value) {
  if (typeof value !== "string") return false;
  value = value.toLowerCase().trim();
  return /^#[0-9a-f]{3,8}$/.test(value) || // hex rgb, rgba, rrggbb, rrggbbaa
  /^(?:url|var|rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix)\(.*\)$/.test(value) || // <funciri>, CSS variable, color, etc.
  namedColors.has(value);
}
function isOpacity(value) {
  return typeof value === "number" && (0 <= value && value <= 1 || isNaN(value));
}
function isNoneish(value) {
  return value == null || isNone(value);
}
function isNone(value) {
  return /^\s*none\s*$/i.test(value);
}
function isRound(value) {
  return /^\s*round\s*$/i.test(value);
}
function maybeAnchor(value, name2) {
  return maybeKeyword(value, name2, [
    "middle",
    "top-left",
    "top",
    "top-right",
    "right",
    "bottom-right",
    "bottom",
    "bottom-left",
    "left"
  ]);
}
function maybeFrameAnchor(value = "middle") {
  return maybeAnchor(value, "frameAnchor");
}
function inherit2(options = {}, ...rest) {
  let o = options;
  for (const defaults22 of rest) {
    for (const key in defaults22) {
      if (o[key] === void 0) {
        const value = defaults22[key];
        if (o === options) o = { ...o, [key]: value };
        else o[key] = value;
      }
    }
  }
  return o;
}
function named2(things) {
  console.warn("named iterables are deprecated; please use an object instead");
  const names = /* @__PURE__ */ new Set();
  return Object.fromEntries(
    Array.from(things, (thing) => {
      const { name: name2 } = thing;
      if (name2 == null) throw new Error("missing name");
      const key = `${name2}`;
      if (key === "__proto__") throw new Error(`illegal name: ${key}`);
      if (names.has(key)) throw new Error(`duplicate name: ${key}`);
      names.add(key);
      return [name2, thing];
    })
  );
}
function maybeNamed(things) {
  return isIterable2(things) ? named2(things) : things;
}
function maybeClip(clip2) {
  if (clip2 === true) clip2 = "frame";
  else if (clip2 === false) clip2 = null;
  else if (!isGeoJSON(clip2) && clip2 != null) {
    clip2 = keyword(clip2, "clip", ["frame", "sphere"]);
    if (clip2 === "sphere") clip2 = { type: "Sphere" };
  }
  return clip2;
}
function isArrowTable2(value) {
  return value && typeof value.getChild === "function" && typeof value.toArray === "function" && value.schema && Array.isArray(value.schema.fields);
}
function isArrowVector(value) {
  return value && typeof value.toArray === "function" && value.type;
}
function isArrowDateType(type2) {
  return type2 && (type2.typeId === 8 || // date
  type2.typeId === 10) && // timestamp
  type2.unit === 1;
}

// ../../../node_modules/@observablehq/plot/src/scales/index.js
var position = Symbol("position");
var color2 = Symbol("color");
var radius = Symbol("radius");
var length3 = Symbol("length");
var opacity = Symbol("opacity");
var symbol = Symbol("symbol");
var projection2 = Symbol("projection");
var registry = /* @__PURE__ */ new Map([
  ["x", position],
  ["y", position],
  ["fx", position],
  ["fy", position],
  ["r", radius],
  ["color", color2],
  ["opacity", opacity],
  ["symbol", symbol],
  ["length", length3],
  ["projection", projection2]
]);
function isPosition(kind) {
  return kind === position || kind === projection2;
}
function hasNumericRange(kind) {
  return kind === position || kind === radius || kind === length3 || kind === opacity;
}

// ../../../node_modules/@observablehq/plot/src/symbol.js
var sqrt35 = Math.sqrt(3);
var sqrt4_3 = 2 / sqrt35;
var symbolHexagon = {
  draw(context, size) {
    const rx = Math.sqrt(size / Math.PI), ry = rx * sqrt4_3, hy = ry / 2;
    context.moveTo(0, ry);
    context.lineTo(rx, hy);
    context.lineTo(rx, -hy);
    context.lineTo(0, -ry);
    context.lineTo(-rx, -hy);
    context.lineTo(-rx, hy);
    context.closePath();
  }
};
var symbols = /* @__PURE__ */ new Map([
  ["asterisk", asterisk_default],
  ["circle", circle_default2],
  ["cross", cross_default],
  ["diamond", diamond_default],
  ["diamond2", diamond2_default],
  ["hexagon", symbolHexagon],
  ["plus", plus_default],
  ["square", square_default],
  ["square2", square2_default],
  ["star", star_default],
  ["times", times_default],
  ["triangle", triangle_default],
  ["triangle2", triangle2_default],
  ["wye", wye_default]
]);
function isSymbolObject(value) {
  return value && typeof value.draw === "function";
}
function isSymbol(value) {
  if (isSymbolObject(value)) return true;
  if (typeof value !== "string") return false;
  return symbols.has(value.toLowerCase());
}
function maybeSymbol(symbol2) {
  if (symbol2 == null || isSymbolObject(symbol2)) return symbol2;
  const value = symbols.get(`${symbol2}`.toLowerCase());
  if (value) return value;
  throw new Error(`invalid symbol: ${symbol2}`);
}
function maybeSymbolChannel(symbol2) {
  if (symbol2 == null || isSymbolObject(symbol2)) return [void 0, symbol2];
  if (typeof symbol2 === "string") {
    const value = symbols.get(`${symbol2}`.toLowerCase());
    if (value) return [void 0, value];
  }
  return [symbol2, void 0];
}

// ../../../node_modules/@observablehq/plot/src/transforms/basic.js
function basic({ filter: f1, sort: s1, reverse: r1, transform: t13, initializer: i1, ...options } = {}, transform3) {
  if (t13 === void 0) {
    if (f1 != null) t13 = filterTransform(f1);
    if (s1 != null && !isDomainSort(s1)) t13 = composeTransform(t13, sortTransform(s1));
    if (r1) t13 = composeTransform(t13, reverseTransform);
  }
  if (transform3 != null && i1 != null) throw new Error("transforms cannot be applied after initializers");
  return {
    ...options,
    ...(s1 === null || isDomainSort(s1)) && { sort: s1 },
    transform: composeTransform(t13, transform3)
  };
}
function initializer({ filter: f1, sort: s1, reverse: r1, initializer: i1, ...options } = {}, initializer2) {
  if (i1 === void 0) {
    if (f1 != null) i1 = filterTransform(f1);
    if (s1 != null && !isDomainSort(s1)) i1 = composeInitializer(i1, sortTransform(s1));
    if (r1) i1 = composeInitializer(i1, reverseTransform);
  }
  return {
    ...options,
    ...(s1 === null || isDomainSort(s1)) && { sort: s1 },
    initializer: composeInitializer(i1, initializer2)
  };
}
function composeTransform(t13, t22) {
  if (t13 == null) return t22 === null ? void 0 : t22;
  if (t22 == null) return t13 === null ? void 0 : t13;
  return function(data, facets, plotOptions) {
    ({ data, facets } = t13.call(this, data, facets, plotOptions));
    return t22.call(this, dataify(data), facets, plotOptions);
  };
}
function composeInitializer(i1, i2) {
  if (i1 == null) return i2 === null ? void 0 : i2;
  if (i2 == null) return i1 === null ? void 0 : i1;
  return function(data, facets, channels, ...args) {
    let c1, d1, f1, c22, d2, f2;
    ({ data: d1 = data, facets: f1 = facets, channels: c1 } = i1.call(this, data, facets, channels, ...args));
    ({ data: d2 = d1, facets: f2 = f1, channels: c22 } = i2.call(this, d1, f1, { ...channels, ...c1 }, ...args));
    return { data: d2, facets: f2, channels: { ...c1, ...c22 } };
  };
}
function apply(options, t) {
  return (options.initializer != null ? initializer : basic)(options, t);
}
function filter2(test, options) {
  return apply(options, filterTransform(test));
}
function filterTransform(value) {
  return (data, facets) => {
    const V = valueof(data, value);
    return { data, facets: facets.map((I) => I.filter((i) => V[i])) };
  };
}
function reverse2({ sort: sort3, ...options } = {}) {
  return {
    ...apply(options, reverseTransform),
    sort: isDomainSort(sort3) ? sort3 : null
  };
}
function reverseTransform(data, facets) {
  return { data, facets: facets.map((I) => I.slice().reverse()) };
}
function shuffle({ seed, sort: sort3, ...options } = {}) {
  return {
    ...apply(options, sortValue(seed == null ? Math.random : lcg(seed))),
    sort: isDomainSort(sort3) ? sort3 : null
  };
}
function sort2(order, { sort: sort3, ...options } = {}) {
  return {
    ...(isOptions(order) && order.channel !== void 0 ? initializer : apply)(options, sortTransform(order)),
    sort: isDomainSort(sort3) ? sort3 : null
  };
}
function sortTransform(value) {
  return (typeof value === "function" && value.length !== 1 ? sortData : sortValue)(value);
}
function sortData(compare) {
  return (data, facets) => {
    const compareData = isArray3(data) ? (i, j) => compare(data[i], data[j]) : (i, j) => compare(data.get(i), data.get(j));
    return { data, facets: facets.map((I) => I.slice().sort(compareData)) };
  };
}
function sortValue(value) {
  let channel, order;
  ({ channel, value, order } = { ...maybeValue(value) });
  const negate2 = channel?.startsWith("-");
  if (negate2) channel = channel.slice(1);
  if (order === void 0) order = negate2 ? descendingDefined : ascendingDefined2;
  if (typeof order !== "function") {
    switch (`${order}`.toLowerCase()) {
      case "ascending":
        order = ascendingDefined2;
        break;
      case "descending":
        order = descendingDefined;
        break;
      default:
        throw new Error(`invalid order: ${order}`);
    }
  }
  return (data, facets, channels) => {
    let V;
    if (channel === void 0) {
      V = valueof(data, value);
    } else {
      if (channels === void 0) throw new Error("channel sort requires an initializer");
      V = channels[channel];
      if (!V) return {};
      V = V.value;
    }
    const compareValue = (i, j) => order(V[i], V[j]);
    return { data, facets: facets.map((I) => I.slice().sort(compareValue)) };
  };
}

// ../../../node_modules/@observablehq/plot/src/transforms/group.js
function groupZ(outputs, options) {
  return groupn(null, null, outputs, options);
}
function groupX(outputs = { y: "count" }, options = {}) {
  const { x: x3 = identity8 } = options;
  if (x3 == null) throw new Error("missing channel: x");
  return groupn(x3, null, outputs, options);
}
function groupY(outputs = { x: "count" }, options = {}) {
  const { y: y3 = identity8 } = options;
  if (y3 == null) throw new Error("missing channel: y");
  return groupn(null, y3, outputs, options);
}
function group2(outputs = { fill: "count" }, options = {}) {
  let { x: x3, y: y3 } = options;
  [x3, y3] = maybeTuple(x3, y3);
  if (x3 == null) throw new Error("missing channel: x");
  if (y3 == null) throw new Error("missing channel: y");
  return groupn(x3, y3, outputs, options);
}
function groupn(x3, y3, {
  data: reduceData = reduceIdentity,
  filter: filter3,
  sort: sort3,
  reverse: reverse3,
  ...outputs
  // output channel definitions
} = {}, inputs = {}) {
  outputs = maybeGroupOutputs(outputs, inputs);
  reduceData = maybeGroupReduce(reduceData, identity8);
  sort3 = sort3 == null ? void 0 : maybeGroupOutput("sort", sort3, inputs);
  filter3 = filter3 == null ? void 0 : maybeGroupEvaluator("filter", filter3, inputs);
  const [GX, setGX] = maybeColumn(x3);
  const [GY, setGY] = maybeColumn(y3);
  const {
    z,
    fill,
    stroke,
    x1: x12,
    x2: x22,
    // consumed if x is an output
    y1: y12,
    y2: y22,
    // consumed if y is an output
    ...options
  } = inputs;
  const [GZ, setGZ] = maybeColumn(z);
  const [vfill] = maybeColorChannel(fill);
  const [vstroke] = maybeColorChannel(stroke);
  const [GF, setGF] = maybeColumn(vfill);
  const [GS, setGS] = maybeColumn(vstroke);
  return {
    ..."z" in inputs && { z: GZ || z },
    ..."fill" in inputs && { fill: GF || fill },
    ..."stroke" in inputs && { stroke: GS || stroke },
    ...basic(options, (data, facets, plotOptions) => {
      const X3 = maybeApplyInterval(valueof(data, x3), plotOptions?.x);
      const Y3 = maybeApplyInterval(valueof(data, y3), plotOptions?.y);
      const Z = valueof(data, z);
      const F = valueof(data, vfill);
      const S = valueof(data, vstroke);
      const G = maybeSubgroup(outputs, { z: Z, fill: F, stroke: S });
      const groupFacets = [];
      const groupData = [];
      const GX2 = X3 && setGX([]);
      const GY2 = Y3 && setGY([]);
      const GZ2 = Z && setGZ([]);
      const GF2 = F && setGF([]);
      const GS2 = S && setGS([]);
      let i = 0;
      for (const o of outputs) o.initialize(data);
      if (sort3) sort3.initialize(data);
      if (filter3) filter3.initialize(data);
      for (const facet of facets) {
        const groupFacet = [];
        for (const o of outputs) o.scope("facet", facet);
        if (sort3) sort3.scope("facet", facet);
        if (filter3) filter3.scope("facet", facet);
        for (const [f, I] of maybeGroup(facet, G)) {
          for (const [y4, gg] of maybeGroup(I, Y3)) {
            for (const [x4, g] of maybeGroup(gg, X3)) {
              const extent4 = { data };
              if (X3) extent4.x = x4;
              if (Y3) extent4.y = y4;
              if (G) extent4.z = f;
              if (filter3 && !filter3.reduce(g, extent4)) continue;
              groupFacet.push(i++);
              groupData.push(reduceData.reduceIndex(g, data, extent4));
              if (X3) GX2.push(x4);
              if (Y3) GY2.push(y4);
              if (Z) GZ2.push(G === Z ? f : Z[g[0]]);
              if (F) GF2.push(G === F ? f : F[g[0]]);
              if (S) GS2.push(G === S ? f : S[g[0]]);
              for (const o of outputs) o.reduce(g, extent4);
              if (sort3) sort3.reduce(g, extent4);
            }
          }
        }
        groupFacets.push(groupFacet);
      }
      maybeSort(groupFacets, sort3, reverse3);
      return { data: groupData, facets: groupFacets };
    }),
    ...!hasOutput(outputs, "x") && (GX ? { x: GX } : { x1: x12, x2: x22 }),
    ...!hasOutput(outputs, "y") && (GY ? { y: GY } : { y1: y12, y2: y22 }),
    ...Object.fromEntries(outputs.map(({ name: name2, output }) => [name2, output]))
  };
}
function hasOutput(outputs, ...names) {
  for (const { name: name2 } of outputs) {
    if (names.includes(name2)) {
      return true;
    }
  }
  return false;
}
function maybeOutputs(outputs, inputs, asOutput = maybeOutput) {
  const entries = Object.entries(outputs);
  if (inputs.title != null && outputs.title === void 0) entries.push(["title", reduceTitle]);
  if (inputs.href != null && outputs.href === void 0) entries.push(["href", reduceFirst]);
  return entries.filter(([, reduce]) => reduce !== void 0).map(([name2, reduce]) => reduce === null ? nullOutput(name2) : asOutput(name2, reduce, inputs));
}
function maybeOutput(name2, reduce, inputs, asEvaluator = maybeEvaluator) {
  let scale3;
  if (isObject(reduce) && "reduce" in reduce) scale3 = reduce.scale, reduce = reduce.reduce;
  const evaluator = asEvaluator(name2, reduce, inputs);
  const [output, setOutput] = column2(evaluator.label);
  let O;
  return {
    name: name2,
    output: scale3 === void 0 ? output : { value: output, scale: scale3 },
    initialize(data) {
      evaluator.initialize(data);
      O = setOutput([]);
    },
    scope(scope, I) {
      evaluator.scope(scope, I);
    },
    reduce(I, extent4) {
      O.push(evaluator.reduce(I, extent4));
    }
  };
}
function nullOutput(name2) {
  return { name: name2, initialize() {
  }, scope() {
  }, reduce() {
  } };
}
function maybeEvaluator(name2, reduce, inputs, asReduce = maybeReduce) {
  const input3 = maybeInput(name2, inputs);
  const reducer2 = asReduce(reduce, input3);
  let V, context;
  return {
    label: labelof(reducer2 === reduceCount ? null : input3, reducer2.label),
    initialize(data) {
      V = input3 === void 0 ? data : valueof(data, input3);
      if (reducer2.scope === "data") {
        context = reducer2.reduceIndex(range2(data), V);
      }
    },
    scope(scope, I) {
      if (reducer2.scope === scope) {
        context = reducer2.reduceIndex(I, V);
      }
    },
    reduce(I, extent4) {
      return reducer2.scope == null ? reducer2.reduceIndex(I, V, extent4) : reducer2.reduceIndex(I, V, context, extent4);
    }
  };
}
function maybeGroup(I, X3) {
  return X3 ? group(I, (i) => X3[i]) : [[, I]];
}
function maybeReduce(reduce, value, fallback = invalidReduce) {
  if (reduce == null) return fallback(reduce);
  if (typeof reduce.reduceIndex === "function") return reduce;
  if (typeof reduce.reduce === "function" && isObject(reduce)) return reduceReduce(reduce);
  if (typeof reduce === "function") return reduceFunction(reduce);
  if (/^p\d{2}$/i.test(reduce)) return reduceAccessor(percentile(reduce));
  switch (`${reduce}`.toLowerCase()) {
    case "first":
      return reduceFirst;
    case "last":
      return reduceLast;
    case "identity":
      return reduceIdentity;
    case "count":
      return reduceCount;
    case "distinct":
      return reduceDistinct;
    case "sum":
      return value == null ? reduceCount : reduceSum;
    case "proportion":
      return reduceProportion(value, "data");
    case "proportion-facet":
      return reduceProportion(value, "facet");
    case "deviation":
      return reduceAccessor(deviation);
    case "min":
      return reduceAccessor(min2);
    case "min-index":
      return reduceAccessor(minIndex);
    case "max":
      return reduceAccessor(max2);
    case "max-index":
      return reduceAccessor(maxIndex);
    case "mean":
      return reduceMaybeTemporalAccessor(mean);
    case "median":
      return reduceMaybeTemporalAccessor(median2);
    case "variance":
      return reduceAccessor(variance2);
    case "mode":
      return reduceAccessor(mode2);
  }
  return fallback(reduce);
}
function invalidReduce(reduce) {
  throw new Error(`invalid reduce: ${reduce}`);
}
function maybeGroupOutputs(outputs, inputs) {
  return maybeOutputs(outputs, inputs, maybeGroupOutput);
}
function maybeGroupOutput(name2, reduce, inputs) {
  return maybeOutput(name2, reduce, inputs, maybeGroupEvaluator);
}
function maybeGroupEvaluator(name2, reduce, inputs) {
  return maybeEvaluator(name2, reduce, inputs, maybeGroupReduce);
}
function maybeGroupReduce(reduce, value) {
  return maybeReduce(reduce, value, maybeGroupReduceFallback);
}
function maybeGroupReduceFallback(reduce) {
  switch (`${reduce}`.toLowerCase()) {
    case "x":
      return reduceX;
    case "y":
      return reduceY;
    case "z":
      return reduceZ;
  }
  throw new Error(`invalid group reduce: ${reduce}`);
}
function maybeSubgroup(outputs, inputs) {
  for (const name2 in inputs) {
    const value = inputs[name2];
    if (value !== void 0 && !outputs.some((o) => o.name === name2)) {
      return value;
    }
  }
}
function maybeSort(facets, sort3, reverse3) {
  if (sort3) {
    const S = sort3.output.transform();
    const compare = (i, j) => ascendingDefined2(S[i], S[j]);
    facets.forEach((f) => f.sort(compare));
  }
  if (reverse3) {
    facets.forEach((f) => f.reverse());
  }
}
function reduceReduce(reduce) {
  console.warn("deprecated reduce interface; implement reduceIndex instead.");
  return { ...reduce, reduceIndex: reduce.reduce.bind(reduce) };
}
function reduceFunction(f) {
  return {
    reduceIndex(I, X3, extent4) {
      return f(take(X3, I), extent4);
    }
  };
}
function reduceAccessor(f) {
  return {
    reduceIndex(I, X3) {
      return f(I, (i) => X3[i]);
    }
  };
}
function reduceMaybeTemporalAccessor(f) {
  return {
    reduceIndex(I, X3) {
      const x3 = f(I, (i) => X3[i]);
      return isTemporal(X3) ? new Date(x3) : x3;
    }
  };
}
var reduceIdentity = {
  reduceIndex(I, X3) {
    return take(X3, I);
  }
};
var reduceFirst = {
  reduceIndex(I, X3) {
    return X3[I[0]];
  }
};
var reduceTitle = {
  reduceIndex(I, X3) {
    const n = 5;
    const groups2 = sort(
      rollup(
        I,
        (V) => V.length,
        (i) => X3[i]
      ),
      second2
    );
    const top2 = groups2.slice(-n).reverse();
    if (top2.length < groups2.length) {
      const bottom2 = groups2.slice(0, 1 - n);
      top2[n - 1] = [`\u2026 ${bottom2.length.toLocaleString("en-US")} more`, sum2(bottom2, second2)];
    }
    return top2.map(([key, value]) => `${key} (${value.toLocaleString("en-US")})`).join("\n");
  }
};
var reduceLast = {
  reduceIndex(I, X3) {
    return X3[I[I.length - 1]];
  }
};
var reduceCount = {
  label: "Frequency",
  reduceIndex(I) {
    return I.length;
  }
};
var reduceDistinct = {
  label: "Distinct",
  reduceIndex(I, X3) {
    const s2 = new InternSet();
    for (const i of I) s2.add(X3[i]);
    return s2.size;
  }
};
var reduceSum = reduceAccessor(sum2);
function reduceProportion(value, scope) {
  return value == null ? { scope, label: "Frequency", reduceIndex: (I, V, basis2 = 1) => I.length / basis2 } : { scope, reduceIndex: (I, V, basis2 = 1) => sum2(I, (i) => V[i]) / basis2 };
}
var reduceX = {
  reduceIndex(I, X3, { x: x3 }) {
    return x3;
  }
};
var reduceY = {
  reduceIndex(I, X3, { y: y3 }) {
    return y3;
  }
};
var reduceZ = {
  reduceIndex(I, X3, { z }) {
    return z;
  }
};
function find2(test) {
  if (typeof test !== "function") throw new Error(`invalid test function: ${test}`);
  return {
    reduceIndex(I, V, { data }) {
      return V[I.find(isArray3(data) ? (i) => test(data[i], i, data) : (i) => test(data.get(i), i, data))];
    }
  };
}

// ../../../node_modules/@observablehq/plot/src/channel.js
function createChannel(data, { scale: scale3, type: type2, value, filter: filter3, hint, label = labelof(value) }, name2) {
  if (hint === void 0 && typeof value?.transform === "function") hint = value.hint;
  return inferChannelScale(name2, {
    scale: scale3,
    type: type2,
    value: valueof(data, value),
    label,
    filter: filter3,
    hint
  });
}
function createChannels(channels, data) {
  return Object.fromEntries(
    Object.entries(channels).map(([name2, channel]) => [name2, createChannel(data, channel, name2)])
  );
}
function valueObject(channels, scales2) {
  const values2 = Object.fromEntries(
    Object.entries(channels).map(([name2, { scale: scaleName, value }]) => {
      const scale3 = scaleName == null ? null : scales2[scaleName];
      return [name2, scale3 == null ? value : map3(value, scale3)];
    })
  );
  values2.channels = channels;
  return values2;
}
function inferChannelScale(name2, channel) {
  const { scale: scale3, value } = channel;
  if (scale3 === true || scale3 === "auto") {
    switch (name2) {
      case "fill":
      case "stroke":
      case "color":
        channel.scale = scale3 !== true && isEvery(value, isColor) ? null : "color";
        channel.defaultScale = "color";
        break;
      case "fillOpacity":
      case "strokeOpacity":
      case "opacity":
        channel.scale = scale3 !== true && isEvery(value, isOpacity) ? null : "opacity";
        channel.defaultScale = "opacity";
        break;
      case "symbol":
        if (scale3 !== true && isEvery(value, isSymbol)) {
          channel.scale = null;
          channel.value = map3(value, maybeSymbol);
        } else {
          channel.scale = "symbol";
        }
        channel.defaultScale = "symbol";
        break;
      default:
        channel.scale = registry.has(name2) ? name2 : null;
        break;
    }
  } else if (scale3 === false) {
    channel.scale = null;
  } else if (scale3 != null && !registry.has(scale3)) {
    throw new Error(`unknown scale: ${scale3}`);
  }
  return channel;
}
function channelDomain(data, facets, channels, facetChannels, options) {
  const { order: defaultOrder, reverse: defaultReverse, reduce: defaultReduce = true, limit: defaultLimit } = options;
  for (const x3 in options) {
    if (!registry.has(x3)) continue;
    let { value: y3, order = defaultOrder, reverse: reverse3 = defaultReverse, reduce = defaultReduce, limit = defaultLimit } = maybeValue(options[x3]);
    const negate2 = y3?.startsWith("-");
    if (negate2) y3 = y3.slice(1);
    order = order === void 0 ? negate2 !== (y3 === "width" || y3 === "height") ? descendingGroup : ascendingGroup : maybeOrder(order);
    if (reduce == null || reduce === false) continue;
    const X3 = x3 === "fx" || x3 === "fy" ? reindexFacetChannel(facets, facetChannels[x3]) : findScaleChannel(channels, x3);
    if (!X3) throw new Error(`missing channel for scale: ${x3}`);
    const XV = X3.value;
    const [lo = 0, hi = Infinity] = isIterable2(limit) ? limit : limit < 0 ? [limit] : [0, limit];
    if (y3 == null) {
      X3.domain = () => {
        let domain = Array.from(new InternSet(XV));
        if (reverse3) domain = domain.reverse();
        if (lo !== 0 || hi !== Infinity) domain = domain.slice(lo, hi);
        return domain;
      };
    } else {
      const YV = y3 === "data" ? data : y3 === "height" ? difference(channels, "y1", "y2") : y3 === "width" ? difference(channels, "x1", "x2") : values(channels, y3, y3 === "y" ? "y2" : y3 === "x" ? "x2" : void 0);
      const reducer2 = maybeReduce(reduce === true ? "max" : reduce, YV);
      X3.domain = () => {
        let domain = rollups(
          range2(XV),
          (I) => reducer2.reduceIndex(I, YV),
          (i) => XV[i]
        );
        if (order) domain.sort(order);
        if (reverse3) domain.reverse();
        if (lo !== 0 || hi !== Infinity) domain = domain.slice(lo, hi);
        return domain.map(first2);
      };
    }
  }
}
function findScaleChannel(channels, scale3) {
  for (const name2 in channels) {
    const channel = channels[name2];
    if (channel.scale === scale3) return channel;
  }
}
function reindexFacetChannel(facets, channel) {
  const originalFacets = facets.original;
  if (originalFacets === facets) return channel;
  const V1 = channel.value;
  const V2 = channel.value = [];
  for (let i = 0; i < originalFacets.length; ++i) {
    const vi = V1[originalFacets[i][0]];
    for (const j of facets[i]) V2[j] = vi;
  }
  return channel;
}
function difference(channels, k1, k2) {
  const X13 = values(channels, k1);
  const X23 = values(channels, k2);
  return map3(X23, (x22, i) => Math.abs(x22 - X13[i]), Float64Array);
}
function values(channels, name2, alias) {
  let channel = channels[name2];
  if (!channel && alias !== void 0) channel = channels[alias];
  if (channel) return channel.value;
  throw new Error(`missing channel: ${name2}`);
}
function maybeOrder(order) {
  if (order == null || typeof order === "function") return order;
  switch (`${order}`.toLowerCase()) {
    case "ascending":
      return ascendingGroup;
    case "descending":
      return descendingGroup;
  }
  throw new Error(`invalid order: ${order}`);
}
function ascendingGroup([ak, av], [bk, bv]) {
  return ascendingDefined2(av, bv) || ascendingDefined2(ak, bk);
}
function descendingGroup([ak, av], [bk, bv]) {
  return descendingDefined(av, bv) || ascendingDefined2(ak, bk);
}
function getSource(channels, key) {
  let channel = channels[key];
  if (!channel) return;
  while (channel.source) channel = channel.source;
  return channel.source === null ? null : channel;
}

// ../../../node_modules/@observablehq/plot/src/scales/schemes.js
var categoricalSchemes = /* @__PURE__ */ new Map([
  ["accent", Accent_default],
  ["category10", category10_default],
  ["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", Tableau10_default]
]);
function isCategoricalScheme(scheme28) {
  return scheme28 != null && categoricalSchemes.has(`${scheme28}`.toLowerCase());
}
var ordinalSchemes = new Map([
  ...categoricalSchemes,
  // diverging
  ["brbg", scheme112(scheme, BrBG_default)],
  ["prgn", scheme112(scheme2, PRGn_default)],
  ["piyg", scheme112(scheme3, PiYG_default)],
  ["puor", scheme112(scheme4, PuOr_default)],
  ["rdbu", scheme112(scheme5, RdBu_default)],
  ["rdgy", scheme112(scheme6, RdGy_default)],
  ["rdylbu", scheme112(scheme7, RdYlBu_default)],
  ["rdylgn", scheme112(scheme8, RdYlGn_default)],
  ["spectral", scheme112(scheme9, Spectral_default)],
  // reversed diverging (for temperature data)
  ["burd", scheme11r(scheme5, RdBu_default)],
  ["buylrd", scheme11r(scheme7, RdYlBu_default)],
  // sequential (single-hue)
  ["blues", scheme92(scheme22, Blues_default)],
  ["greens", scheme92(scheme23, Greens_default)],
  ["greys", scheme92(scheme24, Greys_default)],
  ["oranges", scheme92(scheme27, Oranges_default)],
  ["purples", scheme92(scheme25, Purples_default)],
  ["reds", scheme92(scheme26, Reds_default)],
  // sequential (multi-hue)
  ["turbo", schemei(turbo_default)],
  ["viridis", schemei(viridis_default)],
  ["magma", schemei(magma)],
  ["inferno", schemei(inferno)],
  ["plasma", schemei(plasma)],
  ["cividis", schemei(cividis_default)],
  ["cubehelix", schemei(cubehelix_default2)],
  ["warm", schemei(warm)],
  ["cool", schemei(cool)],
  ["bugn", scheme92(scheme10, BuGn_default)],
  ["bupu", scheme92(scheme11, BuPu_default)],
  ["gnbu", scheme92(scheme12, GnBu_default)],
  ["orrd", scheme92(scheme13, OrRd_default)],
  ["pubu", scheme92(scheme15, PuBu_default)],
  ["pubugn", scheme92(scheme14, PuBuGn_default)],
  ["purd", scheme92(scheme16, PuRd_default)],
  ["rdpu", scheme92(scheme17, RdPu_default)],
  ["ylgn", scheme92(scheme19, YlGn_default)],
  ["ylgnbu", scheme92(scheme18, YlGnBu_default)],
  ["ylorbr", scheme92(scheme20, YlOrBr_default)],
  ["ylorrd", scheme92(scheme21, YlOrRd_default)],
  // cyclical
  ["rainbow", schemeicyclical(rainbow_default)],
  ["sinebow", schemeicyclical(sinebow_default)]
]);
function scheme92(scheme28, interpolate) {
  return ({ length: n }) => {
    if (n === 1) return [scheme28[3][1]];
    if (n === 2) return [scheme28[3][1], scheme28[3][2]];
    n = Math.max(3, Math.floor(n));
    return n > 9 ? quantize_default(interpolate, n) : scheme28[n];
  };
}
function scheme112(scheme28, interpolate) {
  return ({ length: n }) => {
    if (n === 2) return [scheme28[3][0], scheme28[3][2]];
    n = Math.max(3, Math.floor(n));
    return n > 11 ? quantize_default(interpolate, n) : scheme28[n];
  };
}
function scheme11r(scheme28, interpolate) {
  return ({ length: n }) => {
    if (n === 2) return [scheme28[3][2], scheme28[3][0]];
    n = Math.max(3, Math.floor(n));
    return n > 11 ? quantize_default((t) => interpolate(1 - t), n) : scheme28[n].slice().reverse();
  };
}
function schemei(interpolate) {
  return ({ length: n }) => quantize_default(interpolate, Math.max(2, Math.floor(n)));
}
function schemeicyclical(interpolate) {
  return ({ length: n }) => quantize_default(interpolate, Math.floor(n) + 1).slice(0, -1);
}
function ordinalScheme(scheme28) {
  const s2 = `${scheme28}`.toLowerCase();
  if (!ordinalSchemes.has(s2)) throw new Error(`unknown ordinal scheme: ${s2}`);
  return ordinalSchemes.get(s2);
}
function ordinalRange(scheme28, length4) {
  const s2 = ordinalScheme(scheme28);
  const r = typeof s2 === "function" ? s2({ length: length4 }) : s2;
  return r.length !== length4 ? r.slice(0, length4) : r;
}
function maybeBooleanRange(domain, scheme28 = "greys") {
  const range3 = /* @__PURE__ */ new Set();
  const [f, t] = ordinalRange(scheme28, 2);
  for (const value of domain) {
    if (value == null) continue;
    if (value === true) range3.add(t);
    else if (value === false) range3.add(f);
    else return;
  }
  return [...range3];
}
var quantitativeSchemes = /* @__PURE__ */ new Map([
  // diverging
  ["brbg", BrBG_default],
  ["prgn", PRGn_default],
  ["piyg", PiYG_default],
  ["puor", PuOr_default],
  ["rdbu", RdBu_default],
  ["rdgy", RdGy_default],
  ["rdylbu", RdYlBu_default],
  ["rdylgn", RdYlGn_default],
  ["spectral", Spectral_default],
  // reversed diverging (for temperature data)
  ["burd", (t) => RdBu_default(1 - t)],
  ["buylrd", (t) => RdYlBu_default(1 - t)],
  // sequential (single-hue)
  ["blues", Blues_default],
  ["greens", Greens_default],
  ["greys", Greys_default],
  ["purples", Purples_default],
  ["reds", Reds_default],
  ["oranges", Oranges_default],
  // sequential (multi-hue)
  ["turbo", turbo_default],
  ["viridis", viridis_default],
  ["magma", magma],
  ["inferno", inferno],
  ["plasma", plasma],
  ["cividis", cividis_default],
  ["cubehelix", cubehelix_default2],
  ["warm", warm],
  ["cool", cool],
  ["bugn", BuGn_default],
  ["bupu", BuPu_default],
  ["gnbu", GnBu_default],
  ["orrd", OrRd_default],
  ["pubugn", PuBuGn_default],
  ["pubu", PuBu_default],
  ["purd", PuRd_default],
  ["rdpu", RdPu_default],
  ["ylgnbu", YlGnBu_default],
  ["ylgn", YlGn_default],
  ["ylorbr", YlOrBr_default],
  ["ylorrd", YlOrRd_default],
  // cyclical
  ["rainbow", rainbow_default],
  ["sinebow", sinebow_default]
]);
function quantitativeScheme(scheme28) {
  const s2 = `${scheme28}`.toLowerCase();
  if (!quantitativeSchemes.has(s2)) throw new Error(`unknown quantitative scheme: ${s2}`);
  return quantitativeSchemes.get(s2);
}
var divergingSchemes = /* @__PURE__ */ new Set([
  "brbg",
  "prgn",
  "piyg",
  "puor",
  "rdbu",
  "rdgy",
  "rdylbu",
  "rdylgn",
  "spectral",
  "burd",
  "buylrd"
]);
function isDivergingScheme(scheme28) {
  return scheme28 != null && divergingSchemes.has(`${scheme28}`.toLowerCase());
}

// ../../../node_modules/@observablehq/plot/src/scales/quantitative.js
var flip = (i) => (t) => i(1 - t);
var unit2 = [0, 1];
var interpolators = /* @__PURE__ */ new Map([
  // numbers
  ["number", number_default],
  // color spaces
  ["rgb", rgb_default],
  ["hsl", hsl_default],
  ["hcl", hcl_default],
  ["lab", lab2]
]);
function maybeInterpolator(interpolate) {
  const i = `${interpolate}`.toLowerCase();
  if (!interpolators.has(i)) throw new Error(`unknown interpolator: ${i}`);
  return interpolators.get(i);
}
function createScaleQ(key, scale3, channels, {
  type: type2,
  nice: nice3,
  clamp,
  zero: zero3,
  domain = inferAutoDomain(key, channels),
  unknown,
  round: round3,
  scheme: scheme28,
  interval: interval4,
  range: range3 = registry.get(key) === radius ? inferRadialRange(channels, domain) : registry.get(key) === length3 ? inferLengthRange(channels, domain) : registry.get(key) === opacity ? unit2 : void 0,
  interpolate = registry.get(key) === color2 ? scheme28 == null && range3 !== void 0 ? rgb_default : quantitativeScheme(scheme28 !== void 0 ? scheme28 : type2 === "cyclical" ? "rainbow" : "turbo") : round3 ? round_default : number_default,
  reverse: reverse3
}) {
  domain = maybeRepeat(domain);
  interval4 = maybeRangeInterval(interval4, type2);
  if (type2 === "cyclical" || type2 === "sequential") type2 = "linear";
  if (typeof interpolate !== "function") interpolate = maybeInterpolator(interpolate);
  reverse3 = !!reverse3;
  if (range3 !== void 0) {
    const n = domain.length;
    const m = (range3 = maybeRepeat(range3)).length;
    if (n !== m) {
      if (interpolate.length === 1) throw new Error("invalid piecewise interpolator");
      interpolate = piecewise(interpolate, range3);
      range3 = void 0;
    }
  }
  if (interpolate.length === 1) {
    if (reverse3) {
      interpolate = flip(interpolate);
      reverse3 = false;
    }
    if (range3 === void 0) {
      range3 = Float64Array.from(domain, (_, i) => i / (domain.length - 1));
      if (range3.length === 2) range3 = unit2;
    }
    scale3.interpolate((range3 === unit2 ? constant : interpolatePiecewise)(interpolate));
  } else {
    scale3.interpolate(interpolate);
  }
  if (zero3) {
    const [min5, max4] = extent(domain);
    if (min5 > 0 || max4 < 0) {
      domain = slice3(domain);
      const o = orderof(domain) || 1;
      if (o === Math.sign(min5)) domain[0] = 0;
      else domain[domain.length - 1] = 0;
    }
  }
  if (reverse3) domain = reverse(domain);
  scale3.domain(domain).unknown(unknown);
  if (nice3) scale3.nice(maybeNice(nice3, type2)), domain = scale3.domain();
  if (range3 !== void 0) scale3.range(range3);
  if (clamp) scale3.clamp(clamp);
  return { type: type2, domain, range: range3, scale: scale3, interpolate, interval: interval4 };
}
function maybeRepeat(values2) {
  values2 = arrayify2(values2);
  return values2.length >= 2 ? values2 : [values2[0], values2[0]];
}
function maybeNice(nice3, type2) {
  return nice3 === true ? void 0 : typeof nice3 === "number" ? nice3 : maybeNiceInterval(nice3, type2);
}
function createScaleLinear(key, channels, options) {
  return createScaleQ(key, linear2(), channels, options);
}
function createScaleSqrt(key, channels, options) {
  return createScalePow(key, channels, { ...options, exponent: 0.5 });
}
function createScalePow(key, channels, { exponent = 1, ...options }) {
  return createScaleQ(key, pow4().exponent(exponent), channels, { ...options, type: "pow" });
}
function createScaleLog(key, channels, { base = 10, domain = inferLogDomain(channels), ...options }) {
  return createScaleQ(key, log3().base(base), channels, { ...options, domain });
}
function createScaleSymlog(key, channels, { constant: constant2 = 1, ...options }) {
  return createScaleQ(key, symlog().constant(constant2), channels, options);
}
function createScaleQuantile(key, channels, {
  range: range3,
  quantiles = range3 === void 0 ? 5 : (range3 = [...range3]).length,
  // deprecated; use n instead
  n = quantiles,
  scheme: scheme28 = "rdylbu",
  domain = inferQuantileDomain(channels),
  unknown,
  interpolate,
  reverse: reverse3
}) {
  if (range3 === void 0) {
    range3 = interpolate !== void 0 ? quantize_default(interpolate, n) : registry.get(key) === color2 ? ordinalRange(scheme28, n) : void 0;
  }
  if (domain.length > 0) {
    domain = quantile3(domain, range3 === void 0 ? { length: n } : range3).quantiles();
  }
  return createScaleThreshold(key, channels, { domain, range: range3, reverse: reverse3, unknown });
}
function createScaleQuantize(key, channels, {
  range: range3,
  n = range3 === void 0 ? 5 : (range3 = [...range3]).length,
  scheme: scheme28 = "rdylbu",
  domain = inferAutoDomain(key, channels),
  unknown,
  interpolate,
  reverse: reverse3
}) {
  const [min5, max4] = extent(domain);
  let thresholds;
  if (range3 === void 0) {
    thresholds = ticks(min5, max4, n);
    if (thresholds[0] <= min5) thresholds.splice(0, 1);
    if (thresholds[thresholds.length - 1] >= max4) thresholds.pop();
    n = thresholds.length + 1;
    range3 = interpolate !== void 0 ? quantize_default(interpolate, n) : registry.get(key) === color2 ? ordinalRange(scheme28, n) : void 0;
  } else {
    thresholds = quantize_default(number_default(min5, max4), n + 1).slice(1, -1);
    if (min5 instanceof Date) thresholds = thresholds.map((x3) => new Date(x3));
  }
  if (orderof(arrayify2(domain)) < 0) thresholds.reverse();
  return createScaleThreshold(key, channels, { domain: thresholds, range: range3, reverse: reverse3, unknown });
}
function createScaleThreshold(key, channels, {
  domain = [0],
  // explicit thresholds in ascending order
  unknown,
  scheme: scheme28 = "rdylbu",
  interpolate,
  range: range3 = interpolate !== void 0 ? quantize_default(interpolate, domain.length + 1) : registry.get(key) === color2 ? ordinalRange(scheme28, domain.length + 1) : void 0,
  reverse: reverse3
}) {
  domain = arrayify2(domain);
  const sign4 = orderof(domain);
  if (!isNaN(sign4) && !isOrdered(domain, sign4)) throw new Error(`the ${key} scale has a non-monotonic domain`);
  if (reverse3) range3 = reverse(range3);
  return {
    type: "threshold",
    scale: threshold(sign4 < 0 ? reverse(domain) : domain, range3 === void 0 ? [] : range3).unknown(unknown),
    domain,
    range: range3
  };
}
function isOrdered(domain, sign4) {
  for (let i = 1, n = domain.length, d = domain[0]; i < n; ++i) {
    const s2 = descending(d, d = domain[i]);
    if (s2 !== 0 && s2 !== sign4) return false;
  }
  return true;
}
function createScaleIdentity(key) {
  return { type: "identity", scale: hasNumericRange(registry.get(key)) ? identity6() : (d) => d };
}
function inferDomain(channels, f = finite2) {
  return channels.length ? [
    min2(channels, ({ value }) => value === void 0 ? value : min2(value, f)),
    max2(channels, ({ value }) => value === void 0 ? value : max2(value, f))
  ] : [0, 1];
}
function inferAutoDomain(key, channels) {
  const type2 = registry.get(key);
  return (type2 === radius || type2 === opacity || type2 === length3 ? inferZeroDomain : inferDomain)(channels);
}
function inferZeroDomain(channels) {
  return [0, channels.length ? max2(channels, ({ value }) => value === void 0 ? value : max2(value, finite2)) : 1];
}
function inferRadialRange(channels, domain) {
  const hint = channels.find(({ radius: radius2 }) => radius2 !== void 0);
  if (hint !== void 0) return [0, hint.radius];
  const h25 = quantile2(channels, 0.5, ({ value }) => value === void 0 ? NaN : quantile2(value, 0.25, positive));
  const range3 = domain.map((d) => 3 * Math.sqrt(d / h25));
  const k2 = 30 / max2(range3);
  return k2 < 1 ? range3.map((r) => r * k2) : range3;
}
function inferLengthRange(channels, domain) {
  const h50 = median2(channels, ({ value }) => value === void 0 ? NaN : median2(value, Math.abs));
  const range3 = domain.map((d) => 12 * d / h50);
  const k2 = 60 / max2(range3);
  return k2 < 1 ? range3.map((r) => r * k2) : range3;
}
function inferLogDomain(channels) {
  for (const { value } of channels) {
    if (value !== void 0) {
      for (let v2 of value) {
        if (v2 > 0) return inferDomain(channels, positive);
        if (v2 < 0) return inferDomain(channels, negative);
      }
    }
  }
  return [1, 10];
}
function inferQuantileDomain(channels) {
  const domain = [];
  for (const { value } of channels) {
    if (value === void 0) continue;
    for (const v2 of value) domain.push(v2);
  }
  return domain;
}
function interpolatePiecewise(interpolate) {
  return (i, j) => (t) => interpolate(i + t * (j - i));
}

// ../../../node_modules/@observablehq/plot/src/warnings.js
var warnings = 0;
var lastMessage;
function consumeWarnings() {
  const w = warnings;
  warnings = 0;
  lastMessage = void 0;
  return w;
}
function warn(message) {
  if (message === lastMessage) return;
  lastMessage = message;
  console.warn(message);
  ++warnings;
}

// ../../../node_modules/@observablehq/plot/src/scales/diverging.js
function createScaleD(key, scale3, transform3, channels, {
  type: type2,
  nice: nice3,
  clamp,
  domain = inferDomain(channels),
  unknown,
  pivot = 0,
  scheme: scheme28,
  range: range3,
  symmetric = true,
  interpolate = registry.get(key) === color2 ? scheme28 == null && range3 !== void 0 ? rgb_default : quantitativeScheme(scheme28 !== void 0 ? scheme28 : "rdbu") : number_default,
  reverse: reverse3
}) {
  pivot = +pivot;
  domain = arrayify2(domain);
  let [min5, max4] = domain;
  if (domain.length > 2) warn(`Warning: the diverging ${key} scale domain contains extra elements.`);
  if (descending(min5, max4) < 0) [min5, max4] = [max4, min5], reverse3 = !reverse3;
  min5 = Math.min(min5, pivot);
  max4 = Math.max(max4, pivot);
  if (typeof interpolate !== "function") {
    interpolate = maybeInterpolator(interpolate);
  }
  if (range3 !== void 0) {
    interpolate = interpolate.length === 1 ? interpolatePiecewise(interpolate)(...range3) : piecewise(interpolate, range3);
  }
  if (reverse3) interpolate = flip(interpolate);
  if (symmetric) {
    const mid2 = transform3.apply(pivot);
    const mindelta = mid2 - transform3.apply(min5);
    const maxdelta = transform3.apply(max4) - mid2;
    if (mindelta < maxdelta) min5 = transform3.invert(mid2 - maxdelta);
    else if (mindelta > maxdelta) max4 = transform3.invert(mid2 + mindelta);
  }
  scale3.domain([min5, pivot, max4]).unknown(unknown).interpolator(interpolate);
  if (clamp) scale3.clamp(clamp);
  if (nice3) scale3.nice(nice3);
  return { type: type2, domain: [min5, max4], pivot, interpolate, scale: scale3 };
}
function createScaleDiverging(key, channels, options) {
  return createScaleD(key, diverging(), transformIdentity, channels, options);
}
function createScaleDivergingSqrt(key, channels, options) {
  return createScaleDivergingPow(key, channels, { ...options, exponent: 0.5 });
}
function createScaleDivergingPow(key, channels, { exponent = 1, ...options }) {
  return createScaleD(key, divergingPow().exponent(exponent = +exponent), transformPow2(exponent), channels, {
    ...options,
    type: "diverging-pow"
  });
}
function createScaleDivergingLog(key, channels, { base = 10, pivot = 1, domain = inferDomain(channels, pivot < 0 ? negative : positive), ...options }) {
  return createScaleD(key, divergingLog().base(base = +base), transformLog2, channels, {
    domain,
    pivot,
    ...options
  });
}
function createScaleDivergingSymlog(key, channels, { constant: constant2 = 1, ...options }) {
  return createScaleD(
    key,
    divergingSymlog().constant(constant2 = +constant2),
    transformSymlog2(constant2),
    channels,
    options
  );
}
var transformIdentity = {
  apply(x3) {
    return x3;
  },
  invert(x3) {
    return x3;
  }
};
var transformLog2 = {
  apply: Math.log,
  invert: Math.exp
};
var transformSqrt2 = {
  apply(x3) {
    return Math.sign(x3) * Math.sqrt(Math.abs(x3));
  },
  invert(x3) {
    return Math.sign(x3) * (x3 * x3);
  }
};
function transformPow2(exponent) {
  return exponent === 0.5 ? transformSqrt2 : {
    apply(x3) {
      return Math.sign(x3) * Math.pow(Math.abs(x3), exponent);
    },
    invert(x3) {
      return Math.sign(x3) * Math.pow(Math.abs(x3), 1 / exponent);
    }
  };
}
function transformSymlog2(constant2) {
  return {
    apply(x3) {
      return Math.sign(x3) * Math.log1p(Math.abs(x3 / constant2));
    },
    invert(x3) {
      return Math.sign(x3) * Math.expm1(Math.abs(x3)) * constant2;
    }
  };
}

// ../../../node_modules/@observablehq/plot/src/scales/temporal.js
function createScaleT(key, scale3, channels, options) {
  return createScaleQ(key, scale3, channels, options);
}
function createScaleTime(key, channels, options) {
  return createScaleT(key, time2(), channels, options);
}
function createScaleUtc(key, channels, options) {
  return createScaleT(key, utcTime(), channels, options);
}

// ../../../node_modules/@observablehq/plot/src/scales/ordinal.js
var ordinalImplicit = Symbol("ordinal");
function createScaleO(key, scale3, channels, { type: type2, interval: interval4, domain, range: range3, reverse: reverse3, hint }) {
  interval4 = maybeRangeInterval(interval4, type2);
  if (domain === void 0) domain = inferDomain2(channels, interval4, key);
  if (type2 === "categorical" || type2 === ordinalImplicit) type2 = "ordinal";
  if (reverse3) domain = reverse(domain);
  domain = scale3.domain(domain).domain();
  if (range3 !== void 0) {
    if (typeof range3 === "function") range3 = range3(domain);
    scale3.range(range3);
  }
  return { type: type2, domain, range: range3, scale: scale3, hint, interval: interval4 };
}
function createScaleOrdinal(key, channels, { type: type2, interval: interval4, domain, range: range3, scheme: scheme28, unknown, ...options }) {
  interval4 = maybeRangeInterval(interval4, type2);
  if (domain === void 0) domain = inferDomain2(channels, interval4, key);
  let hint;
  if (registry.get(key) === symbol) {
    hint = inferSymbolHint(channels);
    range3 = range3 === void 0 ? inferSymbolRange(hint) : map3(range3, maybeSymbol);
  } else if (registry.get(key) === color2) {
    if (range3 === void 0 && (type2 === "ordinal" || type2 === ordinalImplicit)) {
      range3 = maybeBooleanRange(domain, scheme28);
      if (range3 !== void 0) scheme28 = void 0;
    }
    if (scheme28 === void 0 && range3 === void 0) {
      scheme28 = type2 === "ordinal" ? "turbo" : "observable10";
    }
    if (scheme28 !== void 0) {
      if (range3 !== void 0) {
        const interpolate = quantitativeScheme(scheme28);
        const t03 = range3[0], d = range3[1] - range3[0];
        range3 = ({ length: n }) => quantize_default((t) => interpolate(t03 + d * t), n);
      } else {
        range3 = ordinalScheme(scheme28);
      }
    }
  }
  if (unknown === implicit) {
    throw new Error(`implicit unknown on ${key} scale is not supported`);
  }
  return createScaleO(key, ordinal().unknown(unknown), channels, { ...options, type: type2, domain, range: range3, hint });
}
function createScalePoint(key, channels, { align: align3 = 0.5, padding: padding2 = 0.5, ...options }) {
  return maybeRound(point().align(align3).padding(padding2), channels, options, key);
}
function createScaleBand(key, channels, {
  align: align3 = 0.5,
  padding: padding2 = 0.1,
  paddingInner = padding2,
  paddingOuter = key === "fx" || key === "fy" ? 0 : padding2,
  ...options
}) {
  return maybeRound(
    band().align(align3).paddingInner(paddingInner).paddingOuter(paddingOuter),
    channels,
    options,
    key
  );
}
function maybeRound(scale3, channels, options, key) {
  let { round: round3 } = options;
  if (round3 !== void 0) scale3.round(round3 = !!round3);
  scale3 = createScaleO(key, scale3, channels, options);
  scale3.round = round3;
  return scale3;
}
function inferDomain2(channels, interval4, key) {
  const values2 = new InternSet();
  for (const { value, domain } of channels) {
    if (domain !== void 0) return domain();
    if (value === void 0) continue;
    for (const v2 of value) values2.add(v2);
  }
  if (interval4 !== void 0) {
    const [min5, max4] = extent(values2).map(interval4.floor, interval4);
    return interval4.range(min5, interval4.offset(max4));
  }
  if (values2.size > 1e4 && registry.get(key) === position) {
    throw new Error(`implicit ordinal domain of ${key} scale has more than 10,000 values`);
  }
  return sort(values2, ascendingDefined2);
}
function inferHint(channels, key) {
  let value;
  for (const { hint } of channels) {
    const candidate = hint?.[key];
    if (candidate === void 0) continue;
    if (value === void 0) value = candidate;
    else if (value !== candidate) return;
  }
  return value;
}
function inferSymbolHint(channels) {
  return {
    fill: inferHint(channels, "fill"),
    stroke: inferHint(channels, "stroke")
  };
}
function inferSymbolRange(hint) {
  return isNoneish(hint.fill) ? symbolsStroke : symbolsFill;
}

// ../../../node_modules/@observablehq/plot/src/scales.js
function createScales(channelsByScale, {
  label: globalLabel,
  inset: globalInset = 0,
  insetTop: globalInsetTop = globalInset,
  insetRight: globalInsetRight = globalInset,
  insetBottom: globalInsetBottom = globalInset,
  insetLeft: globalInsetLeft = globalInset,
  round: round3,
  nice: nice3,
  clamp,
  zero: zero3,
  align: align3,
  padding: padding2,
  projection: projection3,
  facet: { label: facetLabel2 = globalLabel } = {},
  ...options
} = {}) {
  const scales2 = {};
  for (const [key, channels] of channelsByScale) {
    const scaleOptions = options[key];
    const scale3 = createScale(key, channels, {
      round: registry.get(key) === position ? round3 : void 0,
      // only for position
      nice: nice3,
      clamp,
      zero: zero3,
      align: align3,
      padding: padding2,
      projection: projection3,
      ...scaleOptions
    });
    if (scale3) {
      let {
        label = key === "fx" || key === "fy" ? facetLabel2 : globalLabel,
        percent,
        transform: transform3,
        inset: inset2,
        insetTop = inset2 !== void 0 ? inset2 : key === "y" ? globalInsetTop : 0,
        // not fy
        insetRight = inset2 !== void 0 ? inset2 : key === "x" ? globalInsetRight : 0,
        // not fx
        insetBottom = inset2 !== void 0 ? inset2 : key === "y" ? globalInsetBottom : 0,
        // not fy
        insetLeft = inset2 !== void 0 ? inset2 : key === "x" ? globalInsetLeft : 0
        // not fx
      } = scaleOptions || {};
      if (transform3 == null) transform3 = void 0;
      else if (typeof transform3 !== "function") throw new Error("invalid scale transform; not a function");
      scale3.percent = !!percent;
      scale3.label = label === void 0 ? inferScaleLabel(channels, scale3) : label;
      scale3.transform = transform3;
      if (key === "x" || key === "fx") {
        scale3.insetLeft = +insetLeft;
        scale3.insetRight = +insetRight;
      } else if (key === "y" || key === "fy") {
        scale3.insetTop = +insetTop;
        scale3.insetBottom = +insetBottom;
      }
      scales2[key] = scale3;
    }
  }
  return scales2;
}
function createScaleFunctions(descriptors) {
  const scales2 = {};
  const scaleFunctions = { scales: scales2 };
  for (const [key, descriptor] of Object.entries(descriptors)) {
    const { scale: scale3, type: type2, interval: interval4, label } = descriptor;
    scales2[key] = exposeScale(descriptor);
    scaleFunctions[key] = scale3;
    scale3.type = type2;
    if (interval4 != null) scale3.interval = interval4;
    if (label != null) scale3.label = label;
  }
  return scaleFunctions;
}
function autoScaleRange(scales2, dimensions) {
  const { x: x3, y: y3, fx, fy } = scales2;
  const superdimensions = fx || fy ? outerDimensions(dimensions) : dimensions;
  if (fx) autoScaleRangeX(fx, superdimensions);
  if (fy) autoScaleRangeY(fy, superdimensions);
  const subdimensions = fx || fy ? innerDimensions(scales2, dimensions) : dimensions;
  if (x3) autoScaleRangeX(x3, subdimensions);
  if (y3) autoScaleRangeY(y3, subdimensions);
}
function inferScaleLabel(channels = [], scale3) {
  let label;
  for (const { label: l } of channels) {
    if (l === void 0) continue;
    if (label === void 0) label = l;
    else if (label !== l) return;
  }
  if (label === void 0) return;
  if (!isOrdinalScale(scale3) && scale3.percent) label = `${label} (%)`;
  return { inferred: true, toString: () => label };
}
function inferScaleOrder(scale3) {
  return Math.sign(orderof(scale3.domain())) * Math.sign(orderof(scale3.range()));
}
function outerDimensions(dimensions) {
  const {
    marginTop: marginTop2,
    marginRight: marginRight2,
    marginBottom: marginBottom2,
    marginLeft: marginLeft2,
    width: width2,
    height: height2,
    facet: {
      marginTop: facetMarginTop2,
      marginRight: facetMarginRight2,
      marginBottom: facetMarginBottom2,
      marginLeft: facetMarginLeft2
    }
  } = dimensions;
  return {
    marginTop: Math.max(marginTop2, facetMarginTop2),
    marginRight: Math.max(marginRight2, facetMarginRight2),
    marginBottom: Math.max(marginBottom2, facetMarginBottom2),
    marginLeft: Math.max(marginLeft2, facetMarginLeft2),
    width: width2,
    height: height2
  };
}
function innerDimensions({ fx, fy }, dimensions) {
  const { marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2, width: width2, height: height2 } = outerDimensions(dimensions);
  return {
    marginTop: marginTop2,
    marginRight: marginRight2,
    marginBottom: marginBottom2,
    marginLeft: marginLeft2,
    width: fx ? fx.scale.bandwidth() + marginLeft2 + marginRight2 : width2,
    height: fy ? fy.scale.bandwidth() + marginTop2 + marginBottom2 : height2,
    facet: { width: width2, height: height2 }
  };
}
function autoScaleRangeX(scale3, dimensions) {
  if (scale3.range === void 0) {
    const { insetLeft, insetRight } = scale3;
    const { width: width2, marginLeft: marginLeft2 = 0, marginRight: marginRight2 = 0 } = dimensions;
    const left2 = marginLeft2 + insetLeft;
    const right2 = width2 - marginRight2 - insetRight;
    scale3.range = [left2, Math.max(left2, right2)];
    if (!isOrdinalScale(scale3)) scale3.range = piecewiseRange(scale3);
    scale3.scale.range(scale3.range);
  }
  autoScaleRound(scale3);
}
function autoScaleRangeY(scale3, dimensions) {
  if (scale3.range === void 0) {
    const { insetTop, insetBottom } = scale3;
    const { height: height2, marginTop: marginTop2 = 0, marginBottom: marginBottom2 = 0 } = dimensions;
    const top2 = marginTop2 + insetTop;
    const bottom2 = height2 - marginBottom2 - insetBottom;
    scale3.range = [Math.max(top2, bottom2), top2];
    if (!isOrdinalScale(scale3)) scale3.range = piecewiseRange(scale3);
    else scale3.range.reverse();
    scale3.scale.range(scale3.range);
  }
  autoScaleRound(scale3);
}
function autoScaleRound(scale3) {
  if (scale3.round === void 0 && isBandScale(scale3) && roundError(scale3) <= 30) {
    scale3.scale.round(true);
  }
}
function roundError({ scale: scale3 }) {
  const n = scale3.domain().length;
  const [start2, stop] = scale3.range();
  const paddingInner = scale3.paddingInner ? scale3.paddingInner() : 1;
  const paddingOuter = scale3.paddingOuter ? scale3.paddingOuter() : scale3.padding();
  const m = n - paddingInner;
  const step = Math.abs(stop - start2) / Math.max(1, m + paddingOuter * 2);
  return (step - Math.floor(step)) * m;
}
function piecewiseRange(scale3) {
  const length4 = scale3.scale.domain().length + isThresholdScale(scale3);
  if (!(length4 > 2)) return scale3.range;
  const [start2, end] = scale3.range;
  return Array.from({ length: length4 }, (_, i) => start2 + i / (length4 - 1) * (end - start2));
}
function normalizeScale(key, scale3, hint) {
  return createScale(key, hint === void 0 ? void 0 : [{ hint }], { ...scale3 });
}
function createScale(key, channels = [], options = {}) {
  const type2 = inferScaleType(key, channels, options);
  if (options.type === void 0 && options.domain === void 0 && options.range === void 0 && options.interval == null && key !== "fx" && key !== "fy" && isOrdinalScale({ type: type2 })) {
    const values2 = channels.map(({ value }) => value).filter((value) => value !== void 0);
    if (values2.some(isTemporal))
      warn(
        `Warning: some data associated with the ${key} scale are dates. Dates are typically associated with a "utc" or "time" scale rather than a "${formatScaleType(
          type2
        )}" scale. If you are using a bar mark, you probably want a rect mark with the interval option instead; if you are using a group transform, you probably want a bin transform instead. If you want to treat this data as ordinal, you can specify the interval of the ${key} scale (e.g., d3.utcDay), or you can suppress this warning by setting the type of the ${key} scale to "${formatScaleType(
          type2
        )}".`
      );
    else if (values2.some(isTemporalString))
      warn(
        `Warning: some data associated with the ${key} scale are strings that appear to be dates (e.g., YYYY-MM-DD). If these strings represent dates, you should parse them to Date objects. Dates are typically associated with a "utc" or "time" scale rather than a "${formatScaleType(
          type2
        )}" scale. If you are using a bar mark, you probably want a rect mark with the interval option instead; if you are using a group transform, you probably want a bin transform instead. If you want to treat this data as ordinal, you can suppress this warning by setting the type of the ${key} scale to "${formatScaleType(
          type2
        )}".`
      );
    else if (values2.some(isNumericString))
      warn(
        `Warning: some data associated with the ${key} scale are strings that appear to be numbers. If these strings represent numbers, you should parse or coerce them to numbers. Numbers are typically associated with a "linear" scale rather than a "${formatScaleType(
          type2
        )}" scale. If you want to treat this data as ordinal, you can specify the interval of the ${key} scale (e.g., 1 for integers), or you can suppress this warning by setting the type of the ${key} scale to "${formatScaleType(
          type2
        )}".`
      );
  }
  options.type = type2;
  switch (type2) {
    case "diverging":
    case "diverging-sqrt":
    case "diverging-pow":
    case "diverging-log":
    case "diverging-symlog":
    case "cyclical":
    case "sequential":
    case "linear":
    case "sqrt":
    case "threshold":
    case "quantile":
    case "pow":
    case "log":
    case "symlog":
      options = coerceType(channels, options, coerceNumbers);
      break;
    case "identity":
      switch (registry.get(key)) {
        case position:
          options = coerceType(channels, options, coerceNumbers);
          break;
        case symbol:
          options = coerceType(channels, options, coerceSymbols);
          break;
      }
      break;
    case "utc":
    case "time":
      options = coerceType(channels, options, coerceDates);
      break;
  }
  switch (type2) {
    case "diverging":
      return createScaleDiverging(key, channels, options);
    case "diverging-sqrt":
      return createScaleDivergingSqrt(key, channels, options);
    case "diverging-pow":
      return createScaleDivergingPow(key, channels, options);
    case "diverging-log":
      return createScaleDivergingLog(key, channels, options);
    case "diverging-symlog":
      return createScaleDivergingSymlog(key, channels, options);
    case "categorical":
    case "ordinal":
    case ordinalImplicit:
      return createScaleOrdinal(key, channels, options);
    case "cyclical":
    case "sequential":
    case "linear":
      return createScaleLinear(key, channels, options);
    case "sqrt":
      return createScaleSqrt(key, channels, options);
    case "threshold":
      return createScaleThreshold(key, channels, options);
    case "quantile":
      return createScaleQuantile(key, channels, options);
    case "quantize":
      return createScaleQuantize(key, channels, options);
    case "pow":
      return createScalePow(key, channels, options);
    case "log":
      return createScaleLog(key, channels, options);
    case "symlog":
      return createScaleSymlog(key, channels, options);
    case "utc":
      return createScaleUtc(key, channels, options);
    case "time":
      return createScaleTime(key, channels, options);
    case "point":
      return createScalePoint(key, channels, options);
    case "band":
      return createScaleBand(key, channels, options);
    case "identity":
      return createScaleIdentity(key);
    case void 0:
      return;
    default:
      throw new Error(`unknown scale type: ${type2}`);
  }
}
function formatScaleType(type2) {
  return typeof type2 === "symbol" ? type2.description : type2;
}
function maybeScaleType(type2) {
  return typeof type2 === "string" ? `${type2}`.toLowerCase() : type2;
}
var typeProjection = { toString: () => "projection" };
function inferScaleType(key, channels, { type: type2, domain, range: range3, scheme: scheme28, pivot, projection: projection3 }) {
  type2 = maybeScaleType(type2);
  if (key === "fx" || key === "fy") return "band";
  if ((key === "x" || key === "y") && projection3 != null) type2 = typeProjection;
  for (const channel of channels) {
    const t = maybeScaleType(channel.type);
    if (t === void 0) continue;
    else if (type2 === void 0) type2 = t;
    else if (type2 !== t) throw new Error(`scale incompatible with channel: ${type2} !== ${t}`);
  }
  if (type2 === typeProjection) return;
  if (type2 !== void 0) return type2;
  if (domain === void 0 && !channels.some(({ value }) => value !== void 0)) return;
  const kind = registry.get(key);
  if (kind === radius) return "sqrt";
  if (kind === opacity || kind === length3) return "linear";
  if (kind === symbol) return "ordinal";
  const n = (domain ?? range3)?.length;
  if (n < 2 || n > 2) return asOrdinalType(kind);
  if (domain !== void 0) {
    if (isOrdinal(domain)) return asOrdinalType(kind);
    if (isTemporal(domain)) return "utc";
  } else {
    const values2 = channels.map(({ value }) => value).filter((value) => value !== void 0);
    if (values2.some(isOrdinal)) return asOrdinalType(kind);
    if (values2.some(isTemporal)) return "utc";
  }
  if (kind === color2) {
    if (pivot != null || isDivergingScheme(scheme28)) return "diverging";
    if (isCategoricalScheme(scheme28)) return "categorical";
  }
  return "linear";
}
function asOrdinalType(kind) {
  switch (kind) {
    case position:
      return "point";
    case color2:
      return ordinalImplicit;
    default:
      return "ordinal";
  }
}
function isOrdinalScale({ type: type2 }) {
  return type2 === "ordinal" || type2 === "point" || type2 === "band" || type2 === ordinalImplicit;
}
function isThresholdScale({ type: type2 }) {
  return type2 === "threshold";
}
function isBandScale({ type: type2 }) {
  return type2 === "point" || type2 === "band";
}
function isCollapsed(scale3) {
  if (scale3 === void 0) return true;
  const domain = scale3.domain();
  const value = scale3(domain[0]);
  for (let i = 1, n = domain.length; i < n; ++i) {
    if (scale3(domain[i]) - value) {
      return false;
    }
  }
  return true;
}
function coerceType(channels, { domain, ...options }, coerceValues) {
  for (const c4 of channels) {
    if (c4.value !== void 0) {
      if (domain === void 0) domain = c4.value?.domain;
      c4.value = coerceValues(c4.value);
    }
  }
  return {
    domain: domain === void 0 ? domain : coerceValues(domain),
    ...options
  };
}
function coerceSymbols(values2) {
  return map3(values2, maybeSymbol);
}
function scale2(options = {}) {
  let scale3;
  for (const key in options) {
    if (!registry.has(key)) continue;
    if (!isScaleOptions(options[key])) continue;
    if (scale3 !== void 0) throw new Error("ambiguous scale definition; multiple scales found");
    scale3 = exposeScale(normalizeScale(key, options[key]));
  }
  if (scale3 === void 0) throw new Error("invalid scale definition; no scale found");
  return scale3;
}
function exposeScales(scales2) {
  return (key) => {
    if (!registry.has(key = `${key}`)) throw new Error(`unknown scale: ${key}`);
    return scales2[key];
  };
}
function exposeScale({ scale: scale3, type: type2, domain, range: range3, interpolate, interval: interval4, transform: transform3, percent, pivot }) {
  if (type2 === "identity") return { type: "identity", apply: (d) => d, invert: (d) => d };
  const unknown = scale3.unknown ? scale3.unknown() : void 0;
  return {
    type: type2,
    domain: slice3(domain),
    // defensive copy
    ...range3 !== void 0 && { range: slice3(range3) },
    // defensive copy
    ...transform3 !== void 0 && { transform: transform3 },
    ...percent && { percent },
    // only exposed if truthy
    ...unknown !== void 0 && { unknown },
    ...interval4 !== void 0 && { interval: interval4 },
    // quantitative
    ...interpolate !== void 0 && { interpolate },
    ...scale3.clamp && { clamp: scale3.clamp() },
    // diverging (always asymmetric; we never want to apply the symmetric transform twice)
    ...pivot !== void 0 && { pivot, symmetric: false },
    // log, diverging-log
    ...scale3.base && { base: scale3.base() },
    // pow, diverging-pow
    ...scale3.exponent && { exponent: scale3.exponent() },
    // symlog, diverging-symlog
    ...scale3.constant && { constant: scale3.constant() },
    // band, point
    ...scale3.align && { align: scale3.align(), round: scale3.round() },
    ...scale3.padding && (scale3.paddingInner ? { paddingInner: scale3.paddingInner(), paddingOuter: scale3.paddingOuter() } : { padding: scale3.padding() }),
    ...scale3.bandwidth && { bandwidth: scale3.bandwidth(), step: scale3.step() },
    // utilities
    apply: (t) => scale3(t),
    ...scale3.invert && { invert: (t) => scale3.invert(t) }
  };
}

// ../../../node_modules/@observablehq/plot/src/facet.js
function createFacets(channelsByScale, options) {
  const { fx, fy } = createScales(channelsByScale, options);
  const fxDomain2 = fx?.scale.domain();
  const fyDomain2 = fy?.scale.domain();
  return fxDomain2 && fyDomain2 ? cross(fxDomain2, fyDomain2).map(([x3, y3], i) => ({ x: x3, y: y3, i })) : fxDomain2 ? fxDomain2.map((x3, i) => ({ x: x3, i })) : fyDomain2 ? fyDomain2.map((y3, i) => ({ y: y3, i })) : void 0;
}
function recreateFacets(facets, { x: X3, y: Y3 }) {
  X3 &&= facetIndex(X3);
  Y3 &&= facetIndex(Y3);
  return facets.filter(
    X3 && Y3 ? (f) => X3.has(f.x) && Y3.has(f.y) : X3 ? (f) => X3.has(f.x) : (f) => Y3.has(f.y)
  ).sort(
    X3 && Y3 ? (a2, b) => X3.get(a2.x) - X3.get(b.x) || Y3.get(a2.y) - Y3.get(b.y) : X3 ? (a2, b) => X3.get(a2.x) - X3.get(b.x) : (a2, b) => Y3.get(a2.y) - Y3.get(b.y)
  );
}
function facetGroups(data, { fx, fy }) {
  const I = range2(data);
  const FX = fx?.value;
  const FY = fy?.value;
  return fx && fy ? rollup(
    I,
    (G) => (G.fx = FX[G[0]], G.fy = FY[G[0]], G),
    (i) => FX[i],
    (i) => FY[i]
  ) : fx ? rollup(
    I,
    (G) => (G.fx = FX[G[0]], G),
    (i) => FX[i]
  ) : rollup(
    I,
    (G) => (G.fy = FY[G[0]], G),
    (i) => FY[i]
  );
}
function facetTranslator(fx, fy, { marginTop: marginTop2, marginLeft: marginLeft2 }) {
  const x3 = fx ? ({ x: x4 }) => fx(x4) - marginLeft2 : () => 0;
  const y3 = fy ? ({ y: y4 }) => fy(y4) - marginTop2 : () => 0;
  return function(d) {
    if (this.tagName === "svg") {
      this.setAttribute("x", x3(d));
      this.setAttribute("y", y3(d));
    } else {
      this.setAttribute("transform", `translate(${x3(d)},${y3(d)})`);
    }
  };
}
function facetExclude(index2) {
  const ex = [];
  const e = new Uint32Array(sum2(index2, (d) => d.length));
  for (const i of index2) {
    let n = 0;
    for (const j of index2) {
      if (i === j) continue;
      e.set(j, n);
      n += j.length;
    }
    ex.push(e.slice(0, n));
  }
  return ex;
}
var facetAnchors = /* @__PURE__ */ new Map([
  ["top", facetAnchorTop],
  ["right", facetAnchorRight],
  ["bottom", facetAnchorBottom],
  ["left", facetAnchorLeft],
  ["top-left", and2(facetAnchorTop, facetAnchorLeft)],
  ["top-right", and2(facetAnchorTop, facetAnchorRight)],
  ["bottom-left", and2(facetAnchorBottom, facetAnchorLeft)],
  ["bottom-right", and2(facetAnchorBottom, facetAnchorRight)],
  ["top-empty", facetAnchorTopEmpty],
  ["right-empty", facetAnchorRightEmpty],
  ["bottom-empty", facetAnchorBottomEmpty],
  ["left-empty", facetAnchorLeftEmpty],
  ["empty", facetAnchorEmpty]
]);
function maybeFacetAnchor(facetAnchor) {
  if (facetAnchor == null) return null;
  const anchor = facetAnchors.get(`${facetAnchor}`.toLowerCase());
  if (anchor) return anchor;
  throw new Error(`invalid facet anchor: ${facetAnchor}`);
}
var indexCache = /* @__PURE__ */ new WeakMap();
function facetIndex(V) {
  let I = indexCache.get(V);
  if (!I) indexCache.set(V, I = new InternMap(map3(V, (v2, i) => [v2, i])));
  return I;
}
function facetIndexOf(V, v2) {
  return facetIndex(V).get(v2);
}
function facetFind(facets, x3, y3) {
  x3 = keyof2(x3);
  y3 = keyof2(y3);
  return facets.find((f) => Object.is(keyof2(f.x), x3) && Object.is(keyof2(f.y), y3));
}
function facetEmpty(facets, x3, y3) {
  return facetFind(facets, x3, y3)?.empty;
}
function facetAnchorTop(facets, { y: Y3 }, { y: y3 }) {
  return Y3 ? facetIndexOf(Y3, y3) === 0 : true;
}
function facetAnchorBottom(facets, { y: Y3 }, { y: y3 }) {
  return Y3 ? facetIndexOf(Y3, y3) === Y3.length - 1 : true;
}
function facetAnchorLeft(facets, { x: X3 }, { x: x3 }) {
  return X3 ? facetIndexOf(X3, x3) === 0 : true;
}
function facetAnchorRight(facets, { x: X3 }, { x: x3 }) {
  return X3 ? facetIndexOf(X3, x3) === X3.length - 1 : true;
}
function facetAnchorTopEmpty(facets, { y: Y3 }, { x: x3, y: y3, empty: empty4 }) {
  if (empty4) return false;
  if (!Y3) return;
  const i = facetIndexOf(Y3, y3);
  if (i > 0) return facetEmpty(facets, x3, Y3[i - 1]);
}
function facetAnchorBottomEmpty(facets, { y: Y3 }, { x: x3, y: y3, empty: empty4 }) {
  if (empty4) return false;
  if (!Y3) return;
  const i = facetIndexOf(Y3, y3);
  if (i < Y3.length - 1) return facetEmpty(facets, x3, Y3[i + 1]);
}
function facetAnchorLeftEmpty(facets, { x: X3 }, { x: x3, y: y3, empty: empty4 }) {
  if (empty4) return false;
  if (!X3) return;
  const i = facetIndexOf(X3, x3);
  if (i > 0) return facetEmpty(facets, X3[i - 1], y3);
}
function facetAnchorRightEmpty(facets, { x: X3 }, { x: x3, y: y3, empty: empty4 }) {
  if (empty4) return false;
  if (!X3) return;
  const i = facetIndexOf(X3, x3);
  if (i < X3.length - 1) return facetEmpty(facets, X3[i + 1], y3);
}
function facetAnchorEmpty(facets, channels, { empty: empty4 }) {
  return empty4;
}
function and2(a2, b) {
  return function() {
    return a2.apply(null, arguments) && b.apply(null, arguments);
  };
}
function facetFilter(facets, { channels: { fx, fy }, groups: groups2 }) {
  return fx && fy ? facets.map(({ x: x3, y: y3 }) => groups2.get(x3)?.get(y3) ?? []) : fx ? facets.map(({ x: x3 }) => groups2.get(x3) ?? []) : facets.map(({ y: y3 }) => groups2.get(y3) ?? []);
}

// ../../../node_modules/@observablehq/plot/src/projection.js
var pi4 = Math.PI;
var tau5 = 2 * pi4;
var defaultAspectRatio = 0.618;
function createProjection({
  projection: projection3,
  inset: globalInset = 0,
  insetTop = globalInset,
  insetRight = globalInset,
  insetBottom = globalInset,
  insetLeft = globalInset
} = {}, dimensions) {
  if (projection3 == null) return;
  if (typeof projection3.stream === "function") return projection3;
  let options;
  let domain;
  let clip2 = "frame";
  if (isObject(projection3)) {
    let inset2;
    ({
      type: projection3,
      domain,
      inset: inset2,
      insetTop = inset2 !== void 0 ? inset2 : insetTop,
      insetRight = inset2 !== void 0 ? inset2 : insetRight,
      insetBottom = inset2 !== void 0 ? inset2 : insetBottom,
      insetLeft = inset2 !== void 0 ? inset2 : insetLeft,
      clip: clip2 = clip2,
      ...options
    } = projection3);
    if (projection3 == null) return;
  }
  if (typeof projection3 !== "function") ({ type: projection3 } = namedProjection(projection3));
  const { width: width2, height: height2, marginLeft: marginLeft2, marginRight: marginRight2, marginTop: marginTop2, marginBottom: marginBottom2 } = dimensions;
  const dx = width2 - marginLeft2 - marginRight2 - insetLeft - insetRight;
  const dy = height2 - marginTop2 - marginBottom2 - insetTop - insetBottom;
  projection3 = projection3?.({ width: dx, height: dy, clip: clip2, ...options });
  if (projection3 == null) return;
  clip2 = maybePostClip(clip2, marginLeft2, marginTop2, width2 - marginRight2, height2 - marginBottom2);
  let tx = marginLeft2 + insetLeft;
  let ty = marginTop2 + insetTop;
  let transform3;
  if (domain != null) {
    const [[x06, y06], [x12, y12]] = path_default(projection3).bounds(domain);
    const k2 = Math.min(dx / (x12 - x06), dy / (y12 - y06));
    if (k2 > 0) {
      tx -= (k2 * (x06 + x12) - dx) / 2;
      ty -= (k2 * (y06 + y12) - dy) / 2;
      transform3 = transform_default({
        point(x3, y3) {
          this.stream.point(x3 * k2 + tx, y3 * k2 + ty);
        }
      });
    } else {
      warn(`Warning: the projection could not be fit to the specified domain; using the default scale.`);
    }
  }
  transform3 ??= tx === 0 && ty === 0 ? identity9() : transform_default({
    point(x3, y3) {
      this.stream.point(x3 + tx, y3 + ty);
    }
  });
  return { stream: (s2) => projection3.stream(transform3.stream(clip2(s2))) };
}
function namedProjection(projection3) {
  switch (`${projection3}`.toLowerCase()) {
    case "albers-usa":
      return scaleProjection(albersUsa_default, 0.7463, 0.4673);
    case "albers":
      return conicProjection2(albers_default, 0.7463, 0.4673);
    case "azimuthal-equal-area":
      return scaleProjection(azimuthalEqualArea_default, 4, 4);
    case "azimuthal-equidistant":
      return scaleProjection(azimuthalEquidistant_default, tau5, tau5);
    case "conic-conformal":
      return conicProjection2(conicConformal_default, tau5, tau5);
    case "conic-equal-area":
      return conicProjection2(conicEqualArea_default, 6.1702, 2.9781);
    case "conic-equidistant":
      return conicProjection2(conicEquidistant_default, 7.312, 3.6282);
    case "equal-earth":
      return scaleProjection(equalEarth_default, 5.4133, 2.6347);
    case "equirectangular":
      return scaleProjection(equirectangular_default, tau5, pi4);
    case "gnomonic":
      return scaleProjection(gnomonic_default, 3.4641, 3.4641);
    case "identity":
      return { type: identity9 };
    case "reflect-y":
      return { type: reflectY };
    case "mercator":
      return scaleProjection(mercator_default, tau5, tau5);
    case "orthographic":
      return scaleProjection(orthographic_default, 2, 2);
    case "stereographic":
      return scaleProjection(stereographic_default, 2, 2);
    case "transverse-mercator":
      return scaleProjection(transverseMercator_default, tau5, tau5);
    default:
      throw new Error(`unknown projection type: ${projection3}`);
  }
}
function maybePostClip(clip2, x12, y12, x22, y22) {
  if (clip2 === false || clip2 == null || typeof clip2 === "number") return (s2) => s2;
  if (clip2 === true) clip2 = "frame";
  switch (`${clip2}`.toLowerCase()) {
    case "frame":
      return clipRectangle(x12, y12, x22, y22);
    default:
      throw new Error(`unknown projection clip type: ${clip2}`);
  }
}
function scaleProjection(createProjection2, kx2, ky2) {
  return {
    type: ({ width: width2, height: height2, rotate, precision = 0.15, clip: clip2 }) => {
      const projection3 = createProjection2();
      if (precision != null) projection3.precision?.(precision);
      if (rotate != null) projection3.rotate?.(rotate);
      if (typeof clip2 === "number") projection3.clipAngle?.(clip2);
      if (width2 != null) {
        projection3.scale(Math.min(width2 / kx2, height2 / ky2));
        projection3.translate([width2 / 2, height2 / 2]);
      }
      return projection3;
    },
    aspectRatio: ky2 / kx2
  };
}
function conicProjection2(createProjection2, kx2, ky2) {
  const { type: type2, aspectRatio: aspectRatio2 } = scaleProjection(createProjection2, kx2, ky2);
  return {
    type: (options) => {
      const { parallels, domain, width: width2, height: height2 } = options;
      const projection3 = type2(options);
      if (parallels != null) {
        projection3.parallels(parallels);
        if (domain === void 0 && width2 != null) {
          projection3.fitSize([width2, height2], { type: "Sphere" });
        }
      }
      return projection3;
    },
    aspectRatio: aspectRatio2
  };
}
var identity9 = constant({ stream: (stream) => stream });
var reflectY = constant(
  transform_default({
    point(x3, y3) {
      this.stream.point(x3, -y3);
    }
  })
);
function project(cx, cy, values2, projection3) {
  const x3 = values2[cx];
  const y3 = values2[cy];
  const n = x3.length;
  const X3 = values2[cx] = new Float64Array(n).fill(NaN);
  const Y3 = values2[cy] = new Float64Array(n).fill(NaN);
  let i;
  const stream = projection3.stream({
    point(x4, y4) {
      X3[i] = x4;
      Y3[i] = y4;
    }
  });
  for (i = 0; i < n; ++i) {
    stream.point(x3[i], y3[i]);
  }
}
function hasProjection({ projection: projection3 } = {}) {
  if (projection3 == null) return false;
  if (typeof projection3.stream === "function") return true;
  if (isObject(projection3)) projection3 = projection3.type;
  return projection3 != null;
}
function projectionAspectRatio(projection3) {
  if (typeof projection3?.stream === "function") return defaultAspectRatio;
  if (isObject(projection3)) {
    let domain, options;
    ({ domain, type: projection3, ...options } = projection3);
    if (domain != null && projection3 != null) {
      const type2 = typeof projection3 === "string" ? namedProjection(projection3).type : projection3;
      const [[x06, y06], [x12, y12]] = path_default(type2({ ...options, width: 100, height: 100 })).bounds(domain);
      const r = (y12 - y06) / (x12 - x06);
      return r && isFinite(r) ? r < 0.2 ? 0.2 : r > 5 ? 5 : r : defaultAspectRatio;
    }
  }
  if (projection3 == null) return;
  if (typeof projection3 !== "function") {
    const { aspectRatio: aspectRatio2 } = namedProjection(projection3);
    if (aspectRatio2) return aspectRatio2;
  }
  return defaultAspectRatio;
}
function applyPosition(channels, scales2, { projection: projection3 }) {
  const { x: x3, y: y3 } = channels;
  let position3 = {};
  if (x3) position3.x = x3;
  if (y3) position3.y = y3;
  position3 = valueObject(position3, scales2);
  if (projection3 && x3?.scale === "x" && y3?.scale === "y") project("x", "y", position3, projection3);
  if (x3) position3.x = coerceNumbers(position3.x);
  if (y3) position3.y = coerceNumbers(position3.y);
  return position3;
}
function getGeometryChannels(channel) {
  const X3 = [];
  const Y3 = [];
  const x3 = { scale: "x", value: X3 };
  const y3 = { scale: "y", value: Y3 };
  const sink = {
    point(x4, y4) {
      X3.push(x4);
      Y3.push(y4);
    },
    lineStart() {
    },
    lineEnd() {
    },
    polygonStart() {
    },
    polygonEnd() {
    },
    sphere() {
    }
  };
  for (const object of channel.value) stream_default(object, sink);
  return [x3, y3];
}
function xyProjection({ x: X3, y: Y3 }) {
  if (X3 || Y3) {
    X3 ??= (x3) => x3;
    Y3 ??= (y3) => y3;
    return transform_default({
      point(x3, y3) {
        this.stream.point(X3(x3), Y3(y3));
      }
    });
  }
}

// ../../../node_modules/@observablehq/plot/src/context.js
function createContext(options = {}) {
  const { document: document2 = typeof window !== "undefined" ? window.document : void 0, clip: clip2 } = options;
  return { document: document2, clip: maybeClip(clip2) };
}
function create3(name2, { document: document2 }) {
  return select_default2(creator_default(name2).call(document2.documentElement));
}

// ../../../node_modules/@observablehq/plot/src/memoize.js
var unset = Symbol("unset");
function memoize1(compute) {
  return (compute.length === 1 ? memoize1Arg : memoize1Args)(compute);
}
function memoize1Arg(compute) {
  let cacheValue;
  let cacheKey = unset;
  return (key) => {
    if (!Object.is(cacheKey, key)) {
      cacheKey = key;
      cacheValue = compute(key);
    }
    return cacheValue;
  };
}
function memoize1Args(compute) {
  let cacheValue, cacheKeys;
  return (...keys) => {
    if (cacheKeys?.length !== keys.length || cacheKeys.some((k2, i) => !Object.is(k2, keys[i]))) {
      cacheKeys = keys;
      cacheValue = compute(...keys);
    }
    return cacheValue;
  };
}

// ../../../node_modules/@observablehq/plot/src/format.js
var numberFormat = memoize1((locale3) => {
  return new Intl.NumberFormat(locale3);
});
var monthFormat = memoize1((locale3, month) => {
  return new Intl.DateTimeFormat(locale3, { timeZone: "UTC", ...month && { month } });
});
var weekdayFormat = memoize1((locale3, weekday) => {
  return new Intl.DateTimeFormat(locale3, { timeZone: "UTC", ...weekday && { weekday } });
});
function formatNumber(locale3 = "en-US") {
  const format3 = numberFormat(locale3);
  return (i) => i != null && !isNaN(i) ? format3.format(i) : void 0;
}
function formatMonth(locale3 = "en-US", format3 = "short") {
  const fmt = monthFormat(locale3, format3);
  return (i) => i != null && !isNaN(i = +new Date(Date.UTC(2e3, +i))) ? fmt.format(i) : void 0;
}
function formatWeekday(locale3 = "en-US", format3 = "short") {
  const fmt = weekdayFormat(locale3, format3);
  return (i) => i != null && !isNaN(i = +new Date(Date.UTC(2001, 0, +i))) ? fmt.format(i) : void 0;
}
function formatIsoDate(date3) {
  return format2(date3, "Invalid Date");
}
function formatAuto(locale3 = "en-US") {
  const number7 = formatNumber(locale3);
  return (v2) => (v2 instanceof Date ? formatIsoDate : typeof v2 === "number" ? number7 : string)(v2);
}
var formatDefault = formatAuto();

// ../../../node_modules/@observablehq/plot/src/style.js
var offset = (typeof window !== "undefined" ? window.devicePixelRatio > 1 : typeof it === "undefined") ? 0 : 0.5;
var nextClipId = 0;
var nextPatternId = 0;
function getClipId() {
  return `plot-clip-${++nextClipId}`;
}
function getPatternId() {
  return `plot-pattern-${++nextPatternId}`;
}
function styles(mark2, {
  title,
  href,
  ariaLabel: variaLabel,
  ariaDescription: ariaDescription2,
  ariaHidden,
  target,
  fill,
  fillOpacity,
  stroke,
  strokeWidth,
  strokeOpacity,
  strokeLinejoin,
  strokeLinecap,
  strokeMiterlimit,
  strokeDasharray,
  strokeDashoffset,
  opacity: opacity2,
  mixBlendMode,
  imageFilter,
  paintOrder,
  pointerEvents,
  shapeRendering,
  channels
}, {
  ariaLabel: cariaLabel,
  fill: defaultFill = "currentColor",
  fillOpacity: defaultFillOpacity,
  stroke: defaultStroke = "none",
  strokeOpacity: defaultStrokeOpacity,
  strokeWidth: defaultStrokeWidth,
  strokeLinecap: defaultStrokeLinecap,
  strokeLinejoin: defaultStrokeLinejoin,
  strokeMiterlimit: defaultStrokeMiterlimit,
  paintOrder: defaultPaintOrder
}) {
  if (defaultFill === null) {
    fill = null;
    fillOpacity = null;
  }
  if (defaultStroke === null) {
    stroke = null;
    strokeOpacity = null;
  }
  if (isNoneish(defaultFill)) {
    if (!isNoneish(defaultStroke) && (!isNoneish(fill) || channels?.fill)) defaultStroke = "none";
  } else {
    if (isNoneish(defaultStroke) && (!isNoneish(stroke) || channels?.stroke)) defaultFill = "none";
  }
  const [vfill, cfill] = maybeColorChannel(fill, defaultFill);
  const [vfillOpacity, cfillOpacity] = maybeNumberChannel(fillOpacity, defaultFillOpacity);
  const [vstroke, cstroke] = maybeColorChannel(stroke, defaultStroke);
  const [vstrokeOpacity, cstrokeOpacity] = maybeNumberChannel(strokeOpacity, defaultStrokeOpacity);
  const [vopacity, copacity] = maybeNumberChannel(opacity2);
  if (!isNone(cstroke)) {
    if (strokeWidth === void 0) strokeWidth = defaultStrokeWidth;
    if (strokeLinecap === void 0) strokeLinecap = defaultStrokeLinecap;
    if (strokeLinejoin === void 0) strokeLinejoin = defaultStrokeLinejoin;
    if (strokeMiterlimit === void 0 && !isRound(strokeLinejoin)) strokeMiterlimit = defaultStrokeMiterlimit;
    if (!isNone(cfill) && paintOrder === void 0) paintOrder = defaultPaintOrder;
  }
  const [vstrokeWidth, cstrokeWidth] = maybeNumberChannel(strokeWidth);
  if (defaultFill !== null) {
    mark2.fill = impliedString(cfill, "currentColor");
    mark2.fillOpacity = impliedNumber(cfillOpacity, 1);
  }
  if (defaultStroke !== null) {
    mark2.stroke = impliedString(cstroke, "none");
    mark2.strokeWidth = impliedNumber(cstrokeWidth, 1);
    mark2.strokeOpacity = impliedNumber(cstrokeOpacity, 1);
    mark2.strokeLinejoin = impliedString(strokeLinejoin, "miter");
    mark2.strokeLinecap = impliedString(strokeLinecap, "butt");
    mark2.strokeMiterlimit = impliedNumber(strokeMiterlimit, 4);
    mark2.strokeDasharray = impliedString(strokeDasharray, "none");
    mark2.strokeDashoffset = impliedString(strokeDashoffset, "0");
  }
  mark2.target = string(target);
  mark2.ariaLabel = string(cariaLabel);
  mark2.ariaDescription = string(ariaDescription2);
  mark2.ariaHidden = string(ariaHidden);
  mark2.opacity = impliedNumber(copacity, 1);
  mark2.mixBlendMode = impliedString(mixBlendMode, "normal");
  mark2.imageFilter = impliedString(imageFilter, "none");
  mark2.paintOrder = impliedString(paintOrder, "normal");
  mark2.pointerEvents = impliedString(pointerEvents, "auto");
  mark2.shapeRendering = impliedString(shapeRendering, "auto");
  return {
    title: { value: title, optional: true, filter: null },
    href: { value: href, optional: true, filter: null },
    ariaLabel: { value: variaLabel, optional: true, filter: null },
    fill: { value: vfill, scale: "auto", optional: true },
    fillOpacity: { value: vfillOpacity, scale: "auto", optional: true },
    stroke: { value: vstroke, scale: "auto", optional: true },
    strokeOpacity: { value: vstrokeOpacity, scale: "auto", optional: true },
    strokeWidth: { value: vstrokeWidth, optional: true },
    opacity: { value: vopacity, scale: "auto", optional: true }
  };
}
function applyTitle(selection2, L) {
  if (L)
    selection2.filter((i) => nonempty(L[i])).append("title").call(applyText, L);
}
function applyTitleGroup(selection2, L) {
  if (L)
    selection2.filter(([i]) => nonempty(L[i])).append("title").call(applyTextGroup, L);
}
function applyText(selection2, T) {
  if (T) selection2.text((i) => formatDefault(T[i]));
}
function applyTextGroup(selection2, T) {
  if (T) selection2.text(([i]) => formatDefault(T[i]));
}
function applyChannelStyles(selection2, { target, tip: tip2 }, {
  ariaLabel: AL,
  title: T,
  fill: F,
  fillOpacity: FO,
  stroke: S,
  strokeOpacity: SO,
  strokeWidth: SW,
  opacity: O,
  href: H
}) {
  if (AL) applyAttr(selection2, "aria-label", (i) => AL[i]);
  if (F) applyAttr(selection2, "fill", (i) => F[i]);
  if (FO) applyAttr(selection2, "fill-opacity", (i) => FO[i]);
  if (S) applyAttr(selection2, "stroke", (i) => S[i]);
  if (SO) applyAttr(selection2, "stroke-opacity", (i) => SO[i]);
  if (SW) applyAttr(selection2, "stroke-width", (i) => SW[i]);
  if (O) applyAttr(selection2, "opacity", (i) => O[i]);
  if (H) applyHref(selection2, (i) => H[i], target);
  if (!tip2) applyTitle(selection2, T);
}
function applyGroupedChannelStyles(selection2, { target, tip: tip2 }, {
  ariaLabel: AL,
  title: T,
  fill: F,
  fillOpacity: FO,
  stroke: S,
  strokeOpacity: SO,
  strokeWidth: SW,
  opacity: O,
  href: H
}) {
  if (AL) applyAttr(selection2, "aria-label", ([i]) => AL[i]);
  if (F) applyAttr(selection2, "fill", ([i]) => F[i]);
  if (FO) applyAttr(selection2, "fill-opacity", ([i]) => FO[i]);
  if (S) applyAttr(selection2, "stroke", ([i]) => S[i]);
  if (SO) applyAttr(selection2, "stroke-opacity", ([i]) => SO[i]);
  if (SW) applyAttr(selection2, "stroke-width", ([i]) => SW[i]);
  if (O) applyAttr(selection2, "opacity", ([i]) => O[i]);
  if (H) applyHref(selection2, ([i]) => H[i], target);
  if (!tip2) applyTitleGroup(selection2, T);
}
function groupAesthetics({
  ariaLabel: AL,
  title: T,
  fill: F,
  fillOpacity: FO,
  stroke: S,
  strokeOpacity: SO,
  strokeWidth: SW,
  opacity: O,
  href: H
}, { tip: tip2 }) {
  return [AL, tip2 ? void 0 : T, F, FO, S, SO, SW, O, H].filter((c4) => c4 !== void 0);
}
function groupZ2(I, Z, z) {
  const G = group(I, (i) => Z[i]);
  if (z === void 0 && G.size > 1 + I.length >> 1) {
    warn(
      `Warning: the implicit z channel has high cardinality. This may occur when the fill or stroke channel is associated with quantitative data rather than ordinal or categorical data. You can suppress this warning by setting the z option explicitly; if this data represents a single series, set z to null.`
    );
  }
  return G.values();
}
function* groupIndex(I, position3, mark2, channels) {
  const { z } = mark2;
  const { z: Z } = channels;
  const A5 = groupAesthetics(channels, mark2);
  const C3 = [...position3, ...A5];
  for (const G of Z ? groupZ2(I, Z, z) : [I]) {
    let Ag;
    let Gg;
    out: for (const i of G) {
      for (const c4 of C3) {
        if (!defined(c4[i])) {
          if (Gg) Gg.push(-1);
          continue out;
        }
      }
      if (Ag === void 0) {
        if (Gg) yield Gg;
        Ag = A5.map((c4) => keyof2(c4[i])), Gg = [i];
        continue;
      }
      Gg.push(i);
      for (let j = 0; j < A5.length; ++j) {
        const k2 = keyof2(A5[j][i]);
        if (k2 !== Ag[j]) {
          yield Gg;
          Ag = A5.map((c4) => keyof2(c4[i])), Gg = [i];
          continue out;
        }
      }
    }
    if (Gg) yield Gg;
  }
}
function applyClip(selection2, mark2, dimensions, context) {
  let clipUrl;
  const { clip: clip2 = context.clip } = mark2;
  if (clip2 === "frame") {
    selection2 = create3("svg:g", context).each(function() {
      this.appendChild(selection2.node());
      selection2.node = () => this;
    });
    clipUrl = getFrameClip(context, dimensions);
  } else if (clip2) {
    clipUrl = getGeoClip(clip2, context);
  }
  applyAttr(selection2, "aria-label", mark2.ariaLabel);
  applyAttr(selection2, "aria-description", mark2.ariaDescription);
  applyAttr(selection2, "aria-hidden", mark2.ariaHidden);
  applyAttr(selection2, "clip-path", clipUrl);
}
function memoizeClip(clip2) {
  const cache = /* @__PURE__ */ new WeakMap();
  return (context, dimensions) => {
    let url = cache.get(context);
    if (!url) {
      const id2 = getClipId();
      select_default2(context.ownerSVGElement).append("clipPath").attr("id", id2).call(clip2, context, dimensions);
      cache.set(context, url = `url(#${id2})`);
    }
    return url;
  };
}
var getFrameClip = memoizeClip((clipPath, context, dimensions) => {
  const { width: width2, height: height2, marginLeft: marginLeft2, marginRight: marginRight2, marginTop: marginTop2, marginBottom: marginBottom2 } = dimensions;
  clipPath.append("rect").attr("x", marginLeft2).attr("y", marginTop2).attr("width", width2 - marginRight2 - marginLeft2).attr("height", height2 - marginTop2 - marginBottom2);
});
var geoClipCache = /* @__PURE__ */ new WeakMap();
var sphere = { type: "Sphere" };
function getGeoClip(geo3, context) {
  let cache, url;
  if (!(cache = geoClipCache.get(context))) geoClipCache.set(context, cache = /* @__PURE__ */ new WeakMap());
  if (geo3.type === "Sphere") geo3 = sphere;
  if (!(url = cache.get(geo3))) {
    const id2 = getClipId();
    select_default2(context.ownerSVGElement).append("clipPath").attr("id", id2).append("path").attr("d", context.path()(geo3));
    cache.set(geo3, url = `url(#${id2})`);
  }
  return url;
}
function applyIndirectStyles(selection2, mark2, dimensions, context) {
  applyClip(selection2, mark2, dimensions, context);
  applyAttr(selection2, "class", mark2.className);
  applyAttr(selection2, "fill", mark2.fill);
  applyAttr(selection2, "fill-opacity", mark2.fillOpacity);
  applyAttr(selection2, "stroke", mark2.stroke);
  applyAttr(selection2, "stroke-width", mark2.strokeWidth);
  applyAttr(selection2, "stroke-opacity", mark2.strokeOpacity);
  applyAttr(selection2, "stroke-linejoin", mark2.strokeLinejoin);
  applyAttr(selection2, "stroke-linecap", mark2.strokeLinecap);
  applyAttr(selection2, "stroke-miterlimit", mark2.strokeMiterlimit);
  applyAttr(selection2, "stroke-dasharray", mark2.strokeDasharray);
  applyAttr(selection2, "stroke-dashoffset", mark2.strokeDashoffset);
  applyAttr(selection2, "shape-rendering", mark2.shapeRendering);
  applyAttr(selection2, "filter", mark2.imageFilter);
  applyAttr(selection2, "paint-order", mark2.paintOrder);
  const { pointerEvents = context.pointerSticky === false ? "none" : void 0 } = mark2;
  applyAttr(selection2, "pointer-events", pointerEvents);
}
function applyDirectStyles(selection2, mark2) {
  applyStyle(selection2, "mix-blend-mode", mark2.mixBlendMode);
  applyAttr(selection2, "opacity", mark2.opacity);
}
function applyHref(selection2, href, target) {
  selection2.each(function(i) {
    const h = href(i);
    if (h != null) {
      const a2 = this.ownerDocument.createElementNS(namespaces_default.svg, "a");
      a2.setAttribute("fill", "inherit");
      a2.setAttributeNS(namespaces_default.xlink, "href", h);
      if (target != null) a2.setAttribute("target", target);
      this.parentNode.insertBefore(a2, this).appendChild(this);
    }
  });
}
function applyAttr(selection2, name2, value) {
  if (value != null) selection2.attr(name2, value);
}
function applyStyle(selection2, name2, value) {
  if (value != null) selection2.style(name2, value);
}
function applyTransform(selection2, mark2, { x: x3, y: y3 }, tx = offset, ty = offset) {
  tx += mark2.dx;
  ty += mark2.dy;
  if (x3?.bandwidth) tx += x3.bandwidth() / 2;
  if (y3?.bandwidth) ty += y3.bandwidth() / 2;
  if (tx || ty) selection2.attr("transform", `translate(${tx},${ty})`);
}
function impliedString(value, impliedValue) {
  if ((value = string(value)) !== impliedValue) return value;
}
function impliedNumber(value, impliedValue) {
  if ((value = number5(value)) !== impliedValue) return value;
}
var validClassName = /^-?([_a-z]|[\240-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])([_a-z0-9-]|[\240-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*$/i;
function maybeClassName(name2) {
  if (name2 === void 0) return "plot-d6a7b5";
  name2 = `${name2}`;
  if (!validClassName.test(name2)) throw new Error(`invalid class name: ${name2}`);
  return name2;
}
function applyInlineStyles(selection2, style2) {
  if (typeof style2 === "string") {
    selection2.property("style", style2);
  } else if (style2 != null) {
    for (const element of selection2) {
      Object.assign(element.style, style2);
    }
  }
}
function applyFrameAnchor({ frameAnchor }, { width: width2, height: height2, marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2 }) {
  return [
    /left$/.test(frameAnchor) ? marginLeft2 : /right$/.test(frameAnchor) ? width2 - marginRight2 : (marginLeft2 + width2 - marginRight2) / 2,
    /^top/.test(frameAnchor) ? marginTop2 : /^bottom/.test(frameAnchor) ? height2 - marginBottom2 : (marginTop2 + height2 - marginBottom2) / 2
  ];
}

// ../../../node_modules/@observablehq/plot/src/mark.js
var Mark = class {
  constructor(data, channels = {}, options = {}, defaults22) {
    const {
      facet = "auto",
      facetAnchor,
      fx,
      fy,
      sort: sort3,
      dx = 0,
      dy = 0,
      margin: margin2 = 0,
      marginTop: marginTop2 = margin2,
      marginRight: marginRight2 = margin2,
      marginBottom: marginBottom2 = margin2,
      marginLeft: marginLeft2 = margin2,
      className,
      clip: clip2 = defaults22?.clip,
      channels: extraChannels,
      tip: tip2,
      render
    } = options;
    this.data = data;
    this.sort = isDomainSort(sort3) ? sort3 : null;
    this.initializer = initializer(options).initializer;
    this.transform = this.initializer ? options.transform : basic(options).transform;
    if (facet === null || facet === false) {
      this.facet = null;
    } else {
      this.facet = keyword(facet === true ? "include" : facet, "facet", ["auto", "include", "exclude", "super"]);
      this.fx = data === singleton && typeof fx === "string" ? [fx] : fx;
      this.fy = data === singleton && typeof fy === "string" ? [fy] : fy;
    }
    this.facetAnchor = maybeFacetAnchor(facetAnchor);
    channels = maybeNamed(channels);
    if (extraChannels !== void 0) channels = { ...maybeChannels(extraChannels), ...channels };
    if (defaults22 !== void 0) channels = { ...styles(this, options, defaults22), ...channels };
    this.channels = Object.fromEntries(
      Object.entries(channels).map(([name2, channel]) => {
        if (isOptions(channel.value)) {
          const { value, label = channel.label, scale: scale3 = channel.scale } = channel.value;
          channel = { ...channel, label, scale: scale3, value };
        }
        if (data === singleton && typeof channel.value === "string") {
          const { value } = channel;
          channel = { ...channel, value: [value] };
        }
        return [name2, channel];
      }).filter(([name2, { value, optional: optional2 }]) => {
        if (value != null) return true;
        if (optional2) return false;
        throw new Error(`missing channel value: ${name2}`);
      })
    );
    this.dx = +dx;
    this.dy = +dy;
    this.marginTop = +marginTop2;
    this.marginRight = +marginRight2;
    this.marginBottom = +marginBottom2;
    this.marginLeft = +marginLeft2;
    this.clip = maybeClip(clip2);
    this.tip = maybeTip(tip2);
    this.className = string(className);
    if (this.facet === "super") {
      if (fx || fy) throw new Error(`super-faceting cannot use fx or fy`);
      for (const name2 in this.channels) {
        const { scale: scale3 } = channels[name2];
        if (scale3 !== "x" && scale3 !== "y") continue;
        throw new Error(`super-faceting cannot use x or y`);
      }
    }
    if (render != null) {
      this.render = composeRender(render, this.render);
    }
  }
  initialize(facets, facetChannels, plotOptions) {
    let data = dataify(this.data);
    if (facets === void 0 && data != null) facets = [range2(data)];
    const originalFacets = facets;
    if (this.transform != null) ({ facets, data } = this.transform(data, facets, plotOptions)), data = dataify(data);
    if (facets !== void 0) facets.original = originalFacets;
    const channels = createChannels(this.channels, data);
    if (this.sort != null) channelDomain(data, facets, channels, facetChannels, this.sort);
    return { data, facets, channels };
  }
  filter(index2, channels, values2) {
    for (const name2 in channels) {
      const { filter: filter3 = defined } = channels[name2];
      if (filter3 !== null) {
        const value = values2[name2];
        index2 = index2.filter((i) => filter3(value[i]));
      }
    }
    return index2;
  }
  // If there is a projection, and there are paired x and y channels associated
  // with the x and y scale respectively (and not already in screen coordinates
  // as with an initializer), then apply the projection, replacing the x and y
  // values. Note that the x and y scales themselves don’t exist if there is a
  // projection, but whether the channels are associated with scales still
  // determines whether the projection should apply; think of the projection as
  // a combination xy-scale.
  project(channels, values2, context) {
    for (const cx in channels) {
      if (channels[cx].scale === "x" && /^x|x$/.test(cx)) {
        const cy = cx.replace(/^x|x$/, "y");
        if (cy in channels && channels[cy].scale === "y") {
          project(cx, cy, values2, context.projection);
        }
      }
    }
  }
  scale(channels, scales2, context) {
    const values2 = valueObject(channels, scales2);
    if (context.projection) this.project(channels, values2, context);
    return values2;
  }
};
function marks(...marks2) {
  marks2.plot = Mark.prototype.plot;
  return marks2;
}
function composeRender(r1, r2) {
  if (r1 == null) return r2 === null ? void 0 : r2;
  if (r2 == null) return r1 === null ? void 0 : r1;
  if (typeof r1 !== "function") throw new TypeError(`invalid render transform: ${r1}`);
  if (typeof r2 !== "function") throw new TypeError(`invalid render transform: ${r2}`);
  return function(i, s2, v2, d, c4, next) {
    return r1.call(this, i, s2, v2, d, c4, (i2, s3, v3, d2, c5) => {
      return r2.call(this, i2, s3, v3, d2, c5, next);
    });
  };
}
function maybeChannels(channels) {
  return Object.fromEntries(
    Object.entries(maybeNamed(channels)).map(([name2, channel]) => {
      channel = typeof channel === "string" ? { value: channel, label: name2 } : maybeValue(channel);
      if (channel.filter === void 0 && channel.scale == null) channel = { ...channel, filter: null };
      return [name2, channel];
    })
  );
}
function maybeTip(tip2) {
  return tip2 === true ? "xy" : tip2 === false || tip2 == null ? null : typeof tip2 === "string" ? keyword(tip2, "tip", ["x", "y", "xy"]) : tip2;
}
function withTip(options, pointer2) {
  return options?.tip === true ? { ...options, tip: pointer2 } : isObject(options?.tip) && options.tip.pointer === void 0 ? { ...options, tip: { ...options.tip, pointer: pointer2 } } : options;
}

// ../../../node_modules/@observablehq/plot/src/dimensions.js
function createDimensions(scales2, marks2, options = {}) {
  let marginTopDefault = 0.5 - offset, marginRightDefault = 0.5 + offset, marginBottomDefault = 0.5 + offset, marginLeftDefault = 0.5 - offset;
  for (const { marginTop: marginTop3, marginRight: marginRight3, marginBottom: marginBottom3, marginLeft: marginLeft3 } of marks2) {
    if (marginTop3 > marginTopDefault) marginTopDefault = marginTop3;
    if (marginRight3 > marginRightDefault) marginRightDefault = marginRight3;
    if (marginBottom3 > marginBottomDefault) marginBottomDefault = marginBottom3;
    if (marginLeft3 > marginLeftDefault) marginLeftDefault = marginLeft3;
  }
  let {
    margin: margin2,
    marginTop: marginTop2 = margin2 !== void 0 ? margin2 : marginTopDefault,
    marginRight: marginRight2 = margin2 !== void 0 ? margin2 : marginRightDefault,
    marginBottom: marginBottom2 = margin2 !== void 0 ? margin2 : marginBottomDefault,
    marginLeft: marginLeft2 = margin2 !== void 0 ? margin2 : marginLeftDefault
  } = options;
  marginTop2 = +marginTop2;
  marginRight2 = +marginRight2;
  marginBottom2 = +marginBottom2;
  marginLeft2 = +marginLeft2;
  let {
    width: width2 = 640,
    height: height2 = autoHeight(scales2, options, {
      width: width2,
      marginTopDefault,
      marginRightDefault,
      marginBottomDefault,
      marginLeftDefault
    }) + Math.max(0, marginTop2 - marginTopDefault + marginBottom2 - marginBottomDefault)
  } = options;
  width2 = +width2;
  height2 = +height2;
  const dimensions = {
    width: width2,
    height: height2,
    marginTop: marginTop2,
    marginRight: marginRight2,
    marginBottom: marginBottom2,
    marginLeft: marginLeft2
  };
  if (scales2.fx || scales2.fy) {
    let {
      margin: facetMargin2,
      marginTop: facetMarginTop2 = facetMargin2 !== void 0 ? facetMargin2 : marginTop2,
      marginRight: facetMarginRight2 = facetMargin2 !== void 0 ? facetMargin2 : marginRight2,
      marginBottom: facetMarginBottom2 = facetMargin2 !== void 0 ? facetMargin2 : marginBottom2,
      marginLeft: facetMarginLeft2 = facetMargin2 !== void 0 ? facetMargin2 : marginLeft2
    } = options.facet ?? {};
    facetMarginTop2 = +facetMarginTop2;
    facetMarginRight2 = +facetMarginRight2;
    facetMarginBottom2 = +facetMarginBottom2;
    facetMarginLeft2 = +facetMarginLeft2;
    dimensions.facet = {
      marginTop: facetMarginTop2,
      marginRight: facetMarginRight2,
      marginBottom: facetMarginBottom2,
      marginLeft: facetMarginLeft2
    };
  }
  return dimensions;
}
function autoHeight({ x: x3, y: y3, fy, fx }, { projection: projection3, aspectRatio: aspectRatio2 }, { width: width2, marginTopDefault, marginRightDefault, marginBottomDefault, marginLeftDefault }) {
  const nfy = fy ? fy.scale.domain().length || 1 : 1;
  const ar = projectionAspectRatio(projection3);
  if (ar) {
    const nfx = fx ? fx.scale.domain().length : 1;
    const far = (1.1 * nfy - 0.1) / (1.1 * nfx - 0.1) * ar;
    const lar = Math.max(0.1, Math.min(10, far));
    return Math.round((width2 - marginLeftDefault - marginRightDefault) * lar + marginTopDefault + marginBottomDefault);
  }
  const ny = y3 ? isOrdinalScale(y3) ? y3.scale.domain().length || 1 : Math.max(7, 17 / nfy) : 1;
  if (aspectRatio2 != null) {
    aspectRatio2 = +aspectRatio2;
    if (!(isFinite(aspectRatio2) && aspectRatio2 > 0)) throw new Error(`invalid aspectRatio: ${aspectRatio2}`);
    const ratio = aspectRatioLength("y", y3) / (aspectRatioLength("x", x3) * aspectRatio2);
    const fxb = fx ? fx.scale.bandwidth() : 1;
    const fyb = fy ? fy.scale.bandwidth() : 1;
    const w = fxb * (width2 - marginLeftDefault - marginRightDefault) - x3.insetLeft - x3.insetRight;
    return (ratio * w + y3.insetTop + y3.insetBottom) / fyb + marginTopDefault + marginBottomDefault;
  }
  return !!(y3 || fy) * Math.max(1, Math.min(60, ny * nfy)) * 20 + !!fx * 30 + 60;
}
function aspectRatioLength(k2, scale3) {
  if (!scale3) throw new Error(`aspectRatio requires ${k2} scale`);
  const { type: type2, domain } = scale3;
  let transform3;
  switch (type2) {
    case "linear":
    case "utc":
    case "time":
      transform3 = Number;
      break;
    case "pow": {
      const exponent = scale3.scale.exponent();
      transform3 = (x3) => Math.pow(x3, exponent);
      break;
    }
    case "log":
      transform3 = Math.log;
      break;
    case "point":
    case "band":
      return domain.length;
    default:
      throw new Error(`unsupported ${k2} scale for aspectRatio: ${type2}`);
  }
  const [min5, max4] = extent(domain);
  return Math.abs(transform3(max4) - transform3(min5));
}

// ../../../node_modules/@observablehq/plot/src/interactions/pointer.js
var states = /* @__PURE__ */ new WeakMap();
function pointerK(kx2, ky2, { x: x3, y: y3, px, py, maxRadius = 40, channels, render, ...options } = {}) {
  maxRadius = +maxRadius;
  if (px != null) x3 ??= null, channels = { ...channels, px: { value: px, scale: "x" } };
  if (py != null) y3 ??= null, channels = { ...channels, py: { value: py, scale: "y" } };
  return {
    x: x3,
    y: y3,
    channels,
    ...options,
    // Unlike other composed transforms, the render transform must be the
    // outermost render function because it will re-render dynamically in
    // response to pointer events.
    render: composeRender(function(index2, scales2, values2, dimensions, context, next) {
      context = { ...context, pointerSticky: false };
      const svg = context.ownerSVGElement;
      const { data } = context.getMarkState(this);
      let state = states.get(svg);
      if (!state) states.set(svg, state = { sticky: false, roots: [], renders: [] });
      let renderIndex = state.renders.push(render2) - 1;
      const { x: x4, y: y4, fx, fy } = scales2;
      let tx = fx ? fx(index2.fx) - dimensions.marginLeft : 0;
      let ty = fy ? fy(index2.fy) - dimensions.marginTop : 0;
      if (x4?.bandwidth) tx += x4.bandwidth() / 2;
      if (y4?.bandwidth) ty += y4.bandwidth() / 2;
      const faceted = index2.fi != null;
      let facetState;
      if (faceted) {
        let facetStates = state.facetStates;
        if (!facetStates) state.facetStates = facetStates = /* @__PURE__ */ new Map();
        facetState = facetStates.get(this);
        if (!facetState) facetStates.set(this, facetState = /* @__PURE__ */ new Map());
      }
      const [cx, cy] = applyFrameAnchor(this, dimensions);
      const { px: PX, py: PY } = values2;
      const px2 = PX ? (i2) => PX[i2] : anchorX(values2, cx);
      const py2 = PY ? (i2) => PY[i2] : anchorY(values2, cy);
      let i;
      let g;
      let s2;
      let f;
      function update(ii, ri) {
        if (faceted) {
          if (f) f = cancelAnimationFrame(f);
          if (ii == null) facetState.delete(index2.fi);
          else {
            facetState.set(index2.fi, ri);
            f = requestAnimationFrame(() => {
              f = null;
              for (const [fi, r] of facetState) {
                if (r < ri || r === ri && fi < index2.fi) {
                  ii = null;
                  break;
                }
              }
              render2(ii);
            });
            return;
          }
        }
        render2(ii);
      }
      function render2(ii) {
        if (i === ii && s2 === state.sticky) return;
        i = ii;
        s2 = context.pointerSticky = state.sticky;
        const I = i == null ? [] : [i];
        if (faceted) I.fx = index2.fx, I.fy = index2.fy, I.fi = index2.fi;
        const r = next(I, scales2, values2, dimensions, context);
        if (g) {
          if (faceted) {
            const p = g.parentNode;
            const ft = g.getAttribute("transform");
            const mt = r.getAttribute("transform");
            ft ? r.setAttribute("transform", ft) : r.removeAttribute("transform");
            mt ? p.setAttribute("transform", mt) : p.removeAttribute("transform");
            r.removeAttribute("aria-label");
            r.removeAttribute("aria-description");
            r.removeAttribute("aria-hidden");
          }
          g.replaceWith(r);
        }
        state.roots[renderIndex] = g = r;
        if (!(i == null && facetState?.size > 1)) {
          const value = i == null ? null : isArray3(data) ? data[i] : data.get(i);
          context.dispatchValue(value);
        }
        return r;
      }
      function pointermove(event) {
        if (state.sticky || event.pointerType === "mouse" && event.buttons === 1) return;
        let [xp, yp] = pointer_default(event);
        xp -= tx, yp -= ty;
        const kpx = xp < dimensions.marginLeft || xp > dimensions.width - dimensions.marginRight ? 1 : kx2;
        const kpy = yp < dimensions.marginTop || yp > dimensions.height - dimensions.marginBottom ? 1 : ky2;
        let ii = null;
        let ri = maxRadius * maxRadius;
        for (const j of index2) {
          const dx = kpx * (px2(j) - xp);
          const dy = kpy * (py2(j) - yp);
          const rj = dx * dx + dy * dy;
          if (rj <= ri) ii = j, ri = rj;
        }
        if (ii != null && (kx2 !== 1 || ky2 !== 1)) {
          const dx = px2(ii) - xp;
          const dy = py2(ii) - yp;
          ri = dx * dx + dy * dy;
        }
        update(ii, ri);
      }
      function pointerdown(event) {
        if (event.pointerType !== "mouse") return;
        if (i == null) return;
        if (state.sticky && state.roots.some((r) => r?.contains(event.target))) return;
        if (state.sticky) state.sticky = false, state.renders.forEach((r) => r(null));
        else state.sticky = true, render2(i);
        event.stopImmediatePropagation();
      }
      function pointerleave(event) {
        if (event.pointerType !== "mouse") return;
        if (!state.sticky) update(null);
      }
      svg.addEventListener("pointerenter", pointermove);
      svg.addEventListener("pointermove", pointermove);
      svg.addEventListener("pointerdown", pointerdown);
      svg.addEventListener("pointerleave", pointerleave);
      return render2(null);
    }, render)
  };
}
function pointer(options) {
  return pointerK(1, 1, options);
}
function pointerX(options) {
  return pointerK(1, 0.01, options);
}
function pointerY(options) {
  return pointerK(0.01, 1, options);
}
function anchorX({ x1: X13, x2: X23, x: X3 = X13 }, cx) {
  return X13 && X23 ? (i) => (X13[i] + X23[i]) / 2 : X3 ? (i) => X3[i] : () => cx;
}
function anchorY({ y1: Y13, y2: Y23, y: Y3 = Y13 }, cy) {
  return Y13 && Y23 ? (i) => (Y13[i] + Y23[i]) / 2 : Y3 ? (i) => Y3[i] : () => cy;
}

// ../../../node_modules/@observablehq/plot/src/axes.js
function inferFontVariant(scale3) {
  return isOrdinalScale(scale3) && scale3.interval === void 0 ? void 0 : "tabular-nums";
}

// ../../../node_modules/@observablehq/plot/src/legends/ramp.js
function legendRamp(color3, options) {
  let {
    label = color3.label,
    tickSize = 6,
    width: width2 = 240,
    height: height2 = 44 + tickSize,
    marginTop: marginTop2 = 18,
    marginRight: marginRight2 = 0,
    marginBottom: marginBottom2 = 16 + tickSize,
    marginLeft: marginLeft2 = 0,
    style: style2,
    ticks: ticks2 = (width2 - marginLeft2 - marginRight2) / 64,
    tickFormat: tickFormat2,
    fontVariant = inferFontVariant(color3),
    round: round3 = true,
    opacity: opacity2,
    className
  } = options;
  const context = createContext(options);
  className = maybeClassName(className);
  opacity2 = maybeNumberChannel(opacity2)[1];
  if (tickFormat2 === null) tickFormat2 = () => null;
  const svg = create3("svg", context).attr("class", `${className}-ramp`).attr("font-family", "system-ui, sans-serif").attr("font-size", 10).attr("width", width2).attr("height", height2).attr("viewBox", `0 0 ${width2} ${height2}`).call(
    (svg2) => (
      // Warning: if you edit this, change defaultClassName.
      svg2.append("style").text(
        `:where(.${className}-ramp) {
  display: block;
  height: auto;
  height: intrinsic;
  max-width: 100%;
  overflow: visible;
}
:where(.${className}-ramp text) {
  white-space: pre;
}`
      )
    )
  ).call(applyInlineStyles, style2);
  let tickAdjust = (g) => g.selectAll(".tick line").attr("y1", marginTop2 + marginBottom2 - height2);
  let x3;
  const applyRange = round3 ? (x4, range4) => x4.rangeRound(range4) : (x4, range4) => x4.range(range4);
  const { type: type2, domain, range: range3, interpolate, scale: scale3, pivot } = color3;
  if (interpolate) {
    const interpolator = range3 === void 0 ? interpolate : piecewise(interpolate.length === 1 ? interpolatePiecewise(interpolate) : interpolate, range3);
    x3 = applyRange(
      scale3.copy(),
      quantize_default(
        number_default(marginLeft2, width2 - marginRight2),
        Math.min(domain.length + (pivot !== void 0), range3 === void 0 ? Infinity : range3.length)
      )
    );
    const n = 256;
    const canvas = context.document.createElement("canvas");
    canvas.width = n;
    canvas.height = 1;
    const context2 = canvas.getContext("2d");
    for (let i = 0, j = n - 1; i < n; ++i) {
      context2.fillStyle = interpolator(i / j);
      context2.fillRect(i, 0, 1, 1);
    }
    svg.append("image").attr("opacity", opacity2).attr("x", marginLeft2).attr("y", marginTop2).attr("width", width2 - marginLeft2 - marginRight2).attr("height", height2 - marginTop2 - marginBottom2).attr("preserveAspectRatio", "none").attr("xlink:href", canvas.toDataURL());
  } else if (type2 === "threshold") {
    const thresholds = domain;
    const thresholdFormat = tickFormat2 === void 0 ? (d) => d : typeof tickFormat2 === "string" ? format(tickFormat2) : tickFormat2;
    x3 = applyRange(linear2().domain([-1, range3.length - 1]), [marginLeft2, width2 - marginRight2]);
    svg.append("g").attr("fill-opacity", opacity2).selectAll().data(range3).enter().append("rect").attr("x", (d, i) => x3(i - 1)).attr("y", marginTop2).attr("width", (d, i) => x3(i) - x3(i - 1)).attr("height", height2 - marginTop2 - marginBottom2).attr("fill", (d) => d);
    ticks2 = map3(thresholds, (_, i) => i);
    tickFormat2 = (i) => thresholdFormat(thresholds[i], i);
  } else {
    x3 = applyRange(band().domain(domain), [marginLeft2, width2 - marginRight2]);
    svg.append("g").attr("fill-opacity", opacity2).selectAll().data(domain).enter().append("rect").attr("x", x3).attr("y", marginTop2).attr("width", Math.max(0, x3.bandwidth() - 1)).attr("height", height2 - marginTop2 - marginBottom2).attr("fill", scale3);
    tickAdjust = () => {
    };
  }
  svg.append("g").attr("transform", `translate(0,${height2 - marginBottom2})`).call(
    axisBottom(x3).ticks(Array.isArray(ticks2) ? null : ticks2, typeof tickFormat2 === "string" ? tickFormat2 : void 0).tickFormat(typeof tickFormat2 === "function" ? tickFormat2 : void 0).tickSize(tickSize).tickValues(Array.isArray(ticks2) ? ticks2 : null)
  ).attr("font-size", null).attr("font-family", null).attr("font-variant", impliedString(fontVariant, "normal")).call(tickAdjust).call((g) => g.select(".domain").remove());
  if (label !== void 0) {
    svg.append("text").attr("x", marginLeft2).attr("y", marginTop2 - 6).attr("fill", "currentColor").attr("font-weight", "bold").text(label);
  }
  return svg.node();
}

// ../../../node_modules/@observablehq/plot/src/math.js
var radians3 = Math.PI / 180;

// ../../../node_modules/@observablehq/plot/src/marker.js
function markers(mark2, { marker, markerStart = marker, markerMid = marker, markerEnd = marker } = {}) {
  mark2.markerStart = maybeMarker(markerStart);
  mark2.markerMid = maybeMarker(markerMid);
  mark2.markerEnd = maybeMarker(markerEnd);
}
function maybeMarker(marker) {
  if (marker == null || marker === false) return null;
  if (marker === true) return markerCircleFill;
  if (typeof marker === "function") return marker;
  switch (`${marker}`.toLowerCase()) {
    case "none":
      return null;
    case "arrow":
      return markerArrow("auto");
    case "arrow-reverse":
      return markerArrow("auto-start-reverse");
    case "dot":
      return markerDot;
    case "circle":
    case "circle-fill":
      return markerCircleFill;
    case "circle-stroke":
      return markerCircleStroke;
    case "tick":
      return markerTick("auto");
    case "tick-x":
      return markerTick(90);
    case "tick-y":
      return markerTick(0);
  }
  throw new Error(`invalid marker: ${marker}`);
}
function markerArrow(orient) {
  return (color3, context) => create3("svg:marker", context).attr("viewBox", "-5 -5 10 10").attr("markerWidth", 6.67).attr("markerHeight", 6.67).attr("orient", orient).attr("fill", "none").attr("stroke", color3).attr("stroke-width", 1.5).attr("stroke-linecap", "round").attr("stroke-linejoin", "round").call((marker) => marker.append("path").attr("d", "M-1.5,-3l3,3l-3,3")).node();
}
function markerDot(color3, context) {
  return create3("svg:marker", context).attr("viewBox", "-5 -5 10 10").attr("markerWidth", 6.67).attr("markerHeight", 6.67).attr("fill", color3).attr("stroke", "none").call((marker) => marker.append("circle").attr("r", 2.5)).node();
}
function markerCircleFill(color3, context) {
  return create3("svg:marker", context).attr("viewBox", "-5 -5 10 10").attr("markerWidth", 6.67).attr("markerHeight", 6.67).attr("fill", color3).attr("stroke", "var(--plot-background)").attr("stroke-width", 1.5).call((marker) => marker.append("circle").attr("r", 3)).node();
}
function markerCircleStroke(color3, context) {
  return create3("svg:marker", context).attr("viewBox", "-5 -5 10 10").attr("markerWidth", 6.67).attr("markerHeight", 6.67).attr("fill", "var(--plot-background)").attr("stroke", color3).attr("stroke-width", 1.5).call((marker) => marker.append("circle").attr("r", 3)).node();
}
function markerTick(orient) {
  return (color3, context) => create3("svg:marker", context).attr("viewBox", "-3 -3 6 6").attr("markerWidth", 6).attr("markerHeight", 6).attr("orient", orient).attr("stroke", color3).call((marker) => marker.append("path").attr("d", "M0,-3v6")).node();
}
var nextMarkerId = 0;
function applyMarkers(path2, mark2, { stroke: S }, context) {
  return applyMarkersColor(path2, mark2, S && ((i) => S[i]), null, context);
}
function applyGroupedMarkers(path2, mark2, { stroke: S, z: Z }, context) {
  return applyMarkersColor(path2, mark2, S && (([i]) => S[i]), Z, context);
}
var START = 1;
var END = 2;
function getGroupedOrientation(path2, Z) {
  const O = new Uint8Array(Z.length);
  const D3 = path2.data().filter((I) => I.length > 1);
  const n = D3.length;
  for (let i = 0, z = unset; i < n; ++i) {
    const I = D3[i];
    if (I.length > 1) {
      const i2 = I[0];
      if (z !== (z = keyof2(Z[i2]))) O[i2] |= START;
    }
  }
  for (let i = n - 1, z = unset; i >= 0; --i) {
    const I = D3[i];
    if (I.length > 1) {
      const i2 = I[0];
      if (z !== (z = keyof2(Z[i2]))) O[i2] |= END;
    }
  }
  return ([i]) => O[i];
}
function applyMarkersColor(path2, { markerStart, markerMid, markerEnd, stroke }, strokeof = () => stroke, Z, context) {
  if (!markerStart && !markerMid && !markerEnd) return;
  const iriByMarkerColor = /* @__PURE__ */ new Map();
  const orient = Z && getGroupedOrientation(path2, Z);
  function applyMarker(name2, marker, filter3) {
    return function(i) {
      if (filter3 && !filter3(i)) return;
      const color3 = strokeof(i);
      let iriByColor = iriByMarkerColor.get(marker);
      if (!iriByColor) iriByMarkerColor.set(marker, iriByColor = /* @__PURE__ */ new Map());
      let iri = iriByColor.get(color3);
      if (!iri) {
        const node = this.parentNode.insertBefore(marker(color3, context), this);
        const id2 = `plot-marker-${++nextMarkerId}`;
        node.setAttribute("id", id2);
        iriByColor.set(color3, iri = `url(#${id2})`);
      }
      this.setAttribute(name2, iri);
    };
  }
  if (markerStart) path2.each(applyMarker("marker-start", markerStart, orient && ((i) => orient(i) & START)));
  if (markerMid && orient) path2.each(applyMarker("marker-start", markerMid, (i) => !(orient(i) & START)));
  if (markerMid) path2.each(applyMarker("marker-mid", markerMid));
  if (markerEnd) path2.each(applyMarker("marker-end", markerEnd, orient && ((i) => orient(i) & END)));
}

// ../../../node_modules/@observablehq/plot/src/transforms/inset.js
function maybeInsetX({ inset: inset2, insetLeft, insetRight, ...options } = {}) {
  [insetLeft, insetRight] = maybeInset(inset2, insetLeft, insetRight);
  return { inset: inset2, insetLeft, insetRight, ...options };
}
function maybeInsetY({ inset: inset2, insetTop, insetBottom, ...options } = {}) {
  [insetTop, insetBottom] = maybeInset(inset2, insetTop, insetBottom);
  return { inset: inset2, insetTop, insetBottom, ...options };
}
function maybeInset(inset2, inset1, inset22) {
  return inset2 === void 0 && inset1 === void 0 && inset22 === void 0 ? offset ? [1, 0] : [0.5, 0.5] : [inset1, inset22];
}

// ../../../node_modules/@observablehq/plot/src/transforms/interval.js
function maybeIntervalValue(value, { interval: interval4 }) {
  value = { ...maybeValue(value) };
  value.interval = maybeInterval(value.interval === void 0 ? interval4 : value.interval);
  return value;
}
function maybeIntervalK(k2, maybeInsetK, options, trivial) {
  const { [k2]: v2, [`${k2}1`]: v1, [`${k2}2`]: v22 } = options;
  const { value, interval: interval4 } = maybeIntervalValue(v2, options);
  if (value == null || interval4 == null && !trivial) return options;
  const label = labelof(v2);
  if (interval4 == null) {
    let V;
    const kv = { transform: (data) => V || (V = valueof(data, value)), label };
    return {
      ...options,
      [k2]: void 0,
      [`${k2}1`]: v1 === void 0 ? kv : v1,
      [`${k2}2`]: v22 === void 0 && !(v1 === v22 && trivial) ? kv : v22
    };
  }
  let D1, V1;
  function transform3(data) {
    if (V1 !== void 0 && data === D1) return V1;
    return V1 = map3(valueof(D1 = data, value), (v3) => interval4.floor(v3));
  }
  return maybeInsetK({
    ...options,
    [k2]: void 0,
    [`${k2}1`]: v1 === void 0 ? { transform: transform3, label } : v1,
    [`${k2}2`]: v22 === void 0 ? { transform: (data) => transform3(data).map((v3) => interval4.offset(v3)), label } : v22
  });
}
function maybeIntervalMidK(k2, maybeInsetK, options) {
  const { [k2]: v2 } = options;
  const { value, interval: interval4 } = maybeIntervalValue(v2, options);
  if (value == null || interval4 == null) return options;
  return maybeInsetK({
    ...options,
    [k2]: {
      label: labelof(v2),
      transform: (data) => {
        const V1 = map3(valueof(data, value), (v3) => interval4.floor(v3));
        const V2 = V1.map((v3) => interval4.offset(v3));
        return V1.map(
          isTemporal(V1) ? (v1, v22) => v1 == null || isNaN(v1 = +v1) || (v22 = V2[v22], v22 == null) || isNaN(v22 = +v22) ? void 0 : new Date((v1 + v22) / 2) : (v1, v22) => v1 == null || (v22 = V2[v22], v22 == null) ? NaN : (+v1 + +v22) / 2
        );
      }
    }
  });
}
function maybeTrivialIntervalX(options = {}) {
  return maybeIntervalK("x", maybeInsetX, options, true);
}
function maybeTrivialIntervalY(options = {}) {
  return maybeIntervalK("y", maybeInsetY, options, true);
}
function maybeIntervalX(options = {}) {
  return maybeIntervalK("x", maybeInsetX, options);
}
function maybeIntervalY(options = {}) {
  return maybeIntervalK("y", maybeInsetY, options);
}
function maybeIntervalMidX(options = {}) {
  return maybeIntervalMidK("x", maybeInsetX, options);
}
function maybeIntervalMidY(options = {}) {
  return maybeIntervalMidK("y", maybeInsetY, options);
}

// ../../../node_modules/@observablehq/plot/src/marks/rule.js
var defaults = {
  ariaLabel: "rule",
  fill: null,
  stroke: "currentColor"
};
var RuleX = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y1: y12, y2: y22, inset: inset2 = 0, insetTop = inset2, insetBottom = inset2 } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y1: { value: y12, scale: "y", optional: true },
        y2: { value: y22, scale: "y", optional: true }
      },
      withTip(options, "x"),
      defaults
    );
    this.insetTop = number5(insetTop);
    this.insetBottom = number5(insetBottom);
    markers(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y1: Y13, y2: Y23 } = channels;
    const { width: width2, height: height2, marginTop: marginTop2, marginRight: marginRight2, marginLeft: marginLeft2, marginBottom: marginBottom2 } = dimensions;
    const { insetTop, insetBottom } = this;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3 }, offset, 0).call(
      (g) => g.selectAll().data(index2).enter().append("line").call(applyDirectStyles, this).attr("x1", X3 ? (i) => X3[i] : (marginLeft2 + width2 - marginRight2) / 2).attr("x2", X3 ? (i) => X3[i] : (marginLeft2 + width2 - marginRight2) / 2).attr("y1", Y13 && !isCollapsed(y3) ? (i) => Y13[i] + insetTop : marginTop2 + insetTop).attr(
        "y2",
        Y23 && !isCollapsed(y3) ? y3.bandwidth ? (i) => Y23[i] + y3.bandwidth() - insetBottom : (i) => Y23[i] - insetBottom : height2 - marginBottom2 - insetBottom
      ).call(applyChannelStyles, this, channels).call(applyMarkers, this, channels, context)
    ).node();
  }
};
var RuleY = class extends Mark {
  constructor(data, options = {}) {
    const { x1: x12, x2: x22, y: y3, inset: inset2 = 0, insetRight = inset2, insetLeft = inset2 } = options;
    super(
      data,
      {
        y: { value: y3, scale: "y", optional: true },
        x1: { value: x12, scale: "x", optional: true },
        x2: { value: x22, scale: "x", optional: true }
      },
      withTip(options, "y"),
      defaults
    );
    this.insetRight = number5(insetRight);
    this.insetLeft = number5(insetLeft);
    markers(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { y: Y3, x1: X13, x2: X23 } = channels;
    const { width: width2, height: height2, marginTop: marginTop2, marginRight: marginRight2, marginLeft: marginLeft2, marginBottom: marginBottom2 } = dimensions;
    const { insetLeft, insetRight } = this;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { y: Y3 && y3 }, 0, offset).call(
      (g) => g.selectAll().data(index2).enter().append("line").call(applyDirectStyles, this).attr("x1", X13 && !isCollapsed(x3) ? (i) => X13[i] + insetLeft : marginLeft2 + insetLeft).attr(
        "x2",
        X23 && !isCollapsed(x3) ? x3.bandwidth ? (i) => X23[i] + x3.bandwidth() - insetRight : (i) => X23[i] - insetRight : width2 - marginRight2 - insetRight
      ).attr("y1", Y3 ? (i) => Y3[i] : (marginTop2 + height2 - marginBottom2) / 2).attr("y2", Y3 ? (i) => Y3[i] : (marginTop2 + height2 - marginBottom2) / 2).call(applyChannelStyles, this, channels).call(applyMarkers, this, channels, context)
    ).node();
  }
};
function ruleX(data, options) {
  let { x: x3 = identity8, y: y3, y1: y12, y2: y22, ...rest } = maybeIntervalY(options);
  [y12, y22] = maybeOptionalZero(y3, y12, y22);
  return new RuleX(data, { ...rest, x: x3, y1: y12, y2: y22 });
}
function ruleY(data, options) {
  let { y: y3 = identity8, x: x3, x1: x12, x2: x22, ...rest } = maybeIntervalX(options);
  [x12, x22] = maybeOptionalZero(x3, x12, x22);
  return new RuleY(data, { ...rest, y: y3, x1: x12, x2: x22 });
}
function maybeOptionalZero(x3, x12, x22) {
  if (x3 == null) {
    if (x12 === void 0) {
      if (x22 !== void 0) return [0, x22];
    } else {
      if (x22 === void 0) return [0, x12];
    }
  } else if (x12 === void 0) {
    return x22 === void 0 ? [0, x3] : [x3, x22];
  } else if (x22 === void 0) {
    return [x3, x12];
  }
  return [x12, x22];
}

// ../../../node_modules/@observablehq/plot/src/template.js
function template(strings, ...parts) {
  let n = parts.length;
  for (let j = 0, copy4 = true; j < n; ++j) {
    if (typeof parts[j] !== "function") {
      if (copy4) {
        strings = strings.slice();
        copy4 = false;
      }
      strings.splice(j, 2, strings[j] + parts[j] + strings[j + 1]);
      parts.splice(j, 1);
      --j, --n;
    }
  }
  return (i) => {
    let s2 = strings[0];
    for (let j = 0; j < n; ++j) {
      s2 += parts[j](i) + strings[j + 1];
    }
    return s2;
  };
}

// ../../../node_modules/@observablehq/plot/src/marks/text.js
var defaults2 = {
  ariaLabel: "text",
  strokeLinejoin: "round",
  strokeWidth: 3,
  paintOrder: "stroke"
};
var softHyphen = "\xAD";
var Text = class extends Mark {
  constructor(data, options = {}) {
    const {
      x: x3,
      y: y3,
      text: text3 = isIterable2(data) && isTextual(data) ? identity8 : indexOf,
      frameAnchor,
      textAnchor = /right$/i.test(frameAnchor) ? "end" : /left$/i.test(frameAnchor) ? "start" : "middle",
      lineAnchor = /^top/i.test(frameAnchor) ? "top" : /^bottom/i.test(frameAnchor) ? "bottom" : "middle",
      lineHeight = 1,
      lineWidth = Infinity,
      textOverflow,
      monospace,
      fontFamily = monospace ? "ui-monospace, monospace" : void 0,
      fontSize,
      fontStyle,
      fontVariant,
      fontWeight,
      rotate
    } = options;
    const [vrotate, crotate] = maybeNumberChannel(rotate, 0);
    const [vfontSize, cfontSize] = maybeFontSizeChannel(fontSize);
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        fontSize: { value: vfontSize, optional: true },
        rotate: { value: numberChannel(vrotate), optional: true },
        text: { value: text3, filter: nonempty, optional: true }
      },
      options,
      defaults2
    );
    this.rotate = crotate;
    this.textAnchor = impliedString(textAnchor, "middle");
    this.lineAnchor = keyword(lineAnchor, "lineAnchor", ["top", "middle", "bottom"]);
    this.lineHeight = +lineHeight;
    this.lineWidth = +lineWidth;
    this.textOverflow = maybeTextOverflow(textOverflow);
    this.monospace = !!monospace;
    this.fontFamily = string(fontFamily);
    this.fontSize = cfontSize;
    this.fontStyle = string(fontStyle);
    this.fontVariant = string(fontVariant);
    this.fontWeight = string(fontWeight);
    this.frameAnchor = maybeFrameAnchor(frameAnchor);
    if (!(this.lineWidth >= 0)) throw new Error(`invalid lineWidth: ${lineWidth}`);
    this.splitLines = splitter2(this);
    this.clipLine = clipper(this);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, rotate: R, text: T, title: TL, fontSize: FS } = channels;
    const { rotate } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyIndirectTextStyles, this, T, dimensions).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      (g) => g.selectAll().data(index2).enter().append("text").call(applyDirectStyles, this).call(applyMultilineText, this, T, TL).attr(
        "transform",
        template`translate(${X3 ? (i) => X3[i] : cx},${Y3 ? (i) => Y3[i] : cy})${R ? (i) => ` rotate(${R[i]})` : rotate ? ` rotate(${rotate})` : ``}`
      ).call(applyAttr, "font-size", FS && ((i) => FS[i])).call(applyChannelStyles, this, channels)
    ).node();
  }
};
function maybeTextOverflow(textOverflow) {
  return textOverflow == null ? null : keyword(textOverflow, "textOverflow", [
    "clip",
    // shorthand for clip-end
    "ellipsis",
    // … ellipsis-end
    "clip-start",
    "clip-end",
    "ellipsis-start",
    "ellipsis-middle",
    "ellipsis-end"
  ]).replace(/^(clip|ellipsis)$/, "$1-end");
}
function applyMultilineText(selection2, mark2, T, TL) {
  if (!T) return;
  const { lineAnchor, lineHeight, textOverflow, splitLines, clipLine } = mark2;
  selection2.each(function(i) {
    const lines = splitLines(formatDefault(T[i]) ?? "").map(clipLine);
    const n = lines.length;
    const y3 = lineAnchor === "top" ? 0.71 : lineAnchor === "bottom" ? 1 - n : (164 - n * 100) / 200;
    if (n > 1) {
      let m = 0;
      for (let i2 = 0; i2 < n; ++i2) {
        ++m;
        if (!lines[i2]) continue;
        const tspan = this.ownerDocument.createElementNS(namespaces_default.svg, "tspan");
        tspan.setAttribute("x", 0);
        if (i2 === m - 1) tspan.setAttribute("y", `${(y3 + i2) * lineHeight}em`);
        else tspan.setAttribute("dy", `${m * lineHeight}em`);
        tspan.textContent = lines[i2];
        this.appendChild(tspan);
        m = 0;
      }
    } else {
      if (y3) this.setAttribute("y", `${y3 * lineHeight}em`);
      this.textContent = lines[0];
    }
    if (textOverflow && !TL && lines[0] !== T[i]) {
      const title = this.ownerDocument.createElementNS(namespaces_default.svg, "title");
      title.textContent = T[i];
      this.appendChild(title);
    }
  });
}
function text(data, { x: x3, y: y3, ...options } = {}) {
  if (options.frameAnchor === void 0) [x3, y3] = maybeTuple(x3, y3);
  return new Text(data, { ...options, x: x3, y: y3 });
}
function textX(data, { x: x3 = identity8, ...options } = {}) {
  return new Text(data, maybeIntervalMidY({ ...options, x: x3 }));
}
function textY(data, { y: y3 = identity8, ...options } = {}) {
  return new Text(data, maybeIntervalMidX({ ...options, y: y3 }));
}
function applyIndirectTextStyles(selection2, mark2, T) {
  applyAttr(selection2, "text-anchor", mark2.textAnchor);
  applyAttr(selection2, "font-family", mark2.fontFamily);
  applyAttr(selection2, "font-size", mark2.fontSize);
  applyAttr(selection2, "font-style", mark2.fontStyle);
  applyAttr(selection2, "font-variant", mark2.fontVariant === void 0 ? inferFontVariant2(T) : mark2.fontVariant);
  applyAttr(selection2, "font-weight", mark2.fontWeight);
}
function inferFontVariant2(T) {
  return T && (isNumeric(T) || isTemporal(T)) ? "tabular-nums" : void 0;
}
var fontSizes = /* @__PURE__ */ new Set([
  // global keywords
  "inherit",
  "initial",
  "revert",
  "unset",
  // absolute keywords
  "xx-small",
  "x-small",
  "small",
  "medium",
  "large",
  "x-large",
  "xx-large",
  "xxx-large",
  // relative keywords
  "larger",
  "smaller"
]);
function maybeFontSizeChannel(fontSize) {
  if (fontSize == null || typeof fontSize === "number") return [void 0, fontSize];
  if (typeof fontSize !== "string") return [fontSize, void 0];
  fontSize = fontSize.trim().toLowerCase();
  return fontSizes.has(fontSize) || /^[+-]?\d*\.?\d+(e[+-]?\d+)?(\w*|%)$/.test(fontSize) ? [void 0, fontSize] : [fontSize, void 0];
}
function lineWrap(input3, maxWidth, widthof2) {
  const lines = [];
  let lineStart, lineEnd = 0;
  for (const [wordStart, wordEnd, required2] of lineBreaks(input3)) {
    if (lineStart === void 0) lineStart = wordStart;
    if (lineEnd > lineStart && widthof2(input3, lineStart, wordEnd) > maxWidth) {
      lines.push(input3.slice(lineStart, lineEnd) + (input3[lineEnd - 1] === softHyphen ? "-" : ""));
      lineStart = wordStart;
    }
    if (required2) {
      lines.push(input3.slice(lineStart, wordEnd));
      lineStart = void 0;
      continue;
    }
    lineEnd = wordEnd;
  }
  return lines;
}
function* lineBreaks(input3) {
  let i = 0, j = 0;
  const n = input3.length;
  while (j < n) {
    let k2 = 1;
    switch (input3[j]) {
      case softHyphen:
      case "-":
        ++j;
        yield [i, j, false];
        i = j;
        break;
      case " ":
        yield [i, j, false];
        while (input3[++j] === " ") ;
        i = j;
        break;
      case "\r":
        if (input3[j + 1] === "\n") ++k2;
      // falls through
      case "\n":
        yield [i, j, true];
        j += k2;
        i = j;
        break;
      default:
        ++j;
        break;
    }
  }
  yield [i, j, true];
}
var defaultWidthMap = {
  a: 56,
  b: 63,
  c: 57,
  d: 63,
  e: 58,
  f: 37,
  g: 62,
  h: 60,
  i: 26,
  j: 26,
  k: 55,
  l: 26,
  m: 88,
  n: 60,
  o: 60,
  p: 62,
  q: 62,
  r: 39,
  s: 54,
  t: 38,
  u: 60,
  v: 55,
  w: 79,
  x: 54,
  y: 55,
  z: 55,
  A: 69,
  B: 67,
  C: 73,
  D: 74,
  E: 61,
  F: 58,
  G: 76,
  H: 75,
  I: 28,
  J: 55,
  K: 67,
  L: 58,
  M: 89,
  N: 75,
  O: 78,
  P: 65,
  Q: 78,
  R: 67,
  S: 65,
  T: 65,
  U: 75,
  V: 69,
  W: 98,
  X: 69,
  Y: 67,
  Z: 67,
  0: 64,
  1: 48,
  2: 62,
  3: 64,
  4: 66,
  5: 63,
  6: 65,
  7: 58,
  8: 65,
  9: 65,
  " ": 29,
  "!": 32,
  '"': 49,
  "'": 31,
  "(": 39,
  ")": 39,
  ",": 31,
  "-": 48,
  ".": 31,
  "/": 32,
  ":": 31,
  ";": 31,
  "?": 52,
  "\u2018": 31,
  "\u2019": 31,
  "\u201C": 47,
  "\u201D": 47,
  "\u2026": 82
};
function defaultWidth(text3, start2 = 0, end = text3.length) {
  let sum4 = 0;
  for (let i = start2; i < end; i = readCharacter(text3, i)) {
    sum4 += defaultWidthMap[text3[i]] ?? (isPictographic(text3, i) ? 120 : defaultWidthMap.e);
  }
  return sum4;
}
function monospaceWidth(text3, start2 = 0, end = text3.length) {
  let sum4 = 0;
  for (let i = start2; i < end; i = readCharacter(text3, i)) {
    sum4 += isPictographic(text3, i) ? 126 : 63;
  }
  return sum4;
}
function splitter2({ monospace, lineWidth, textOverflow }) {
  if (textOverflow != null || lineWidth == Infinity) return (text3) => text3.split(/\r\n?|\n/g);
  const widthof2 = monospace ? monospaceWidth : defaultWidth;
  const maxWidth = lineWidth * 100;
  return (text3) => lineWrap(text3, maxWidth, widthof2);
}
function clipper({ monospace, lineWidth, textOverflow }) {
  if (textOverflow == null || lineWidth == Infinity) return (text3) => text3;
  const widthof2 = monospace ? monospaceWidth : defaultWidth;
  const maxWidth = lineWidth * 100;
  switch (textOverflow) {
    case "clip-start":
      return (text3) => clipStart(text3, maxWidth, widthof2, "");
    case "clip-end":
      return (text3) => clipEnd(text3, maxWidth, widthof2, "");
    case "ellipsis-start":
      return (text3) => clipStart(text3, maxWidth, widthof2, ellipsis);
    case "ellipsis-middle":
      return (text3) => clipMiddle(text3, maxWidth, widthof2, ellipsis);
    case "ellipsis-end":
      return (text3) => clipEnd(text3, maxWidth, widthof2, ellipsis);
  }
}
var ellipsis = "\u2026";
function cut(text3, width2, widthof2, inset2) {
  const I = [];
  let w = 0;
  for (let i = 0, j = 0, n = text3.length; i < n; i = j) {
    j = readCharacter(text3, i);
    const l = widthof2(text3, i, j);
    if (w + l > width2) {
      w += inset2;
      while (w > width2 && i > 0) j = i, i = I.pop(), w -= widthof2(text3, i, j);
      return [i, width2 - w];
    }
    w += l;
    I.push(i);
  }
  return [-1, 0];
}
function clipEnd(text3, width2, widthof2, ellipsis2) {
  text3 = text3.trim();
  const e = widthof2(ellipsis2);
  const [i] = cut(text3, width2, widthof2, e);
  return i < 0 ? text3 : text3.slice(0, i).trimEnd() + ellipsis2;
}
function clipMiddle(text3, width2, widthof2, ellipsis2) {
  text3 = text3.trim();
  const w = widthof2(text3);
  if (w <= width2) return text3;
  const e = widthof2(ellipsis2) / 2;
  const [i, ei] = cut(text3, width2 / 2, widthof2, e);
  const [j] = cut(text3, w - width2 / 2 - ei + e, widthof2, -e);
  return j < 0 ? ellipsis2 : text3.slice(0, i).trimEnd() + ellipsis2 + text3.slice(readCharacter(text3, j)).trimStart();
}
function clipStart(text3, width2, widthof2, ellipsis2) {
  text3 = text3.trim();
  const w = widthof2(text3);
  if (w <= width2) return text3;
  const e = widthof2(ellipsis2);
  const [j] = cut(text3, w - width2 + e, widthof2, -e);
  return j < 0 ? ellipsis2 : ellipsis2 + text3.slice(readCharacter(text3, j)).trimStart();
}
var reCombiner = /[\p{Combining_Mark}\p{Emoji_Modifier}]+/uy;
var rePictographic = /\p{Extended_Pictographic}/uy;
function readCharacter(text3, i) {
  i += isSurrogatePair(text3, i) ? 2 : 1;
  if (isCombiner(text3, i)) i = reCombiner.lastIndex;
  if (isZeroWidthJoiner(text3, i)) return readCharacter(text3, i + 1);
  return i;
}
function isAscii(text3, i) {
  return text3.charCodeAt(i) < 128;
}
function isSurrogatePair(text3, i) {
  const hi = text3.charCodeAt(i);
  if (hi >= 55296 && hi < 56320) {
    const lo = text3.charCodeAt(i + 1);
    return lo >= 56320 && lo < 57344;
  }
  return false;
}
function isZeroWidthJoiner(text3, i) {
  return text3.charCodeAt(i) === 8205;
}
function isCombiner(text3, i) {
  return isAscii(text3, i) ? false : (reCombiner.lastIndex = i, reCombiner.test(text3));
}
function isPictographic(text3, i) {
  return isAscii(text3, i) ? false : (rePictographic.lastIndex = i, rePictographic.test(text3));
}

// ../../../node_modules/@observablehq/plot/src/marks/vector.js
var defaults3 = {
  ariaLabel: "vector",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeLinejoin: "round",
  strokeLinecap: "round"
};
var defaultRadius = 3.5;
var wingRatio = defaultRadius * 5;
var shapeArrow = {
  draw(context, l, r) {
    const wing = l * r / wingRatio;
    context.moveTo(0, 0);
    context.lineTo(0, -l);
    context.moveTo(-wing, wing - l);
    context.lineTo(0, -l);
    context.lineTo(wing, wing - l);
  }
};
var shapeSpike = {
  draw(context, l, r) {
    context.moveTo(-r, 0);
    context.lineTo(0, -l);
    context.lineTo(r, 0);
  }
};
var shapes = /* @__PURE__ */ new Map([
  ["arrow", shapeArrow],
  ["spike", shapeSpike]
]);
function isShapeObject(value) {
  return value && typeof value.draw === "function";
}
function maybeShape(shape) {
  if (isShapeObject(shape)) return shape;
  const value = shapes.get(`${shape}`.toLowerCase());
  if (value) return value;
  throw new Error(`invalid shape: ${shape}`);
}
var Vector = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, r = defaultRadius, length: length4, rotate, shape = shapeArrow, anchor = "middle", frameAnchor } = options;
    const [vl, cl] = maybeNumberChannel(length4, 12);
    const [vr, cr] = maybeNumberChannel(rotate, 0);
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        length: { value: vl, scale: "length", optional: true },
        rotate: { value: vr, optional: true }
      },
      options,
      defaults3
    );
    this.r = +r;
    this.length = cl;
    this.rotate = cr;
    this.shape = maybeShape(shape);
    this.anchor = keyword(anchor, "anchor", ["start", "middle", "end"]);
    this.frameAnchor = maybeFrameAnchor(frameAnchor);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, length: L, rotate: A5 } = channels;
    const { length: length4, rotate, anchor, shape, r } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      (g) => g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr(
        "transform",
        template`translate(${X3 ? (i) => X3[i] : cx},${Y3 ? (i) => Y3[i] : cy})${A5 ? (i) => ` rotate(${A5[i]})` : rotate ? ` rotate(${rotate})` : ``}${anchor === "start" ? `` : anchor === "end" ? L ? (i) => ` translate(0,${L[i]})` : ` translate(0,${length4})` : L ? (i) => ` translate(0,${L[i] / 2})` : ` translate(0,${length4 / 2})`}`
      ).attr(
        "d",
        L ? (i) => {
          const p = pathRound();
          shape.draw(p, L[i], r);
          return p;
        } : (() => {
          const p = pathRound();
          shape.draw(p, length4, r);
          return p;
        })()
      ).call(applyChannelStyles, this, channels)
    ).node();
  }
};
function vector(data, options = {}) {
  let { x: x3, y: y3, ...rest } = options;
  if (options.frameAnchor === void 0) [x3, y3] = maybeTuple(x3, y3);
  return new Vector(data, { ...rest, x: x3, y: y3 });
}
function vectorX(data, options = {}) {
  const { x: x3 = identity8, ...rest } = options;
  return new Vector(data, { ...rest, x: x3 });
}
function vectorY(data, options = {}) {
  const { y: y3 = identity8, ...rest } = options;
  return new Vector(data, { ...rest, y: y3 });
}
function spike(data, options = {}) {
  const {
    shape = shapeSpike,
    stroke = defaults3.stroke,
    strokeWidth = 1,
    fill = stroke,
    fillOpacity = 0.3,
    anchor = "start",
    ...rest
  } = options;
  return vector(data, { ...rest, shape, stroke, strokeWidth, fill, fillOpacity, anchor });
}

// ../../../node_modules/@observablehq/plot/src/marks/axis.js
function maybeData(data, options) {
  if (arguments.length < 2 && !isIterable2(data)) options = data, data = null;
  if (options === void 0) options = {};
  return [data, options];
}
function maybeAnchor2({ anchor } = {}, anchors) {
  return anchor === void 0 ? anchors[0] : keyword(anchor, "anchor", anchors);
}
function anchorY2(options) {
  return maybeAnchor2(options, ["left", "right"]);
}
function anchorFy(options) {
  return maybeAnchor2(options, ["right", "left"]);
}
function anchorX2(options) {
  return maybeAnchor2(options, ["bottom", "top"]);
}
function anchorFx(options) {
  return maybeAnchor2(options, ["top", "bottom"]);
}
function axisY() {
  const [data, options] = maybeData(...arguments);
  return axisKy("y", anchorY2(options), data, options);
}
function axisFy() {
  const [data, options] = maybeData(...arguments);
  return axisKy("fy", anchorFy(options), data, options);
}
function axisX() {
  const [data, options] = maybeData(...arguments);
  return axisKx("x", anchorX2(options), data, options);
}
function axisFx() {
  const [data, options] = maybeData(...arguments);
  return axisKx("fx", anchorFx(options), data, options);
}
function axisKy(k2, anchor, data, {
  color: color3 = "currentColor",
  opacity: opacity2 = 1,
  stroke = color3,
  strokeOpacity = opacity2,
  strokeWidth = 1,
  fill = color3,
  fillOpacity = opacity2,
  textAnchor,
  textStroke,
  textStrokeOpacity,
  textStrokeWidth,
  tickSize = k2 === "y" ? 6 : 0,
  tickPadding,
  tickRotate,
  x: x3,
  margin: margin2,
  marginTop: marginTop2 = margin2 === void 0 ? 20 : margin2,
  marginRight: marginRight2 = margin2 === void 0 ? anchor === "right" ? 40 : 0 : margin2,
  marginBottom: marginBottom2 = margin2 === void 0 ? 20 : margin2,
  marginLeft: marginLeft2 = margin2 === void 0 ? anchor === "left" ? 40 : 0 : margin2,
  label,
  labelAnchor,
  labelArrow,
  labelOffset,
  ariaLabel: ariaLabel2 = `${k2}-axis`,
  ...options
}) {
  tickSize = number5(tickSize);
  tickPadding = number5(tickPadding);
  tickRotate = number5(tickRotate);
  if (labelAnchor !== void 0) labelAnchor = keyword(labelAnchor, "labelAnchor", ["center", "top", "bottom"]);
  labelArrow = maybeLabelArrow(labelArrow);
  return marks(
    tickSize && !isNoneish(stroke) ? axisTickKy(k2, anchor, data, {
      stroke,
      strokeOpacity,
      strokeWidth,
      tickSize,
      tickPadding,
      tickRotate,
      x: x3,
      ariaLabel: ariaLabel2,
      ...options
    }) : null,
    !isNoneish(fill) ? axisTextKy(k2, anchor, data, {
      fill,
      fillOpacity,
      stroke: textStroke,
      strokeOpacity: textStrokeOpacity,
      strokeWidth: textStrokeWidth,
      textAnchor,
      tickSize,
      tickPadding,
      tickRotate,
      x: x3,
      marginTop: marginTop2,
      marginRight: marginRight2,
      marginBottom: marginBottom2,
      marginLeft: marginLeft2,
      ariaLabel: ariaLabel2,
      ...options
    }) : null,
    !isNoneish(fill) && label !== null ? text(
      [],
      labelOptions({ fill, fillOpacity, ...options }, function(data2, facets, channels, scales2, dimensions) {
        const scale3 = scales2[k2];
        const { marginTop: marginTop3, marginRight: marginRight3, marginBottom: marginBottom3, marginLeft: marginLeft3 } = k2 === "y" && dimensions.inset || dimensions;
        const cla = labelAnchor ?? (scale3.bandwidth ? "center" : "top");
        const clo = labelOffset ?? (anchor === "right" ? marginRight3 : marginLeft3) - 3;
        if (cla === "center") {
          this.textAnchor = void 0;
          this.lineAnchor = anchor === "right" ? "bottom" : "top";
          this.frameAnchor = anchor;
          this.rotate = -90;
        } else {
          this.textAnchor = anchor === "right" ? "end" : "start";
          this.lineAnchor = cla;
          this.frameAnchor = `${cla}-${anchor}`;
          this.rotate = 0;
        }
        this.dy = cla === "top" ? 3 - marginTop3 : cla === "bottom" ? marginBottom3 - 3 : 0;
        this.dx = anchor === "right" ? clo : -clo;
        this.ariaLabel = `${ariaLabel2} label`;
        return {
          facets: [[0]],
          channels: { text: { value: [formatAxisLabel(k2, scale3, { anchor, label, labelAnchor: cla, labelArrow })] } }
        };
      })
    ) : null
  );
}
function axisKx(k2, anchor, data, {
  color: color3 = "currentColor",
  opacity: opacity2 = 1,
  stroke = color3,
  strokeOpacity = opacity2,
  strokeWidth = 1,
  fill = color3,
  fillOpacity = opacity2,
  textAnchor,
  textStroke,
  textStrokeOpacity,
  textStrokeWidth,
  tickSize = k2 === "x" ? 6 : 0,
  tickPadding,
  tickRotate,
  y: y3,
  margin: margin2,
  marginTop: marginTop2 = margin2 === void 0 ? anchor === "top" ? 30 : 0 : margin2,
  marginRight: marginRight2 = margin2 === void 0 ? 20 : margin2,
  marginBottom: marginBottom2 = margin2 === void 0 ? anchor === "bottom" ? 30 : 0 : margin2,
  marginLeft: marginLeft2 = margin2 === void 0 ? 20 : margin2,
  label,
  labelAnchor,
  labelArrow,
  labelOffset,
  ariaLabel: ariaLabel2 = `${k2}-axis`,
  ...options
}) {
  tickSize = number5(tickSize);
  tickPadding = number5(tickPadding);
  tickRotate = number5(tickRotate);
  if (labelAnchor !== void 0) labelAnchor = keyword(labelAnchor, "labelAnchor", ["center", "left", "right"]);
  labelArrow = maybeLabelArrow(labelArrow);
  return marks(
    tickSize && !isNoneish(stroke) ? axisTickKx(k2, anchor, data, {
      stroke,
      strokeOpacity,
      strokeWidth,
      tickSize,
      tickPadding,
      tickRotate,
      y: y3,
      ariaLabel: ariaLabel2,
      ...options
    }) : null,
    !isNoneish(fill) ? axisTextKx(k2, anchor, data, {
      fill,
      fillOpacity,
      stroke: textStroke,
      strokeOpacity: textStrokeOpacity,
      strokeWidth: textStrokeWidth,
      textAnchor,
      tickSize,
      tickPadding,
      tickRotate,
      y: y3,
      marginTop: marginTop2,
      marginRight: marginRight2,
      marginBottom: marginBottom2,
      marginLeft: marginLeft2,
      ariaLabel: ariaLabel2,
      ...options
    }) : null,
    !isNoneish(fill) && label !== null ? text(
      [],
      labelOptions({ fill, fillOpacity, ...options }, function(data2, facets, channels, scales2, dimensions) {
        const scale3 = scales2[k2];
        const { marginTop: marginTop3, marginRight: marginRight3, marginBottom: marginBottom3, marginLeft: marginLeft3 } = k2 === "x" && dimensions.inset || dimensions;
        const cla = labelAnchor ?? (scale3.bandwidth ? "center" : "right");
        const clo = labelOffset ?? (anchor === "top" ? marginTop3 : marginBottom3) - 3;
        if (cla === "center") {
          this.frameAnchor = anchor;
          this.textAnchor = void 0;
        } else {
          this.frameAnchor = `${anchor}-${cla}`;
          this.textAnchor = cla === "right" ? "end" : "start";
        }
        this.lineAnchor = anchor;
        this.dy = anchor === "top" ? -clo : clo;
        this.dx = cla === "right" ? marginRight3 - 3 : cla === "left" ? 3 - marginLeft3 : 0;
        this.ariaLabel = `${ariaLabel2} label`;
        return {
          facets: [[0]],
          channels: { text: { value: [formatAxisLabel(k2, scale3, { anchor, label, labelAnchor: cla, labelArrow })] } }
        };
      })
    ) : null
  );
}
function axisTickKy(k2, anchor, data, {
  strokeWidth = 1,
  strokeLinecap = null,
  strokeLinejoin = null,
  facetAnchor = anchor + (k2 === "y" ? "-empty" : ""),
  frameAnchor = anchor,
  tickSize,
  inset: inset2 = 0,
  insetLeft = inset2,
  insetRight = inset2,
  dx = 0,
  y: y3 = k2 === "y" ? void 0 : null,
  ariaLabel: ariaLabel2,
  ...options
}) {
  return axisMark(
    vectorY,
    k2,
    data,
    {
      ariaLabel: `${ariaLabel2} tick`,
      ariaHidden: true
    },
    {
      strokeWidth,
      strokeLinecap,
      strokeLinejoin,
      facetAnchor,
      frameAnchor,
      y: y3,
      ...options,
      dx: anchor === "left" ? +dx - offset + +insetLeft : +dx + offset - insetRight,
      anchor: "start",
      length: tickSize,
      shape: anchor === "left" ? shapeTickLeft : shapeTickRight
    }
  );
}
function axisTickKx(k2, anchor, data, {
  strokeWidth = 1,
  strokeLinecap = null,
  strokeLinejoin = null,
  facetAnchor = anchor + (k2 === "x" ? "-empty" : ""),
  frameAnchor = anchor,
  tickSize,
  inset: inset2 = 0,
  insetTop = inset2,
  insetBottom = inset2,
  dy = 0,
  x: x3 = k2 === "x" ? void 0 : null,
  ariaLabel: ariaLabel2,
  ...options
}) {
  return axisMark(
    vectorX,
    k2,
    data,
    {
      ariaLabel: `${ariaLabel2} tick`,
      ariaHidden: true
    },
    {
      strokeWidth,
      strokeLinejoin,
      strokeLinecap,
      facetAnchor,
      frameAnchor,
      x: x3,
      ...options,
      dy: anchor === "bottom" ? +dy - offset - insetBottom : +dy + offset + +insetTop,
      anchor: "start",
      length: tickSize,
      shape: anchor === "bottom" ? shapeTickBottom : shapeTickTop
    }
  );
}
function axisTextKy(k2, anchor, data, {
  facetAnchor = anchor + (k2 === "y" ? "-empty" : ""),
  frameAnchor = anchor,
  tickSize,
  tickRotate = 0,
  tickPadding = Math.max(3, 9 - tickSize) + (Math.abs(tickRotate) > 60 ? 4 * Math.cos(tickRotate * radians3) : 0),
  text: text3,
  textAnchor = Math.abs(tickRotate) > 60 ? "middle" : anchor === "left" ? "end" : "start",
  lineAnchor = tickRotate > 60 ? "top" : tickRotate < -60 ? "bottom" : "middle",
  fontVariant,
  inset: inset2 = 0,
  insetLeft = inset2,
  insetRight = inset2,
  dx = 0,
  ariaLabel: ariaLabel2,
  y: y3 = k2 === "y" ? void 0 : null,
  ...options
}) {
  return axisMark(
    textY,
    k2,
    data,
    { ariaLabel: `${ariaLabel2} tick label` },
    {
      facetAnchor,
      frameAnchor,
      text: text3,
      textAnchor,
      lineAnchor,
      fontVariant,
      rotate: tickRotate,
      y: y3,
      ...options,
      dx: anchor === "left" ? +dx - tickSize - tickPadding + +insetLeft : +dx + +tickSize + +tickPadding - insetRight
    },
    function(scale3, data2, ticks2, tickFormat2, channels) {
      if (fontVariant === void 0) this.fontVariant = inferFontVariant3(scale3);
      if (text3 === void 0) channels.text = inferTextChannel(scale3, data2, ticks2, tickFormat2, anchor);
    }
  );
}
function axisTextKx(k2, anchor, data, {
  facetAnchor = anchor + (k2 === "x" ? "-empty" : ""),
  frameAnchor = anchor,
  tickSize,
  tickRotate = 0,
  tickPadding = Math.max(3, 9 - tickSize) + (Math.abs(tickRotate) >= 10 ? 4 * Math.cos(tickRotate * radians3) : 0),
  text: text3,
  textAnchor = Math.abs(tickRotate) >= 10 ? tickRotate < 0 ^ anchor === "bottom" ? "start" : "end" : "middle",
  lineAnchor = Math.abs(tickRotate) >= 10 ? "middle" : anchor === "bottom" ? "top" : "bottom",
  fontVariant,
  inset: inset2 = 0,
  insetTop = inset2,
  insetBottom = inset2,
  dy = 0,
  x: x3 = k2 === "x" ? void 0 : null,
  ariaLabel: ariaLabel2,
  ...options
}) {
  return axisMark(
    textX,
    k2,
    data,
    { ariaLabel: `${ariaLabel2} tick label` },
    {
      facetAnchor,
      frameAnchor,
      text: text3 === void 0 ? null : text3,
      textAnchor,
      lineAnchor,
      fontVariant,
      rotate: tickRotate,
      x: x3,
      ...options,
      dy: anchor === "bottom" ? +dy + +tickSize + +tickPadding - insetBottom : +dy - tickSize - tickPadding + +insetTop
    },
    function(scale3, data2, ticks2, tickFormat2, channels) {
      if (fontVariant === void 0) this.fontVariant = inferFontVariant3(scale3);
      if (text3 === void 0) channels.text = inferTextChannel(scale3, data2, ticks2, tickFormat2, anchor);
    }
  );
}
function gridY() {
  const [data, options] = maybeData(...arguments);
  return gridKy("y", anchorY2(options), data, options);
}
function gridFy() {
  const [data, options] = maybeData(...arguments);
  return gridKy("fy", anchorFy(options), data, options);
}
function gridX() {
  const [data, options] = maybeData(...arguments);
  return gridKx("x", anchorX2(options), data, options);
}
function gridFx() {
  const [data, options] = maybeData(...arguments);
  return gridKx("fx", anchorFx(options), data, options);
}
function gridKy(k2, anchor, data, {
  y: y3 = k2 === "y" ? void 0 : null,
  x: x3 = null,
  x1: x12 = anchor === "left" ? x3 : null,
  x2: x22 = anchor === "right" ? x3 : null,
  ariaLabel: ariaLabel2 = `${k2}-grid`,
  ariaHidden = true,
  ...options
}) {
  return axisMark(ruleY, k2, data, { ariaLabel: ariaLabel2, ariaHidden }, { y: y3, x1: x12, x2: x22, ...gridDefaults(options) });
}
function gridKx(k2, anchor, data, {
  x: x3 = k2 === "x" ? void 0 : null,
  y: y3 = null,
  y1: y12 = anchor === "top" ? y3 : null,
  y2: y22 = anchor === "bottom" ? y3 : null,
  ariaLabel: ariaLabel2 = `${k2}-grid`,
  ariaHidden = true,
  ...options
}) {
  return axisMark(ruleX, k2, data, { ariaLabel: ariaLabel2, ariaHidden }, { x: x3, y1: y12, y2: y22, ...gridDefaults(options) });
}
function gridDefaults({
  color: color3 = "currentColor",
  opacity: opacity2 = 0.1,
  stroke = color3,
  strokeOpacity = opacity2,
  strokeWidth = 1,
  ...options
}) {
  return { stroke, strokeOpacity, strokeWidth, ...options };
}
function labelOptions({
  fill,
  fillOpacity,
  fontFamily,
  fontSize,
  fontStyle,
  fontVariant,
  fontWeight,
  monospace,
  pointerEvents,
  shapeRendering,
  clip: clip2 = false
}, initializer2) {
  [, fill] = maybeColorChannel(fill);
  [, fillOpacity] = maybeNumberChannel(fillOpacity);
  return {
    facet: "super",
    x: null,
    y: null,
    fill,
    fillOpacity,
    fontFamily,
    fontSize,
    fontStyle,
    fontVariant,
    fontWeight,
    monospace,
    pointerEvents,
    shapeRendering,
    clip: clip2,
    initializer: initializer2
  };
}
function axisMark(mark2, k2, data, properties, options, initialize) {
  let channels;
  function axisInitializer(data2, facets, _channels, scales2, dimensions, context) {
    const initializeFacets = data2 == null && (k2 === "fx" || k2 === "fy");
    const { [k2]: scale3 } = scales2;
    if (!scale3) throw new Error(`missing scale: ${k2}`);
    const domain = scale3.domain();
    let { interval: interval4, ticks: ticks2, tickFormat: tickFormat2, tickSpacing = k2 === "x" ? 80 : 35 } = options;
    if (typeof ticks2 === "string" && hasTemporalDomain(scale3)) interval4 = ticks2, ticks2 = void 0;
    if (ticks2 === void 0) ticks2 = maybeRangeInterval(interval4, scale3.type) ?? inferTickCount(scale3, tickSpacing);
    if (data2 == null) {
      if (isIterable2(ticks2)) {
        data2 = arrayify2(ticks2);
      } else if (isInterval(ticks2)) {
        data2 = inclusiveRange(ticks2, ...extent(domain));
      } else if (scale3.interval) {
        let interval5 = scale3.interval;
        if (scale3.ticks) {
          const [min5, max4] = extent(domain);
          const n = (max4 - min5) / interval5[intervalDuration];
          interval5 = generalizeTimeInterval(interval5, n / ticks2) ?? interval5;
          data2 = inclusiveRange(interval5, min5, max4);
        } else {
          data2 = domain;
          const n = data2.length;
          interval5 = generalizeTimeInterval(interval5, n / ticks2) ?? interval5;
          if (interval5 !== scale3.interval) data2 = inclusiveRange(interval5, ...extent(data2));
        }
        if (interval5 === scale3.interval) {
          const n = Math.round(data2.length / ticks2);
          if (n > 1) data2 = data2.filter((d, i) => i % n === 0);
        }
      } else if (scale3.ticks) {
        data2 = scale3.ticks(ticks2);
      } else {
        data2 = domain;
      }
      if (!scale3.ticks && data2.length && data2 !== domain) {
        const domainSet = new InternSet(domain);
        data2 = data2.filter((d) => domainSet.has(d));
        if (!data2.length) warn(`Warning: the ${k2}-axis ticks appear to not align with the scale domain, resulting in no ticks. Try different ticks?`);
      }
      if (k2 === "y" || k2 === "x") {
        facets = [range2(data2)];
      } else {
        channels[k2] = { scale: k2, value: identity8 };
      }
    }
    initialize?.call(this, scale3, data2, ticks2, tickFormat2, channels);
    const initializedChannels = Object.fromEntries(
      Object.entries(channels).map(([name2, channel]) => {
        return [name2, { ...channel, value: valueof(data2, channel.value) }];
      })
    );
    if (initializeFacets) facets = context.filterFacets(data2, initializedChannels);
    return { data: data2, facets, channels: initializedChannels };
  }
  const basicInitializer = initializer(options).initializer;
  const m = mark2(data, initializer({ ...options, initializer: axisInitializer }, basicInitializer));
  if (data == null) {
    channels = m.channels;
    m.channels = {};
  } else {
    channels = {};
  }
  if (properties !== void 0) Object.assign(m, properties);
  if (m.clip === void 0) m.clip = false;
  return m;
}
function inferTickCount(scale3, tickSpacing) {
  const [min5, max4] = extent(scale3.range());
  return (max4 - min5) / tickSpacing;
}
function inferTextChannel(scale3, data, ticks2, tickFormat2, anchor) {
  return { value: inferTickFormat(scale3, data, ticks2, tickFormat2, anchor) };
}
function inferTickFormat(scale3, data, ticks2, tickFormat2, anchor) {
  return typeof tickFormat2 === "function" && !(scale3.type === "log" && scale3.tickFormat) ? tickFormat2 : tickFormat2 === void 0 && data && isTemporal(data) ? inferTimeFormat(scale3.type, data, anchor) ?? formatDefault : scale3.tickFormat ? scale3.tickFormat(typeof ticks2 === "number" ? ticks2 : null, tickFormat2) : typeof tickFormat2 === "string" && scale3.domain().length > 0 ? (isTemporal(scale3.domain()) ? utcFormat : format)(tickFormat2) : tickFormat2 === void 0 ? formatDefault : constant(tickFormat2);
}
function inclusiveRange(interval4, min5, max4) {
  return interval4.range(min5, interval4.offset(interval4.floor(max4)));
}
var shapeTickBottom = {
  draw(context, l) {
    context.moveTo(0, 0);
    context.lineTo(0, l);
  }
};
var shapeTickTop = {
  draw(context, l) {
    context.moveTo(0, 0);
    context.lineTo(0, -l);
  }
};
var shapeTickLeft = {
  draw(context, l) {
    context.moveTo(0, 0);
    context.lineTo(-l, 0);
  }
};
var shapeTickRight = {
  draw(context, l) {
    context.moveTo(0, 0);
    context.lineTo(l, 0);
  }
};
function inferFontVariant3(scale3) {
  return scale3.bandwidth && !scale3.interval ? void 0 : "tabular-nums";
}
function formatAxisLabel(k2, scale3, { anchor, label = scale3.label, labelAnchor, labelArrow } = {}) {
  if (label == null || label.inferred && hasTemporalDomain(scale3) && /^(date|time|year)$/i.test(label)) return;
  label = String(label);
  if (labelArrow === "auto") labelArrow = (!scale3.bandwidth || scale3.interval) && !/[↑↓→←]/.test(label);
  if (!labelArrow) return label;
  if (labelArrow === true) {
    const order = inferScaleOrder(scale3);
    if (order)
      labelArrow = /x$/.test(k2) || labelAnchor === "center" ? /x$/.test(k2) === order < 0 ? "left" : "right" : order < 0 ? "up" : "down";
  }
  switch (labelArrow) {
    case "left":
      return `\u2190 ${label}`;
    case "right":
      return `${label} \u2192`;
    case "up":
      return anchor === "right" ? `${label} \u2191` : `\u2191 ${label}`;
    case "down":
      return anchor === "right" ? `${label} \u2193` : `\u2193 ${label}`;
  }
  return label;
}
function maybeLabelArrow(labelArrow = "auto") {
  return isNoneish(labelArrow) ? false : typeof labelArrow === "boolean" ? labelArrow : keyword(labelArrow, "labelArrow", ["auto", "up", "right", "down", "left"]);
}
function hasTemporalDomain(scale3) {
  return isTemporal(scale3.domain());
}

// ../../../node_modules/@observablehq/plot/src/legends/swatches.js
function maybeScale(scale3, key) {
  if (key == null) return key;
  const s2 = scale3(key);
  if (!s2) throw new Error(`scale not found: ${key}`);
  return s2;
}
function legendSwatches(color3, { opacity: opacity2, ...options } = {}) {
  if (!isOrdinalScale(color3) && !isThresholdScale(color3))
    throw new Error(`swatches legend requires ordinal or threshold color scale (not ${color3.type})`);
  return legendItems(
    color3,
    options,
    (selection2, scale3, width2, height2) => selection2.append("svg").attr("width", width2).attr("height", height2).attr("fill", scale3.scale).attr("fill-opacity", maybeNumberChannel(opacity2)[1]).append("rect").attr("width", "100%").attr("height", "100%")
  );
}
function legendSymbols(symbol2, {
  fill = symbol2.hint?.fill !== void 0 ? symbol2.hint.fill : "none",
  fillOpacity = 1,
  stroke = symbol2.hint?.stroke !== void 0 ? symbol2.hint.stroke : isNoneish(fill) ? "currentColor" : "none",
  strokeOpacity = 1,
  strokeWidth = 1.5,
  r = 4.5,
  ...options
} = {}, scale3) {
  const [vf, cf] = maybeColorChannel(fill);
  const [vs, cs] = maybeColorChannel(stroke);
  const sf = maybeScale(scale3, vf);
  const ss = maybeScale(scale3, vs);
  const size = r * r * Math.PI;
  fillOpacity = maybeNumberChannel(fillOpacity)[1];
  strokeOpacity = maybeNumberChannel(strokeOpacity)[1];
  strokeWidth = maybeNumberChannel(strokeWidth)[1];
  return legendItems(
    symbol2,
    options,
    (selection2, scale4, width2, height2) => selection2.append("svg").attr("viewBox", "-8 -8 16 16").attr("width", width2).attr("height", height2).attr("fill", vf === "color" ? (d) => sf.scale(d) : cf).attr("fill-opacity", fillOpacity).attr("stroke", vs === "color" ? (d) => ss.scale(d) : cs).attr("stroke-opacity", strokeOpacity).attr("stroke-width", strokeWidth).append("path").attr("d", (d) => {
      const p = pathRound();
      symbol2.scale(d).draw(p, size);
      return p;
    })
  );
}
function legendItems(scale3, options = {}, swatch) {
  let {
    columns,
    tickFormat: tickFormat2,
    fontVariant = inferFontVariant(scale3),
    // TODO label,
    swatchSize = 15,
    swatchWidth = swatchSize,
    swatchHeight = swatchSize,
    marginLeft: marginLeft2 = 0,
    className,
    style: style2,
    width: width2
  } = options;
  const context = createContext(options);
  className = maybeClassName(className);
  tickFormat2 = inferTickFormat(scale3.scale, scale3.domain, void 0, tickFormat2);
  const swatches = create3("div", context).attr(
    "class",
    `${className}-swatches ${className}-swatches-${columns != null ? "columns" : "wrap"}`
  );
  let extraStyle;
  if (columns != null) {
    extraStyle = `:where(.${className}-swatches-columns .${className}-swatch) {
  display: flex;
  align-items: center;
  break-inside: avoid;
  padding-bottom: 1px;
}
:where(.${className}-swatches-columns .${className}-swatch::before) {
  flex-shrink: 0;
}
:where(.${className}-swatches-columns .${className}-swatch-label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}`;
    swatches.style("columns", columns).selectAll().data(scale3.domain).enter().append("div").attr("class", `${className}-swatch`).call(swatch, scale3, swatchWidth, swatchHeight).call(
      (item) => item.append("div").attr("class", `${className}-swatch-label`).attr("title", tickFormat2).text(tickFormat2)
    );
  } else {
    extraStyle = `:where(.${className}-swatches-wrap) {
  display: flex;
  align-items: center;
  min-height: 33px;
  flex-wrap: wrap;
}
:where(.${className}-swatches-wrap .${className}-swatch) {
  display: inline-flex;
  align-items: center;
  margin-right: 1em;
}`;
    swatches.selectAll().data(scale3.domain).enter().append("span").attr("class", `${className}-swatch`).call(swatch, scale3, swatchWidth, swatchHeight).append(function() {
      return this.ownerDocument.createTextNode(tickFormat2.apply(this, arguments));
    });
  }
  return swatches.call(
    (div2) => div2.insert("style", "*").text(
      `:where(.${className}-swatches) {
  font-family: system-ui, sans-serif;
  font-size: 10px;
  margin-bottom: 0.5em;
}
:where(.${className}-swatch > svg) {
  margin-right: 0.5em;
  overflow: visible;
}
${extraStyle}`
    )
  ).style("margin-left", marginLeft2 ? `${+marginLeft2}px` : null).style("width", width2 === void 0 ? null : `${+width2}px`).style("font-variant", impliedString(fontVariant, "normal")).call(applyInlineStyles, style2).node();
}

// ../../../node_modules/@observablehq/plot/src/legends.js
var legendRegistry = /* @__PURE__ */ new Map([
  ["symbol", legendSymbols],
  ["color", legendColor],
  ["opacity", legendOpacity]
]);
function legend(options = {}) {
  for (const [key, value] of legendRegistry) {
    const scale3 = options[key];
    if (isScaleOptions(scale3)) {
      const context = createContext(options);
      let hint;
      if (key === "symbol") {
        const { fill, stroke = fill === void 0 && isScaleOptions(options.color) ? "color" : void 0 } = options;
        hint = { fill, stroke };
      }
      return value(
        normalizeScale(key, scale3, hint),
        legendOptions(context, scale3, options),
        (key2) => isScaleOptions(options[key2]) ? normalizeScale(key2, options[key2]) : null
      );
    }
  }
  throw new Error("unknown legend type; no scale found");
}
function exposeLegends(scales2, context, defaults22 = {}) {
  return (key, options) => {
    if (!legendRegistry.has(key)) throw new Error(`unknown legend type: ${key}`);
    if (!(key in scales2)) return;
    return legendRegistry.get(key)(scales2[key], legendOptions(context, defaults22[key], options), (key2) => scales2[key2]);
  };
}
function legendOptions({ className, ...context }, { label, ticks: ticks2, tickFormat: tickFormat2 } = {}, options) {
  return inherit2(options, { className, ...context }, { label, ticks: ticks2, tickFormat: tickFormat2 });
}
function legendColor(color3, { legend: legend3 = true, ...options }) {
  if (legend3 === true) legend3 = color3.type === "ordinal" ? "swatches" : "ramp";
  if (color3.domain === void 0) return;
  switch (`${legend3}`.toLowerCase()) {
    case "swatches":
      return legendSwatches(color3, options);
    case "ramp":
      return legendRamp(color3, options);
    default:
      throw new Error(`unknown legend type: ${legend3}`);
  }
}
function legendOpacity({ type: type2, interpolate, ...scale3 }, { legend: legend3 = true, color: color3 = rgb(0, 0, 0), ...options }) {
  if (!interpolate) throw new Error(`${type2} opacity scales are not supported`);
  if (legend3 === true) legend3 = "ramp";
  if (`${legend3}`.toLowerCase() !== "ramp") throw new Error(`${legend3} opacity legends are not supported`);
  return legendColor({ type: type2, ...scale3, interpolate: interpolateOpacity(color3) }, { legend: legend3, ...options });
}
function interpolateOpacity(color3) {
  const { r, g, b } = rgb(color3) || rgb(0, 0, 0);
  return (t) => `rgba(${r},${g},${b},${t})`;
}
function createLegends(scales2, context, options) {
  const legends = [];
  for (const [key, value] of legendRegistry) {
    const o = options[key];
    if (o?.legend && key in scales2) {
      const legend3 = value(scales2[key], legendOptions(context, scales2[key], o), (key2) => scales2[key2]);
      if (legend3 != null) legends.push(legend3);
    }
  }
  return legends;
}

// ../../../node_modules/@observablehq/plot/src/transforms/identity.js
function maybeIdentityX(options = {}, k2 = "x") {
  return hasX(options) ? options : { ...options, [k2]: identity8 };
}
function maybeIdentityY(options = {}, k2 = "y") {
  return hasY(options) ? options : { ...options, [k2]: identity8 };
}

// ../../../node_modules/@observablehq/plot/src/transforms/exclusiveFacets.js
function exclusiveFacets(data, facets) {
  if (facets.length === 1) return { data, facets };
  const n = lengthof(data);
  const O = new Uint8Array(n);
  let overlaps = 0;
  for (const facet of facets) {
    for (const i of facet) {
      if (O[i]) ++overlaps;
      O[i] = 1;
    }
  }
  if (overlaps === 0) return { data, facets };
  data = slice3(data);
  const R = data[reindex] = new Uint32Array(n + overlaps);
  facets = facets.map((facet) => slice3(facet, Uint32Array));
  let j = n;
  O.fill(0);
  for (const facet of facets) {
    for (let k2 = 0, m = facet.length; k2 < m; ++k2) {
      const i = facet[k2];
      if (O[i]) facet[k2] = j, data[j] = data[i], R[j] = i, ++j;
      else R[i] = i;
      O[i] = 1;
    }
  }
  return { data, facets };
}

// ../../../node_modules/@observablehq/plot/src/transforms/stack.js
function stackX(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { y1: y12, y: y3 = y12, x: x3, ...rest } = options;
  const [transform3, Y3, x12, x22] = stack(y3, x3, "y", "x", stackOptions, rest);
  return { ...transform3, y1: y12, y: Y3, x1: x12, x2: x22, x: mid(x12, x22) };
}
function stackX1(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { y1: y12, y: y3 = y12, x: x3 } = options;
  const [transform3, Y3, X3] = stack(y3, x3, "y", "x", stackOptions, options);
  return { ...transform3, y1: y12, y: Y3, x: X3 };
}
function stackX2(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { y1: y12, y: y3 = y12, x: x3 } = options;
  const [transform3, Y3, , X3] = stack(y3, x3, "y", "x", stackOptions, options);
  return { ...transform3, y1: y12, y: Y3, x: X3 };
}
function stackY(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { x1: x12, x: x3 = x12, y: y3, ...rest } = options;
  const [transform3, X3, y12, y22] = stack(x3, y3, "x", "y", stackOptions, rest);
  return { ...transform3, x1: x12, x: X3, y1: y12, y2: y22, y: mid(y12, y22) };
}
function stackY1(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { x1: x12, x: x3 = x12, y: y3 } = options;
  const [transform3, X3, Y3] = stack(x3, y3, "x", "y", stackOptions, options);
  return { ...transform3, x1: x12, x: X3, y: Y3 };
}
function stackY2(stackOptions = {}, options = {}) {
  if (arguments.length === 1) [stackOptions, options] = mergeOptions(stackOptions);
  const { x1: x12, x: x3 = x12, y: y3 } = options;
  const [transform3, X3, , Y3] = stack(x3, y3, "x", "y", stackOptions, options);
  return { ...transform3, x1: x12, x: X3, y: Y3 };
}
function maybeStackX({ x: x3, x1: x12, x2: x22, ...options } = {}) {
  options = withTip(options, "y");
  if (x12 === void 0 && x22 === void 0) return stackX({ x: x3, ...options });
  [x12, x22] = maybeZero(x3, x12, x22);
  return { ...options, x1: x12, x2: x22 };
}
function maybeStackY({ y: y3, y1: y12, y2: y22, ...options } = {}) {
  options = withTip(options, "x");
  if (y12 === void 0 && y22 === void 0) return stackY({ y: y3, ...options });
  [y12, y22] = maybeZero(y3, y12, y22);
  return { ...options, y1: y12, y2: y22 };
}
function mergeOptions(options) {
  const { offset: offset2, order, reverse: reverse3, ...rest } = options;
  return [{ offset: offset2, order, reverse: reverse3 }, rest];
}
var lengthy = { length: true };
function stack(x3, y3 = one2, kx2, ky2, { offset: offset2, order, reverse: reverse3 }, options) {
  if (y3 === null) throw new Error(`stack requires ${ky2}`);
  const z = maybeZ(options);
  const [X3, setX] = maybeColumn(x3);
  const [Y13, setY1] = column2(y3);
  const [Y23, setY2] = column2(y3);
  Y13.hint = Y23.hint = lengthy;
  offset2 = maybeOffset(offset2);
  order = maybeOrder2(order, offset2, ky2);
  return [
    basic(options, (data, facets, plotOptions) => {
      ({ data, facets } = exclusiveFacets(data, facets));
      const X4 = x3 == null ? void 0 : setX(maybeApplyInterval(valueof(data, x3), plotOptions?.[kx2]));
      const Y3 = valueof(data, y3, Float64Array);
      const Z = valueof(data, z);
      const compare = order && order(data, X4, Y3, Z);
      const n = lengthof(data);
      const Y14 = setY1(new Float64Array(n));
      const Y24 = setY2(new Float64Array(n));
      const facetstacks = [];
      for (const facet of facets) {
        const stacks = X4 ? Array.from(group(facet, (i) => X4[i]).values()) : [facet];
        if (compare) for (const stack2 of stacks) stack2.sort(compare);
        for (const stack2 of stacks) {
          let yn = 0;
          let yp = 0;
          if (reverse3) stack2.reverse();
          for (const i of stack2) {
            const y4 = Y3[i];
            if (y4 < 0) yn = Y24[i] = (Y14[i] = yn) + y4;
            else if (y4 > 0) yp = Y24[i] = (Y14[i] = yp) + y4;
            else Y24[i] = Y14[i] = yp;
          }
        }
        facetstacks.push(stacks);
      }
      if (offset2) offset2(facetstacks, Y14, Y24, Z);
      return { data, facets };
    }),
    X3,
    Y13,
    Y23
  ];
}
function maybeOffset(offset2) {
  if (offset2 == null) return;
  if (typeof offset2 === "function") return offset2;
  switch (`${offset2}`.toLowerCase()) {
    case "expand":
    case "normalize":
      return offsetExpand;
    case "center":
    case "silhouette":
      return offsetCenter;
    case "wiggle":
      return offsetWiggle;
  }
  throw new Error(`unknown offset: ${offset2}`);
}
function extent2(stack2, Y23) {
  let min5 = 0, max4 = 0;
  for (const i of stack2) {
    const y3 = Y23[i];
    if (y3 < min5) min5 = y3;
    if (y3 > max4) max4 = y3;
  }
  return [min5, max4];
}
function offsetExpand(facetstacks, Y13, Y23) {
  for (const stacks of facetstacks) {
    for (const stack2 of stacks) {
      const [yn, yp] = extent2(stack2, Y23);
      for (const i of stack2) {
        const m = 1 / (yp - yn || 1);
        Y13[i] = m * (Y13[i] - yn);
        Y23[i] = m * (Y23[i] - yn);
      }
    }
  }
}
function offsetCenter(facetstacks, Y13, Y23) {
  for (const stacks of facetstacks) {
    for (const stack2 of stacks) {
      const [yn, yp] = extent2(stack2, Y23);
      for (const i of stack2) {
        const m = (yp + yn) / 2;
        Y13[i] -= m;
        Y23[i] -= m;
      }
    }
    offsetZero(stacks, Y13, Y23);
  }
  offsetCenterFacets(facetstacks, Y13, Y23);
}
function offsetWiggle(facetstacks, Y13, Y23, Z) {
  for (const stacks of facetstacks) {
    const prev = new InternMap();
    let y3 = 0;
    for (const stack2 of stacks) {
      let j = -1;
      const Fi = stack2.map((i) => Math.abs(Y23[i] - Y13[i]));
      const Df = stack2.map((i) => {
        j = Z ? Z[i] : ++j;
        const value = Y23[i] - Y13[i];
        const diff = prev.has(j) ? value - prev.get(j) : 0;
        prev.set(j, value);
        return diff;
      });
      const Cf1 = [0, ...cumsum(Df)];
      for (const i of stack2) {
        Y13[i] += y3;
        Y23[i] += y3;
      }
      const s1 = sum2(Fi);
      if (s1) y3 -= sum2(Fi, (d, i) => (Df[i] / 2 + Cf1[i]) * d) / s1;
    }
    offsetZero(stacks, Y13, Y23);
  }
  offsetCenterFacets(facetstacks, Y13, Y23);
}
function offsetZero(stacks, Y13, Y23) {
  const m = min2(stacks, (stack2) => min2(stack2, (i) => Y13[i]));
  for (const stack2 of stacks) {
    for (const i of stack2) {
      Y13[i] -= m;
      Y23[i] -= m;
    }
  }
}
function offsetCenterFacets(facetstacks, Y13, Y23) {
  const n = facetstacks.length;
  if (n === 1) return;
  const facets = facetstacks.map((stacks) => stacks.flat());
  const m = facets.map((I) => (min2(I, (i) => Y13[i]) + max2(I, (i) => Y23[i])) / 2);
  const m0 = min2(m);
  for (let j = 0; j < n; j++) {
    const p = m0 - m[j];
    for (const i of facets[j]) {
      Y13[i] += p;
      Y23[i] += p;
    }
  }
}
function maybeOrder2(order, offset2, ky2) {
  if (order === void 0 && offset2 === offsetWiggle) return orderInsideOut(ascendingDefined2);
  if (order == null) return;
  if (typeof order === "string") {
    const negate2 = order.startsWith("-");
    const compare = negate2 ? descendingDefined : ascendingDefined2;
    switch ((negate2 ? order.slice(1) : order).toLowerCase()) {
      case "value":
      case ky2:
        return orderY(compare);
      case "z":
        return orderZ(compare);
      case "sum":
        return orderSum(compare);
      case "appearance":
        return orderAppearance(compare);
      case "inside-out":
        return orderInsideOut(compare);
    }
    return orderAccessor(field2(order));
  }
  if (typeof order === "function") return (order.length === 1 ? orderAccessor : orderComparator)(order);
  if (isArray3(order)) return orderGiven(order);
  throw new Error(`invalid order: ${order}`);
}
function orderY(compare) {
  return (data, X3, Y3) => (i, j) => compare(Y3[i], Y3[j]);
}
function orderZ(compare) {
  return (data, X3, Y3, Z) => (i, j) => compare(Z[i], Z[j]);
}
function orderSum(compare) {
  return orderZDomain(
    compare,
    (data, X3, Y3, Z) => groupSort(
      range2(data),
      (I) => sum2(I, (i) => Y3[i]),
      (i) => Z[i]
    )
  );
}
function orderAppearance(compare) {
  return orderZDomain(
    compare,
    (data, X3, Y3, Z) => groupSort(
      range2(data),
      (I) => X3[greatest2(I, (i) => Y3[i])],
      (i) => Z[i]
    )
  );
}
function orderInsideOut(compare) {
  return orderZDomain(compare, (data, X3, Y3, Z) => {
    const I = range2(data);
    const K2 = groupSort(
      I,
      (I2) => X3[greatest2(I2, (i) => Y3[i])],
      (i) => Z[i]
    );
    const sums = rollup(
      I,
      (I2) => sum2(I2, (i) => Y3[i]),
      (i) => Z[i]
    );
    const Kp = [], Kn = [];
    let s2 = 0;
    for (const k2 of K2) {
      if (s2 < 0) {
        s2 += sums.get(k2);
        Kp.push(k2);
      } else {
        s2 -= sums.get(k2);
        Kn.push(k2);
      }
    }
    return Kn.reverse().concat(Kp);
  });
}
function orderAccessor(f) {
  return (data) => {
    const O = valueof(data, f);
    return (i, j) => ascendingDefined2(O[i], O[j]);
  };
}
function orderComparator(f) {
  return (data) => {
    return isArray3(data) ? (i, j) => f(data[i], data[j]) : (i, j) => f(data.get(i), data.get(j));
  };
}
function orderGiven(domain) {
  return orderZDomain(ascendingDefined2, () => domain);
}
function orderZDomain(compare, domain) {
  return (data, X3, Y3, Z) => {
    if (!Z) throw new Error("missing channel: z");
    const map5 = new InternMap(domain(data, X3, Y3, Z).map((d, i) => [d, i]));
    return (i, j) => compare(map5.get(Z[i]), map5.get(Z[j]));
  };
}

// ../../../node_modules/@observablehq/plot/src/marks/rect.js
var defaults4 = {
  ariaLabel: "rect"
};
var Rect = class extends Mark {
  constructor(data, options = {}) {
    const { x1: x12, y1: y12, x2: x22, y2: y22 } = options;
    super(
      data,
      {
        x1: { value: x12, scale: "x", type: x12 != null && x22 == null ? "band" : void 0, optional: true },
        y1: { value: y12, scale: "y", type: y12 != null && y22 == null ? "band" : void 0, optional: true },
        x2: { value: x22, scale: "x", optional: true },
        y2: { value: y22, scale: "y", optional: true }
      },
      options,
      defaults4
    );
    rectInsets(this, options);
    rectRadii(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    let { x1: X13, y1: Y13, x2: X23, y2: Y23 } = channels;
    const { marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2, width: width2, height: height2 } = dimensions;
    const { projection: projection3 } = context;
    const { insetTop, insetRight, insetBottom, insetLeft } = this;
    const { rx, ry, rx1y1, rx1y2, rx2y1, rx2y2 } = this;
    if ((X13 || X23) && !projection3 && isCollapsed(x3)) X13 = X23 = null;
    if ((Y13 || Y23) && !projection3 && isCollapsed(y3)) Y13 = Y23 = null;
    const bx = x3?.bandwidth ? x3.bandwidth() : 0;
    const by = y3?.bandwidth ? y3.bandwidth() : 0;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, {}, 0, 0).call(
      (g) => g.selectAll().data(index2).enter().call(
        rx1y1 || rx1y2 || rx2y1 || rx2y2 ? (g2) => g2.append("path").call(applyDirectStyles, this).call(
          applyRoundedRect,
          X13 && X23 ? (i) => X13[i] + (X23[i] < X13[i] ? -insetRight : insetLeft) : X13 ? (i) => X13[i] + insetLeft : marginLeft2 + insetLeft,
          Y13 && Y23 ? (i) => Y13[i] + (Y23[i] < Y13[i] ? -insetBottom : insetTop) : Y13 ? (i) => Y13[i] + insetTop : marginTop2 + insetTop,
          X13 && X23 ? (i) => X23[i] - (X23[i] < X13[i] ? -insetLeft : insetRight) : X13 ? (i) => X13[i] + bx - insetRight : width2 - marginRight2 - insetRight,
          Y13 && Y23 ? (i) => Y23[i] - (Y23[i] < Y13[i] ? -insetTop : insetBottom) : Y13 ? (i) => Y13[i] + by - insetBottom : height2 - marginBottom2 - insetBottom,
          this
        ).call(applyChannelStyles, this, channels) : (g2) => g2.append("rect").call(applyDirectStyles, this).attr(
          "x",
          X13 ? X23 ? (i) => Math.min(X13[i], X23[i]) + insetLeft : (i) => X13[i] + insetLeft : marginLeft2 + insetLeft
        ).attr(
          "y",
          Y13 ? Y23 ? (i) => Math.min(Y13[i], Y23[i]) + insetTop : (i) => Y13[i] + insetTop : marginTop2 + insetTop
        ).attr(
          "width",
          X13 ? X23 ? (i) => Math.max(0, Math.abs(X23[i] - X13[i]) + bx - insetLeft - insetRight) : bx - insetLeft - insetRight : width2 - marginRight2 - marginLeft2 - insetRight - insetLeft
        ).attr(
          "height",
          Y13 ? Y23 ? (i) => Math.max(0, Math.abs(Y13[i] - Y23[i]) + by - insetTop - insetBottom) : by - insetTop - insetBottom : height2 - marginTop2 - marginBottom2 - insetTop - insetBottom
        ).call(applyAttr, "rx", rx).call(applyAttr, "ry", ry).call(applyChannelStyles, this, channels)
      )
    ).node();
  }
};
function rectInsets(mark2, { inset: inset2 = 0, insetTop = inset2, insetRight = inset2, insetBottom = inset2, insetLeft = inset2 } = {}) {
  mark2.insetTop = number5(insetTop);
  mark2.insetRight = number5(insetRight);
  mark2.insetBottom = number5(insetBottom);
  mark2.insetLeft = number5(insetLeft);
}
function rectRadii(mark2, {
  r,
  rx,
  // for elliptic corners
  ry,
  // for elliptic corners
  rx1 = r,
  ry1 = r,
  rx2 = r,
  ry2 = r,
  rx1y1 = rx1 !== void 0 ? +rx1 : ry1 !== void 0 ? +ry1 : 0,
  rx1y2 = rx1 !== void 0 ? +rx1 : ry2 !== void 0 ? +ry2 : 0,
  rx2y1 = rx2 !== void 0 ? +rx2 : ry1 !== void 0 ? +ry1 : 0,
  rx2y2 = rx2 !== void 0 ? +rx2 : ry2 !== void 0 ? +ry2 : 0
} = {}) {
  if (rx1y1 || rx1y2 || rx2y1 || rx2y2) {
    mark2.rx1y1 = rx1y1;
    mark2.rx1y2 = rx1y2;
    mark2.rx2y1 = rx2y1;
    mark2.rx2y2 = rx2y2;
  } else {
    mark2.rx = impliedString(rx, "auto");
    mark2.ry = impliedString(ry, "auto");
  }
}
function applyRoundedRect(selection2, X13, Y13, X23, Y23, mark2) {
  const { rx1y1: r11, rx1y2: r12, rx2y1: r21, rx2y2: r22 } = mark2;
  if (typeof X13 !== "function") X13 = constant(X13);
  if (typeof Y13 !== "function") Y13 = constant(Y13);
  if (typeof X23 !== "function") X23 = constant(X23);
  if (typeof Y23 !== "function") Y23 = constant(Y23);
  const rx = Math.max(Math.abs(r11 + r21), Math.abs(r12 + r22));
  const ry = Math.max(Math.abs(r11 + r12), Math.abs(r21 + r22));
  selection2.attr("d", (i) => {
    const x12 = X13(i);
    const y12 = Y13(i);
    const x22 = X23(i);
    const y22 = Y23(i);
    const ix = x12 > x22;
    const iy = y12 > y22;
    const l = ix ? x22 : x12;
    const r = ix ? x12 : x22;
    const t = iy ? y22 : y12;
    const b = iy ? y12 : y22;
    const k2 = Math.min(1, (r - l) / rx, (b - t) / ry);
    const tl = k2 * (ix ? iy ? r22 : r21 : iy ? r12 : r11);
    const tr = k2 * (ix ? iy ? r12 : r11 : iy ? r22 : r21);
    const br = k2 * (ix ? iy ? r11 : r12 : iy ? r21 : r22);
    const bl = k2 * (ix ? iy ? r21 : r22 : iy ? r11 : r12);
    return `M${l},${t + biasY(tl, bl)}A${tl},${tl} 0 0 ${tl < 0 ? 0 : 1} ${l + biasX(tl, bl)},${t}H${r - biasX(tr, br)}A${tr},${tr} 0 0 ${tr < 0 ? 0 : 1} ${r},${t + biasY(tr, br)}V${b - biasY(br, tr)}A${br},${br} 0 0 ${br < 0 ? 0 : 1} ${r - biasX(br, tr)},${b}H${l + biasX(bl, tl)}A${bl},${bl} 0 0 ${bl < 0 ? 0 : 1} ${l},${b - biasY(bl, tl)}Z`;
  });
}
function biasX(r1, r2) {
  return r2 < 0 ? r1 : Math.abs(r1);
}
function biasY(r1, r2) {
  return r2 < 0 ? Math.abs(r1) : r1;
}
function rect(data, options) {
  return new Rect(data, maybeTrivialIntervalX(maybeTrivialIntervalY(options)));
}
function rectX(data, options = {}) {
  if (!hasXY(options)) options = { ...options, y: indexOf, x2: identity8, interval: 1 };
  return new Rect(data, maybeStackX(maybeTrivialIntervalY(maybeIdentityX(options))));
}
function rectY(data, options = {}) {
  if (!hasXY(options)) options = { ...options, x: indexOf, y2: identity8, interval: 1 };
  return new Rect(data, maybeStackY(maybeTrivialIntervalX(maybeIdentityY(options))));
}

// ../../../node_modules/@observablehq/plot/src/marks/frame.js
var defaults5 = {
  ariaLabel: "frame",
  fill: "none",
  stroke: "currentColor",
  clip: false
};
var lineDefaults = {
  ariaLabel: "frame",
  fill: null,
  stroke: "currentColor",
  strokeLinecap: "square",
  clip: false
};
var Frame = class extends Mark {
  constructor(options = {}) {
    const { anchor = null } = options;
    super(singleton, void 0, options, anchor == null ? defaults5 : lineDefaults);
    this.anchor = maybeKeyword(anchor, "anchor", ["top", "right", "bottom", "left"]);
    rectInsets(this, options);
    if (!anchor) rectRadii(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2, width: width2, height: height2 } = dimensions;
    const { anchor, insetTop, insetRight, insetBottom, insetLeft } = this;
    const { rx, ry, rx1y1, rx1y2, rx2y1, rx2y2 } = this;
    const x12 = marginLeft2 + insetLeft;
    const x22 = width2 - marginRight2 - insetRight;
    const y12 = marginTop2 + insetTop;
    const y22 = height2 - marginBottom2 - insetBottom;
    return create3(anchor ? "svg:line" : rx1y1 || rx1y2 || rx2y1 || rx2y2 ? "svg:path" : "svg:rect", context).datum(0).call(applyIndirectStyles, this, dimensions, context).call(applyDirectStyles, this).call(applyChannelStyles, this, channels).call(applyTransform, this, {}).call(
      anchor === "left" ? (line3) => line3.attr("x1", x12).attr("x2", x12).attr("y1", y12).attr("y2", y22) : anchor === "right" ? (line3) => line3.attr("x1", x22).attr("x2", x22).attr("y1", y12).attr("y2", y22) : anchor === "top" ? (line3) => line3.attr("x1", x12).attr("x2", x22).attr("y1", y12).attr("y2", y12) : anchor === "bottom" ? (line3) => line3.attr("x1", x12).attr("x2", x22).attr("y1", y22).attr("y2", y22) : rx1y1 || rx1y2 || rx2y1 || rx2y2 ? (path2) => path2.call(applyRoundedRect, x12, y12, x22, y22, this) : (rect3) => rect3.attr("x", x12).attr("y", y12).attr("width", x22 - x12).attr("height", y22 - y12).attr("rx", rx).attr("ry", ry)
    ).node();
  }
};
function frame2(options) {
  return new Frame(options);
}

// ../../../node_modules/@observablehq/plot/src/marks/tip.js
var defaults6 = {
  ariaLabel: "tip",
  fill: "var(--plot-background)",
  stroke: "currentColor"
};
var ignoreChannels = /* @__PURE__ */ new Set(["geometry", "href", "src", "ariaLabel", "scales"]);
var Tip = class extends Mark {
  constructor(data, options = {}) {
    if (options.tip) options = { ...options, tip: false };
    if (options.title === void 0 && isIterable2(data) && isTextual(data)) options = { ...options, title: identity8 };
    const {
      x: x3,
      y: y3,
      x1: x12,
      x2: x22,
      y1: y12,
      y2: y22,
      anchor,
      preferredAnchor = "bottom",
      monospace,
      fontFamily = monospace ? "ui-monospace, monospace" : void 0,
      fontSize,
      fontStyle,
      fontVariant,
      fontWeight,
      lineHeight = 1,
      lineWidth = 20,
      frameAnchor,
      format: format3,
      textAnchor = "start",
      textOverflow,
      textPadding = 8,
      title,
      pointerSize = 12,
      pathFilter = "drop-shadow(0 3px 4px rgba(0,0,0,0.2))"
    } = options;
    super(
      data,
      {
        x: { value: x12 != null && x22 != null ? null : x3, scale: "x", optional: true },
        // ignore midpoint
        y: { value: y12 != null && y22 != null ? null : y3, scale: "y", optional: true },
        // ignore midpoint
        x1: { value: x12, scale: "x", optional: x22 == null },
        y1: { value: y12, scale: "y", optional: y22 == null },
        x2: { value: x22, scale: "x", optional: x12 == null },
        y2: { value: y22, scale: "y", optional: y12 == null },
        title: { value: title, optional: true }
        // filter: defined
      },
      options,
      defaults6
    );
    this.anchor = maybeAnchor(anchor, "anchor");
    this.preferredAnchor = maybeAnchor(preferredAnchor, "preferredAnchor");
    this.frameAnchor = maybeFrameAnchor(frameAnchor);
    this.textAnchor = impliedString(textAnchor, "middle");
    this.textPadding = +textPadding;
    this.pointerSize = +pointerSize;
    this.pathFilter = string(pathFilter);
    this.lineHeight = +lineHeight;
    this.lineWidth = +lineWidth;
    this.textOverflow = maybeTextOverflow(textOverflow);
    this.monospace = !!monospace;
    this.fontFamily = string(fontFamily);
    this.fontSize = number5(fontSize);
    this.fontStyle = string(fontStyle);
    this.fontVariant = string(fontVariant);
    this.fontWeight = string(fontWeight);
    for (const key in defaults6) if (key in this.channels) this[key] = defaults6[key];
    this.splitLines = splitter2(this);
    this.clipLine = clipper(this);
    this.format = typeof format3 === "string" || typeof format3 === "function" ? { title: format3 } : { ...format3 };
  }
  render(index2, scales2, values2, dimensions, context) {
    const mark2 = this;
    const { x: x3, y: y3, fx, fy } = scales2;
    const { ownerSVGElement: svg, document: document2 } = context;
    const { anchor, monospace, lineHeight, lineWidth } = this;
    const { textPadding: r, pointerSize: m, pathFilter } = this;
    const { marginTop: marginTop2, marginLeft: marginLeft2 } = dimensions;
    const { x1: X13, y1: Y13, x2: X23, y2: Y23, x: X3 = X13 ?? X23, y: Y3 = Y13 ?? Y23 } = values2;
    const ox2 = fx ? fx(index2.fx) - marginLeft2 : 0;
    const oy2 = fy ? fy(index2.fy) - marginTop2 : 0;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    const px = anchorX(values2, cx);
    const py = anchorY(values2, cy);
    const widthof2 = monospace ? monospaceWidth : defaultWidth;
    const ee = widthof2(ellipsis);
    let sources, format3;
    if ("title" in values2) {
      sources = getSourceChannels.call(this, { title: values2.channels.title }, scales2);
      format3 = formatTitle;
    } else {
      sources = getSourceChannels.call(this, values2.channels, scales2);
      format3 = formatChannels;
    }
    const g = create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyIndirectTextStyles, this).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      (g2) => g2.selectAll().data(index2).enter().append("g").attr("transform", (i) => `translate(${Math.round(px(i))},${Math.round(py(i))})`).call(applyDirectStyles, this).call((g3) => g3.append("path").attr("filter", pathFilter)).call(
        (g3) => g3.append("text").each(function(i) {
          const that = select_default2(this);
          this.setAttribute("fill", "currentColor");
          this.setAttribute("fill-opacity", 1);
          this.setAttribute("stroke", "none");
          const lines = format3.call(mark2, i, index2, sources, scales2, values2);
          if (typeof lines === "string") {
            for (const line3 of mark2.splitLines(lines)) {
              renderLine(that, { value: mark2.clipLine(line3) });
            }
          } else {
            const labels = /* @__PURE__ */ new Set();
            for (const line3 of lines) {
              const { label = "" } = line3;
              if (label && labels.has(label)) continue;
              else labels.add(label);
              renderLine(that, line3);
            }
          }
        })
      )
    );
    function renderLine(selection2, { label, value, color: color3, opacity: opacity2 }) {
      label ??= "", value ??= "";
      const swatch = color3 != null || opacity2 != null;
      let title;
      let w = lineWidth * 100;
      const [j] = cut(label, w, widthof2, ee);
      if (j >= 0) {
        label = label.slice(0, j).trimEnd() + ellipsis;
        title = value.trim();
        value = "";
      } else {
        if (label || !value && !swatch) value = " " + value;
        const [k2] = cut(value, w - widthof2(label), widthof2, ee);
        if (k2 >= 0) {
          title = value.trim();
          value = value.slice(0, k2).trimEnd() + ellipsis;
        }
      }
      const line3 = selection2.append("tspan").attr("x", 0).attr("dy", `${lineHeight}em`).text("\u200B");
      if (label) line3.append("tspan").attr("font-weight", "bold").text(label);
      if (value) line3.append(() => document2.createTextNode(value));
      if (swatch) line3.append("tspan").text(" \u25A0").attr("fill", color3).attr("fill-opacity", opacity2).style("user-select", "none");
      if (title) line3.append("title").text(title);
    }
    function postrender() {
      const { width: width2, height: height2 } = dimensions.facet ?? dimensions;
      g.selectChildren().each(function(i) {
        let { x: tx, width: w, height: h } = this.getBBox();
        w = Math.round(w), h = Math.round(h);
        let a2 = anchor;
        if (a2 === void 0) {
          const x4 = px(i) + ox2;
          const y4 = py(i) + oy2;
          const fitLeft = x4 + w + m + r * 2 < width2;
          const fitRight = x4 - w - m - r * 2 > 0;
          const fitTop = y4 + h + m + r * 2 < height2;
          const fitBottom = y4 - h - m - r * 2 > 0;
          a2 = fitLeft && fitRight ? fitTop && fitBottom ? mark2.preferredAnchor : fitBottom ? "bottom" : "top" : fitTop && fitBottom ? fitLeft ? "left" : "right" : (fitLeft || fitRight) && (fitTop || fitBottom) ? `${fitBottom ? "bottom" : "top"}-${fitLeft ? "left" : "right"}` : mark2.preferredAnchor;
        }
        const path2 = this.firstChild;
        const text3 = this.lastChild;
        path2.setAttribute("d", getPath(a2, m, r, w, h));
        if (tx) for (const t of text3.childNodes) t.setAttribute("x", -tx);
        text3.setAttribute("y", `${+getLineOffset(a2, text3.childNodes.length, lineHeight).toFixed(6)}em`);
        text3.setAttribute("transform", `translate(${getTextTranslate(a2, m, r, w, h)})`);
      });
      g.attr("visibility", null);
    }
    if (index2.length) {
      g.attr("visibility", "hidden");
      if (svg.isConnected) Promise.resolve().then(postrender);
      else if (typeof requestAnimationFrame !== "undefined") requestAnimationFrame(postrender);
    }
    return g.node();
  }
};
function tip(data, { x: x3, y: y3, ...options } = {}) {
  if (options.frameAnchor === void 0) [x3, y3] = maybeTuple(x3, y3);
  return new Tip(data, { ...options, x: x3, y: y3 });
}
function getLineOffset(anchor, length4, lineHeight) {
  return /^top(?:-|$)/.test(anchor) ? 0.94 - lineHeight : /^bottom(?:-|$)/ ? -0.29 - length4 * lineHeight : length4 / 2 * lineHeight;
}
function getTextTranslate(anchor, m, r, width2, height2) {
  switch (anchor) {
    case "middle":
      return [-width2 / 2, height2 / 2];
    case "top-left":
      return [r, m + r];
    case "top":
      return [-width2 / 2, m / 2 + r];
    case "top-right":
      return [-width2 - r, m + r];
    case "right":
      return [-m / 2 - width2 - r, height2 / 2];
    case "bottom-left":
      return [r, -m - r];
    case "bottom":
      return [-width2 / 2, -m / 2 - r];
    case "bottom-right":
      return [-width2 - r, -m - r];
    case "left":
      return [r + m / 2, height2 / 2];
  }
}
function getPath(anchor, m, r, width2, height2) {
  const w = width2 + r * 2;
  const h = height2 + r * 2;
  switch (anchor) {
    case "middle":
      return `M${-w / 2},${-h / 2}h${w}v${h}h${-w}z`;
    case "top-left":
      return `M0,0l${m},${m}h${w - m}v${h}h${-w}z`;
    case "top":
      return `M0,0l${m / 2},${m / 2}h${(w - m) / 2}v${h}h${-w}v${-h}h${(w - m) / 2}z`;
    case "top-right":
      return `M0,0l${-m},${m}h${m - w}v${h}h${w}z`;
    case "right":
      return `M0,0l${-m / 2},${-m / 2}v${m / 2 - h / 2}h${-w}v${h}h${w}v${m / 2 - h / 2}z`;
    case "bottom-left":
      return `M0,0l${m},${-m}h${w - m}v${-h}h${-w}z`;
    case "bottom":
      return `M0,0l${m / 2},${-m / 2}h${(w - m) / 2}v${-h}h${-w}v${h}h${(w - m) / 2}z`;
    case "bottom-right":
      return `M0,0l${-m},${-m}h${m - w}v${-h}h${w}z`;
    case "left":
      return `M0,0l${m / 2},${-m / 2}v${m / 2 - h / 2}h${w}v${h}h${-w}v${m / 2 - h / 2}z`;
  }
}
function getSourceChannels(channels, scales2) {
  const sources = {};
  let format3 = this.format;
  format3 = maybeExpandPairedFormat(format3, channels, "x");
  format3 = maybeExpandPairedFormat(format3, channels, "y");
  this.format = format3;
  for (const key in format3) {
    const value = format3[key];
    if (value === null || value === false) {
      continue;
    } else if (key === "fx" || key === "fy") {
      sources[key] = true;
    } else {
      const source = getSource(channels, key);
      if (source) sources[key] = source;
    }
  }
  for (const key in channels) {
    if (key in sources || key in format3 || ignoreChannels.has(key)) continue;
    if ((key === "x" || key === "y") && channels.geometry) continue;
    const source = getSource(channels, key);
    if (source) {
      if (source.scale == null && source.defaultScale === "color") continue;
      sources[key] = source;
    }
  }
  if (this.facet) {
    if (scales2.fx && !("fx" in format3)) sources.fx = true;
    if (scales2.fy && !("fy" in format3)) sources.fy = true;
  }
  for (const key in sources) {
    const format4 = this.format[key];
    if (typeof format4 === "string") {
      const value = sources[key]?.value ?? scales2[key]?.domain() ?? [];
      this.format[key] = (isTemporal(value) ? utcFormat : format)(format4);
    } else if (format4 === void 0 || format4 === true) {
      const scale3 = scales2[key];
      this.format[key] = scale3?.bandwidth ? inferTickFormat(scale3, scale3.domain()) : formatDefault;
    }
  }
  return sources;
}
function maybeExpandPairedFormat(format3, channels, key) {
  if (!(key in format3)) return format3;
  const key1 = `${key}1`;
  const key2 = `${key}2`;
  if ((key1 in format3 || !(key1 in channels)) && (key2 in format3 || !(key2 in channels))) return format3;
  const entries = Object.entries(format3);
  const value = format3[key];
  entries.splice(entries.findIndex(([name2]) => name2 === key) + 1, 0, [key1, value], [key2, value]);
  return Object.fromEntries(entries);
}
function formatTitle(i, index2, { title }) {
  return this.format.title(title.value[i], i);
}
function* formatChannels(i, index2, channels, scales2, values2) {
  for (const key in channels) {
    if (key === "fx" || key === "fy") {
      yield {
        label: formatLabel(scales2, channels, key),
        value: this.format[key](index2[key], i)
      };
      continue;
    }
    if (key === "x1" && "x2" in channels) continue;
    if (key === "y1" && "y2" in channels) continue;
    const channel = channels[key];
    if (key === "x2" && "x1" in channels) {
      yield {
        label: formatPairLabel(scales2, channels, "x"),
        value: formatPair(this.format.x2, channels.x1, channel, i)
      };
    } else if (key === "y2" && "y1" in channels) {
      yield {
        label: formatPairLabel(scales2, channels, "y"),
        value: formatPair(this.format.y2, channels.y1, channel, i)
      };
    } else {
      const value = channel.value[i];
      const scale3 = channel.scale;
      if (!defined(value) && scale3 == null) continue;
      yield {
        label: formatLabel(scales2, channels, key),
        value: this.format[key](value, i),
        color: scale3 === "color" ? values2[key][i] : null,
        opacity: scale3 === "opacity" ? values2[key][i] : null
      };
    }
  }
}
function formatPair(formatValue, c1, c22, i) {
  return c22.hint?.length ? `${formatValue(c22.value[i] - c1.value[i], i)}` : `${formatValue(c1.value[i], i)}\u2013${formatValue(c22.value[i], i)}`;
}
function formatPairLabel(scales2, channels, key) {
  const l1 = formatLabel(scales2, channels, `${key}1`, key);
  const l2 = formatLabel(scales2, channels, `${key}2`, key);
  return l1 === l2 ? l1 : `${l1}\u2013${l2}`;
}
function formatLabel(scales2, channels, key, defaultLabel = key) {
  const channel = channels[key];
  const scale3 = scales2[channel?.scale ?? key];
  return String(scale3?.label ?? channel?.label ?? defaultLabel);
}

// ../../../node_modules/@observablehq/plot/src/plot.js
function plot(options = {}) {
  const { facet, style: style2, title, subtitle, caption, ariaLabel: ariaLabel2, ariaDescription: ariaDescription2 } = options;
  const className = maybeClassName(options.className);
  const marks2 = options.marks === void 0 ? [] : flatMarks(options.marks);
  marks2.push(...inferTips(marks2));
  const topFacetState = maybeTopFacet(facet, options);
  const facetStateByMark = /* @__PURE__ */ new Map();
  for (const mark2 of marks2) {
    const facetState = maybeMarkFacet(mark2, topFacetState, options);
    if (facetState) facetStateByMark.set(mark2, facetState);
  }
  const channelsByScale = /* @__PURE__ */ new Map();
  if (topFacetState) addScaleChannels(channelsByScale, [topFacetState], options);
  addScaleChannels(channelsByScale, facetStateByMark, options);
  const axes = flatMarks(inferAxes(marks2, channelsByScale, options));
  for (const mark2 of axes) {
    const facetState = maybeMarkFacet(mark2, topFacetState, options);
    if (facetState) facetStateByMark.set(mark2, facetState);
  }
  marks2.unshift(...axes);
  let facets = createFacets(channelsByScale, options);
  if (facets !== void 0) {
    const topFacetsIndex = topFacetState ? facetFilter(facets, topFacetState) : void 0;
    for (const mark2 of marks2) {
      if (mark2.facet === null || mark2.facet === "super") continue;
      const facetState = facetStateByMark.get(mark2);
      if (facetState === void 0) continue;
      facetState.facetsIndex = mark2.fx != null || mark2.fy != null ? facetFilter(facets, facetState) : topFacetsIndex;
    }
    const nonEmpty = /* @__PURE__ */ new Set();
    for (const { facetsIndex } of facetStateByMark.values()) {
      facetsIndex?.forEach((index2, i) => {
        if (index2?.length > 0) {
          nonEmpty.add(i);
        }
      });
    }
    facets.forEach(
      0 < nonEmpty.size && nonEmpty.size < facets.length ? (f, i) => f.empty = !nonEmpty.has(i) : (f) => f.empty = false
    );
    for (const mark2 of marks2) {
      if (mark2.facet === "exclude") {
        const facetState = facetStateByMark.get(mark2);
        if (facetState !== void 0) facetState.facetsIndex = facetExclude(facetState.facetsIndex);
      }
    }
  }
  for (const key of registry.keys()) {
    if (isScaleOptions(options[key]) && key !== "fx" && key !== "fy") {
      channelsByScale.set(key, []);
    }
  }
  const stateByMark = /* @__PURE__ */ new Map();
  for (const mark2 of marks2) {
    if (stateByMark.has(mark2)) throw new Error("duplicate mark; each mark must be unique");
    const { facetsIndex, channels: facetChannels } = facetStateByMark.get(mark2) ?? {};
    const { data, facets: facets2, channels } = mark2.initialize(facetsIndex, facetChannels, options);
    applyScaleTransforms(channels, options);
    stateByMark.set(mark2, { data, facets: facets2, channels });
  }
  const scaleDescriptors = createScales(addScaleChannels(channelsByScale, stateByMark, options), options);
  const dimensions = createDimensions(scaleDescriptors, marks2, options);
  autoScaleRange(scaleDescriptors, dimensions);
  const scales2 = createScaleFunctions(scaleDescriptors);
  const { fx, fy } = scales2;
  const subdimensions = fx || fy ? innerDimensions(scaleDescriptors, dimensions) : dimensions;
  const superdimensions = fx || fy ? actualDimensions(scales2, dimensions) : dimensions;
  const context = createContext(options);
  const document2 = context.document;
  const svg = creator_default("svg").call(document2.documentElement);
  let figure = svg;
  context.ownerSVGElement = svg;
  context.className = className;
  context.projection = createProjection(options, subdimensions);
  context.path = function() {
    return path_default(this.projection ?? xyProjection(scales2));
  };
  context.filterFacets = (data, channels) => {
    return facetFilter(facets, { channels, groups: facetGroups(data, channels) });
  };
  context.getMarkState = (mark2) => {
    const state = stateByMark.get(mark2);
    const facetState = facetStateByMark.get(mark2);
    return { ...state, channels: { ...state.channels, ...facetState?.channels } };
  };
  context.dispatchValue = (value) => {
    if (figure.value === value) return;
    figure.value = value;
    figure.dispatchEvent(new context.document.defaultView.Event("input", { bubbles: true }));
  };
  const newByScale = /* @__PURE__ */ new Set();
  for (const [mark2, state] of stateByMark) {
    if (mark2.initializer != null) {
      const dimensions2 = mark2.facet === "super" ? superdimensions : subdimensions;
      const update = mark2.initializer(state.data, state.facets, state.channels, scales2, dimensions2, context);
      if (update.data !== void 0) {
        state.data = update.data;
      }
      if (update.facets !== void 0) {
        state.facets = update.facets;
      }
      if (update.channels !== void 0) {
        const { fx: fx2, fy: fy2, ...channels } = update.channels;
        inferChannelScales(channels);
        Object.assign(state.channels, channels);
        for (const channel of Object.values(channels)) {
          const { scale: scale3 } = channel;
          if (scale3 != null && !isPosition(registry.get(scale3))) {
            applyScaleTransform(channel, options);
            newByScale.add(scale3);
          }
        }
        if (fx2 != null || fy2 != null) facetStateByMark.set(mark2, true);
      }
    }
  }
  if (newByScale.size) {
    const newChannelsByScale = /* @__PURE__ */ new Map();
    addScaleChannels(newChannelsByScale, stateByMark, options, (key) => newByScale.has(key));
    addScaleChannels(channelsByScale, stateByMark, options, (key) => newByScale.has(key));
    const newScaleDescriptors = inheritScaleLabels(createScales(newChannelsByScale, options), scaleDescriptors);
    const { scales: newExposedScales, ...newScales } = createScaleFunctions(newScaleDescriptors);
    Object.assign(scaleDescriptors, newScaleDescriptors);
    Object.assign(scales2, newScales);
    Object.assign(scales2.scales, newExposedScales);
  }
  let facetDomains, facetTranslate;
  if (facets !== void 0) {
    facetDomains = { x: fx?.domain(), y: fy?.domain() };
    facets = recreateFacets(facets, facetDomains);
    facetTranslate = facetTranslator(fx, fy, dimensions);
  }
  for (const [mark2, state] of stateByMark) {
    state.values = mark2.scale(state.channels, scales2, context);
  }
  const { width: width2, height: height2 } = dimensions;
  select_default2(svg).attr("class", className).attr("fill", "currentColor").attr("font-family", "system-ui, sans-serif").attr("font-size", 10).attr("text-anchor", "middle").attr("width", width2).attr("height", height2).attr("viewBox", `0 0 ${width2} ${height2}`).attr("aria-label", ariaLabel2).attr("aria-description", ariaDescription2).call(
    (svg2) => (
      // Warning: if you edit this, change defaultClassName.
      svg2.append("style").text(
        `:where(.${className}) {
  --plot-background: white;
  display: block;
  height: auto;
  height: intrinsic;
  max-width: 100%;
}
:where(.${className} text),
:where(.${className} tspan) {
  white-space: pre;
}`
      )
    )
  ).call(applyInlineStyles, style2);
  for (const mark2 of marks2) {
    const { channels, values: values2, facets: indexes2 } = stateByMark.get(mark2);
    if (facets === void 0 || mark2.facet === "super") {
      let index2 = null;
      if (indexes2) {
        index2 = indexes2[0];
        index2 = mark2.filter(index2, channels, values2);
        if (index2.length === 0) continue;
      }
      const node = mark2.render(index2, scales2, values2, superdimensions, context);
      if (node == null) continue;
      svg.appendChild(node);
    } else {
      let g;
      for (const f of facets) {
        if (!(mark2.facetAnchor?.(facets, facetDomains, f) ?? !f.empty)) continue;
        let index2 = null;
        if (indexes2) {
          const faceted = facetStateByMark.has(mark2);
          index2 = indexes2[faceted ? f.i : 0];
          index2 = mark2.filter(index2, channels, values2);
          if (index2.length === 0) continue;
          if (!faceted && index2 === indexes2[0]) index2 = subarray(index2);
          index2.fx = f.x, index2.fy = f.y, index2.fi = f.i;
        }
        const node = mark2.render(index2, scales2, values2, subdimensions, context);
        if (node == null) continue;
        (g ??= select_default2(svg).append("g")).append(() => node).datum(f);
        for (const name2 of ["aria-label", "aria-description", "aria-hidden", "transform"]) {
          if (node.hasAttribute(name2)) {
            g.attr(name2, node.getAttribute(name2));
            node.removeAttribute(name2);
          }
        }
      }
      g?.selectChildren().each(facetTranslate);
    }
  }
  const legends = createLegends(scaleDescriptors, context, options);
  const { figure: figured = title != null || subtitle != null || caption != null || legends.length > 0 } = options;
  if (figured) {
    figure = document2.createElement("figure");
    figure.className = `${className}-figure`;
    figure.style.maxWidth = "initial";
    if (title != null) figure.append(createTitleElement(document2, title, "h2"));
    if (subtitle != null) figure.append(createTitleElement(document2, subtitle, "h3"));
    figure.append(...legends, svg);
    if (caption != null) figure.append(createFigcaption(document2, caption));
    if ("value" in svg) figure.value = svg.value, delete svg.value;
  }
  figure.scale = exposeScales(scales2.scales);
  figure.legend = exposeLegends(scaleDescriptors, context, options);
  const w = consumeWarnings();
  if (w > 0) {
    select_default2(svg).append("text").attr("x", width2).attr("y", 20).attr("dy", "-1em").attr("text-anchor", "end").attr("font-family", "initial").text("\u26A0\uFE0F").append("title").text(`${w.toLocaleString("en-US")} warning${w === 1 ? "" : "s"}. Please check the console.`);
  }
  return figure;
}
function createTitleElement(document2, contents, tag) {
  if (contents.ownerDocument) return contents;
  const e = document2.createElement(tag);
  e.append(contents);
  return e;
}
function createFigcaption(document2, caption) {
  const e = document2.createElement("figcaption");
  e.append(caption);
  return e;
}
function flatMarks(marks2) {
  return marks2.flat(Infinity).filter((mark2) => mark2 != null).map(markify);
}
function markify(mark2) {
  return typeof mark2.render === "function" ? mark2 : new Render(mark2);
}
var Render = class extends Mark {
  constructor(render) {
    if (typeof render !== "function") throw new TypeError("invalid mark; missing render function");
    super();
    this.render = render;
  }
  render() {
  }
};
function applyScaleTransforms(channels, options) {
  for (const name2 in channels) applyScaleTransform(channels[name2], options);
  return channels;
}
function applyScaleTransform(channel, options) {
  const { scale: scale3, transform: t = true } = channel;
  if (scale3 == null || !t) return;
  const {
    type: type2,
    percent,
    interval: interval4,
    transform: transform3 = percent ? (x3) => x3 == null ? NaN : x3 * 100 : maybeIntervalTransform(interval4, type2)
  } = options[scale3] ?? {};
  if (transform3 == null) return;
  channel.value = map3(channel.value, transform3);
  channel.transform = false;
}
function inferChannelScales(channels) {
  for (const name2 in channels) {
    inferChannelScale(name2, channels[name2]);
  }
}
function addScaleChannels(channelsByScale, stateByMark, options, filter3 = yes) {
  for (const { channels } of stateByMark.values()) {
    for (const name2 in channels) {
      const channel = channels[name2];
      const { scale: scale3 } = channel;
      if (scale3 != null && filter3(scale3)) {
        if (scale3 === "projection") {
          if (!hasProjection(options)) {
            const gx = options.x?.domain === void 0;
            const gy = options.y?.domain === void 0;
            if (gx || gy) {
              const [x3, y3] = getGeometryChannels(channel);
              if (gx) addScaleChannel(channelsByScale, "x", x3);
              if (gy) addScaleChannel(channelsByScale, "y", y3);
            }
          }
        } else {
          addScaleChannel(channelsByScale, scale3, channel);
        }
      }
    }
  }
  return channelsByScale;
}
function addScaleChannel(channelsByScale, scale3, channel) {
  const scaleChannels = channelsByScale.get(scale3);
  if (scaleChannels !== void 0) scaleChannels.push(channel);
  else channelsByScale.set(scale3, [channel]);
}
function maybeTopFacet(facet, options) {
  if (facet == null) return;
  const { x: x3, y: y3 } = facet;
  if (x3 == null && y3 == null) return;
  const data = dataify(facet.data);
  if (data == null) throw new Error("missing facet data");
  const channels = {};
  if (x3 != null) channels.fx = createChannel(data, { value: x3, scale: "fx" });
  if (y3 != null) channels.fy = createChannel(data, { value: y3, scale: "fy" });
  applyScaleTransforms(channels, options);
  const groups2 = facetGroups(data, channels);
  return { channels, groups: groups2, data: facet.data };
}
function maybeMarkFacet(mark2, topFacetState, options) {
  if (mark2.facet === null || mark2.facet === "super") return;
  const { fx, fy } = mark2;
  if (fx != null || fy != null) {
    const data2 = dataify(mark2.data ?? fx ?? fy);
    if (data2 === void 0) throw new Error(`missing facet data in ${mark2.ariaLabel}`);
    if (data2 === null) return;
    const channels2 = {};
    if (fx != null) channels2.fx = createChannel(data2, { value: fx, scale: "fx" });
    if (fy != null) channels2.fy = createChannel(data2, { value: fy, scale: "fy" });
    applyScaleTransforms(channels2, options);
    return { channels: channels2, groups: facetGroups(data2, channels2) };
  }
  if (topFacetState === void 0) return;
  const { channels, groups: groups2, data } = topFacetState;
  if (mark2.facet !== "auto" || mark2.data === data) return { channels, groups: groups2 };
  if (data.length > 0 && (groups2.size > 1 || groups2.size === 1 && channels.fx && channels.fy && [...groups2][0][1].size > 1) && lengthof(dataify(mark2.data)) === lengthof(data)) {
    warn(
      `Warning: the ${mark2.ariaLabel} mark appears to use faceted data, but isn\u2019t faceted. The mark data has the same length as the facet data and the mark facet option is "auto", but the mark data and facet data are distinct. If this mark should be faceted, set the mark facet option to true; otherwise, suppress this warning by setting the mark facet option to false.`
    );
  }
}
function derive(mark2, options = {}) {
  return initializer({ ...options, x: null, y: null }, (data, facets, channels, scales2, dimensions, context) => {
    return context.getMarkState(mark2);
  });
}
function inferTips(marks2) {
  const tips = [];
  for (const mark2 of marks2) {
    let tipOptions = mark2.tip;
    if (tipOptions) {
      if (tipOptions === true) tipOptions = {};
      else if (typeof tipOptions === "string") tipOptions = { pointer: tipOptions };
      let { pointer: p, preferredAnchor: a2 } = tipOptions;
      p = /^x$/i.test(p) ? pointerX : /^y$/i.test(p) ? pointerY : pointer;
      tipOptions = p(derive(mark2, tipOptions));
      tipOptions.title = null;
      if (a2 === void 0) tipOptions.preferredAnchor = p === pointerY ? "left" : "bottom";
      const t = tip(mark2.data, tipOptions);
      t.facet = mark2.facet;
      t.facetAnchor = mark2.facetAnchor;
      tips.push(t);
    }
  }
  return tips;
}
function inferAxes(marks2, channelsByScale, options) {
  let {
    projection: projection3,
    x: x3 = {},
    y: y3 = {},
    fx = {},
    fy = {},
    axis: axis3,
    grid: grid2,
    facet = {},
    facet: { axis: facetAxis = axis3, grid: facetGrid2 } = facet,
    x: { axis: xAxis2 = axis3, grid: xGrid2 = xAxis2 === null ? null : grid2 } = x3,
    y: { axis: yAxis2 = axis3, grid: yGrid2 = yAxis2 === null ? null : grid2 } = y3,
    fx: { axis: fxAxis2 = facetAxis, grid: fxGrid2 = fxAxis2 === null ? null : facetGrid2 } = fx,
    fy: { axis: fyAxis2 = facetAxis, grid: fyGrid2 = fyAxis2 === null ? null : facetGrid2 } = fy
  } = options;
  if (projection3 || !isScaleOptions(x3) && !hasPositionChannel("x", marks2)) xAxis2 = xGrid2 = null;
  if (projection3 || !isScaleOptions(y3) && !hasPositionChannel("y", marks2)) yAxis2 = yGrid2 = null;
  if (!channelsByScale.has("fx")) fxAxis2 = fxGrid2 = null;
  if (!channelsByScale.has("fy")) fyAxis2 = fyGrid2 = null;
  if (xAxis2 === void 0) xAxis2 = !hasAxis(marks2, "x");
  if (yAxis2 === void 0) yAxis2 = !hasAxis(marks2, "y");
  if (fxAxis2 === void 0) fxAxis2 = !hasAxis(marks2, "fx");
  if (fyAxis2 === void 0) fyAxis2 = !hasAxis(marks2, "fy");
  if (xAxis2 === true) xAxis2 = "bottom";
  if (yAxis2 === true) yAxis2 = "left";
  if (fxAxis2 === true) fxAxis2 = xAxis2 === "top" || xAxis2 === null ? "bottom" : "top";
  if (fyAxis2 === true) fyAxis2 = yAxis2 === "right" || yAxis2 === null ? "left" : "right";
  const axes = [];
  maybeGrid(axes, fyGrid2, gridFy, fy);
  maybeAxis(axes, fyAxis2, axisFy, "right", "left", facet, fy);
  maybeGrid(axes, fxGrid2, gridFx, fx);
  maybeAxis(axes, fxAxis2, axisFx, "top", "bottom", facet, fx);
  maybeGrid(axes, yGrid2, gridY, y3);
  maybeAxis(axes, yAxis2, axisY, "left", "right", options, y3);
  maybeGrid(axes, xGrid2, gridX, x3);
  maybeAxis(axes, xAxis2, axisX, "bottom", "top", options, x3);
  return axes;
}
function maybeAxis(axes, axis3, axisType, primary, secondary, defaults22, options) {
  if (!axis3) return;
  const both = isBoth(axis3);
  options = axisOptions(both ? primary : axis3, defaults22, options);
  const { line: line3 } = options;
  if ((axisType === axisY || axisType === axisX) && line3 && !isNone(line3)) axes.push(frame2(lineOptions(options)));
  axes.push(axisType(options));
  if (both) axes.push(axisType({ ...options, anchor: secondary, label: null }));
}
function maybeGrid(axes, grid2, gridType, options) {
  if (!grid2 || isNone(grid2)) return;
  axes.push(gridType(gridOptions(grid2, options)));
}
function isBoth(value) {
  return /^\s*both\s*$/i.test(value);
}
function axisOptions(anchor, defaults22, {
  line: line3 = defaults22.line,
  ticks: ticks2,
  tickSize,
  tickSpacing,
  tickPadding,
  tickFormat: tickFormat2,
  tickRotate,
  fontVariant,
  ariaLabel: ariaLabel2,
  ariaDescription: ariaDescription2,
  label = defaults22.label,
  labelAnchor,
  labelArrow = defaults22.labelArrow,
  labelOffset
}) {
  return {
    anchor,
    line: line3,
    ticks: ticks2,
    tickSize,
    tickSpacing,
    tickPadding,
    tickFormat: tickFormat2,
    tickRotate,
    fontVariant,
    ariaLabel: ariaLabel2,
    ariaDescription: ariaDescription2,
    label,
    labelAnchor,
    labelArrow,
    labelOffset
  };
}
function lineOptions(options) {
  const { anchor, line: line3 } = options;
  return { anchor, facetAnchor: anchor + "-empty", stroke: line3 === true ? void 0 : line3 };
}
function gridOptions(grid2, {
  stroke = isColor(grid2) ? grid2 : void 0,
  ticks: ticks2 = isGridTicks(grid2) ? grid2 : void 0,
  tickSpacing,
  ariaLabel: ariaLabel2,
  ariaDescription: ariaDescription2
}) {
  return {
    stroke,
    ticks: ticks2,
    tickSpacing,
    ariaLabel: ariaLabel2,
    ariaDescription: ariaDescription2
  };
}
function isGridTicks(grid2) {
  switch (typeof grid2) {
    case "number":
      return true;
    case "string":
      return !isColor(grid2);
  }
  return isIterable2(grid2) || typeof grid2?.range === "function";
}
function hasAxis(marks2, k2) {
  const prefix2 = `${k2}-axis `;
  return marks2.some((m) => m.ariaLabel?.startsWith(prefix2));
}
function hasPositionChannel(k2, marks2) {
  for (const mark2 of marks2) {
    for (const key in mark2.channels) {
      const { scale: scale3 } = mark2.channels[key];
      if (scale3 === k2 || scale3 === "projection") {
        return true;
      }
    }
  }
  return false;
}
function inheritScaleLabels(newScales, scales2) {
  for (const key in newScales) {
    const newScale = newScales[key];
    const scale3 = scales2[key];
    if (newScale.label === void 0 && scale3) {
      newScale.label = scale3.label;
    }
  }
  return newScales;
}
function actualDimensions({ fx, fy }, dimensions) {
  const { marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2, width: width2, height: height2 } = outerDimensions(dimensions);
  const fxr = fx && outerRange(fx);
  const fyr = fy && outerRange(fy);
  return {
    marginTop: fy ? fyr[0] : marginTop2,
    marginRight: fx ? width2 - fxr[1] : marginRight2,
    marginBottom: fy ? height2 - fyr[1] : marginBottom2,
    marginLeft: fx ? fxr[0] : marginLeft2,
    // Some marks, namely the x- and y-axis labels, want to know what the
    // desired (rather than actual) margins are for positioning.
    inset: {
      marginTop: dimensions.marginTop,
      marginRight: dimensions.marginRight,
      marginBottom: dimensions.marginBottom,
      marginLeft: dimensions.marginLeft
    },
    width: width2,
    height: height2
  };
}
function outerRange(scale3) {
  const domain = scale3.domain();
  if (domain.length === 0) return [0, scale3.bandwidth()];
  let x12 = scale3(domain[0]);
  let x22 = scale3(domain[domain.length - 1]);
  if (x22 < x12) [x12, x22] = [x22, x12];
  return [x12, x22 + scale3.bandwidth()];
}

// ../../../node_modules/@observablehq/plot/src/curve.js
var curves = /* @__PURE__ */ new Map([
  ["basis", basis_default2],
  ["basis-closed", basisClosed_default2],
  ["basis-open", basisOpen_default],
  ["bundle", bundle_default],
  ["bump-x", bumpX],
  ["bump-y", bumpY],
  ["cardinal", cardinal_default],
  ["cardinal-closed", cardinalClosed_default],
  ["cardinal-open", cardinalOpen_default],
  ["catmull-rom", catmullRom_default],
  ["catmull-rom-closed", catmullRomClosed_default],
  ["catmull-rom-open", catmullRomOpen_default],
  ["linear", linear_default],
  ["linear-closed", linearClosed_default],
  ["monotone-x", monotoneX],
  ["monotone-y", monotoneY],
  ["natural", natural_default],
  ["step", step_default],
  ["step-after", stepAfter],
  ["step-before", stepBefore]
]);
function maybeCurve(curve = linear_default, tension) {
  if (typeof curve === "function") return curve;
  const c4 = curves.get(`${curve}`.toLowerCase());
  if (!c4) throw new Error(`unknown curve: ${curve}`);
  if (tension !== void 0) {
    if ("beta" in c4) {
      return c4.beta(tension);
    } else if ("tension" in c4) {
      return c4.tension(tension);
    } else if ("alpha" in c4) {
      return c4.alpha(tension);
    }
  }
  return c4;
}
function maybeCurveAuto(curve = curveAuto, tension) {
  return typeof curve !== "function" && `${curve}`.toLowerCase() === "auto" ? curveAuto : maybeCurve(curve, tension);
}
function curveAuto(context) {
  return linear_default(context);
}

// ../../../node_modules/@observablehq/plot/src/transforms/bin.js
function binX(outputs = { y: "count" }, options = {}) {
  [outputs, options] = mergeOptions2(outputs, options);
  const { x: x3, y: y3 } = options;
  return binn(maybeBinValue(x3, options, identity8), null, null, y3, outputs, maybeInsetX(options));
}
function binY(outputs = { x: "count" }, options = {}) {
  [outputs, options] = mergeOptions2(outputs, options);
  const { x: x3, y: y3 } = options;
  return binn(null, maybeBinValue(y3, options, identity8), x3, null, outputs, maybeInsetY(options));
}
function bin(outputs = { fill: "count" }, options = {}) {
  [outputs, options] = mergeOptions2(outputs, options);
  const { x: x3, y: y3 } = maybeBinValueTuple(options);
  return binn(x3, y3, null, null, outputs, maybeInsetX(maybeInsetY(options)));
}
function maybeDenseInterval(bin3, k2, options = {}) {
  if (options?.interval == null) return options;
  const { reduce = reduceFirst } = options;
  const outputs = { filter: null };
  if (options[k2] != null) outputs[k2] = reduce;
  if (options[`${k2}1`] != null) outputs[`${k2}1`] = reduce;
  if (options[`${k2}2`] != null) outputs[`${k2}2`] = reduce;
  return bin3(outputs, options);
}
function maybeDenseIntervalX(options = {}) {
  return maybeDenseInterval(binX, "y", withTip(options, "x"));
}
function maybeDenseIntervalY(options = {}) {
  return maybeDenseInterval(binY, "x", withTip(options, "y"));
}
function binn(bx, by, gx, gy, {
  data: reduceData = reduceIdentity,
  // TODO avoid materializing when unused?
  filter: filter3 = reduceCount,
  // return only non-empty bins by default
  sort: sort3,
  reverse: reverse3,
  ...outputs
  // output channel definitions
} = {}, inputs = {}) {
  bx = maybeBin(bx);
  by = maybeBin(by);
  outputs = maybeBinOutputs(outputs, inputs);
  reduceData = maybeBinReduce(reduceData, identity8);
  sort3 = sort3 == null ? void 0 : maybeBinOutput("sort", sort3, inputs);
  filter3 = filter3 == null ? void 0 : maybeBinEvaluator("filter", filter3, inputs);
  if (gx != null && hasOutput(outputs, "x", "x1", "x2")) gx = null;
  if (gy != null && hasOutput(outputs, "y", "y1", "y2")) gy = null;
  const [BX1, setBX1] = maybeColumn(bx);
  const [BX2, setBX2] = maybeColumn(bx);
  const [BY1, setBY1] = maybeColumn(by);
  const [BY2, setBY2] = maybeColumn(by);
  const [k2, gk] = gx != null ? [gx, "x"] : gy != null ? [gy, "y"] : [];
  const [GK, setGK] = maybeColumn(k2);
  const {
    x: x3,
    y: y3,
    z,
    fill,
    stroke,
    x1: x12,
    x2: x22,
    // consumed if x is an output
    y1: y12,
    y2: y22,
    // consumed if y is an output
    domain,
    cumulative,
    thresholds,
    interval: interval4,
    ...options
  } = inputs;
  const [GZ, setGZ] = maybeColumn(z);
  const [vfill] = maybeColorChannel(fill);
  const [vstroke] = maybeColorChannel(stroke);
  const [GF, setGF] = maybeColumn(vfill);
  const [GS, setGS] = maybeColumn(vstroke);
  return {
    ..."z" in inputs && { z: GZ || z },
    ..."fill" in inputs && { fill: GF || fill },
    ..."stroke" in inputs && { stroke: GS || stroke },
    ...basic(options, (data, facets, plotOptions) => {
      const K2 = maybeApplyInterval(valueof(data, k2), plotOptions?.[gk]);
      const Z = valueof(data, z);
      const F = valueof(data, vfill);
      const S = valueof(data, vstroke);
      const G = maybeSubgroup(outputs, { z: Z, fill: F, stroke: S });
      const groupFacets = [];
      const groupData = [];
      const GK2 = K2 && setGK([]);
      const GZ2 = Z && setGZ([]);
      const GF2 = F && setGF([]);
      const GS2 = S && setGS([]);
      const BX12 = bx && setBX1([]);
      const BX22 = bx && setBX2([]);
      const BY12 = by && setBY1([]);
      const BY22 = by && setBY2([]);
      const bin3 = bing(bx, by, data);
      let i = 0;
      for (const o of outputs) o.initialize(data);
      if (sort3) sort3.initialize(data);
      if (filter3) filter3.initialize(data);
      for (const facet of facets) {
        const groupFacet = [];
        for (const o of outputs) o.scope("facet", facet);
        if (sort3) sort3.scope("facet", facet);
        if (filter3) filter3.scope("facet", facet);
        for (const [f, I] of maybeGroup(facet, G)) {
          for (const [k3, g] of maybeGroup(I, K2)) {
            for (const [b, extent4] of bin3(g)) {
              if (G) extent4.z = f;
              if (filter3 && !filter3.reduce(b, extent4)) continue;
              groupFacet.push(i++);
              groupData.push(reduceData.reduceIndex(b, data, extent4));
              if (K2) GK2.push(k3);
              if (Z) GZ2.push(G === Z ? f : Z[(b.length > 0 ? b : g)[0]]);
              if (F) GF2.push(G === F ? f : F[(b.length > 0 ? b : g)[0]]);
              if (S) GS2.push(G === S ? f : S[(b.length > 0 ? b : g)[0]]);
              if (BX12) BX12.push(extent4.x1), BX22.push(extent4.x2);
              if (BY12) BY12.push(extent4.y1), BY22.push(extent4.y2);
              for (const o of outputs) o.reduce(b, extent4);
              if (sort3) sort3.reduce(b, extent4);
            }
          }
        }
        groupFacets.push(groupFacet);
      }
      maybeSort(groupFacets, sort3, reverse3);
      return { data: groupData, facets: groupFacets };
    }),
    ...!hasOutput(outputs, "x") && (BX1 ? { x1: BX1, x2: BX2, x: mid(BX1, BX2) } : { x: x3, x1: x12, x2: x22 }),
    ...!hasOutput(outputs, "y") && (BY1 ? { y1: BY1, y2: BY2, y: mid(BY1, BY2) } : { y: y3, y1: y12, y2: y22 }),
    ...GK && { [gk]: GK },
    ...Object.fromEntries(outputs.map(({ name: name2, output }) => [name2, output]))
  };
}
function mergeOptions2({ cumulative, domain, thresholds, interval: interval4, ...outputs }, options) {
  return [outputs, { cumulative, domain, thresholds, interval: interval4, ...options }];
}
function maybeBinValue(value, { cumulative, domain, thresholds, interval: interval4 }, defaultValue) {
  value = { ...maybeValue(value) };
  if (value.domain === void 0) value.domain = domain;
  if (value.cumulative === void 0) value.cumulative = cumulative;
  if (value.thresholds === void 0) value.thresholds = thresholds;
  if (value.interval === void 0) value.interval = interval4;
  if (value.value === void 0) value.value = defaultValue;
  value.thresholds = maybeThresholds(value.thresholds, value.interval);
  return value;
}
function maybeBinValueTuple(options) {
  let { x: x3, y: y3 } = options;
  x3 = maybeBinValue(x3, options);
  y3 = maybeBinValue(y3, options);
  [x3.value, y3.value] = maybeTuple(x3.value, y3.value);
  return { x: x3, y: y3 };
}
function maybeBin(options) {
  if (options == null) return;
  const { value, cumulative, domain = extent, thresholds } = options;
  const bin3 = (data) => {
    let V = valueof(data, value);
    let T;
    if (isTemporal(V) || isTimeThresholds(thresholds)) {
      V = map3(V, coerceDate, Float64Array);
      let [min5, max4] = typeof domain === "function" ? domain(V) : domain;
      let t = typeof thresholds === "function" && !isInterval(thresholds) ? thresholds(V, min5, max4) : thresholds;
      if (typeof t === "number") t = utcTickInterval(min5, max4, t);
      if (isInterval(t)) {
        if (domain === extent) {
          min5 = t.floor(min5);
          max4 = t.offset(t.floor(max4));
        }
        t = t.range(min5, t.offset(max4));
      }
      T = t;
    } else {
      V = coerceNumbers(V);
      let [min5, max4] = typeof domain === "function" ? domain(V) : domain;
      let t = typeof thresholds === "function" && !isInterval(thresholds) ? thresholds(V, min5, max4) : thresholds;
      if (typeof t === "number") {
        if (domain === extent) {
          let step = tickIncrement(min5, max4, t);
          if (isFinite(step)) {
            if (step > 0) {
              let r0 = Math.round(min5 / step);
              let r1 = Math.round(max4 / step);
              if (!(r0 * step <= min5)) --r0;
              if (!(r1 * step > max4)) ++r1;
              let n = r1 - r0 + 1;
              t = new Float64Array(n);
              for (let i = 0; i < n; ++i) t[i] = (r0 + i) * step;
            } else if (step < 0) {
              step = -step;
              let r0 = Math.round(min5 * step);
              let r1 = Math.round(max4 * step);
              if (!(r0 / step <= min5)) --r0;
              if (!(r1 / step > max4)) ++r1;
              let n = r1 - r0 + 1;
              t = new Float64Array(n);
              for (let i = 0; i < n; ++i) t[i] = (r0 + i) / step;
            } else {
              t = [min5];
            }
          } else {
            t = [min5];
          }
        } else {
          t = ticks(min5, max4, t);
        }
      } else if (isInterval(t)) {
        if (domain === extent) {
          min5 = t.floor(min5);
          max4 = t.offset(t.floor(max4));
        }
        t = t.range(min5, t.offset(max4));
      }
      T = t;
    }
    const E2 = [];
    if (T.length === 1) E2.push([T[0], T[0]]);
    else for (let i = 1; i < T.length; ++i) E2.push([T[i - 1], T[i]]);
    E2.bin = (cumulative < 0 ? bin1cn : cumulative > 0 ? bin1cp : bin1)(E2, T, V);
    return E2;
  };
  bin3.label = labelof(value);
  return bin3;
}
function maybeThresholds(thresholds, interval4, defaultThresholds = thresholdAuto) {
  if (thresholds === void 0) {
    return interval4 === void 0 ? defaultThresholds : maybeRangeInterval(interval4);
  }
  if (typeof thresholds === "string") {
    switch (thresholds.toLowerCase()) {
      case "freedman-diaconis":
        return thresholdFreedmanDiaconis;
      case "scott":
        return thresholdScott;
      case "sturges":
        return thresholdSturges;
      case "auto":
        return thresholdAuto;
    }
    return utcInterval(thresholds);
  }
  return thresholds;
}
function maybeBinOutputs(outputs, inputs) {
  return maybeOutputs(outputs, inputs, maybeBinOutput);
}
function maybeBinOutput(name2, reduce, inputs) {
  return maybeOutput(name2, reduce, inputs, maybeBinEvaluator);
}
function maybeBinEvaluator(name2, reduce, inputs) {
  return maybeEvaluator(name2, reduce, inputs, maybeBinReduce);
}
function maybeBinReduce(reduce, value) {
  return maybeReduce(reduce, value, maybeBinReduceFallback);
}
function maybeBinReduceFallback(reduce) {
  switch (`${reduce}`.toLowerCase()) {
    case "x":
      return reduceX2;
    case "x1":
      return reduceX1;
    case "x2":
      return reduceX22;
    case "y":
      return reduceY2;
    case "y1":
      return reduceY1;
    case "y2":
      return reduceY22;
    case "z":
      return reduceZ;
  }
  throw new Error(`invalid bin reduce: ${reduce}`);
}
function thresholdAuto(values2, min5, max4) {
  return Math.min(200, thresholdScott(values2, min5, max4));
}
function isTimeThresholds(t) {
  return isTimeInterval(t) || isIterable2(t) && isTemporal(t);
}
function bing(bx, by, data) {
  const EX = bx?.(data);
  const EY = by?.(data);
  return EX && EY ? function* (I) {
    const X3 = EX.bin(I);
    for (const [ix, [x12, x22]] of EX.entries()) {
      const Y3 = EY.bin(X3[ix]);
      for (const [iy, [y12, y22]] of EY.entries()) {
        yield [Y3[iy], { data, x1: x12, y1: y12, x2: x22, y2: y22 }];
      }
    }
  } : EX ? function* (I) {
    const X3 = EX.bin(I);
    for (const [i, [x12, x22]] of EX.entries()) {
      yield [X3[i], { data, x1: x12, x2: x22 }];
    }
  } : function* (I) {
    const Y3 = EY.bin(I);
    for (const [i, [y12, y22]] of EY.entries()) {
      yield [Y3[i], { data, y1: y12, y2: y22 }];
    }
  };
}
function bin1(E2, T, V) {
  T = coerceNumbers(T);
  return (I) => {
    const B3 = E2.map(() => []);
    for (const i of I) B3[bisect_default(T, V[i]) - 1]?.push(i);
    return B3;
  };
}
function bin1cp(E2, T, V) {
  const bin3 = bin1(E2, T, V);
  return (I) => {
    const B3 = bin3(I);
    for (let i = 1, n = B3.length; i < n; ++i) {
      const C3 = B3[i - 1];
      const b = B3[i];
      for (const j of C3) b.push(j);
    }
    return B3;
  };
}
function bin1cn(E2, T, V) {
  const bin3 = bin1(E2, T, V);
  return (I) => {
    const B3 = bin3(I);
    for (let i = B3.length - 2; i >= 0; --i) {
      const C3 = B3[i + 1];
      const b = B3[i];
      for (const j of C3) b.push(j);
    }
    return B3;
  };
}
function mid1(x12, x22) {
  const m = (+x12 + +x22) / 2;
  return x12 instanceof Date ? new Date(m) : m;
}
var reduceX2 = {
  reduceIndex(I, X3, { x1: x12, x2: x22 }) {
    return mid1(x12, x22);
  }
};
var reduceY2 = {
  reduceIndex(I, X3, { y1: y12, y2: y22 }) {
    return mid1(y12, y22);
  }
};
var reduceX1 = {
  reduceIndex(I, X3, { x1: x12 }) {
    return x12;
  }
};
var reduceX22 = {
  reduceIndex(I, X3, { x2: x22 }) {
    return x22;
  }
};
var reduceY1 = {
  reduceIndex(I, X3, { y1: y12 }) {
    return y12;
  }
};
var reduceY22 = {
  reduceIndex(I, X3, { y2: y22 }) {
    return y22;
  }
};

// ../../../node_modules/@observablehq/plot/src/marks/area.js
var defaults7 = {
  ariaLabel: "area",
  strokeWidth: 1,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  strokeMiterlimit: 1
};
var Area = class extends Mark {
  constructor(data, options = {}) {
    const { x1: x12, y1: y12, x2: x22, y2: y22, z, curve, tension } = options;
    super(
      data,
      {
        x1: { value: x12, scale: "x" },
        y1: { value: y12, scale: "y" },
        x2: { value: x22, scale: "x", optional: true },
        y2: { value: y22, scale: "y", optional: true },
        z: { value: maybeZ(options), optional: true }
      },
      options,
      defaults7
    );
    this.z = z;
    this.curve = maybeCurve(curve, tension);
  }
  filter(index2) {
    return index2;
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x1: X13, y1: Y13, x2: X23 = X13, y2: Y23 = Y13 } = channels;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2, 0, 0).call(
      (g) => g.selectAll().data(groupIndex(index2, [X13, Y13, X23, Y23], this, channels)).enter().append("path").call(applyDirectStyles, this).call(applyGroupedChannelStyles, this, channels).attr(
        "d",
        area_default3().curve(this.curve).defined((i) => i >= 0).x0((i) => X13[i]).y0((i) => Y13[i]).x1((i) => X23[i]).y1((i) => Y23[i])
      )
    ).node();
  }
};
function area(data, options) {
  if (options === void 0) return areaY(data, { x: first2, y: second2 });
  return new Area(data, options);
}
function areaX(data, options) {
  const { y: y3 = indexOf, ...rest } = maybeDenseIntervalY(options);
  return new Area(data, maybeStackX(maybeIdentityX({ ...rest, y1: y3, y2: void 0 }, y3 === indexOf ? "x2" : "x")));
}
function areaY(data, options) {
  const { x: x3 = indexOf, ...rest } = maybeDenseIntervalX(options);
  return new Area(data, maybeStackY(maybeIdentityY({ ...rest, x1: x3, x2: void 0 }, x3 === indexOf ? "y2" : "y")));
}

// ../../../node_modules/@observablehq/plot/src/marks/link.js
var defaults8 = {
  ariaLabel: "link",
  fill: "none",
  stroke: "currentColor",
  strokeMiterlimit: 1
};
var Link = class extends Mark {
  constructor(data, options = {}) {
    const { x1: x12, y1: y12, x2: x22, y2: y22, curve, tension } = options;
    super(
      data,
      {
        x1: { value: x12, scale: "x" },
        y1: { value: y12, scale: "y" },
        x2: { value: x22, scale: "x", optional: true },
        y2: { value: y22, scale: "y", optional: true }
      },
      options,
      defaults8
    );
    this.curve = maybeCurveAuto(curve, tension);
    markers(this, options);
  }
  project(channels, values2, context) {
    if (this.curve !== curveAuto) {
      super.project(channels, values2, context);
    }
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x1: X13, y1: Y13, x2: X23 = X13, y2: Y23 = Y13 } = channels;
    const { curve } = this;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call(
      (g) => g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr(
        "d",
        curve === curveAuto && context.projection ? sphereLink(context.path(), X13, Y13, X23, Y23) : (i) => {
          const p = pathRound();
          const c4 = curve(p);
          c4.lineStart();
          c4.point(X13[i], Y13[i]);
          c4.point(X23[i], Y23[i]);
          c4.lineEnd();
          return p;
        }
      ).call(applyChannelStyles, this, channels).call(applyMarkers, this, channels, context)
    ).node();
  }
};
function sphereLink(path2, X13, Y13, X23, Y23) {
  X13 = coerceNumbers(X13);
  Y13 = coerceNumbers(Y13);
  X23 = coerceNumbers(X23);
  Y23 = coerceNumbers(Y23);
  return (i) => path2({
    type: "LineString",
    coordinates: [
      [X13[i], Y13[i]],
      [X23[i], Y23[i]]
    ]
  });
}
function link2(data, { x: x3, x1: x12, x2: x22, y: y3, y1: y12, y2: y22, ...options } = {}) {
  [x12, x22] = maybeSameValue(x3, x12, x22);
  [y12, y22] = maybeSameValue(y3, y12, y22);
  return new Link(data, { ...options, x1: x12, x2: x22, y1: y12, y2: y22 });
}
function maybeSameValue(x3, x12, x22) {
  if (x3 === void 0) {
    if (x12 === void 0) {
      if (x22 !== void 0) return [x22];
    } else {
      if (x22 === void 0) return [x12];
    }
  } else if (x12 === void 0) {
    return x22 === void 0 ? [x3] : [x3, x22];
  } else if (x22 === void 0) {
    return [x3, x12];
  }
  return [x12, x22];
}

// ../../../node_modules/@observablehq/plot/src/marks/arrow.js
var defaults9 = {
  ariaLabel: "arrow",
  fill: "none",
  stroke: "currentColor",
  strokeLinecap: "round",
  strokeMiterlimit: 1,
  strokeWidth: 1.5
};
var Arrow = class extends Mark {
  constructor(data, options = {}) {
    const {
      x1: x12,
      y1: y12,
      x2: x22,
      y2: y22,
      bend = 0,
      headAngle = 60,
      headLength = 8,
      // Disable the arrow with headLength = 0; or, use Plot.link.
      inset: inset2 = 0,
      insetStart = inset2,
      insetEnd = inset2,
      sweep
    } = options;
    super(
      data,
      {
        x1: { value: x12, scale: "x" },
        y1: { value: y12, scale: "y" },
        x2: { value: x22, scale: "x", optional: true },
        y2: { value: y22, scale: "y", optional: true }
      },
      options,
      defaults9
    );
    this.bend = bend === true ? 22.5 : Math.max(-90, Math.min(90, bend));
    this.headAngle = +headAngle;
    this.headLength = +headLength;
    this.insetStart = +insetStart;
    this.insetEnd = +insetEnd;
    this.sweep = maybeSweep(sweep);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x1: X13, y1: Y13, x2: X23 = X13, y2: Y23 = Y13, SW } = channels;
    const { strokeWidth, bend, headAngle, headLength, insetStart, insetEnd } = this;
    const sw = SW ? (i) => SW[i] : constant(strokeWidth === void 0 ? 1 : strokeWidth);
    const wingAngle = headAngle * radians3 / 2;
    const wingScale = headLength / 1.5;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call(
      (g) => g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr("d", (i) => {
        let x12 = X13[i], y12 = Y13[i], x22 = X23[i], y22 = Y23[i];
        const lineLength = Math.hypot(x22 - x12, y22 - y12);
        if (lineLength <= insetStart + insetEnd) return null;
        let lineAngle = Math.atan2(y22 - y12, x22 - x12);
        const headLength2 = Math.min(wingScale * sw(i), lineLength / 3);
        const bendAngle = this.sweep(x12, y12, x22, y22) * bend * radians3;
        const r = Math.hypot(lineLength / Math.tan(bendAngle), lineLength) / 2;
        if (insetStart || insetEnd) {
          if (r < 1e5) {
            const sign4 = Math.sign(bendAngle);
            const [cx, cy] = pointPointCenter([x12, y12], [x22, y22], r, sign4);
            if (insetStart) {
              [x12, y12] = circleCircleIntersect([cx, cy, r], [x12, y12, insetStart], -sign4 * Math.sign(insetStart));
            }
            if (insetEnd) {
              const [x5, y5] = circleCircleIntersect([cx, cy, r], [x22, y22, insetEnd], sign4 * Math.sign(insetEnd));
              lineAngle += Math.atan2(y5 - cy, x5 - cx) - Math.atan2(y22 - cy, x22 - cx);
              x22 = x5, y22 = y5;
            }
          } else {
            const dx = x22 - x12, dy = y22 - y12, d = Math.hypot(dx, dy);
            if (insetStart) x12 += dx / d * insetStart, y12 += dy / d * insetStart;
            if (insetEnd) x22 -= dx / d * insetEnd, y22 -= dy / d * insetEnd;
          }
        }
        const endAngle = lineAngle + bendAngle;
        const leftAngle = endAngle + wingAngle;
        const rightAngle = endAngle - wingAngle;
        const x3 = x22 - headLength2 * Math.cos(leftAngle);
        const y3 = y22 - headLength2 * Math.sin(leftAngle);
        const x4 = x22 - headLength2 * Math.cos(rightAngle);
        const y4 = y22 - headLength2 * Math.sin(rightAngle);
        const a2 = r < 1e5 ? `A${r},${r} 0,0,${bendAngle > 0 ? 1 : 0} ` : `L`;
        const h = headLength2 ? `M${x3},${y3}L${x22},${y22}L${x4},${y4}` : "";
        return `M${x12},${y12}${a2}${x22},${y22}${h}`;
      }).call(applyChannelStyles, this, channels)
    ).node();
  }
};
function maybeSweep(sweep = 1) {
  if (typeof sweep === "number") return constant(Math.sign(sweep));
  if (typeof sweep === "function") return (x12, y12, x22, y22) => Math.sign(sweep(x12, y12, x22, y22));
  switch (keyword(sweep, "sweep", ["+x", "-x", "+y", "-y"])) {
    case "+x":
      return (x12, y12, x22) => ascending(x12, x22);
    case "-x":
      return (x12, y12, x22) => descending(x12, x22);
    case "+y":
      return (x12, y12, x22, y22) => ascending(y12, y22);
    case "-y":
      return (x12, y12, x22, y22) => descending(y12, y22);
  }
}
function pointPointCenter([ax, ay], [bx, by], r, sign4) {
  const dx = bx - ax, dy = by - ay, d = Math.hypot(dx, dy);
  const k2 = sign4 * Math.sqrt(r * r - d * d / 4) / d;
  return [(ax + bx) / 2 - dy * k2, (ay + by) / 2 + dx * k2];
}
function circleCircleIntersect([ax, ay, ar], [bx, by, br], sign4) {
  const dx = bx - ax, dy = by - ay, d = Math.hypot(dx, dy);
  const x3 = (dx * dx + dy * dy - br * br + ar * ar) / (2 * d);
  const y3 = sign4 * Math.sqrt(ar * ar - x3 * x3);
  return [ax + (dx * x3 + dy * y3) / d, ay + (dy * x3 - dx * y3) / d];
}
function arrow(data, { x: x3, x1: x12, x2: x22, y: y3, y1: y12, y2: y22, ...options } = {}) {
  [x12, x22] = maybeSameValue(x3, x12, x22);
  [y12, y22] = maybeSameValue(y3, y12, y22);
  return new Arrow(data, { ...options, x1: x12, x2: x22, y1: y12, y2: y22 });
}

// ../../../node_modules/@observablehq/plot/src/marks/bar.js
var barDefaults = {
  ariaLabel: "bar"
};
var AbstractBar = class extends Mark {
  constructor(data, channels, options = {}, defaults22 = barDefaults) {
    super(data, channels, options, defaults22);
    rectInsets(this, options);
    rectRadii(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { rx, ry, rx1y1, rx1y2, rx2y1, rx2y2 } = this;
    const x3 = this._x(scales2, channels, dimensions);
    const y3 = this._y(scales2, channels, dimensions);
    const w = this._width(scales2, channels, dimensions);
    const h = this._height(scales2, channels, dimensions);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(this._transform, this, scales2).call(
      (g) => g.selectAll().data(index2).enter().call(
        rx1y1 || rx1y2 || rx2y1 || rx2y2 ? (g2) => g2.append("path").call(applyDirectStyles, this).call(applyRoundedRect, x3, y3, add2(x3, w), add2(y3, h), this).call(applyChannelStyles, this, channels) : (g2) => g2.append("rect").call(applyDirectStyles, this).attr("x", x3).attr("width", w).attr("y", y3).attr("height", h).call(applyAttr, "rx", rx).call(applyAttr, "ry", ry).call(applyChannelStyles, this, channels)
      )
    ).node();
  }
  _x(scales2, { x: X3 }, { marginLeft: marginLeft2 }) {
    const { insetLeft } = this;
    return X3 ? (i) => X3[i] + insetLeft : marginLeft2 + insetLeft;
  }
  _y(scales2, { y: Y3 }, { marginTop: marginTop2 }) {
    const { insetTop } = this;
    return Y3 ? (i) => Y3[i] + insetTop : marginTop2 + insetTop;
  }
  _width({ x: x3 }, { x: X3 }, { marginRight: marginRight2, marginLeft: marginLeft2, width: width2 }) {
    const { insetLeft, insetRight } = this;
    const bandwidth = X3 && x3 ? x3.bandwidth() : width2 - marginRight2 - marginLeft2;
    return Math.max(0, bandwidth - insetLeft - insetRight);
  }
  _height({ y: y3 }, { y: Y3 }, { marginTop: marginTop2, marginBottom: marginBottom2, height: height2 }) {
    const { insetTop, insetBottom } = this;
    const bandwidth = Y3 && y3 ? y3.bandwidth() : height2 - marginTop2 - marginBottom2;
    return Math.max(0, bandwidth - insetTop - insetBottom);
  }
};
function add2(a2, b) {
  return typeof a2 === "function" && typeof b === "function" ? (i) => a2(i) + b(i) : typeof a2 === "function" ? (i) => a2(i) + b : typeof b === "function" ? (i) => a2 + b(i) : a2 + b;
}
var BarX = class extends AbstractBar {
  constructor(data, options = {}, defaults22) {
    const { x1: x12, x2: x22, y: y3 } = options;
    super(
      data,
      {
        x1: { value: x12, scale: "x" },
        x2: { value: x22, scale: "x" },
        y: { value: y3, scale: "y", type: "band", optional: true }
      },
      options,
      defaults22
    );
  }
  _transform(selection2, mark2, { x: x3 }) {
    selection2.call(applyTransform, mark2, { x: x3 }, 0, 0);
  }
  _x({ x: x3 }, { x1: X13, x2: X23 }, { marginLeft: marginLeft2 }) {
    const { insetLeft } = this;
    return isCollapsed(x3) ? marginLeft2 + insetLeft : (i) => Math.min(X13[i], X23[i]) + insetLeft;
  }
  _width({ x: x3 }, { x1: X13, x2: X23 }, { marginRight: marginRight2, marginLeft: marginLeft2, width: width2 }) {
    const { insetLeft, insetRight } = this;
    return isCollapsed(x3) ? width2 - marginRight2 - marginLeft2 - insetLeft - insetRight : (i) => Math.max(0, Math.abs(X23[i] - X13[i]) - insetLeft - insetRight);
  }
};
var BarY = class extends AbstractBar {
  constructor(data, options = {}, defaults22) {
    const { x: x3, y1: y12, y2: y22 } = options;
    super(
      data,
      {
        y1: { value: y12, scale: "y" },
        y2: { value: y22, scale: "y" },
        x: { value: x3, scale: "x", type: "band", optional: true }
      },
      options,
      defaults22
    );
  }
  _transform(selection2, mark2, { y: y3 }) {
    selection2.call(applyTransform, mark2, { y: y3 }, 0, 0);
  }
  _y({ y: y3 }, { y1: Y13, y2: Y23 }, { marginTop: marginTop2 }) {
    const { insetTop } = this;
    return isCollapsed(y3) ? marginTop2 + insetTop : (i) => Math.min(Y13[i], Y23[i]) + insetTop;
  }
  _height({ y: y3 }, { y1: Y13, y2: Y23 }, { marginTop: marginTop2, marginBottom: marginBottom2, height: height2 }) {
    const { insetTop, insetBottom } = this;
    return isCollapsed(y3) ? height2 - marginTop2 - marginBottom2 - insetTop - insetBottom : (i) => Math.max(0, Math.abs(Y23[i] - Y13[i]) - insetTop - insetBottom);
  }
};
function barX(data, options = {}) {
  if (!hasXY(options)) options = { ...options, y: indexOf, x2: identity8 };
  return new BarX(data, maybeStackX(maybeIntervalX(maybeIdentityX(options))));
}
function barY(data, options = {}) {
  if (!hasXY(options)) options = { ...options, x: indexOf, y2: identity8 };
  return new BarY(data, maybeStackY(maybeIntervalY(maybeIdentityY(options))));
}

// ../../../node_modules/@observablehq/plot/src/marks/cell.js
var defaults10 = {
  ariaLabel: "cell"
};
var Cell = class extends AbstractBar {
  constructor(data, { x: x3, y: y3, ...options } = {}) {
    super(
      data,
      {
        x: { value: x3, scale: "x", type: "band", optional: true },
        y: { value: y3, scale: "y", type: "band", optional: true }
      },
      options,
      defaults10
    );
  }
  _transform(selection2, mark2) {
    selection2.call(applyTransform, mark2, {}, 0, 0);
  }
};
function cell(data, { x: x3, y: y3, ...options } = {}) {
  [x3, y3] = maybeTuple(x3, y3);
  return new Cell(data, { ...options, x: x3, y: y3 });
}
function cellX(data, { x: x3 = indexOf, fill, stroke, ...options } = {}) {
  if (fill === void 0 && maybeColorChannel(stroke)[0] === void 0) fill = identity8;
  return new Cell(data, { ...options, x: x3, fill, stroke });
}
function cellY(data, { y: y3 = indexOf, fill, stroke, ...options } = {}) {
  if (fill === void 0 && maybeColorChannel(stroke)[0] === void 0) fill = identity8;
  return new Cell(data, { ...options, y: y3, fill, stroke });
}

// ../../../node_modules/@observablehq/plot/src/marks/dot.js
var defaults11 = {
  ariaLabel: "dot",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5
};
function withDefaultSort(options) {
  return options.sort === void 0 && options.reverse === void 0 ? sort2({ channel: "-r" }, options) : options;
}
var Dot = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, r, rotate, symbol: symbol2 = circle_default2, frameAnchor } = options;
    const [vrotate, crotate] = maybeNumberChannel(rotate, 0);
    const [vsymbol, csymbol] = maybeSymbolChannel(symbol2);
    const [vr, cr] = maybeNumberChannel(r, vsymbol == null ? 3 : 4.5);
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        r: { value: vr, scale: "r", filter: positive, optional: true },
        rotate: { value: vrotate, optional: true },
        symbol: { value: vsymbol, scale: "auto", optional: true }
      },
      withDefaultSort(options),
      defaults11
    );
    this.r = cr;
    this.rotate = crotate;
    this.symbol = csymbol;
    this.frameAnchor = maybeFrameAnchor(frameAnchor);
    const { channels } = this;
    const { symbol: symbolChannel } = channels;
    if (symbolChannel) {
      const { fill: fillChannel, stroke: strokeChannel } = channels;
      symbolChannel.hint = {
        fill: fillChannel ? fillChannel.value === symbolChannel.value ? "color" : "currentColor" : this.fill ?? "currentColor",
        stroke: strokeChannel ? strokeChannel.value === symbolChannel.value ? "color" : "currentColor" : this.stroke ?? "none"
      };
    }
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, r: R, rotate: A5, symbol: S } = channels;
    const { r, rotate, symbol: symbol2 } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    const circle3 = symbol2 === circle_default2;
    const size = R ? void 0 : r * r * Math.PI;
    if (negative(r)) index2 = [];
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      (g) => g.selectAll().data(index2).enter().append(circle3 ? "circle" : "path").call(applyDirectStyles, this).call(
        circle3 ? (selection2) => {
          selection2.attr("cx", X3 ? (i) => X3[i] : cx).attr("cy", Y3 ? (i) => Y3[i] : cy).attr("r", R ? (i) => R[i] : r);
        } : (selection2) => {
          selection2.attr(
            "transform",
            template`translate(${X3 ? (i) => X3[i] : cx},${Y3 ? (i) => Y3[i] : cy})${A5 ? (i) => ` rotate(${A5[i]})` : rotate ? ` rotate(${rotate})` : ``}`
          ).attr(
            "d",
            R && S ? (i) => {
              const p = pathRound();
              S[i].draw(p, R[i] * R[i] * Math.PI);
              return p;
            } : R ? (i) => {
              const p = pathRound();
              symbol2.draw(p, R[i] * R[i] * Math.PI);
              return p;
            } : S ? (i) => {
              const p = pathRound();
              S[i].draw(p, size);
              return p;
            } : (() => {
              const p = pathRound();
              symbol2.draw(p, size);
              return p;
            })()
          );
        }
      ).call(applyChannelStyles, this, channels)
    ).node();
  }
};
function dot(data, { x: x3, y: y3, ...options } = {}) {
  if (options.frameAnchor === void 0) [x3, y3] = maybeTuple(x3, y3);
  return new Dot(data, { ...options, x: x3, y: y3 });
}
function dotX(data, { x: x3 = identity8, ...options } = {}) {
  return new Dot(data, maybeIntervalMidY({ ...options, x: x3 }));
}
function dotY(data, { y: y3 = identity8, ...options } = {}) {
  return new Dot(data, maybeIntervalMidX({ ...options, y: y3 }));
}
function circle(data, options) {
  return dot(data, { ...options, symbol: "circle" });
}
function hexagon(data, options) {
  return dot(data, { ...options, symbol: "hexagon" });
}

// ../../../node_modules/@observablehq/plot/src/marks/line.js
var defaults12 = {
  ariaLabel: "line",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  strokeMiterlimit: 1
};
var Line = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, z, curve, tension } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x" },
        y: { value: y3, scale: "y" },
        z: { value: maybeZ(options), optional: true }
      },
      options,
      defaults12
    );
    this.z = z;
    this.curve = maybeCurveAuto(curve, tension);
    markers(this, options);
  }
  filter(index2) {
    return index2;
  }
  project(channels, values2, context) {
    if (this.curve !== curveAuto) {
      super.project(channels, values2, context);
    }
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: X3, y: Y3 } = channels;
    const { curve } = this;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call(
      (g) => g.selectAll().data(groupIndex(index2, [X3, Y3], this, channels)).enter().append("path").call(applyDirectStyles, this).call(applyGroupedChannelStyles, this, channels).call(applyGroupedMarkers, this, channels, context).attr(
        "d",
        curve === curveAuto && context.projection ? sphereLine(context.path(), X3, Y3) : line_default2().curve(curve).defined((i) => i >= 0).x((i) => X3[i]).y((i) => Y3[i])
      )
    ).node();
  }
};
function sphereLine(path2, X3, Y3) {
  X3 = coerceNumbers(X3);
  Y3 = coerceNumbers(Y3);
  return (I) => {
    let line3 = [];
    const lines = [line3];
    for (const i of I) {
      if (i === -1) {
        line3 = [];
        lines.push(line3);
      } else {
        line3.push([X3[i], Y3[i]]);
      }
    }
    return path2({ type: "MultiLineString", coordinates: lines });
  };
}
function line(data, { x: x3, y: y3, ...options } = {}) {
  [x3, y3] = maybeTuple(x3, y3);
  return new Line(data, { ...options, x: x3, y: y3 });
}
function lineX(data, { x: x3 = identity8, y: y3 = indexOf, ...options } = {}) {
  return new Line(data, maybeDenseIntervalY({ ...options, x: x3, y: y3 }));
}
function lineY(data, { x: x3 = indexOf, y: y3 = identity8, ...options } = {}) {
  return new Line(data, maybeDenseIntervalX({ ...options, x: x3, y: y3 }));
}

// ../../../node_modules/@observablehq/plot/src/marks/auto.js
function autoSpec(data, options) {
  options = normalizeOptions(options);
  const { x: x3, y: y3, color: color3, size } = options;
  const X3 = materializeValue(data, x3);
  const Y3 = materializeValue(data, y3);
  const C3 = materializeValue(data, color3);
  const S = materializeValue(data, size);
  let {
    fx,
    fy,
    x: { value: xValue, reduce: xReduce, zero: xZero2, ...xOptions },
    y: { value: yValue, reduce: yReduce, zero: yZero2, ...yOptions },
    color: { value: colorValue, color: colorColor, reduce: colorReduce },
    size: { value: sizeValue, reduce: sizeReduce },
    // TODO constant radius?
    mark: mark2
  } = options;
  if (xReduce === void 0)
    xReduce = yReduce == null && xValue == null && sizeValue == null && yValue != null ? "count" : null;
  if (yReduce === void 0)
    yReduce = xReduce == null && yValue == null && sizeValue == null && xValue != null ? "count" : null;
  if (sizeReduce === void 0 && sizeValue == null && colorReduce == null && xReduce == null && yReduce == null && (xValue == null || isOrdinal(X3)) && (yValue == null || isOrdinal(Y3))) {
    sizeReduce = "count";
  }
  if (xZero2 === void 0) xZero2 = isZeroReducer(xReduce) ? true : void 0;
  if (yZero2 === void 0) yZero2 = isZeroReducer(yReduce) ? true : void 0;
  if (xValue == null && yValue == null) throw new Error("must specify x or y");
  if (xReduce != null && yValue == null) throw new Error("reducing x requires y");
  if (yReduce != null && xValue == null) throw new Error("reducing y requires x");
  if (mark2 === void 0) {
    mark2 = sizeValue != null || sizeReduce != null ? "dot" : isZeroReducer(xReduce) || isZeroReducer(yReduce) || colorReduce != null ? "bar" : xValue != null && yValue != null ? isOrdinal(X3) || isOrdinal(Y3) || xReduce == null && yReduce == null && !isMonotonic(X3) && !isMonotonic(Y3) ? "dot" : "line" : xValue != null || yValue != null ? "rule" : null;
  }
  let Z;
  let colorMode;
  let markImpl;
  switch (mark2) {
    case "dot":
      markImpl = dot;
      colorMode = "stroke";
      break;
    case "line":
      markImpl = X3 && Y3 || xReduce != null || yReduce != null ? yZero2 || yReduce != null || X3 && isMonotonic(X3) ? lineY : xZero2 || xReduce != null || Y3 && isMonotonic(Y3) ? lineX : line : X3 ? lineX : lineY;
      colorMode = "stroke";
      if (isHighCardinality(C3)) Z = null;
      break;
    case "area":
      markImpl = !(yZero2 || yReduce != null) && (xZero2 || xReduce != null || Y3 && isMonotonic(Y3)) ? areaX : areaY;
      colorMode = "fill";
      if (isHighCardinality(C3)) Z = null;
      break;
    case "rule":
      markImpl = X3 ? ruleX : ruleY;
      colorMode = "stroke";
      break;
    case "bar":
      markImpl = xReduce != null ? isOrdinal(Y3) ? isSelectReducer(xReduce) && X3 && isOrdinal(X3) ? cell : barX : rectX : yReduce != null ? isOrdinal(X3) ? isSelectReducer(yReduce) && Y3 && isOrdinal(Y3) ? cell : barY : rectY : colorReduce != null || sizeReduce != null ? X3 && isOrdinal(X3) && Y3 && isOrdinal(Y3) ? cell : X3 && isOrdinal(X3) ? barY : Y3 && isOrdinal(Y3) ? barX : rect : X3 && isNumeric(X3) && !(Y3 && isNumeric(Y3)) ? barX : Y3 && isNumeric(Y3) && !(X3 && isNumeric(X3)) ? barY : cell;
      colorMode = "fill";
      break;
    default:
      throw new Error(`invalid mark: ${mark2}`);
  }
  let markOptions2 = {
    fx,
    fy,
    x: X3 ?? void 0,
    // treat null x as undefined for implicit stack
    y: Y3 ?? void 0,
    // treat null y as undefined for implicit stack
    [colorMode]: C3 ?? colorColor,
    z: Z,
    r: S ?? void 0,
    // treat null size as undefined for default constant radius
    tip: true
  };
  let transformImpl;
  let transformOptions = { [colorMode]: colorReduce ?? void 0, r: sizeReduce ?? void 0 };
  if (xReduce != null && yReduce != null) {
    throw new Error(`cannot reduce both x and y`);
  } else if (yReduce != null) {
    transformOptions.y = yReduce;
    transformImpl = isOrdinal(X3) ? groupX : binX;
  } else if (xReduce != null) {
    transformOptions.x = xReduce;
    transformImpl = isOrdinal(Y3) ? groupY : binY;
  } else if (colorReduce != null || sizeReduce != null) {
    if (X3 && Y3) {
      transformImpl = isOrdinal(X3) && isOrdinal(Y3) ? group2 : isOrdinal(X3) ? binY : isOrdinal(Y3) ? binX : bin;
    } else if (X3) {
      transformImpl = isOrdinal(X3) ? groupX : binX;
    } else if (Y3) {
      transformImpl = isOrdinal(Y3) ? groupY : binY;
    }
  }
  if (transformImpl === bin || transformImpl === binX) markOptions2.x = { value: X3, ...xOptions };
  if (transformImpl === bin || transformImpl === binY) markOptions2.y = { value: Y3, ...yOptions };
  if (xZero2 === void 0)
    xZero2 = X3 && !(transformImpl === bin || transformImpl === binX) && (markImpl === barX || markImpl === areaX || markImpl === rectX || markImpl === ruleY);
  if (yZero2 === void 0)
    yZero2 = Y3 && !(transformImpl === bin || transformImpl === binY) && (markImpl === barY || markImpl === areaY || markImpl === rectY || markImpl === ruleX);
  return {
    fx: fx ?? null,
    fy: fy ?? null,
    x: {
      value: xValue ?? null,
      reduce: xReduce ?? null,
      zero: !!xZero2,
      ...xOptions
    },
    y: {
      value: yValue ?? null,
      reduce: yReduce ?? null,
      zero: !!yZero2,
      ...yOptions
    },
    color: {
      value: colorValue ?? null,
      reduce: colorReduce ?? null,
      ...colorColor !== void 0 && { color: colorColor }
    },
    size: {
      value: sizeValue ?? null,
      reduce: sizeReduce ?? null
    },
    mark: mark2,
    markImpl: implNames[markImpl],
    markOptions: markOptions2,
    transformImpl: implNames[transformImpl],
    transformOptions,
    colorMode
  };
}
function auto(data, options) {
  const spec = autoSpec(data, options);
  const {
    fx,
    fy,
    x: { zero: xZero2 },
    y: { zero: yZero2 },
    markOptions: markOptions2,
    transformOptions,
    colorMode
  } = spec;
  const markImpl = impls[spec.markImpl];
  const transformImpl = impls[spec.transformImpl];
  const frames = fx != null || fy != null ? frame2({ strokeOpacity: 0.1 }) : null;
  const rules = [xZero2 ? ruleX([0]) : null, yZero2 ? ruleY([0]) : null];
  const mark2 = markImpl(data, transformImpl ? transformImpl(transformOptions, markOptions2) : markOptions2);
  return colorMode === "stroke" ? marks(frames, rules, mark2) : marks(frames, mark2, rules);
}
function isMonotonic(values2) {
  let previous;
  let previousOrder;
  for (const value of values2) {
    if (value == null) continue;
    if (previous === void 0) {
      previous = value;
      continue;
    }
    const order = Math.sign(ascending(previous, value));
    if (!order) continue;
    if (previousOrder !== void 0 && order !== previousOrder) return false;
    previous = value;
    previousOrder = order;
  }
  return true;
}
function normalizeOptions({ x: x3, y: y3, color: color3, size, fx, fy, mark: mark2 } = {}) {
  if (!isOptions(x3)) x3 = makeOptions(x3);
  if (!isOptions(y3)) y3 = makeOptions(y3);
  if (!isOptions(color3)) color3 = isColor(color3) ? { color: color3 } : makeOptions(color3);
  if (!isOptions(size)) size = makeOptions(size);
  if (isOptions(fx)) ({ value: fx } = makeOptions(fx));
  if (isOptions(fy)) ({ value: fy } = makeOptions(fy));
  if (mark2 != null) mark2 = `${mark2}`.toLowerCase();
  return { x: x3, y: y3, color: color3, size, fx, fy, mark: mark2 };
}
function materializeValue(data, options) {
  const V = valueof(data, options.value);
  if (V) V.label = labelof(options.value);
  return V;
}
function makeOptions(value) {
  return isReducer(value) ? { reduce: value } : { value };
}
function isZeroReducer(reduce) {
  return /^(?:distinct|count|sum|proportion)$/i.test(reduce);
}
function isSelectReducer(reduce) {
  return /^(?:first|last|mode)$/i.test(reduce);
}
function isReducer(reduce) {
  if (reduce == null) return false;
  if (typeof reduce.reduceIndex === "function") return true;
  if (typeof reduce.reduce === "function" && isObject(reduce)) return true;
  if (/^p\d{2}$/i.test(reduce)) return true;
  switch (`${reduce}`.toLowerCase()) {
    case "first":
    case "last":
    case "count":
    case "distinct":
    case "sum":
    case "proportion":
    case "proportion-facet":
    // TODO remove me?
    case "deviation":
    case "min":
    case "min-index":
    // TODO remove me?
    case "max":
    case "max-index":
    // TODO remove me?
    case "mean":
    case "median":
    case "variance":
    case "mode":
      return true;
  }
  return false;
}
function isHighCardinality(value) {
  return value ? new InternSet(value).size > value.length >> 1 : false;
}
var impls = {
  dot,
  line,
  lineX,
  lineY,
  areaX,
  areaY,
  ruleX,
  ruleY,
  barX,
  barY,
  rect,
  rectX,
  rectY,
  cell,
  bin,
  binX,
  binY,
  group: group2,
  groupX,
  groupY
};
var implNames = Object.fromEntries(Object.entries(impls).map(([name2, impl]) => [impl, name2]));

// ../../../node_modules/@observablehq/plot/src/transforms/map.js
function mapX(mapper, options = {}) {
  let { x: x3, x1: x12, x2: x22 } = options;
  if (x3 === void 0 && x12 === void 0 && x22 === void 0) options = { ...options, x: x3 = identity8 };
  const outputs = {};
  if (x3 != null) outputs.x = mapper;
  if (x12 != null) outputs.x1 = mapper;
  if (x22 != null) outputs.x2 = mapper;
  return map4(outputs, options);
}
function mapY(mapper, options = {}) {
  let { y: y3, y1: y12, y2: y22 } = options;
  if (y3 === void 0 && y12 === void 0 && y22 === void 0) options = { ...options, y: y3 = identity8 };
  const outputs = {};
  if (y3 != null) outputs.y = mapper;
  if (y12 != null) outputs.y1 = mapper;
  if (y22 != null) outputs.y2 = mapper;
  return map4(outputs, options);
}
function map4(outputs = {}, options = {}) {
  const z = maybeZ(options);
  const channels = Object.entries(outputs).map(([key, map5]) => {
    const input3 = maybeInput(key, options);
    if (input3 == null) throw new Error(`missing channel: ${key}`);
    const [output, setOutput] = column2(input3);
    return { key, input: input3, output, setOutput, map: maybeMap(map5) };
  });
  return {
    ...basic(options, (data, facets) => {
      const Z = valueof(data, z);
      const X3 = channels.map(({ input: input3 }) => valueof(data, input3));
      const MX = channels.map(({ setOutput }) => setOutput(new Array(data.length)));
      for (const facet of facets) {
        for (const I of Z ? group(facet, (i) => Z[i]).values() : [facet]) {
          channels.forEach(({ map: map5 }, i) => map5.mapIndex(I, X3[i], MX[i]));
        }
      }
      return { data, facets };
    }),
    ...Object.fromEntries(channels.map(({ key, output }) => [key, output]))
  };
}
function maybeMap(map5) {
  if (map5 == null) throw new Error("missing map");
  if (typeof map5.mapIndex === "function") return map5;
  if (typeof map5.map === "function" && isObject(map5)) return mapMap(map5);
  if (typeof map5 === "function") return mapFunction(taker(map5));
  switch (`${map5}`.toLowerCase()) {
    case "cumsum":
      return mapCumsum;
    case "rank":
      return mapFunction((I, V) => rank2(I, (i) => V[i]));
    case "quantile":
      return mapFunction((I, V) => rankQuantile(I, (i) => V[i]));
  }
  throw new Error(`invalid map: ${map5}`);
}
function mapMap(map5) {
  console.warn("deprecated map interface; implement mapIndex instead.");
  return { mapIndex: map5.map.bind(map5) };
}
function rankQuantile(I, f) {
  const n = count2(I, f) - 1;
  return rank2(I, f).map((r) => r / n);
}
function mapFunction(f) {
  return {
    mapIndex(I, S, T) {
      const M2 = f(I, S);
      if (M2.length !== I.length) throw new Error("map function returned a mismatched length");
      for (let i = 0, n = I.length; i < n; ++i) T[I[i]] = M2[i];
    }
  };
}
var mapCumsum = {
  mapIndex(I, S, T) {
    let sum4 = 0;
    for (const i of I) T[i] = sum4 += S[i];
  }
};

// ../../../node_modules/@observablehq/plot/src/transforms/window.js
function windowX(windowOptions = {}, options) {
  if (arguments.length === 1) options = windowOptions;
  return mapX(window2(windowOptions), options);
}
function windowY(windowOptions = {}, options) {
  if (arguments.length === 1) options = windowOptions;
  return mapY(window2(windowOptions), options);
}
function window2(options = {}) {
  if (typeof options === "number") options = { k: options };
  let { k: k2, reduce, shift, anchor, strict } = options;
  if (anchor === void 0 && shift !== void 0) {
    anchor = maybeShift(shift);
    warn(`Warning: the shift option is deprecated; please use anchor "${anchor}" instead.`);
  }
  if (!((k2 = Math.floor(k2)) > 0)) throw new Error(`invalid k: ${k2}`);
  return maybeReduce2(reduce)(k2, maybeAnchor3(anchor, k2), strict);
}
function maybeAnchor3(anchor = "middle", k2) {
  switch (`${anchor}`.toLowerCase()) {
    case "middle":
      return k2 - 1 >> 1;
    case "start":
      return 0;
    case "end":
      return k2 - 1;
  }
  throw new Error(`invalid anchor: ${anchor}`);
}
function maybeShift(shift) {
  switch (`${shift}`.toLowerCase()) {
    case "centered":
      return "middle";
    case "leading":
      return "start";
    case "trailing":
      return "end";
  }
  throw new Error(`invalid shift: ${shift}`);
}
function maybeReduce2(reduce = "mean") {
  if (typeof reduce === "string") {
    if (/^p\d{2}$/i.test(reduce)) return reduceAccessor2(percentile(reduce));
    switch (reduce.toLowerCase()) {
      case "deviation":
        return reduceAccessor2(deviation);
      case "max":
        return reduceArray((I, V) => max2(I, (i) => V[i]));
      case "mean":
        return reduceMean;
      case "median":
        return reduceAccessor2(median2);
      case "min":
        return reduceArray((I, V) => min2(I, (i) => V[i]));
      case "mode":
        return reduceArray((I, V) => mode2(I, (i) => V[i]));
      case "sum":
        return reduceSum2;
      case "variance":
        return reduceAccessor2(variance2);
      case "difference":
        return reduceDifference;
      case "ratio":
        return reduceRatio;
      case "first":
        return reduceFirst2;
      case "last":
        return reduceLast2;
    }
  }
  if (typeof reduce !== "function") throw new Error(`invalid reduce: ${reduce}`);
  return reduceArray(taker(reduce));
}
function reduceAccessor2(f) {
  return (k2, s2, strict) => strict ? {
    mapIndex(I, S, T) {
      const v2 = (i) => S[i] == null ? NaN : +S[i];
      let nans = 0;
      for (let i = 0; i < k2 - 1; ++i) if (isNaN(v2(i))) ++nans;
      for (let i = 0, n = I.length - k2 + 1; i < n; ++i) {
        if (isNaN(v2(i + k2 - 1))) ++nans;
        T[I[i + s2]] = nans === 0 ? f(subarray(I, i, i + k2), v2) : NaN;
        if (isNaN(v2(i))) --nans;
      }
    }
  } : {
    mapIndex(I, S, T) {
      const v2 = (i) => S[i] == null ? NaN : +S[i];
      for (let i = -s2; i < 0; ++i) {
        T[I[i + s2]] = f(subarray(I, 0, i + k2), v2);
      }
      for (let i = 0, n = I.length - s2; i < n; ++i) {
        T[I[i + s2]] = f(subarray(I, i, i + k2), v2);
      }
    }
  };
}
function reduceArray(f) {
  return (k2, s2, strict) => strict ? {
    mapIndex(I, S, T) {
      let count4 = 0;
      for (let i = 0; i < k2 - 1; ++i) count4 += defined(S[I[i]]);
      for (let i = 0, n = I.length - k2 + 1; i < n; ++i) {
        count4 += defined(S[I[i + k2 - 1]]);
        if (count4 === k2) T[I[i + s2]] = f(subarray(I, i, i + k2), S);
        count4 -= defined(S[I[i]]);
      }
    }
  } : {
    mapIndex(I, S, T) {
      for (let i = -s2; i < 0; ++i) {
        T[I[i + s2]] = f(subarray(I, 0, i + k2), S);
      }
      for (let i = 0, n = I.length - s2; i < n; ++i) {
        T[I[i + s2]] = f(subarray(I, i, i + k2), S);
      }
    }
  };
}
function reduceSum2(k2, s2, strict) {
  return strict ? {
    mapIndex(I, S, T) {
      let nans = 0;
      let sum4 = 0;
      for (let i = 0; i < k2 - 1; ++i) {
        const v2 = S[I[i]];
        if (v2 === null || isNaN(v2)) ++nans;
        else sum4 += +v2;
      }
      for (let i = 0, n = I.length - k2 + 1; i < n; ++i) {
        const a2 = S[I[i]];
        const b = S[I[i + k2 - 1]];
        if (b === null || isNaN(b)) ++nans;
        else sum4 += +b;
        T[I[i + s2]] = nans === 0 ? sum4 : NaN;
        if (a2 === null || isNaN(a2)) --nans;
        else sum4 -= +a2;
      }
    }
  } : {
    mapIndex(I, S, T) {
      let sum4 = 0;
      const n = I.length;
      for (let i = 0, j = Math.min(n, k2 - s2 - 1); i < j; ++i) {
        sum4 += +S[I[i]] || 0;
      }
      for (let i = -s2, j = n - s2; i < j; ++i) {
        sum4 += +S[I[i + k2 - 1]] || 0;
        T[I[i + s2]] = sum4;
        sum4 -= +S[I[i]] || 0;
      }
    }
  };
}
function reduceMean(k2, s2, strict) {
  if (strict) {
    const sum4 = reduceSum2(k2, s2, strict);
    return {
      mapIndex(I, S, T) {
        sum4.mapIndex(I, S, T);
        for (let i = 0, n = I.length - k2 + 1; i < n; ++i) {
          T[I[i + s2]] /= k2;
        }
      }
    };
  } else {
    return {
      mapIndex(I, S, T) {
        let sum4 = 0;
        let count4 = 0;
        const n = I.length;
        for (let i = 0, j = Math.min(n, k2 - s2 - 1); i < j; ++i) {
          let v2 = S[I[i]];
          if (v2 !== null && !isNaN(v2 = +v2)) sum4 += v2, ++count4;
        }
        for (let i = -s2, j = n - s2; i < j; ++i) {
          let a2 = S[I[i + k2 - 1]];
          let b = S[I[i]];
          if (a2 !== null && !isNaN(a2 = +a2)) sum4 += a2, ++count4;
          T[I[i + s2]] = sum4 / count4;
          if (b !== null && !isNaN(b = +b)) sum4 -= b, --count4;
        }
      }
    };
  }
}
function firstDefined(S, I, i, k2) {
  for (let j = i + k2; i < j; ++i) {
    const v2 = S[I[i]];
    if (defined(v2)) return v2;
  }
}
function lastDefined(S, I, i, k2) {
  for (let j = i + k2 - 1; j >= i; --j) {
    const v2 = S[I[j]];
    if (defined(v2)) return v2;
  }
}
function firstNumber(S, I, i, k2) {
  for (let j = i + k2; i < j; ++i) {
    let v2 = S[I[i]];
    if (v2 !== null && !isNaN(v2 = +v2)) return v2;
  }
}
function lastNumber(S, I, i, k2) {
  for (let j = i + k2 - 1; j >= i; --j) {
    let v2 = S[I[j]];
    if (v2 !== null && !isNaN(v2 = +v2)) return v2;
  }
}
function reduceDifference(k2, s2, strict) {
  return strict ? {
    mapIndex(I, S, T) {
      for (let i = 0, n = I.length - k2; i < n; ++i) {
        const a2 = S[I[i]];
        const b = S[I[i + k2 - 1]];
        T[I[i + s2]] = a2 === null || b === null ? NaN : b - a2;
      }
    }
  } : {
    mapIndex(I, S, T) {
      for (let i = -s2, n = I.length - k2 + s2 + 1; i < n; ++i) {
        T[I[i + s2]] = lastNumber(S, I, i, k2) - firstNumber(S, I, i, k2);
      }
    }
  };
}
function reduceRatio(k2, s2, strict) {
  return strict ? {
    mapIndex(I, S, T) {
      for (let i = 0, n = I.length - k2; i < n; ++i) {
        const a2 = S[I[i]];
        const b = S[I[i + k2 - 1]];
        T[I[i + s2]] = a2 === null || b === null ? NaN : b / a2;
      }
    }
  } : {
    mapIndex(I, S, T) {
      for (let i = -s2, n = I.length - k2 + s2 + 1; i < n; ++i) {
        T[I[i + s2]] = lastNumber(S, I, i, k2) / firstNumber(S, I, i, k2);
      }
    }
  };
}
function reduceFirst2(k2, s2, strict) {
  return strict ? {
    mapIndex(I, S, T) {
      for (let i = 0, n = I.length - k2; i < n; ++i) {
        T[I[i + s2]] = S[I[i]];
      }
    }
  } : {
    mapIndex(I, S, T) {
      for (let i = -s2, n = I.length - k2 + s2 + 1; i < n; ++i) {
        T[I[i + s2]] = firstDefined(S, I, i, k2);
      }
    }
  };
}
function reduceLast2(k2, s2, strict) {
  return strict ? {
    mapIndex(I, S, T) {
      for (let i = 0, n = I.length - k2; i < n; ++i) {
        T[I[i + s2]] = S[I[i + k2 - 1]];
      }
    }
  } : {
    mapIndex(I, S, T) {
      for (let i = -s2, n = I.length - k2 + s2 + 1; i < n; ++i) {
        T[I[i + s2]] = lastDefined(S, I, i, k2);
      }
    }
  };
}

// ../../../node_modules/@observablehq/plot/src/marks/bollinger.js
var defaults13 = {
  n: 20,
  k: 2,
  color: "currentColor",
  opacity: 0.2,
  strict: true,
  anchor: "end"
};
function bollingerX(data, {
  x: x3 = identity8,
  y: y3,
  k: k2 = defaults13.k,
  color: color3 = defaults13.color,
  opacity: opacity2 = defaults13.opacity,
  fill = color3,
  fillOpacity = opacity2,
  stroke = color3,
  strokeOpacity,
  strokeWidth,
  ...options
} = {}) {
  return marks(
    isNoneish(fill) ? null : areaX(
      data,
      map4(
        { x1: bollinger({ k: -k2, ...options }), x2: bollinger({ k: k2, ...options }) },
        { x1: x3, x2: x3, y: y3, fill, fillOpacity, ...options }
      )
    ),
    isNoneish(stroke) ? null : lineX(data, map4({ x: bollinger(options) }, { x: x3, y: y3, stroke, strokeOpacity, strokeWidth, ...options }))
  );
}
function bollingerY(data, {
  x: x3,
  y: y3 = identity8,
  k: k2 = defaults13.k,
  color: color3 = defaults13.color,
  opacity: opacity2 = defaults13.opacity,
  fill = color3,
  fillOpacity = opacity2,
  stroke = color3,
  strokeOpacity,
  strokeWidth,
  ...options
} = {}) {
  return marks(
    isNoneish(fill) ? null : areaY(
      data,
      map4(
        { y1: bollinger({ k: -k2, ...options }), y2: bollinger({ k: k2, ...options }) },
        { x: x3, y1: y3, y2: y3, fill, fillOpacity, ...options }
      )
    ),
    isNoneish(stroke) ? null : lineY(data, map4({ y: bollinger(options) }, { x: x3, y: y3, stroke, strokeOpacity, strokeWidth, ...options }))
  );
}
function bollinger({ n = defaults13.n, k: k2 = 0, strict = defaults13.strict, anchor = defaults13.anchor } = {}) {
  return window2({ k: n, reduce: (Y3) => mean(Y3) + k2 * (deviation(Y3) || 0), strict, anchor });
}

// ../../../node_modules/@observablehq/plot/src/marks/tick.js
var defaults14 = {
  ariaLabel: "tick",
  fill: null,
  stroke: "currentColor"
};
var AbstractTick = class extends Mark {
  constructor(data, channels, options) {
    super(data, channels, options, defaults14);
    markers(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(this._transform, this, scales2).call(
      (g) => g.selectAll().data(index2).enter().append("line").call(applyDirectStyles, this).attr("x1", this._x1(scales2, channels, dimensions)).attr("x2", this._x2(scales2, channels, dimensions)).attr("y1", this._y1(scales2, channels, dimensions)).attr("y2", this._y2(scales2, channels, dimensions)).call(applyChannelStyles, this, channels).call(applyMarkers, this, channels, context)
    ).node();
  }
};
var TickX = class extends AbstractTick {
  constructor(data, options = {}) {
    const { x: x3, y: y3, inset: inset2 = 0, insetTop = inset2, insetBottom = inset2 } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x" },
        y: { value: y3, scale: "y", type: "band", optional: true }
      },
      options
    );
    this.insetTop = number5(insetTop);
    this.insetBottom = number5(insetBottom);
  }
  _transform(selection2, mark2, { x: x3 }) {
    selection2.call(applyTransform, mark2, { x: x3 }, offset, 0);
  }
  _x1(scales2, { x: X3 }) {
    return (i) => X3[i];
  }
  _x2(scales2, { x: X3 }) {
    return (i) => X3[i];
  }
  _y1({ y: y3 }, { y: Y3 }, { marginTop: marginTop2 }) {
    const { insetTop } = this;
    return Y3 && y3 ? (i) => Y3[i] + insetTop : marginTop2 + insetTop;
  }
  _y2({ y: y3 }, { y: Y3 }, { height: height2, marginBottom: marginBottom2 }) {
    const { insetBottom } = this;
    return Y3 && y3 ? (i) => Y3[i] + y3.bandwidth() - insetBottom : height2 - marginBottom2 - insetBottom;
  }
};
var TickY = class extends AbstractTick {
  constructor(data, options = {}) {
    const { x: x3, y: y3, inset: inset2 = 0, insetRight = inset2, insetLeft = inset2 } = options;
    super(
      data,
      {
        y: { value: y3, scale: "y" },
        x: { value: x3, scale: "x", type: "band", optional: true }
      },
      options
    );
    this.insetRight = number5(insetRight);
    this.insetLeft = number5(insetLeft);
  }
  _transform(selection2, mark2, { y: y3 }) {
    selection2.call(applyTransform, mark2, { y: y3 }, 0, offset);
  }
  _x1({ x: x3 }, { x: X3 }, { marginLeft: marginLeft2 }) {
    const { insetLeft } = this;
    return X3 && x3 ? (i) => X3[i] + insetLeft : marginLeft2 + insetLeft;
  }
  _x2({ x: x3 }, { x: X3 }, { width: width2, marginRight: marginRight2 }) {
    const { insetRight } = this;
    return X3 && x3 ? (i) => X3[i] + x3.bandwidth() - insetRight : width2 - marginRight2 - insetRight;
  }
  _y1(scales2, { y: Y3 }) {
    return (i) => Y3[i];
  }
  _y2(scales2, { y: Y3 }) {
    return (i) => Y3[i];
  }
};
function tickX(data, { x: x3 = identity8, ...options } = {}) {
  return new TickX(data, { ...options, x: x3 });
}
function tickY(data, { y: y3 = identity8, ...options } = {}) {
  return new TickY(data, { ...options, y: y3 });
}

// ../../../node_modules/@observablehq/plot/src/marks/box.js
function boxX(data, {
  x: x3 = identity8,
  y: y3 = null,
  r,
  fill = "#ccc",
  fillOpacity,
  stroke = "currentColor",
  strokeOpacity,
  strokeWidth = 2,
  sort: sort3,
  ...options
} = {}) {
  const group3 = y3 != null ? groupY : groupZ;
  return marks(
    ruleY(data, group3({ x1: loqr1, x2: hiqr2 }, { x: x3, y: y3, stroke, strokeOpacity, ...options })),
    barX(data, group3({ x1: "p25", x2: "p75" }, { x: x3, y: y3, fill, fillOpacity, ...options })),
    tickX(data, group3({ x: "p50" }, { x: x3, y: y3, stroke, strokeOpacity, strokeWidth, sort: sort3, ...options })),
    dot(data, map4({ x: oqr }, { x: x3, y: y3, z: y3, r, stroke, strokeOpacity, ...options }))
  );
}
function boxY(data, {
  y: y3 = identity8,
  x: x3 = null,
  r,
  fill = "#ccc",
  fillOpacity,
  stroke = "currentColor",
  strokeOpacity,
  strokeWidth = 2,
  sort: sort3,
  ...options
} = {}) {
  const group3 = x3 != null ? groupX : groupZ;
  return marks(
    ruleX(data, group3({ y1: loqr1, y2: hiqr2 }, { x: x3, y: y3, stroke, strokeOpacity, ...options })),
    barY(data, group3({ y1: "p25", y2: "p75" }, { x: x3, y: y3, fill, fillOpacity, ...options })),
    tickY(data, group3({ y: "p50" }, { x: x3, y: y3, stroke, strokeOpacity, strokeWidth, sort: sort3, ...options })),
    dot(data, map4({ y: oqr }, { x: x3, y: y3, z: x3, r, stroke, strokeOpacity, ...options }))
  );
}
function oqr(values2) {
  const r1 = loqr1(values2);
  const r2 = hiqr2(values2);
  return values2.map((v2) => v2 < r1 || v2 > r2 ? v2 : NaN);
}
function loqr1(values2) {
  const lo = quartile1(values2) * 2.5 - quartile3(values2) * 1.5;
  return min2(values2, (d) => d >= lo ? d : NaN);
}
function hiqr2(values2) {
  const hi = quartile3(values2) * 2.5 - quartile1(values2) * 1.5;
  return max2(values2, (d) => d <= hi ? d : NaN);
}
function quartile1(values2) {
  return quantile2(values2, 0.25);
}
function quartile3(values2) {
  return quantile2(values2, 0.75);
}

// ../../../node_modules/@observablehq/plot/src/marks/raster.js
var defaults15 = {
  ariaLabel: "raster",
  stroke: null,
  pixelSize: 1
};
function number6(input3, name2) {
  const x3 = +input3;
  if (isNaN(x3)) throw new Error(`invalid ${name2}: ${input3}`);
  return x3;
}
function integer(input3, name2) {
  const x3 = Math.floor(input3);
  if (isNaN(x3)) throw new Error(`invalid ${name2}: ${input3}`);
  return x3;
}
var AbstractRaster = class extends Mark {
  constructor(data, channels, options = {}, defaults22) {
    let {
      width: width2,
      height: height2,
      x: x3,
      y: y3,
      x1: x12 = x3 == null ? 0 : void 0,
      y1: y12 = y3 == null ? 0 : void 0,
      x2: x22 = x3 == null ? width2 : void 0,
      y2: y22 = y3 == null ? height2 : void 0,
      pixelSize = defaults22.pixelSize,
      blur: blur3 = 0,
      interpolate
    } = options;
    if (width2 != null) width2 = integer(width2, "width");
    if (height2 != null) height2 = integer(height2, "height");
    if (x12 != null) x12 = number6(x12, "x1");
    if (y12 != null) y12 = number6(y12, "y1");
    if (x22 != null) x22 = number6(x22, "x2");
    if (y22 != null) y22 = number6(y22, "y2");
    if (x3 == null && (x12 == null || x22 == null)) throw new Error("missing x");
    if (y3 == null && (y12 == null || y22 == null)) throw new Error("missing y");
    if (data != null && width2 != null && height2 != null) {
      if (x3 === void 0 && x12 != null && x22 != null) x3 = denseX(x12, x22, width2, height2);
      if (y3 === void 0 && y12 != null && y22 != null) y3 = denseY(y12, y22, width2, height2);
    }
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        x1: { value: x12 == null ? null : [x12], scale: "x", optional: true, filter: null },
        y1: { value: y12 == null ? null : [y12], scale: "y", optional: true, filter: null },
        x2: { value: x22 == null ? null : [x22], scale: "x", optional: true, filter: null },
        y2: { value: y22 == null ? null : [y22], scale: "y", optional: true, filter: null },
        ...channels
      },
      options,
      defaults22
    );
    this.width = width2;
    this.height = height2;
    this.pixelSize = number6(pixelSize, "pixelSize");
    this.blur = number6(blur3, "blur");
    this.interpolate = x3 == null || y3 == null ? null : maybeInterpolate(interpolate);
  }
};
var Raster = class extends AbstractRaster {
  constructor(data, options = {}) {
    const { imageRendering } = options;
    if (data == null) {
      const { fill, fillOpacity } = options;
      if (maybeNumberChannel(fillOpacity)[0] !== void 0) options = sampler("fillOpacity", options);
      if (maybeColorChannel(fill)[0] !== void 0) options = sampler("fill", options);
    }
    super(data, void 0, options, defaults15);
    this.imageRendering = impliedString(imageRendering, "auto");
  }
  // Ignore the color scale, so the fill channel is returned unscaled.
  scale(channels, { color: color3, ...scales2 }, context) {
    return super.scale(channels, scales2, context);
  }
  render(index2, scales2, values2, dimensions, context) {
    const color3 = scales2[values2.channels.fill?.scale] ?? ((x3) => x3);
    const { x: X3, y: Y3 } = values2;
    const { document: document2 } = context;
    const [x12, y12, x22, y22] = renderBounds(values2, dimensions, context);
    const dx = x22 - x12;
    const dy = y22 - y12;
    const { pixelSize: k2, width: w = Math.round(Math.abs(dx) / k2), height: h = Math.round(Math.abs(dy) / k2) } = this;
    const n = w * h;
    let { fill: F, fillOpacity: FO } = values2;
    let offset2 = 0;
    if (this.interpolate) {
      const kx2 = w / dx;
      const ky2 = h / dy;
      const IX = map3(X3, (x3) => (x3 - x12) * kx2, Float64Array);
      const IY = map3(Y3, (y3) => (y3 - y12) * ky2, Float64Array);
      if (F) F = this.interpolate(index2, w, h, IX, IY, F);
      if (FO) FO = this.interpolate(index2, w, h, IX, IY, FO);
    } else if (this.data == null && index2) offset2 = index2.fi * n;
    const canvas = document2.createElement("canvas");
    canvas.width = w;
    canvas.height = h;
    const context2d = canvas.getContext("2d");
    const image3 = context2d.createImageData(w, h);
    const imageData3 = image3.data;
    let { r, g, b } = rgb(this.fill) ?? { r: 0, g: 0, b: 0 };
    let a2 = (this.fillOpacity ?? 1) * 255;
    for (let i = 0; i < n; ++i) {
      const j = i << 2;
      if (F) {
        const fi = color3(F[i + offset2]);
        if (fi == null) {
          imageData3[j + 3] = 0;
          continue;
        }
        ({ r, g, b } = rgb(fi));
      }
      if (FO) a2 = FO[i + offset2] * 255;
      imageData3[j + 0] = r;
      imageData3[j + 1] = g;
      imageData3[j + 2] = b;
      imageData3[j + 3] = a2;
    }
    if (this.blur > 0) blurImage(image3, this.blur);
    context2d.putImageData(image3, 0, 0);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call(
      (g2) => g2.append("image").attr("transform", `translate(${x12},${y12}) scale(${Math.sign(x22 - x12)},${Math.sign(y22 - y12)})`).attr("width", Math.abs(dx)).attr("height", Math.abs(dy)).attr("preserveAspectRatio", "none").call(applyAttr, "image-rendering", this.imageRendering).call(applyDirectStyles, this).attr("xlink:href", canvas.toDataURL())
    ).node();
  }
};
function maybeTuples(k2, data, options) {
  if (arguments.length < 3) options = data, data = null;
  let { x: x3, y: y3, [k2]: z, ...rest } = options;
  if (x3 === void 0 && y3 === void 0 && isTuples(data)) {
    x3 = first2, y3 = second2;
    if (z === void 0) z = third;
  }
  return [data, { ...rest, x: x3, y: y3, [k2]: z }];
}
function raster() {
  const [data, options] = maybeTuples("fill", ...arguments);
  return new Raster(
    data,
    data == null || options.fill !== void 0 || options.fillOpacity !== void 0 ? options : { ...options, fill: identity8 }
  );
}
function renderBounds({ x1: x12, y1: y12, x2: x22, y2: y22 }, dimensions, { projection: projection3 }) {
  const { width: width2, height: height2, marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2 } = dimensions;
  return [
    x12 && projection3 == null ? x12[0] : marginLeft2,
    y12 && projection3 == null ? y12[0] : marginTop2,
    x22 && projection3 == null ? x22[0] : width2 - marginRight2,
    y22 && projection3 == null ? y22[0] : height2 - marginBottom2
  ];
}
function rasterBounds({ x1: x12, y1: y12, x2: x22, y2: y22 }, scales2, dimensions, context) {
  const channels = {};
  if (x12) channels.x1 = x12;
  if (y12) channels.y1 = y12;
  if (x22) channels.x2 = x22;
  if (y22) channels.y2 = y22;
  return renderBounds(valueObject(channels, scales2), dimensions, context);
}
function sampler(name2, options = {}) {
  const { [name2]: value } = options;
  if (typeof value !== "function") throw new Error(`invalid ${name2}: not a function`);
  return initializer({ ...options, [name2]: void 0 }, function(data, facets, channels, scales2, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    if (!x3) throw new Error("missing scale: x");
    if (!y3) throw new Error("missing scale: y");
    const [x12, y12, x22, y22] = rasterBounds(channels, scales2, dimensions, context);
    const dx = x22 - x12;
    const dy = y22 - y12;
    const { pixelSize: k2 } = this;
    const { width: w = Math.round(Math.abs(dx) / k2), height: h = Math.round(Math.abs(dy) / k2) } = options;
    const V = new Array(w * h * (facets ? facets.length : 1));
    const kx2 = dx / w;
    const ky2 = dy / h;
    let i = 0;
    for (const facet of facets ?? [void 0]) {
      for (let yi = 0.5; yi < h; ++yi) {
        for (let xi = 0.5; xi < w; ++xi, ++i) {
          V[i] = value(x3.invert(x12 + xi * kx2), y3.invert(y12 + yi * ky2), facet);
        }
      }
    }
    return { data: V, facets, channels: { [name2]: { value: V, scale: "auto" } } };
  });
}
function maybeInterpolate(interpolate) {
  if (typeof interpolate === "function") return interpolate;
  if (interpolate == null) return interpolateNone;
  switch (`${interpolate}`.toLowerCase()) {
    case "none":
      return interpolateNone;
    case "nearest":
      return interpolateNearest;
    case "barycentric":
      return interpolatorBarycentric();
    case "random-walk":
      return interpolatorRandomWalk();
  }
  throw new Error(`invalid interpolate: ${interpolate}`);
}
function interpolateNone(index2, width2, height2, X3, Y3, V) {
  const W = new Array(width2 * height2);
  for (const i of index2) {
    if (X3[i] < 0 || X3[i] >= width2 || Y3[i] < 0 || Y3[i] >= height2) continue;
    W[Math.floor(Y3[i]) * width2 + Math.floor(X3[i])] = V[i];
  }
  return W;
}
function interpolatorBarycentric({ random = lcg(42) } = {}) {
  return (index2, width2, height2, X3, Y3, V) => {
    const { points: points2, triangles, hull: hull3 } = Delaunay.from(
      index2,
      (i) => X3[i],
      (i) => Y3[i]
    );
    const W = new V.constructor(width2 * height2).fill(NaN);
    const S = new Uint8Array(width2 * height2);
    const mix = mixer(V, random);
    for (let i = 0; i < triangles.length; i += 3) {
      const ta = triangles[i];
      const tb = triangles[i + 1];
      const tc = triangles[i + 2];
      const Ax = points2[2 * ta];
      const Bx = points2[2 * tb];
      const Cx = points2[2 * tc];
      const Ay = points2[2 * ta + 1];
      const By = points2[2 * tb + 1];
      const Cy = points2[2 * tc + 1];
      const x12 = Math.min(Ax, Bx, Cx);
      const x22 = Math.max(Ax, Bx, Cx);
      const y12 = Math.min(Ay, By, Cy);
      const y22 = Math.max(Ay, By, Cy);
      const z = (By - Cy) * (Ax - Cx) + (Ay - Cy) * (Cx - Bx);
      if (!z) continue;
      const va = V[index2[ta]];
      const vb = V[index2[tb]];
      const vc = V[index2[tc]];
      for (let x3 = Math.floor(x12); x3 < x22; ++x3) {
        for (let y3 = Math.floor(y12); y3 < y22; ++y3) {
          if (x3 < 0 || x3 >= width2 || y3 < 0 || y3 >= height2) continue;
          const xp = x3 + 0.5;
          const yp = y3 + 0.5;
          const s2 = Math.sign(z);
          const ga = (By - Cy) * (xp - Cx) + (yp - Cy) * (Cx - Bx);
          if (ga * s2 < 0) continue;
          const gb = (Cy - Ay) * (xp - Cx) + (yp - Cy) * (Ax - Cx);
          if (gb * s2 < 0) continue;
          const gc = z - (ga + gb);
          if (gc * s2 < 0) continue;
          const i2 = x3 + width2 * y3;
          W[i2] = mix(va, ga / z, vb, gb / z, vc, gc / z, x3, y3);
          S[i2] = 1;
        }
      }
    }
    extrapolateBarycentric(W, S, X3, Y3, V, width2, height2, hull3, index2, mix);
    return W;
  };
}
function extrapolateBarycentric(W, S, X3, Y3, V, width2, height2, hull3, index2, mix) {
  X3 = Float64Array.from(hull3, (i) => X3[index2[i]]);
  Y3 = Float64Array.from(hull3, (i) => Y3[index2[i]]);
  V = Array.from(hull3, (i) => V[index2[i]]);
  const n = X3.length;
  const rays = Array.from({ length: n }, (_, j) => ray(j, X3, Y3));
  let k2 = 0;
  for (let y3 = 0; y3 < height2; ++y3) {
    const yp = y3 + 0.5;
    for (let x3 = 0; x3 < width2; ++x3) {
      const i = x3 + width2 * y3;
      if (!S[i]) {
        const xp = x3 + 0.5;
        for (let l = 0; l < n; ++l) {
          const j = (n + k2 + (l % 2 ? (l + 1) / 2 : -l / 2)) % n;
          if (rays[j](xp, yp)) {
            const t = segmentProject(X3.at(j - 1), Y3.at(j - 1), X3[j], Y3[j], xp, yp);
            W[i] = mix(V.at(j - 1), t, V[j], 1 - t, V[j], 0, x3, y3);
            k2 = j;
            break;
          }
        }
      }
    }
  }
}
function segmentProject(x12, y12, x22, y22, x3, y3) {
  const dx = x22 - x12;
  const dy = y22 - y12;
  const a2 = dx * (x22 - x3) + dy * (y22 - y3);
  const b = dx * (x3 - x12) + dy * (y3 - y12);
  return a2 > 0 && b > 0 ? a2 / (a2 + b) : +(a2 > b);
}
function cross2(xa, ya, xb, yb) {
  return xa * yb - xb * ya;
}
function ray(j, X3, Y3) {
  const n = X3.length;
  const xc = X3.at(j - 2);
  const yc = Y3.at(j - 2);
  const xa = X3.at(j - 1);
  const ya = Y3.at(j - 1);
  const xb = X3[j];
  const yb = Y3[j];
  const xd = X3.at(j + 1 - n);
  const yd = Y3.at(j + 1 - n);
  const dxab = xa - xb;
  const dyab = ya - yb;
  const dxca = xc - xa;
  const dyca = yc - ya;
  const dxbd = xb - xd;
  const dybd = yb - yd;
  const hab = Math.hypot(dxab, dyab);
  const hca = Math.hypot(dxca, dyca);
  const hbd = Math.hypot(dxbd, dybd);
  return (x3, y3) => {
    const dxa = x3 - xa;
    const dya = y3 - ya;
    const dxb = x3 - xb;
    const dyb = y3 - yb;
    return cross2(dxa, dya, dxb, dyb) > -1e-6 && cross2(dxa, dya, dxab, dyab) * hca - cross2(dxa, dya, dxca, dyca) * hab > -1e-6 && cross2(dxb, dyb, dxbd, dybd) * hab - cross2(dxb, dyb, dxab, dyab) * hbd <= 0;
  };
}
function interpolateNearest(index2, width2, height2, X3, Y3, V) {
  const W = new V.constructor(width2 * height2);
  const delaunay = Delaunay.from(
    index2,
    (i) => X3[i],
    (i) => Y3[i]
  );
  let iy, ix;
  for (let y3 = 0.5, k2 = 0; y3 < height2; ++y3) {
    ix = iy;
    for (let x3 = 0.5; x3 < width2; ++x3, ++k2) {
      ix = delaunay.find(x3, y3, ix);
      if (x3 === 0.5) iy = ix;
      W[k2] = V[index2[ix]];
    }
  }
  return W;
}
function interpolatorRandomWalk({ random = lcg(42), minDistance = 0.5, maxSteps = 2 } = {}) {
  return (index2, width2, height2, X3, Y3, V) => {
    const W = new V.constructor(width2 * height2);
    const delaunay = Delaunay.from(
      index2,
      (i) => X3[i],
      (i) => Y3[i]
    );
    let iy, ix, iw;
    for (let y3 = 0.5, k2 = 0; y3 < height2; ++y3) {
      ix = iy;
      for (let x3 = 0.5; x3 < width2; ++x3, ++k2) {
        let cx = x3;
        let cy = y3;
        iw = ix = delaunay.find(cx, cy, ix);
        if (x3 === 0.5) iy = ix;
        let distance;
        let step = 0;
        while ((distance = Math.hypot(X3[index2[iw]] - cx, Y3[index2[iw]] - cy)) > minDistance && step < maxSteps) {
          const angle = random(x3, y3, step) * 2 * Math.PI;
          cx += Math.cos(angle) * distance;
          cy += Math.sin(angle) * distance;
          iw = delaunay.find(cx, cy, iw);
          ++step;
        }
        W[k2] = V[index2[iw]];
      }
    }
    return W;
  };
}
function blend(a2, ca3, b, cb, c4, cc2) {
  return ca3 * a2 + cb * b + cc2 * c4;
}
function pick(random) {
  return (a2, ca3, b, cb, c4, cc2, x3, y3) => {
    const u4 = random(x3, y3);
    return u4 < ca3 ? a2 : u4 < ca3 + cb ? b : c4;
  };
}
function mixer(F, random) {
  return isNumeric(F) || isTemporal(F) ? blend : pick(random);
}
function denseX(x12, x22, width2) {
  return {
    transform(data) {
      const n = data.length;
      const X3 = new Float64Array(n);
      const kx2 = (x22 - x12) / width2;
      const x06 = x12 + kx2 / 2;
      for (let i = 0; i < n; ++i) X3[i] = i % width2 * kx2 + x06;
      return X3;
    }
  };
}
function denseY(y12, y22, width2, height2) {
  return {
    transform(data) {
      const n = data.length;
      const Y3 = new Float64Array(n);
      const ky2 = (y22 - y12) / height2;
      const y06 = y12 + ky2 / 2;
      for (let i = 0; i < n; ++i) Y3[i] = Math.floor(i / width2) % height2 * ky2 + y06;
      return Y3;
    }
  };
}

// ../../../node_modules/@observablehq/plot/src/marks/contour.js
var defaults16 = {
  ariaLabel: "contour",
  fill: "none",
  stroke: "currentColor",
  strokeMiterlimit: 1,
  pixelSize: 2
};
var Contour = class extends AbstractRaster {
  constructor(data, { smooth = true, value, ...options } = {}) {
    const channels = styles({}, options, defaults16);
    if (value === void 0) {
      for (const key in channels) {
        if (channels[key].value != null) {
          if (value !== void 0) throw new Error("ambiguous contour value");
          value = options[key];
          options[key] = "value";
        }
      }
    }
    if (value != null) {
      const v2 = { transform: (D3) => D3.map((d) => d.value), label: labelof(value) };
      for (const key in channels) {
        if (options[key] === "value") {
          options[key] = v2;
        }
      }
    }
    if (data == null) {
      if (value == null) throw new Error("missing contour value");
      options = sampler("value", { value, ...options });
      value = null;
    } else {
      let { interpolate } = options;
      if (value === void 0) value = identity8;
      if (interpolate === void 0) options.interpolate = "nearest";
    }
    super(data, { value: { value, optional: true } }, contourGeometry(options), defaults16);
    const contourChannels = { geometry: { value: identity8 } };
    for (const key in this.channels) {
      const channel = this.channels[key];
      const { scale: scale3 } = channel;
      if (scale3 === "x" || scale3 === "y" || key === "value") continue;
      contourChannels[key] = channel;
      delete this.channels[key];
    }
    this.contourChannels = contourChannels;
    this.smooth = !!smooth;
  }
  filter(index2, { x: x3, y: y3, value, ...channels }, values2) {
    return super.filter(index2, channels, values2);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { geometry: G } = channels;
    const path2 = path_default();
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call((g) => {
      g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr("d", (i) => path2(G[i])).call(applyChannelStyles, this, channels);
    }).node();
  }
};
function contourGeometry({ thresholds, interval: interval4, ...options }) {
  thresholds = maybeThresholds(thresholds, interval4, thresholdSturges);
  return initializer(options, function(data, facets, channels, scales2, dimensions, context) {
    const [x12, y12, x22, y22] = rasterBounds(channels, scales2, dimensions, context);
    const dx = x22 - x12;
    const dy = y22 - y12;
    const { pixelSize: k2, width: w = Math.round(Math.abs(dx) / k2), height: h = Math.round(Math.abs(dy) / k2) } = this;
    const kx2 = w / dx;
    const ky2 = h / dy;
    const V = channels.value.value;
    const VV = [];
    if (this.interpolate) {
      const { x: X3, y: Y3 } = applyPosition(channels, scales2, context);
      const IX = map3(X3, (x3) => (x3 - x12) * kx2, Float64Array);
      const IY = map3(Y3, (y3) => (y3 - y12) * ky2, Float64Array);
      const ichannels = [channels.x, channels.y, channels.value];
      const ivalues = [IX, IY, V];
      for (const facet of facets) {
        const index2 = this.filter(facet, ichannels, ivalues);
        VV.push(this.interpolate(index2, w, h, IX, IY, V));
      }
    } else if (facets) {
      const n = w * h;
      const m = facets.length;
      for (let i = 0; i < m; ++i) VV.push(V.slice(i * n, i * n + n));
    } else {
      VV.push(V);
    }
    if (this.blur > 0) for (const V2 of VV) blur2({ data: V2, width: w, height: h }, this.blur);
    const T = maybeTicks(thresholds, V, ...finiteExtent(VV));
    if (T === null) throw new Error(`unsupported thresholds: ${thresholds}`);
    const { contour: contour3 } = contours_default().size([w, h]).smooth(this.smooth);
    const contourData = [];
    const contourFacets = [];
    for (const V2 of VV) {
      contourFacets.push(range(contourData.length, contourData.push(...map3(T, (t) => contour3(V2, t)))));
    }
    for (const { coordinates } of contourData) {
      for (const rings of coordinates) {
        for (const ring of rings) {
          for (const point6 of ring) {
            point6[0] = point6[0] / kx2 + x12;
            point6[1] = point6[1] / ky2 + y12;
          }
        }
      }
    }
    return {
      data: contourData,
      facets: contourFacets,
      channels: createChannels(this.contourChannels, contourData)
    };
  });
}
function maybeTicks(thresholds, V, min5, max4) {
  if (typeof thresholds?.range === "function") return thresholds.range(thresholds.floor(min5), max4);
  if (typeof thresholds === "function") thresholds = thresholds(V, min5, max4);
  if (typeof thresholds !== "number") return arrayify2(thresholds);
  const tz = ticks(...nice(min5, max4, thresholds), thresholds);
  while (tz[tz.length - 1] >= max4) tz.pop();
  while (tz[1] < min5) tz.shift();
  return tz;
}
function contour() {
  return new Contour(...maybeTuples("value", ...arguments));
}
function finiteExtent(VV) {
  return [min2(VV, (V) => min2(V, finite3)), max2(VV, (V) => max2(V, finite3))];
}
function finite3(x3) {
  return isFinite(x3) ? x3 : NaN;
}

// ../../../node_modules/@observablehq/plot/src/marks/crosshair.js
function crosshair(data, options) {
  return crosshairK(pointer, data, options);
}
function crosshairX(data, options = {}) {
  return crosshairK(pointerX, data, options);
}
function crosshairY(data, options = {}) {
  return crosshairK(pointerY, data, options);
}
function crosshairK(pointer2, data, options = {}) {
  const { x: x3, y: y3, maxRadius } = options;
  const p = pointer2({ px: x3, py: y3, maxRadius });
  const M2 = [];
  if (x3 != null) M2.push(ruleX(data, ruleOptions("x", { ...p, inset: -6 }, options)));
  if (y3 != null) M2.push(ruleY(data, ruleOptions("y", { ...p, inset: -6 }, options)));
  if (x3 != null) M2.push(text(data, textOptions("x", { ...p, dy: 9, frameAnchor: "bottom", lineAnchor: "top" }, options)));
  if (y3 != null) M2.push(text(data, textOptions("y", { ...p, dx: -9, frameAnchor: "left", textAnchor: "end" }, options)));
  for (const m of M2) m.ariaLabel = `crosshair ${m.ariaLabel}`;
  return marks(...M2);
}
function markOptions(k2, { channels: pointerChannels, ...pointerOptions }, { facet, facetAnchor, fx, fy, [k2]: p, channels, transform: transform3, initializer: initializer2 }) {
  return {
    ...pointerOptions,
    facet,
    facetAnchor,
    fx,
    fy,
    [k2]: p,
    channels: { ...pointerChannels, ...channels },
    transform: transform3,
    initializer: pxpy(k2, initializer2)
  };
}
function pxpy(k2, i) {
  if (i == null) return i;
  return function(data, facets, { x: x12, y: y12, px, py, ...c1 }, ...args) {
    const { channels: { x: x3, y: y3, ...c4 } = {}, ...rest } = i.call(this, data, facets, { ...c1, x: px, y: py }, ...args);
    return {
      channels: {
        ...c4,
        ...x3 && { px: x3, ...k2 === "x" && { x: x3 } },
        ...y3 && { py: y3, ...k2 === "y" && { y: y3 } }
      },
      ...rest
    };
  };
}
function ruleOptions(k2, pointerOptions, options) {
  const {
    color: color3 = "currentColor",
    opacity: opacity2 = 0.2,
    ruleStroke: stroke = color3,
    ruleStrokeOpacity: strokeOpacity = opacity2,
    ruleStrokeWidth: strokeWidth
  } = options;
  return {
    ...markOptions(k2, pointerOptions, options),
    stroke,
    strokeOpacity,
    strokeWidth
  };
}
function textOptions(k2, pointerOptions, options) {
  const {
    color: color3 = "currentColor",
    textFill: fill = color3,
    textFillOpacity: fillOpacity,
    textStroke: stroke = "var(--plot-background)",
    textStrokeOpacity: strokeOpacity,
    textStrokeWidth: strokeWidth = 5
  } = options;
  return {
    ...markOptions(k2, pointerOptions, textChannel(k2, options)),
    fill,
    fillOpacity,
    stroke,
    strokeOpacity,
    strokeWidth
  };
}
function textChannel(source, options) {
  return initializer(options, (data, facets, channels) => {
    return { channels: { text: { value: getSource(channels, source)?.value } } };
  });
}

// ../../../node_modules/@observablehq/plot/src/marks/delaunay.js
var delaunayLinkDefaults = {
  ariaLabel: "delaunay link",
  fill: "none",
  stroke: "currentColor",
  strokeMiterlimit: 1
};
var delaunayMeshDefaults = {
  ariaLabel: "delaunay mesh",
  fill: null,
  stroke: "currentColor",
  strokeOpacity: 0.2
};
var hullDefaults = {
  ariaLabel: "hull",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeMiterlimit: 1
};
var voronoiDefaults = {
  ariaLabel: "voronoi",
  fill: "none",
  stroke: "currentColor",
  strokeMiterlimit: 1
};
var voronoiMeshDefaults = {
  ariaLabel: "voronoi mesh",
  fill: null,
  stroke: "currentColor",
  strokeOpacity: 0.2
};
var DelaunayLink = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, z, curve, tension } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        z: { value: z, optional: true }
      },
      options,
      delaunayLinkDefaults
    );
    this.curve = maybeCurve(curve, tension);
    markers(this, options);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, z: Z } = channels;
    const { curve } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    const xi = X3 ? (i) => X3[i] : constant(cx);
    const yi = Y3 ? (i) => Y3[i] : constant(cy);
    const mark2 = this;
    function links(index3) {
      let i = -1;
      const newIndex = [];
      const newChannels = {};
      for (const k2 in channels) newChannels[k2] = [];
      const X13 = [];
      const X23 = [];
      const Y13 = [];
      const Y23 = [];
      function link4(ti, tj) {
        ti = index3[ti];
        tj = index3[tj];
        newIndex.push(++i);
        X13[i] = xi(ti);
        Y13[i] = yi(ti);
        X23[i] = xi(tj);
        Y23[i] = yi(tj);
        for (const k2 in channels) newChannels[k2].push(channels[k2][tj]);
      }
      const { halfedges, hull: hull3, triangles } = Delaunay.from(index3, xi, yi);
      for (let i2 = 0; i2 < halfedges.length; ++i2) {
        const j = halfedges[i2];
        if (j > i2) link4(triangles[i2], triangles[j]);
      }
      for (let i2 = 0; i2 < hull3.length; ++i2) {
        link4(hull3[i2], hull3[(i2 + 1) % hull3.length]);
      }
      select_default2(this).selectAll().data(newIndex).enter().append("path").call(applyDirectStyles, mark2).attr("d", (i2) => {
        const p = pathRound();
        const c4 = curve(p);
        c4.lineStart();
        c4.point(X13[i2], Y13[i2]);
        c4.point(X23[i2], Y23[i2]);
        c4.lineEnd();
        return p;
      }).call(applyChannelStyles, mark2, newChannels).call(applyMarkers, mark2, newChannels, context);
    }
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      Z ? (g) => g.selectAll().data(group(index2, (i) => Z[i]).values()).enter().append("g").each(links) : (g) => g.datum(index2).each(links)
    ).node();
  }
};
var AbstractDelaunayMark = class extends Mark {
  constructor(data, options = {}, defaults22, zof = ({ z }) => z) {
    const { x: x3, y: y3 } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        z: { value: zof(options), optional: true }
      },
      options,
      defaults22
    );
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, z: Z } = channels;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    const xi = X3 ? (i) => X3[i] : constant(cx);
    const yi = Y3 ? (i) => Y3[i] : constant(cy);
    const mark2 = this;
    function mesh(index3) {
      const delaunay = Delaunay.from(index3, xi, yi);
      select_default2(this).append("path").datum(index3[0]).call(applyDirectStyles, mark2).attr("d", mark2._render(delaunay, dimensions)).call(applyChannelStyles, mark2, channels);
    }
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      Z ? (g) => g.selectAll().data(group(index2, (i) => Z[i]).values()).enter().append("g").each(mesh) : (g) => g.datum(index2).each(mesh)
    ).node();
  }
};
var DelaunayMesh = class extends AbstractDelaunayMark {
  constructor(data, options = {}) {
    super(data, options, delaunayMeshDefaults);
    this.fill = "none";
  }
  _render(delaunay) {
    return delaunay.render();
  }
};
var Hull = class extends AbstractDelaunayMark {
  constructor(data, options = {}) {
    super(data, options, hullDefaults, maybeZ);
  }
  _render(delaunay) {
    return delaunay.renderHull();
  }
};
var Voronoi2 = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, z } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        z: { value: z, optional: true }
      },
      initializer(options, function(data2, facets, channels, scales2, dimensions, context) {
        let { x: X3, y: Y3, z: Z } = channels;
        ({ x: X3, y: Y3 } = applyPosition(channels, scales2, context));
        Z = Z?.value;
        const C3 = new Array((X3 ?? Y3).length).fill(null);
        const [cx, cy] = applyFrameAnchor(this, dimensions);
        const xi = X3 ? (i) => X3[i] : constant(cx);
        const yi = Y3 ? (i) => Y3[i] : constant(cy);
        for (let I of facets) {
          if (X3) I = I.filter((i) => defined(xi(i)));
          if (Y3) I = I.filter((i) => defined(yi(i)));
          for (const [, J] of maybeGroup(I, Z)) {
            const delaunay = Delaunay.from(J, xi, yi);
            const voronoi3 = voronoiof(delaunay, dimensions);
            for (let i = 0, n = J.length; i < n; ++i) {
              C3[J[i]] = voronoi3.renderCell(i);
            }
          }
        }
        return { data: data2, facets, channels: { cells: { value: C3 } } };
      }),
      voronoiDefaults
    );
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, cells: C3 } = channels;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call((g) => {
      g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr("d", (i) => C3[i]).call(applyChannelStyles, this, channels);
    }).node();
  }
};
var VoronoiMesh = class extends AbstractDelaunayMark {
  constructor(data, options) {
    super(data, options, voronoiMeshDefaults);
    this.fill = "none";
  }
  _render(delaunay, dimensions) {
    return voronoiof(delaunay, dimensions).render();
  }
};
function voronoiof(delaunay, dimensions) {
  const { width: width2, height: height2, marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2 } = dimensions;
  return delaunay.voronoi([marginLeft2, marginTop2, width2 - marginRight2, height2 - marginBottom2]);
}
function delaunayMark(DelaunayMark, data, { x: x3, y: y3, ...options } = {}) {
  [x3, y3] = maybeTuple(x3, y3);
  return new DelaunayMark(data, { ...options, x: x3, y: y3 });
}
function delaunayLink(data, options) {
  return delaunayMark(DelaunayLink, data, options);
}
function delaunayMesh(data, options) {
  return delaunayMark(DelaunayMesh, data, options);
}
function hull(data, options) {
  return delaunayMark(Hull, data, options);
}
function voronoi(data, { x: x3, y: y3, initializer: initializer2, ...options } = {}) {
  return delaunayMark(Voronoi2, data, { ...basic({ ...options, x: x3, y: y3 }, exclusiveFacets), initializer: initializer2 });
}
function voronoiMesh(data, options) {
  return delaunayMark(VoronoiMesh, data, options);
}

// ../../../node_modules/@observablehq/plot/src/marks/density.js
var defaults17 = {
  ariaLabel: "density",
  fill: "none",
  stroke: "currentColor",
  strokeMiterlimit: 1
};
var Density = class extends Mark {
  constructor(data, { x: x3, y: y3, z, weight, fill, stroke, ...options } = {}) {
    const fillDensity = isDensity(fill) && (fill = "currentColor", true);
    const strokeDensity = isDensity(stroke) && (stroke = "currentColor", true);
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        z: { value: maybeZ({ z, fill, stroke }), optional: true },
        weight: { value: weight, optional: true }
      },
      densityInitializer({ ...options, fill, stroke }, fillDensity, strokeDensity),
      defaults17
    );
    if (fillDensity) this.fill = void 0;
    if (strokeDensity) this.stroke = void 0;
    this.z = z;
  }
  filter(index2) {
    return index2;
  }
  render(index2, scales2, channels, dimensions, context) {
    const { contours } = channels;
    const path2 = path_default();
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, {}).call(
      (g) => g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).call(applyChannelStyles, this, channels).attr("d", (i) => path2(contours[i]))
    ).node();
  }
};
function density(data, { x: x3, y: y3, ...options } = {}) {
  [x3, y3] = maybeTuple(x3, y3);
  return new Density(data, { ...options, x: x3, y: y3 });
}
var dropChannels = /* @__PURE__ */ new Set(["x", "y", "z", "weight"]);
function densityInitializer(options, fillDensity, strokeDensity) {
  const k2 = 100;
  let { bandwidth, thresholds } = options;
  bandwidth = bandwidth === void 0 ? 20 : +bandwidth;
  thresholds = thresholds === void 0 ? 20 : typeof thresholds?.[Symbol.iterator] === "function" ? coerceNumbers(thresholds) : +thresholds;
  return initializer(options, function(data, facets, channels, scales2, dimensions, context) {
    const W = channels.weight ? coerceNumbers(channels.weight.value) : null;
    const Z = channels.z?.value;
    const { z } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    const { width: width2, height: height2 } = dimensions;
    const { x: X3, y: Y3 } = applyPosition(channels, scales2, context);
    const newChannels = Object.fromEntries(
      Object.entries(channels).filter(([key]) => !dropChannels.has(key)).map(([key, channel]) => [key, { ...channel, value: [] }])
    );
    const FD = fillDensity && [];
    const SD = strokeDensity && [];
    const density3 = density_default().x(X3 ? (i) => X3[i] : cx).y(Y3 ? (i) => Y3[i] : cy).weight(W ? (i) => W[i] : 1).size([width2, height2]).bandwidth(bandwidth);
    const facetsContours = [];
    for (const facet of facets) {
      const facetContours = [];
      facetsContours.push(facetContours);
      for (const index2 of Z ? groupZ2(facet, Z, z) : [facet]) {
        const contour3 = density3.contours(index2);
        facetContours.push([index2, contour3]);
      }
    }
    let T = thresholds;
    if (!(T instanceof TypedArray2)) {
      let maxValue = 0;
      for (const facetContours of facetsContours) {
        for (const [, contour3] of facetContours) {
          const max4 = contour3.max;
          if (max4 > maxValue) maxValue = max4;
        }
      }
      T = Float64Array.from({ length: thresholds - 1 }, (_, i) => maxValue * k2 * (i + 1) / thresholds);
    }
    const newFacets = [];
    const contours = [];
    for (const facetContours of facetsContours) {
      const newFacet = [];
      newFacets.push(newFacet);
      for (const [index2, contour3] of facetContours) {
        for (const t of T) {
          newFacet.push(contours.length);
          contours.push(contour3(t / k2));
          if (FD) FD.push(t);
          if (SD) SD.push(t);
          for (const key in newChannels) {
            newChannels[key].value.push(channels[key].value[index2[0]]);
          }
        }
      }
    }
    if (FD) FD.push(0);
    if (SD) SD.push(0);
    return {
      data,
      facets: newFacets,
      channels: {
        ...newChannels,
        ...FD && { fill: { value: FD, scale: "color" } },
        ...SD && { stroke: { value: SD, scale: "color" } },
        contours: { value: contours }
      }
    };
  });
}
function isDensity(value) {
  return /^density$/i.test(value);
}

// ../../../node_modules/@observablehq/plot/src/marks/difference.js
function differenceX(data, options) {
  return differenceK("x", data, options);
}
function differenceY(data, options) {
  return differenceK("y", data, options);
}
function differenceK(k2, data, {
  x1: x12,
  x2: x22,
  y1: y12,
  y2: y22,
  x: x3 = x12 === void 0 && x22 === void 0 ? k2 === "y" ? indexOf : identity8 : void 0,
  y: y3 = y12 === void 0 && y22 === void 0 ? k2 === "x" ? indexOf : identity8 : void 0,
  fill,
  // ignored
  positiveFill = "#3ca951",
  negativeFill = "#4269d0",
  fillOpacity = 1,
  positiveFillOpacity = fillOpacity,
  negativeFillOpacity = fillOpacity,
  stroke,
  strokeOpacity,
  z = maybeColorChannel(stroke)[0],
  clip: clip2,
  // optional additional clip for area
  tip: tip2,
  render,
  ...options
} = {}) {
  [x12, x22] = memoTuple(x3, x12, x22);
  [y12, y22] = memoTuple(y3, y12, y22);
  if (x12 === x22 && y12 === y22) {
    if (k2 === "y") y12 = memo(0);
    else x12 = memo(0);
  }
  ({ tip: tip2 } = withTip({ tip: tip2 }, k2 === "y" ? "x" : "y"));
  return marks(
    !isNoneish(positiveFill) ? Object.assign(
      area(data, {
        x1: x12,
        x2: x22,
        y1: y12,
        y2: y22,
        z,
        fill: positiveFill,
        fillOpacity: positiveFillOpacity,
        render: composeRender(render, clipDifference(k2, true)),
        clip: clip2,
        ...options
      }),
      { ariaLabel: "positive difference" }
    ) : null,
    !isNoneish(negativeFill) ? Object.assign(
      area(data, {
        x1: x12,
        x2: x22,
        y1: y12,
        y2: y22,
        z,
        fill: negativeFill,
        fillOpacity: negativeFillOpacity,
        render: composeRender(render, clipDifference(k2, false)),
        clip: clip2,
        ...options
      }),
      { ariaLabel: "negative difference" }
    ) : null,
    line(data, {
      x: x22,
      y: y22,
      z,
      stroke,
      strokeOpacity,
      tip: tip2,
      clip: true,
      ...options
    })
  );
}
function memoTuple(x3, x12, x22) {
  if (x12 === void 0 && x22 === void 0) {
    x12 = x22 = memo(x3);
  } else if (x12 === void 0) {
    x22 = memo(x22);
    x12 = x3 === void 0 ? x22 : memo(x3);
  } else if (x22 === void 0) {
    x12 = memo(x12);
    x22 = x3 === void 0 ? x12 : memo(x3);
  } else {
    x12 = memo(x12);
    x22 = memo(x22);
  }
  return [x12, x22];
}
function memo(v2) {
  let V;
  const { value, label = labelof(value) } = maybeValue(v2);
  return { transform: (data) => V || (V = valueof(data, value)), label };
}
function clipDifference(k2, positive2) {
  const f = k2 === "x" ? "y" : "x";
  const f1 = `${f}1`;
  const f2 = `${f}2`;
  const k1 = `${k2}1`;
  const k22 = `${k2}2`;
  return (index2, scales2, channels, dimensions, context, next) => {
    const { [f1]: F1, [f2]: F2 } = channels;
    const K1 = new Float32Array(F1.length);
    const K2 = new Float32Array(F2.length);
    const m = dimensions[k2 === "y" ? "height" : "width"];
    (positive2 === inferScaleOrder(scales2[k2]) < 0 ? K1 : K2).fill(m);
    const oc = next(index2, scales2, { ...channels, [f2]: F1, [k22]: K2 }, dimensions, context);
    const og = next(index2, scales2, { ...channels, [f1]: F2, [k1]: K1 }, dimensions, context);
    const c4 = oc.querySelector("g") ?? oc;
    const g = og.querySelector("g") ?? og;
    for (let i = 0; c4.firstChild; i += 2) {
      const id2 = getClipId();
      const clipPath = create3("svg:clipPath", context).attr("id", id2).node();
      clipPath.appendChild(c4.firstChild);
      g.childNodes[i].setAttribute("clip-path", `url(#${id2})`);
      g.insertBefore(clipPath, g.childNodes[i]);
    }
    return og;
  };
}

// ../../../node_modules/@observablehq/plot/src/transforms/centroid.js
function centroid2({ geometry = identity8, ...options } = {}) {
  const getG = memoize1((data) => valueof(data, geometry));
  return initializer(
    // Suppress defaults for x and y since they will be computed by the initializer.
    // Propagate the (memoized) geometry channel in case it’s still needed.
    { ...options, x: null, y: null, geometry: { transform: getG } },
    (data, facets, channels, scales2, dimensions, context) => {
      const G = getG(data);
      const n = G.length;
      const X3 = new Float64Array(n);
      const Y3 = new Float64Array(n);
      const { centroid: centroid3 } = context.path();
      for (let i = 0; i < n; ++i) [X3[i], Y3[i]] = centroid3(G[i]);
      return {
        data,
        facets,
        channels: { x: { value: X3, scale: null, source: null }, y: { value: Y3, scale: null, source: null } }
      };
    }
  );
}
function geoCentroid({ geometry = identity8, ...options } = {}) {
  const getG = memoize1((data) => valueof(data, geometry));
  const getC = memoize1((data) => valueof(getG(data), centroid_default));
  return {
    ...options,
    x: { transform: (data) => Float64Array.from(getC(data), ([x3]) => x3) },
    y: { transform: (data) => Float64Array.from(getC(data), ([, y3]) => y3) },
    geometry: { transform: getG }
  };
}

// ../../../node_modules/@observablehq/plot/src/marks/geo.js
var defaults18 = {
  ariaLabel: "geo",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 1,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  strokeMiterlimit: 1
};
var Geo = class extends Mark {
  constructor(data, options = {}) {
    const [vr, cr] = maybeNumberChannel(options.r, 3);
    super(
      data,
      {
        x: { value: options.tip ? options.x : null, scale: "x", optional: true },
        y: { value: options.tip ? options.y : null, scale: "y", optional: true },
        r: { value: vr, scale: "r", filter: positive, optional: true },
        geometry: { value: options.geometry, scale: "projection" }
      },
      withDefaultSort(options),
      defaults18
    );
    this.r = cr;
  }
  render(index2, scales2, channels, dimensions, context) {
    const { geometry: G, r: R } = channels;
    const path2 = context.path();
    const { r } = this;
    if (negative(r)) index2 = [];
    else if (r !== void 0) path2.pointRadius(r);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call((g) => {
      g.selectAll().data(index2).enter().append("path").call(applyDirectStyles, this).attr("d", R ? (i) => path2.pointRadius(R[i])(G[i]) : (i) => path2(G[i])).call(applyChannelStyles, this, channels);
    }).node();
  }
};
function geo(data, options = {}) {
  if (options.tip && options.x === void 0 && options.y === void 0) options = centroid2(options);
  else if (options.geometry === void 0) options = { ...options, geometry: identity8 };
  return new Geo(data, options);
}
function sphere2({ strokeWidth = 1.5, ...options } = {}) {
  return geo({ type: "Sphere" }, { strokeWidth, ...options });
}
function graticule2({ strokeOpacity = 0.1, ...options } = {}) {
  return geo(graticule10(), { strokeOpacity, ...options });
}

// ../../../node_modules/@observablehq/plot/src/transforms/hexbin.js
var ox = 0.5;
var oy = 0;
function hexbin(outputs = { fill: "count" }, { binWidth, ...options } = {}) {
  const { z } = options;
  binWidth = binWidth === void 0 ? 20 : number5(binWidth);
  outputs = maybeGroupOutputs(outputs, options);
  if (hasOutput(outputs, "fill")) options.channels = { ...options.channels, fill: { value: [] } };
  if (options.symbol === void 0) options.symbol = "hexagon";
  if (options.r === void 0 && !hasOutput(outputs, "r")) options.r = binWidth / 2;
  return initializer(options, (data, facets, channels, scales2, _, context) => {
    let { x: X3, y: Y3, z: Z, fill: F, stroke: S, symbol: Q } = channels;
    if (X3 === void 0) throw new Error("missing channel: x");
    if (Y3 === void 0) throw new Error("missing channel: y");
    ({ x: X3, y: Y3 } = applyPosition(channels, scales2, context));
    Z = Z ? Z.value : valueof(data, z);
    F = F?.value;
    S = S?.value;
    Q = Q?.value;
    const G = maybeSubgroup(outputs, { z: Z, fill: F, stroke: S, symbol: Q });
    const GZ = Z && [];
    const GF = F && [];
    const GS = S && [];
    const GQ = Q && [];
    const binFacets = [];
    const BX = [];
    const BY = [];
    let i = -1;
    for (const o of outputs) o.initialize(data);
    for (const facet of facets) {
      const binFacet = [];
      for (const o of outputs) o.scope("facet", facet);
      for (const [f, I] of maybeGroup(facet, G)) {
        for (const { index: b, extent: extent4 } of hbin(data, I, X3, Y3, binWidth)) {
          binFacet.push(++i);
          BX.push(extent4.x);
          BY.push(extent4.y);
          if (Z) GZ.push(G === Z ? f : Z[b[0]]);
          if (F) GF.push(G === F ? f : F[b[0]]);
          if (S) GS.push(G === S ? f : S[b[0]]);
          if (Q) GQ.push(G === Q ? f : Q[b[0]]);
          for (const o of outputs) o.reduce(b, extent4);
        }
      }
      binFacets.push(binFacet);
    }
    const sx = channels.x.scale;
    const sy = channels.y.scale;
    const binChannels = {
      x: { value: BX, source: scales2[sx] ? { value: map3(BX, scales2[sx].invert), scale: sx } : null },
      y: { value: BY, source: scales2[sy] ? { value: map3(BY, scales2[sy].invert), scale: sy } : null },
      ...Z && { z: { value: GZ } },
      ...F && { fill: { value: GF, scale: "auto" } },
      ...S && { stroke: { value: GS, scale: "auto" } },
      ...Q && { symbol: { value: GQ, scale: "auto" } },
      ...Object.fromEntries(
        outputs.map(({ name: name2, output }) => [
          name2,
          {
            scale: "auto",
            label: output.label,
            radius: name2 === "r" ? binWidth / 2 : void 0,
            value: output.transform()
          }
        ])
      )
    };
    return { data, facets: binFacets, channels: binChannels };
  });
}
function hbin(data, I, X3, Y3, dx) {
  const dy = dx * (1.5 / sqrt35);
  const bins = /* @__PURE__ */ new Map();
  for (const i of I) {
    let px = X3[i], py = Y3[i];
    if (isNaN(px) || isNaN(py)) continue;
    let pj = Math.round(py = (py - oy) / dy), pi5 = Math.round(px = (px - ox) / dx - (pj & 1) / 2), py1 = py - pj;
    if (Math.abs(py1) * 3 > 1) {
      let px1 = px - pi5, pi22 = pi5 + (px < pi5 ? -1 : 1) / 2, pj2 = pj + (py < pj ? -1 : 1), px2 = px - pi22, py2 = py - pj2;
      if (px1 * px1 + py1 * py1 > px2 * px2 + py2 * py2) pi5 = pi22 + (pj & 1 ? 1 : -1) / 2, pj = pj2;
    }
    const key = `${pi5},${pj}`;
    let bin3 = bins.get(key);
    if (bin3 === void 0) {
      bin3 = { index: [], extent: { data, x: (pi5 + (pj & 1) / 2) * dx + ox, y: pj * dy + oy } };
      bins.set(key, bin3);
    }
    bin3.index.push(i);
  }
  return bins.values();
}

// ../../../node_modules/@observablehq/plot/src/marks/hexgrid.js
var defaults19 = {
  ariaLabel: "hexgrid",
  fill: "none",
  stroke: "currentColor",
  strokeOpacity: 0.1
};
function hexgrid(options) {
  return new Hexgrid(options);
}
var Hexgrid = class extends Mark {
  constructor({ binWidth = 20, clip: clip2 = true, ...options } = {}) {
    super(singleton, void 0, { clip: clip2, ...options }, defaults19);
    this.binWidth = number5(binWidth);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { binWidth } = this;
    const { marginTop: marginTop2, marginRight: marginRight2, marginBottom: marginBottom2, marginLeft: marginLeft2, width: width2, height: height2 } = dimensions;
    const x06 = marginLeft2 - ox, x12 = width2 - marginRight2 - ox, y06 = marginTop2 - oy, y12 = height2 - marginBottom2 - oy, rx = binWidth / 2, ry = rx * sqrt4_3, hy = ry / 2, wx = rx * 2, wy = ry * 1.5, i0 = Math.floor(x06 / wx), i1 = Math.ceil(x12 / wx), j0 = Math.floor((y06 + hy) / wy), j1 = Math.ceil((y12 - hy) / wy) + 1, path2 = `m0,${round2(-ry)}l${round2(rx)},${round2(hy)}v${round2(ry)}l${round2(-rx)},${round2(hy)}`;
    let d = path2;
    for (let j = j0; j < j1; ++j) {
      for (let i = i0; i < i1; ++i) {
        d += `M${round2(i * wx + (j & 1) * rx)},${round2(j * wy)}${path2}`;
      }
    }
    return create3("svg:g", context).datum(0).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, {}, offset + ox, offset + oy).call((g) => g.append("path").call(applyDirectStyles, this).call(applyChannelStyles, this, channels).attr("d", d)).node();
  }
};
function round2(x3) {
  return Math.round(x3 * 1e3) / 1e3;
}

// ../../../node_modules/@observablehq/plot/src/marks/image.js
var defaults20 = {
  ariaLabel: "image",
  fill: null,
  stroke: null
};
function isPath(string2) {
  return /^\.*\//.test(string2);
}
function isUrl(string2) {
  return /^(blob|data|file|http|https):/i.test(string2);
}
function maybePathChannel(value) {
  return typeof value === "string" && (isPath(value) || isUrl(value)) ? [void 0, value] : [value, void 0];
}
var Image = class extends Mark {
  constructor(data, options = {}) {
    let { x: x3, y: y3, r, width: width2, height: height2, rotate, src, preserveAspectRatio, crossOrigin, frameAnchor, imageRendering } = options;
    if (r == null) r = void 0;
    if (r === void 0 && width2 === void 0 && height2 === void 0) width2 = height2 = 16;
    else if (width2 === void 0 && height2 !== void 0) width2 = height2;
    else if (height2 === void 0 && width2 !== void 0) height2 = width2;
    const [vs, cs] = maybePathChannel(src);
    const [vr, cr] = maybeNumberChannel(r);
    const [vw, cw] = maybeNumberChannel(width2, cr !== void 0 ? cr * 2 : void 0);
    const [vh, ch] = maybeNumberChannel(height2, cr !== void 0 ? cr * 2 : void 0);
    const [va, ca3] = maybeNumberChannel(rotate, 0);
    super(
      data,
      {
        x: { value: x3, scale: "x", optional: true },
        y: { value: y3, scale: "y", optional: true },
        r: { value: vr, scale: "r", filter: positive, optional: true },
        width: { value: vw, filter: positive, optional: true },
        height: { value: vh, filter: positive, optional: true },
        rotate: { value: va, optional: true },
        src: { value: vs, optional: true }
      },
      withDefaultSort(options),
      defaults20
    );
    this.src = cs;
    this.width = cw;
    this.rotate = ca3;
    this.height = ch;
    this.r = cr;
    this.preserveAspectRatio = impliedString(preserveAspectRatio, "xMidYMid");
    this.crossOrigin = string(crossOrigin);
    this.frameAnchor = maybeFrameAnchor(frameAnchor);
    this.imageRendering = impliedString(imageRendering, "auto");
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: x3, y: y3 } = scales2;
    const { x: X3, y: Y3, width: W, height: H, r: R, rotate: A5, src: S } = channels;
    const { r, width: width2, height: height2, rotate } = this;
    const [cx, cy] = applyFrameAnchor(this, dimensions);
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, { x: X3 && x3, y: Y3 && y3 }).call(
      (g) => g.selectAll().data(index2).enter().append("image").call(applyDirectStyles, this).attr("x", position2(X3, W, R, cx, width2, r)).attr("y", position2(Y3, H, R, cy, height2, r)).attr("width", W ? (i) => W[i] : width2 !== void 0 ? width2 : R ? (i) => R[i] * 2 : r * 2).attr("height", H ? (i) => H[i] : height2 !== void 0 ? height2 : R ? (i) => R[i] * 2 : r * 2).attr("transform", A5 ? (i) => `rotate(${A5[i]})` : rotate ? `rotate(${rotate})` : null).attr("transform-origin", A5 || rotate ? template`${X3 ? (i) => X3[i] : cx}px ${Y3 ? (i) => Y3[i] : cy}px` : null).call(applyAttr, "href", S ? (i) => S[i] : this.src).call(applyAttr, "preserveAspectRatio", this.preserveAspectRatio).call(applyAttr, "crossorigin", this.crossOrigin).call(applyAttr, "image-rendering", this.imageRendering).call(applyAttr, "clip-path", R ? (i) => `circle(${R[i]}px)` : r !== void 0 ? `circle(${r}px)` : null).call(applyChannelStyles, this, channels)
    ).node();
  }
};
function position2(X3, W, R, x3, w, r) {
  return W && X3 ? (i) => X3[i] - W[i] / 2 : W ? (i) => x3 - W[i] / 2 : X3 && w !== void 0 ? (i) => X3[i] - w / 2 : w !== void 0 ? x3 - w / 2 : R && X3 ? (i) => X3[i] - R[i] : R ? (i) => x3 - R[i] : X3 ? (i) => X3[i] - r : x3 - r;
}
function image(data, { x: x3, y: y3, ...options } = {}) {
  if (options.frameAnchor === void 0) [x3, y3] = maybeTuple(x3, y3);
  return new Image(data, { ...options, x: x3, y: y3 });
}

// ../../../node_modules/@observablehq/plot/src/stats.js
function ibetainv(p, a2, b) {
  var EPS2 = 1e-8;
  var a1 = a2 - 1;
  var b1 = b - 1;
  var j = 0;
  var lna, lnb, pp, t, u4, err, x3, al, h, w, afac;
  if (p <= 0) return 0;
  if (p >= 1) return 1;
  if (a2 >= 1 && b >= 1) {
    pp = p < 0.5 ? p : 1 - p;
    t = Math.sqrt(-2 * Math.log(pp));
    x3 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
    if (p < 0.5) x3 = -x3;
    al = (x3 * x3 - 3) / 6;
    h = 2 / (1 / (2 * a2 - 1) + 1 / (2 * b - 1));
    w = x3 * Math.sqrt(al + h) / h - (1 / (2 * b - 1) - 1 / (2 * a2 - 1)) * (al + 5 / 6 - 2 / (3 * h));
    x3 = a2 / (a2 + b * Math.exp(2 * w));
  } else {
    lna = Math.log(a2 / (a2 + b));
    lnb = Math.log(b / (a2 + b));
    t = Math.exp(a2 * lna) / a2;
    u4 = Math.exp(b * lnb) / b;
    w = t + u4;
    if (p < t / w) x3 = Math.pow(a2 * w * p, 1 / a2);
    else x3 = 1 - Math.pow(b * w * (1 - p), 1 / b);
  }
  afac = -gammaln(a2) - gammaln(b) + gammaln(a2 + b);
  for (; j < 10; j++) {
    if (x3 === 0 || x3 === 1) return x3;
    err = ibeta(x3, a2, b) - p;
    t = Math.exp(a1 * Math.log(x3) + b1 * Math.log(1 - x3) + afac);
    u4 = err / t;
    x3 -= t = u4 / (1 - 0.5 * Math.min(1, u4 * (a1 / x3 - b1 / (1 - x3))));
    if (x3 <= 0) x3 = 0.5 * (x3 + t);
    if (x3 >= 1) x3 = 0.5 * (x3 + t + 1);
    if (Math.abs(t) < EPS2 * x3 && j > 0) break;
  }
  return x3;
}
function ibeta(x3, a2, b) {
  var bt = x3 === 0 || x3 === 1 ? 0 : Math.exp(gammaln(a2 + b) - gammaln(a2) - gammaln(b) + a2 * Math.log(x3) + b * Math.log(1 - x3));
  if (x3 < 0 || x3 > 1) return false;
  if (x3 < (a2 + 1) / (a2 + b + 2))
    return bt * betacf(x3, a2, b) / a2;
  return 1 - bt * betacf(1 - x3, b, a2) / b;
}
function betacf(x3, a2, b) {
  var fpmin = 1e-30;
  var m = 1;
  var qab = a2 + b;
  var qap = a2 + 1;
  var qam = a2 - 1;
  var c4 = 1;
  var d = 1 - qab * x3 / qap;
  var m2, aa2, del, h;
  if (Math.abs(d) < fpmin) d = fpmin;
  d = 1 / d;
  h = d;
  for (; m <= 100; m++) {
    m2 = 2 * m;
    aa2 = m * (b - m) * x3 / ((qam + m2) * (a2 + m2));
    d = 1 + aa2 * d;
    if (Math.abs(d) < fpmin) d = fpmin;
    c4 = 1 + aa2 / c4;
    if (Math.abs(c4) < fpmin) c4 = fpmin;
    d = 1 / d;
    h *= d * c4;
    aa2 = -(a2 + m) * (qab + m) * x3 / ((a2 + m2) * (qap + m2));
    d = 1 + aa2 * d;
    if (Math.abs(d) < fpmin) d = fpmin;
    c4 = 1 + aa2 / c4;
    if (Math.abs(c4) < fpmin) c4 = fpmin;
    d = 1 / d;
    del = d * c4;
    h *= del;
    if (Math.abs(del - 1) < 3e-7) break;
  }
  return h;
}
function gammaln(x3) {
  var j = 0;
  var cof = [
    76.18009172947146,
    -86.5053203294167,
    24.01409824083091,
    -1.231739572450155,
    0.001208650973866179,
    -5395239384953e-18
  ];
  var ser = 1.000000000190015;
  var xx, y3, tmp;
  tmp = (y3 = xx = x3) + 5.5;
  tmp -= (xx + 0.5) * Math.log(tmp);
  for (; j < 6; j++) ser += cof[j] / ++y3;
  return Math.log(2.506628274631 * ser / xx) - tmp;
}
function qt(p, dof) {
  var x3 = ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);
  x3 = Math.sqrt(dof * (1 - x3) / x3);
  return p > 0.5 ? x3 : -x3;
}

// ../../../node_modules/@observablehq/plot/src/marks/linearRegression.js
var defaults21 = {
  ariaLabel: "linear-regression",
  fill: "currentColor",
  fillOpacity: 0.1,
  stroke: "currentColor",
  strokeWidth: 1.5,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  strokeMiterlimit: 1
};
var LinearRegression = class extends Mark {
  constructor(data, options = {}) {
    const { x: x3, y: y3, z, ci = 0.95, precision = 4 } = options;
    super(
      data,
      {
        x: { value: x3, scale: "x" },
        y: { value: y3, scale: "y" },
        z: { value: maybeZ(options), optional: true }
      },
      options,
      defaults21
    );
    this.z = z;
    this.ci = +ci;
    this.precision = +precision;
    if (!(0 <= this.ci && this.ci < 1)) throw new Error(`invalid ci; not in [0, 1): ${ci}`);
    if (!(this.precision > 0)) throw new Error(`invalid precision: ${precision}`);
  }
  render(index2, scales2, channels, dimensions, context) {
    const { x: X3, y: Y3, z: Z } = channels;
    const { ci } = this;
    return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(applyTransform, this, scales2).call(
      (g) => g.selectAll().data(Z ? groupZ2(index2, Z, this.z) : [index2]).enter().call(
        (enter) => enter.append("path").attr("fill", "none").call(applyDirectStyles, this).call(applyGroupedChannelStyles, this, { ...channels, fill: null, fillOpacity: null }).attr("d", (I) => this._renderLine(I, X3, Y3)).call(
          ci && !isNone(this.fill) ? (path2) => path2.select(pathBefore).attr("stroke", "none").call(applyDirectStyles, this).call(applyGroupedChannelStyles, this, {
            ...channels,
            stroke: null,
            strokeOpacity: null,
            strokeWidth: null
          }).attr("d", (I) => this._renderBand(I, X3, Y3)) : () => {
          }
        )
      )
    ).node();
  }
};
function pathBefore() {
  return this.parentNode.insertBefore(this.ownerDocument.createElementNS(namespaces_default.svg, "path"), this);
}
var LinearRegressionX = class extends LinearRegression {
  constructor(data, options) {
    super(data, options);
  }
  _renderBand(I, X3, Y3) {
    const { ci, precision } = this;
    const [y12, y22] = extent(I, (i) => Y3[i]);
    const f = linearRegressionF(I, Y3, X3);
    const g = confidenceIntervalF(I, Y3, X3, (1 - ci) / 2, f);
    return area_default3().y((y3) => y3).x0((y3) => g(y3, -1)).x1((y3) => g(y3, 1))(range(y12, y22 - precision / 2, precision).concat(y22));
  }
  _renderLine(I, X3, Y3) {
    const [y12, y22] = extent(I, (i) => Y3[i]);
    const f = linearRegressionF(I, Y3, X3);
    return `M${f(y12)},${y12}L${f(y22)},${y22}`;
  }
};
var LinearRegressionY = class extends LinearRegression {
  constructor(data, options) {
    super(data, options);
  }
  _renderBand(I, X3, Y3) {
    const { ci, precision } = this;
    const [x12, x22] = extent(I, (i) => X3[i]);
    const f = linearRegressionF(I, X3, Y3);
    const g = confidenceIntervalF(I, X3, Y3, (1 - ci) / 2, f);
    return area_default3().x((x3) => x3).y0((x3) => g(x3, -1)).y1((x3) => g(x3, 1))(range(x12, x22 - precision / 2, precision).concat(x22));
  }
  _renderLine(I, X3, Y3) {
    const [x12, x22] = extent(I, (i) => X3[i]);
    const f = linearRegressionF(I, X3, Y3);
    return `M${x12},${f(x12)}L${x22},${f(x22)}`;
  }
};
function linearRegressionX(data, { y: y3 = indexOf, x: x3 = identity8, stroke, fill = isNoneish(stroke) ? "currentColor" : stroke, ...options } = {}) {
  return new LinearRegressionX(data, maybeDenseIntervalY({ ...options, x: x3, y: y3, fill, stroke }));
}
function linearRegressionY(data, { x: x3 = indexOf, y: y3 = identity8, stroke, fill = isNoneish(stroke) ? "currentColor" : stroke, ...options } = {}) {
  return new LinearRegressionY(data, maybeDenseIntervalX({ ...options, x: x3, y: y3, fill, stroke }));
}
function linearRegressionF(I, X3, Y3) {
  let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
  for (const i of I) {
    const xi = X3[i];
    const yi = Y3[i];
    sumX += xi;
    sumY += yi;
    sumXY += xi * yi;
    sumX2 += xi * xi;
  }
  const n = I.length;
  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
  const intercept = (sumY - slope * sumX) / n;
  return (x3) => slope * x3 + intercept;
}
function confidenceIntervalF(I, X3, Y3, p, f) {
  const mean2 = sum2(I, (i) => X3[i]) / I.length;
  let a2 = 0, b = 0;
  for (const i of I) {
    a2 += (X3[i] - mean2) ** 2;
    b += (Y3[i] - f(X3[i])) ** 2;
  }
  const sy = Math.sqrt(b / (I.length - 2));
  const t = qt(p, I.length - 2);
  return (x3, k2) => {
    const Y4 = f(x3);
    const se = sy * Math.sqrt(1 / I.length + (x3 - mean2) ** 2 / a2);
    return Y4 + k2 * t * se;
  };
}

// ../../../node_modules/@observablehq/plot/src/transforms/tree.js
function treeNode({
  path: path2 = identity8,
  // the delimited path
  delimiter,
  // how the path is separated
  frameAnchor,
  treeLayout = tree_default,
  treeSort,
  treeSeparation,
  treeAnchor,
  treeFilter,
  ...options
} = {}) {
  treeAnchor = maybeTreeAnchor(treeAnchor);
  treeSort = maybeTreeSort(treeSort);
  if (treeFilter != null) treeFilter = maybeNodeValue(treeFilter);
  if (frameAnchor === void 0) frameAnchor = treeAnchor.frameAnchor;
  const normalize4 = normalizer(delimiter);
  const outputs = treeOutputs(options, maybeNodeValue);
  const [X3, setX] = column2();
  const [Y3, setY] = column2();
  return {
    x: X3,
    y: Y3,
    frameAnchor,
    ...basic(options, (data, facets) => {
      const P = normalize4(valueof(data, path2));
      const X4 = setX([]);
      const Y4 = setY([]);
      let treeIndex = -1;
      const treeData = [];
      const treeFacets = [];
      const rootof = stratify_default().path((i) => P[i]);
      const setData = isArray3(data) ? (node) => node.data = data[node.data] : (node) => node.data = data.get(node.data);
      const layout = treeLayout();
      if (layout.nodeSize) layout.nodeSize([1, 1]);
      if (layout.separation && treeSeparation !== void 0) layout.separation(treeSeparation ?? one2);
      for (const o of outputs) o[output_values] = o[output_setValues]([]);
      for (const facet of facets) {
        const treeFacet = [];
        const root2 = rootof(facet.filter((i) => P[i] != null)).each(setData);
        if (treeSort != null) root2.sort(treeSort);
        layout(root2);
        for (const node of root2.descendants()) {
          if (treeFilter != null && !treeFilter(node)) continue;
          treeFacet.push(++treeIndex);
          treeData[treeIndex] = node.data;
          treeAnchor.position(node, treeIndex, X4, Y4);
          for (const o of outputs) o[output_values][treeIndex] = o[output_evaluate](node);
        }
        treeFacets.push(treeFacet);
      }
      return { data: treeData, facets: treeFacets };
    }),
    ...Object.fromEntries(outputs)
  };
}
function treeLink({
  path: path2 = identity8,
  // the delimited path
  delimiter,
  // how the path is separated
  curve = "bump-x",
  stroke = "#555",
  strokeWidth = 1.5,
  strokeOpacity = 0.5,
  treeLayout = tree_default,
  treeSort,
  treeSeparation,
  treeAnchor,
  treeFilter,
  ...options
} = {}) {
  treeAnchor = maybeTreeAnchor(treeAnchor);
  treeSort = maybeTreeSort(treeSort);
  if (treeFilter != null) treeFilter = maybeLinkValue(treeFilter);
  options = { curve, stroke, strokeWidth, strokeOpacity, ...options };
  const normalize4 = normalizer(delimiter);
  const outputs = treeOutputs(options, maybeLinkValue);
  const [X13, setX1] = column2();
  const [X23, setX2] = column2();
  const [Y13, setY1] = column2();
  const [Y23, setY2] = column2();
  return {
    x1: X13,
    x2: X23,
    y1: Y13,
    y2: Y23,
    ...basic(options, (data, facets) => {
      const P = normalize4(valueof(data, path2));
      const X14 = setX1([]);
      const X24 = setX2([]);
      const Y14 = setY1([]);
      const Y24 = setY2([]);
      let treeIndex = -1;
      const treeData = [];
      const treeFacets = [];
      const rootof = stratify_default().path((i) => P[i]);
      const layout = treeLayout();
      if (layout.nodeSize) layout.nodeSize([1, 1]);
      if (layout.separation && treeSeparation !== void 0) layout.separation(treeSeparation ?? one2);
      for (const o of outputs) o[output_values] = o[output_setValues]([]);
      for (const facet of facets) {
        const treeFacet = [];
        const root2 = rootof(facet.filter((i) => P[i] != null)).each((node) => node.data = data[node.data]);
        if (treeSort != null) root2.sort(treeSort);
        layout(root2);
        for (const { source, target } of root2.links()) {
          if (treeFilter != null && !treeFilter(target, source)) continue;
          treeFacet.push(++treeIndex);
          treeData[treeIndex] = target.data;
          treeAnchor.position(source, treeIndex, X14, Y14);
          treeAnchor.position(target, treeIndex, X24, Y24);
          for (const o of outputs) o[output_values][treeIndex] = o[output_evaluate](target, source);
        }
        treeFacets.push(treeFacet);
      }
      return { data: treeData, facets: treeFacets };
    }),
    ...Object.fromEntries(outputs)
  };
}
function maybeTreeAnchor(anchor = "left") {
  switch (`${anchor}`.trim().toLowerCase()) {
    case "left":
      return treeAnchorLeft;
    case "right":
      return treeAnchorRight;
  }
  throw new Error(`invalid tree anchor: ${anchor}`);
}
var treeAnchorLeft = {
  frameAnchor: "left",
  dx: 6,
  position({ x: x3, y: y3 }, i, X3, Y3) {
    X3[i] = y3;
    Y3[i] = -x3;
  }
};
var treeAnchorRight = {
  frameAnchor: "right",
  dx: -6,
  position({ x: x3, y: y3 }, i, X3, Y3) {
    X3[i] = -y3;
    Y3[i] = -x3;
  }
};
function maybeTreeSort(sort3) {
  return sort3 == null || typeof sort3 === "function" ? sort3 : `${sort3}`.trim().toLowerCase().startsWith("node:") ? nodeSort(maybeNodeValue(sort3)) : nodeSort(nodeData(sort3));
}
function nodeSort(value) {
  return (a2, b) => ascendingDefined2(value(a2), value(b));
}
function nodeData(field3) {
  return (node) => node.data?.[field3];
}
function normalizer(delimiter = "/") {
  delimiter = `${delimiter}`;
  if (delimiter === "/") return (P) => P;
  if (delimiter.length !== 1) throw new Error("delimiter must be exactly one character");
  const delimiterCode = delimiter.charCodeAt(0);
  return (P) => P.map((p) => slashDelimiter(p, delimiterCode));
}
var CODE_BACKSLASH = 92;
var CODE_SLASH = 47;
function slashDelimiter(input3, delimiterCode) {
  if (delimiterCode === CODE_BACKSLASH) throw new Error("delimiter cannot be backslash");
  let afterBackslash = false;
  for (let i = 0, n = input3.length; i < n; ++i) {
    switch (input3.charCodeAt(i)) {
      case CODE_BACKSLASH:
        if (!afterBackslash) {
          afterBackslash = true;
          continue;
        }
        break;
      case delimiterCode:
        if (afterBackslash) {
          input3 = input3.slice(0, i - 1) + input3.slice(i), --i, --n;
        } else {
          input3 = input3.slice(0, i) + "/" + input3.slice(i + 1);
        }
        break;
      case CODE_SLASH:
        if (afterBackslash) {
          input3 = input3.slice(0, i) + "\\\\" + input3.slice(i), i += 2, n += 2;
        } else {
          input3 = input3.slice(0, i) + "\\" + input3.slice(i), ++i, ++n;
        }
        break;
    }
    afterBackslash = false;
  }
  return input3;
}
function slashUnescape(input3) {
  let afterBackslash = false;
  for (let i = 0, n = input3.length; i < n; ++i) {
    switch (input3.charCodeAt(i)) {
      case CODE_BACKSLASH:
        if (!afterBackslash) {
          afterBackslash = true;
          continue;
        }
      // eslint-disable-next-line no-fallthrough
      case CODE_SLASH:
        if (afterBackslash) {
          input3 = input3.slice(0, i - 1) + input3.slice(i), --i, --n;
        }
        break;
    }
    afterBackslash = false;
  }
  return input3;
}
function isNodeValue(option) {
  return isObject(option) && typeof option.node === "function";
}
function isLinkValue(option) {
  return isObject(option) && typeof option.link === "function";
}
function maybeNodeValue(value) {
  if (isNodeValue(value)) return value.node;
  value = `${value}`.trim().toLowerCase();
  if (!value.startsWith("node:")) return;
  switch (value) {
    case "node:name":
      return nodeName;
    case "node:path":
      return nodePath;
    case "node:internal":
      return nodeInternal;
    case "node:external":
      return nodeExternal;
    case "node:depth":
      return nodeDepth;
    case "node:height":
      return nodeHeight;
  }
  throw new Error(`invalid node value: ${value}`);
}
function maybeLinkValue(value) {
  if (isNodeValue(value)) return value.node;
  if (isLinkValue(value)) return value.link;
  value = `${value}`.trim().toLowerCase();
  if (!value.startsWith("node:") && !value.startsWith("parent:")) return;
  switch (value) {
    case "parent:name":
      return parentValue(nodeName);
    case "parent:path":
      return parentValue(nodePath);
    case "parent:depth":
      return parentValue(nodeDepth);
    case "parent:height":
      return parentValue(nodeHeight);
    case "node:name":
      return nodeName;
    case "node:path":
      return nodePath;
    case "node:internal":
      return nodeInternal;
    case "node:external":
      return nodeExternal;
    case "node:depth":
      return nodeDepth;
    case "node:height":
      return nodeHeight;
  }
  throw new Error(`invalid link value: ${value}`);
}
function nodePath(node) {
  return node.id;
}
function nodeName(node) {
  return nameof(node.id);
}
function nodeDepth(node) {
  return node.depth;
}
function nodeHeight(node) {
  return node.height;
}
function nodeInternal(node) {
  return !!node.children;
}
function nodeExternal(node) {
  return !node.children;
}
function parentValue(evaluate) {
  return (child, parent) => parent == null ? void 0 : evaluate(parent);
}
function nameof(path2) {
  let i = path2.length;
  while (--i > 0) if (slash2(path2, i)) break;
  return slashUnescape(path2.slice(i + 1));
}
function slash2(path2, i) {
  if (path2[i] === "/") {
    let k2 = 0;
    while (i > 0 && path2[--i] === "\\") ++k2;
    if ((k2 & 1) === 0) return true;
  }
  return false;
}
var output_setValues = 2;
var output_evaluate = 3;
var output_values = 4;
function treeOutputs(options, maybeTreeValue) {
  const outputs = [];
  for (const name2 in options) {
    const value = options[name2];
    const treeValue = maybeTreeValue(value);
    if (treeValue !== void 0) {
      outputs.push([name2, ...column2(value), treeValue]);
    }
  }
  return outputs;
}

// ../../../node_modules/@observablehq/plot/src/marks/tree.js
function tree(data, {
  fill,
  stroke,
  strokeWidth,
  strokeOpacity,
  strokeLinejoin,
  strokeLinecap,
  strokeMiterlimit,
  strokeDasharray,
  strokeDashoffset,
  marker,
  markerStart = marker,
  markerEnd = marker,
  dot: dotDot = isNoneish(markerStart) && isNoneish(markerEnd),
  text: textText = "node:name",
  textStroke = "var(--plot-background)",
  title = "node:path",
  dx,
  dy,
  textAnchor,
  treeLayout = tree_default,
  textLayout = treeLayout === tree_default || treeLayout === cluster_default ? "mirrored" : "normal",
  tip: tip2,
  ...options
} = {}) {
  if (dx === void 0) dx = maybeTreeAnchor(options.treeAnchor).dx;
  if (textAnchor !== void 0) throw new Error("textAnchor is not a configurable tree option");
  textLayout = keyword(textLayout, "textLayout", ["mirrored", "normal"]);
  function treeText(textOptions2) {
    return text(
      data,
      treeNode({
        treeLayout,
        text: textText,
        fill: fill === void 0 ? "currentColor" : fill,
        stroke: textStroke,
        dx,
        dy,
        title,
        ...textOptions2,
        ...options
      })
    );
  }
  return marks(
    link2(
      data,
      treeLink({
        treeLayout,
        markerStart,
        markerEnd,
        stroke: stroke !== void 0 ? stroke : fill === void 0 ? "node:internal" : fill,
        strokeWidth,
        strokeOpacity,
        strokeLinejoin,
        strokeLinecap,
        strokeMiterlimit,
        strokeDasharray,
        strokeDashoffset,
        ...options
      })
    ),
    dotDot ? dot(data, treeNode({ treeLayout, fill: fill === void 0 ? "node:internal" : fill, title, tip: tip2, ...options })) : null,
    textText != null ? textLayout === "mirrored" ? [
      treeText({ textAnchor: "start", treeFilter: "node:external" }),
      treeText({ textAnchor: "end", treeFilter: "node:internal", dx: -dx })
    ] : treeText() : null
  );
}
function cluster(data, options) {
  return tree(data, { ...options, treeLayout: cluster_default });
}

// ../../../node_modules/@observablehq/plot/src/marks/waffle.js
var waffleDefaults = {
  ariaLabel: "waffle"
};
var WaffleX = class extends BarX {
  constructor(data, { unit: unit3 = 1, gap = 1, round: round3, multiple, ...options } = {}) {
    super(data, wafflePolygon("x", options), waffleDefaults);
    this.unit = Math.max(0, unit3);
    this.gap = +gap;
    this.round = maybeRound2(round3);
    this.multiple = maybeMultiple(multiple);
  }
};
var WaffleY = class extends BarY {
  constructor(data, { unit: unit3 = 1, gap = 1, round: round3, multiple, ...options } = {}) {
    super(data, wafflePolygon("y", options), waffleDefaults);
    this.unit = Math.max(0, unit3);
    this.gap = +gap;
    this.round = maybeRound2(round3);
    this.multiple = maybeMultiple(multiple);
  }
};
function wafflePolygon(y3, options) {
  const x3 = y3 === "y" ? "x" : "y";
  const y12 = `${y3}1`;
  const y22 = `${y3}2`;
  return initializer(waffleRender(options), function(data, facets, channels, scales2, dimensions) {
    const { round: round3, unit: unit3 } = this;
    const Y13 = channels[y12].value;
    const Y23 = channels[y22].value;
    const xy = valueObject({ ...x3 in channels && { [x3]: channels[x3] }, [y12]: channels[y12], [y22]: channels[y22] }, scales2);
    const barwidth = this[y3 === "y" ? "_width" : "_height"](scales2, xy, dimensions);
    const barx = this[y3 === "y" ? "_x" : "_y"](scales2, xy, dimensions);
    const scale3 = unit3 * scaleof(scales2.scales[y3]);
    const { multiple = Math.max(1, Math.floor(Math.sqrt(barwidth / scale3))) } = this;
    const cx = Math.min(barwidth / multiple, scale3 * multiple);
    const cy = scale3 * multiple;
    const tx = (barwidth - multiple * cx) / 2;
    const x06 = typeof barx === "function" ? (i) => barx(i) + tx : barx + tx;
    const y06 = scales2[y3](0);
    const transform3 = y3 === "y" ? ([x4, y4]) => [x4 * cx, -y4 * cy] : ([x4, y4]) => [y4 * cy, x4 * cx];
    const mx = typeof x06 === "function" ? (i) => x06(i) - barwidth / 2 : () => x06;
    const [ix, iy] = y3 === "y" ? [0, 1] : [1, 0];
    const n = Y23.length;
    const P = new Array(n);
    const X3 = new Float64Array(n);
    const Y3 = new Float64Array(n);
    for (let i = 0; i < n; ++i) {
      P[i] = wafflePoints(round3(Y13[i] / unit3), round3(Y23[i] / unit3), multiple).map(transform3);
      const c4 = P[i].pop();
      X3[i] = c4[ix] + mx(i);
      Y3[i] = c4[iy] + y06;
    }
    return {
      channels: {
        polygon: { value: P, source: null, filter: null },
        [`c${x3}`]: { value: [cx, x06], source: null, filter: null },
        [`c${y3}`]: { value: [cy, y06], source: null, filter: null },
        [x3]: { value: X3, scale: null, source: null },
        [y12]: { value: Y3, scale: null, source: channels[y12] },
        [y22]: { value: Y3, scale: null, source: channels[y22] }
      }
    };
  });
}
function waffleRender({ render, ...options }) {
  return {
    ...options,
    render: composeRender(render, function(index2, scales2, values2, dimensions, context) {
      const { gap, rx, ry } = this;
      const { channels, ariaLabel: ariaLabel2, href, title, ...visualValues } = values2;
      const { document: document2 } = context;
      const polygon = channels.polygon.value;
      const [cx, x06] = channels.cx.value;
      const [cy, y06] = channels.cy.value;
      const patternId = getPatternId();
      const basePattern = document2.createElementNS(namespaces_default.svg, "pattern");
      basePattern.setAttribute("width", cx);
      basePattern.setAttribute("height", cy);
      basePattern.setAttribute("patternUnits", "userSpaceOnUse");
      const basePatternRect = basePattern.appendChild(document2.createElementNS(namespaces_default.svg, "rect"));
      basePatternRect.setAttribute("x", gap / 2);
      basePatternRect.setAttribute("y", gap / 2);
      basePatternRect.setAttribute("width", cx - gap);
      basePatternRect.setAttribute("height", cy - gap);
      if (rx != null) basePatternRect.setAttribute("rx", rx);
      if (ry != null) basePatternRect.setAttribute("ry", ry);
      return create3("svg:g", context).call(applyIndirectStyles, this, dimensions, context).call(this._transform, this, scales2).call(
        (g) => g.selectAll().data(index2).enter().append(() => basePattern.cloneNode(true)).attr("id", (i) => `${patternId}-${i}`).select("rect").call(applyDirectStyles, this).call(applyChannelStyles, this, visualValues)
      ).call(
        (g) => g.selectAll().data(index2).enter().append("path").attr("transform", template`translate(${x06},${y06})`).attr("d", (i) => `M${polygon[i].join("L")}Z`).attr("fill", (i) => `url(#${patternId}-${i})`).attr("stroke", this.stroke == null ? null : "none").call(applyChannelStyles, this, { ariaLabel: ariaLabel2, href, title })
      ).node();
    })
  };
}
function wafflePoints(i1, i2, columns) {
  if (i2 < i1) return wafflePoints(i2, i1, columns);
  if (i1 < 0) return wafflePointsOffset(i1, i2, columns, Math.ceil(-Math.min(i1, i2) / columns));
  const x1f = Math.floor(i1 % columns);
  const x1c = Math.ceil(i1 % columns);
  const x2f = Math.floor(i2 % columns);
  const x2c = Math.ceil(i2 % columns);
  const y1f = Math.floor(i1 / columns);
  const y1c = Math.ceil(i1 / columns);
  const y2f = Math.floor(i2 / columns);
  const y2c = Math.ceil(i2 / columns);
  const points2 = [];
  if (y2c > y1c) points2.push([0, y1c]);
  points2.push([x1f, y1c], [x1f, y1f + i1 % 1], [x1c, y1f + i1 % 1]);
  if (!(i1 % columns > columns - 1)) {
    points2.push([x1c, y1f]);
    if (y2f > y1f) points2.push([columns, y1f]);
  }
  if (y2f > y1f) points2.push([columns, y2f]);
  points2.push([x2c, y2f], [x2c, y2f + i2 % 1], [x2f, y2f + i2 % 1]);
  if (!(i2 % columns < 1)) {
    points2.push([x2f, y2c]);
    if (y2c > y1c) points2.push([0, y2c]);
  }
  points2.push(waffleCentroid(i1, i2, columns));
  return points2;
}
function wafflePointsOffset(i1, i2, columns, k2) {
  return wafflePoints(i1 + k2 * columns, i2 + k2 * columns, columns).map(([x3, y3]) => [x3, y3 - k2]);
}
function waffleCentroid(i1, i2, columns) {
  const r = Math.floor(i2 / columns) - Math.floor(i1 / columns);
  return r === 0 ? (
    // Single row
    waffleRowCentroid(i1, i2, columns)
  ) : r === 1 ? (
    // Two incomplete rows; use the midpoint of their overlap if any, otherwise the larger row
    Math.floor(i2 % columns) > Math.ceil(i1 % columns) ? [(Math.floor(i2 % columns) + Math.ceil(i1 % columns)) / 2, Math.floor(i2 / columns)] : i2 % columns > columns - i1 % columns ? waffleRowCentroid(i2 - i2 % columns, i2, columns) : waffleRowCentroid(i1, columns * Math.ceil(i1 / columns), columns)
  ) : (
    // At least one full row; take the midpoint of all the rows that include the middle
    [columns / 2, (Math.round(i1 / columns) + Math.round(i2 / columns)) / 2]
  );
}
function waffleRowCentroid(i1, i2, columns) {
  const c4 = Math.floor(i2) - Math.floor(i1);
  return c4 === 0 ? (
    // Single cell
    [Math.floor(i1 % columns) + 0.5, Math.floor(i1 / columns) + (i1 + i2) / 2 % 1]
  ) : c4 === 1 ? (
    // Two incomplete cells; use the overlap if large enough, otherwise use the largest
    i2 % 1 - i1 % 1 > 0.5 ? [Math.ceil(i1 % columns), Math.floor(i2 / columns) + (i1 % 1 + i2 % 1) / 2] : i2 % 1 > 1 - i1 % 1 ? [Math.floor(i2 % columns) + 0.5, Math.floor(i2 / columns) + i2 % 1 / 2] : [Math.floor(i1 % columns) + 0.5, Math.floor(i1 / columns) + (1 + i1 % 1) / 2]
  ) : (
    // At least one full cell; take the midpoint
    [
      Math.ceil(i1 % columns) + Math.ceil(Math.floor(i2) - Math.ceil(i1)) / 2,
      Math.floor(i1 / columns) + (i2 >= 1 + i1 ? 0.5 : (i1 + i2) / 2 % 1)
    ]
  );
}
function maybeRound2(round3) {
  if (round3 === void 0 || round3 === false) return Number;
  if (round3 === true) return Math.round;
  if (typeof round3 !== "function") throw new Error(`invalid round: ${round3}`);
  return round3;
}
function maybeMultiple(multiple) {
  return multiple === void 0 ? void 0 : Math.max(1, Math.floor(multiple));
}
function scaleof({ domain, range: range3 }) {
  return spread(range3) / spread(domain);
}
function spread(domain) {
  const [min5, max4] = extent(domain);
  return max4 - min5;
}
function waffleX(data, { tip: tip2, ...options } = {}) {
  if (!hasXY(options)) options = { ...options, y: indexOf, x2: identity8 };
  return new WaffleX(data, { tip: waffleTip(tip2), ...maybeStackX(maybeIntervalX(maybeIdentityX(options))) });
}
function waffleY(data, { tip: tip2, ...options } = {}) {
  if (!hasXY(options)) options = { ...options, x: indexOf, y2: identity8 };
  return new WaffleY(data, { tip: waffleTip(tip2), ...maybeStackY(maybeIntervalY(maybeIdentityY(options))) });
}
function waffleTip(tip2) {
  return tip2 === true ? { maxRadius: Infinity } : isObject(tip2) && tip2.maxRadius === void 0 ? { ...tip2, maxRadius: Infinity } : void 0;
}

// ../../../node_modules/@observablehq/plot/src/transforms/dodge.js
var import_interval_tree_1d = __toESM(require_interval_tree(), 1);
var anchorXLeft = ({ marginLeft: marginLeft2 }) => [1, marginLeft2];
var anchorXRight = ({ width: width2, marginRight: marginRight2 }) => [-1, width2 - marginRight2];
var anchorXMiddle = ({ width: width2, marginLeft: marginLeft2, marginRight: marginRight2 }) => [0, (marginLeft2 + width2 - marginRight2) / 2];
var anchorYTop = ({ marginTop: marginTop2 }) => [1, marginTop2];
var anchorYBottom = ({ height: height2, marginBottom: marginBottom2 }) => [-1, height2 - marginBottom2];
var anchorYMiddle = ({ height: height2, marginTop: marginTop2, marginBottom: marginBottom2 }) => [0, (marginTop2 + height2 - marginBottom2) / 2];
function maybeAnchor4(anchor) {
  return typeof anchor === "string" ? { anchor } : anchor;
}
function dodgeX(dodgeOptions = {}, options = {}) {
  if (arguments.length === 1) [dodgeOptions, options] = mergeOptions3(dodgeOptions);
  let { anchor = "left", padding: padding2 = 1, r = options.r } = maybeAnchor4(dodgeOptions);
  switch (`${anchor}`.toLowerCase()) {
    case "left":
      anchor = anchorXLeft;
      break;
    case "right":
      anchor = anchorXRight;
      break;
    case "middle":
      anchor = anchorXMiddle;
      break;
    default:
      throw new Error(`unknown dodge anchor: ${anchor}`);
  }
  return dodge("x", "y", anchor, number5(padding2), r, options);
}
function dodgeY(dodgeOptions = {}, options = {}) {
  if (arguments.length === 1) [dodgeOptions, options] = mergeOptions3(dodgeOptions);
  let { anchor = "bottom", padding: padding2 = 1, r = options.r } = maybeAnchor4(dodgeOptions);
  switch (`${anchor}`.toLowerCase()) {
    case "top":
      anchor = anchorYTop;
      break;
    case "bottom":
      anchor = anchorYBottom;
      break;
    case "middle":
      anchor = anchorYMiddle;
      break;
    default:
      throw new Error(`unknown dodge anchor: ${anchor}`);
  }
  return dodge("y", "x", anchor, number5(padding2), r, options);
}
function mergeOptions3(options) {
  const { anchor, padding: padding2, ...rest } = options;
  const { r } = rest;
  return [{ anchor, padding: padding2, r }, rest];
}
function dodge(y3, x3, anchor, padding2, r, options) {
  if (r != null && typeof r !== "number") {
    let { channels, sort: sort3, reverse: reverse3 } = options;
    channels = maybeNamed(channels);
    if (channels?.r === void 0) options = { ...options, channels: { ...channels, r: { value: r, scale: "r" } } };
    if (sort3 === void 0 && reverse3 === void 0) options.sort = { channel: "-r" };
  }
  return initializer(options, function(data, facets, channels, scales2, dimensions, context) {
    let { [x3]: X3, r: R } = channels;
    if (!channels[x3]) throw new Error(`missing channel: ${x3}`);
    ({ [x3]: X3 } = applyPosition(channels, scales2, context));
    const cr = R ? void 0 : r !== void 0 ? number5(r) : this.r !== void 0 ? this.r : 3;
    if (R) R = valueof(R.value, scales2[R.scale] || identity8, Float64Array);
    let [ky2, ty] = anchor(dimensions);
    const compare = ky2 ? compareAscending : compareSymmetric;
    const Y3 = new Float64Array(X3.length);
    const radius2 = R ? (i) => R[i] : () => cr;
    for (let I of facets) {
      const tree2 = (0, import_interval_tree_1d.default)();
      I = I.filter(R ? (i) => finite2(X3[i]) && positive(R[i]) : (i) => finite2(X3[i]));
      const intervals = new Float64Array(2 * I.length + 2);
      for (const i of I) {
        const ri = radius2(i);
        const y06 = ky2 ? ri + padding2 : 0;
        const l = X3[i] - ri;
        const h = X3[i] + ri;
        let k2 = 2;
        tree2.queryInterval(l - padding2, h + padding2, ([, , j]) => {
          const yj = Y3[j] - y06;
          const dx = X3[i] - X3[j];
          const dr = padding2 + (R ? R[i] + R[j] : 2 * cr);
          const dy = Math.sqrt(dr * dr - dx * dx);
          intervals[k2++] = yj - dy;
          intervals[k2++] = yj + dy;
        });
        let candidates = intervals.slice(0, k2);
        if (ky2) candidates = candidates.filter((y4) => y4 >= 0);
        out: for (const y4 of candidates.sort(compare)) {
          for (let j = 0; j < k2; j += 2) {
            if (intervals[j] + 1e-6 < y4 && y4 < intervals[j + 1] - 1e-6) {
              continue out;
            }
          }
          Y3[i] = y4 + y06;
          break;
        }
        tree2.insert([l, h, i]);
      }
    }
    if (!ky2) ky2 = 1;
    for (const I of facets) {
      for (const i of I) {
        Y3[i] = Y3[i] * ky2 + ty;
      }
    }
    return {
      data,
      facets,
      channels: {
        [y3]: { value: Y3, source: null },
        // don’t show in tooltip
        [x3]: { value: X3, source: channels[x3] },
        ...R && { r: { value: R, source: channels.r } }
      }
    };
  });
}
function compareSymmetric(a2, b) {
  return Math.abs(a2) - Math.abs(b);
}
function compareAscending(a2, b) {
  return a2 - b;
}

// ../../../node_modules/@observablehq/plot/src/transforms/normalize.js
function normalizeX(basis2, options) {
  if (arguments.length === 1) ({ basis: basis2, ...options } = basis2);
  return mapX(normalize3(basis2), options);
}
function normalizeY(basis2, options) {
  if (arguments.length === 1) ({ basis: basis2, ...options } = basis2);
  return mapY(normalize3(basis2), options);
}
function normalize3(basis2) {
  if (basis2 === void 0) return normalizeFirst;
  if (typeof basis2 === "function") return normalizeBasis(taker(basis2));
  if (/^p\d{2}$/i.test(basis2)) return normalizeAccessor(percentile(basis2));
  switch (`${basis2}`.toLowerCase()) {
    case "deviation":
      return normalizeDeviation;
    case "first":
      return normalizeFirst;
    case "last":
      return normalizeLast;
    case "max":
      return normalizeMax;
    case "mean":
      return normalizeMean;
    case "median":
      return normalizeMedian;
    case "min":
      return normalizeMin;
    case "sum":
      return normalizeSum;
    case "extent":
      return normalizeExtent;
  }
  throw new Error(`invalid basis: ${basis2}`);
}
function normalizeBasis(basis2) {
  return {
    mapIndex(I, S, T) {
      const b = +basis2(I, S);
      for (const i of I) {
        T[i] = S[i] === null ? NaN : S[i] / b;
      }
    }
  };
}
function normalizeAccessor(f) {
  return normalizeBasis((I, S) => f(I, (i) => S[i]));
}
var normalizeExtent = {
  mapIndex(I, S, T) {
    const [s1, s2] = extent(I, (i) => S[i]);
    const d = s2 - s1;
    for (const i of I) {
      T[i] = S[i] === null ? NaN : (S[i] - s1) / d;
    }
  }
};
var normalizeFirst = normalizeBasis((I, S) => {
  for (let i = 0; i < I.length; ++i) {
    const s2 = S[I[i]];
    if (defined(s2)) return s2;
  }
});
var normalizeLast = normalizeBasis((I, S) => {
  for (let i = I.length - 1; i >= 0; --i) {
    const s2 = S[I[i]];
    if (defined(s2)) return s2;
  }
});
var normalizeDeviation = {
  mapIndex(I, S, T) {
    const m = mean(I, (i) => S[i]);
    const d = deviation(I, (i) => S[i]);
    for (const i of I) {
      T[i] = S[i] === null ? NaN : d ? (S[i] - m) / d : 0;
    }
  }
};
var normalizeMax = normalizeAccessor(max2);
var normalizeMean = normalizeAccessor(mean);
var normalizeMedian = normalizeAccessor(median2);
var normalizeMin = normalizeAccessor(min2);
var normalizeSum = normalizeAccessor(sum2);

// ../../../node_modules/@observablehq/plot/src/transforms/shift.js
function shiftX(interval4, options) {
  return shiftK("x", interval4, options);
}
function shiftY(interval4, options) {
  return shiftK("y", interval4, options);
}
function shiftK(x3, interval4, options = {}) {
  let offset2;
  let k2 = 1;
  if (typeof interval4 === "number") {
    k2 = interval4;
    offset2 = (x4, k3) => +x4 + k3;
  } else {
    if (typeof interval4 === "string") {
      const sign4 = interval4.startsWith("-") ? -1 : 1;
      [interval4, k2] = parseTimeInterval(interval4.replace(/^[+-]/, ""));
      k2 *= sign4;
    }
    interval4 = maybeInterval(interval4);
    offset2 = (x4, k3) => interval4.offset(x4, k3);
  }
  const x12 = `${x3}1`;
  const x22 = `${x3}2`;
  const mapped = map4(
    {
      [x12]: (D3) => D3.map((d) => offset2(d, k2)),
      [x22]: (D3) => D3
    },
    options
  );
  const t = mapped[x22].transform;
  mapped[x22].transform = () => {
    const V = t();
    const [x06, x13] = extent(V);
    V.domain = k2 < 0 ? [x06, offset2(x13, k2)] : [offset2(x06, k2), x13];
    return V;
  };
  return mapped;
}

// ../../../node_modules/@observablehq/plot/src/transforms/select.js
function select(selector, options = {}) {
  if (typeof selector === "string") {
    switch (selector.toLowerCase()) {
      case "first":
        return selectFirst(options);
      case "last":
        return selectLast(options);
    }
  }
  if (typeof selector === "function") {
    return selectChannel(null, selector, options);
  }
  let key, value;
  for (key in selector) {
    if (value !== void 0) throw new Error("ambiguous selector; multiple inputs");
    value = maybeSelector(selector[key]);
  }
  if (value === void 0) throw new Error(`invalid selector: ${selector}`);
  return selectChannel(key, value, options);
}
function maybeSelector(selector) {
  if (typeof selector === "function") return selector;
  switch (`${selector}`.toLowerCase()) {
    case "min":
      return selectorMin;
    case "max":
      return selectorMax;
  }
  throw new Error(`unknown selector: ${selector}`);
}
function selectFirst(options) {
  return selectChannel(null, selectorFirst, options);
}
function selectLast(options) {
  return selectChannel(null, selectorLast, options);
}
function selectMinX(options) {
  return selectChannel("x", selectorMin, options);
}
function selectMinY(options) {
  return selectChannel("y", selectorMin, options);
}
function selectMaxX(options) {
  return selectChannel("x", selectorMax, options);
}
function selectMaxY(options) {
  return selectChannel("y", selectorMax, options);
}
function* selectorFirst(I) {
  yield I[0];
}
function* selectorLast(I) {
  yield I[I.length - 1];
}
function* selectorMin(I, X3) {
  yield least2(I, (i) => X3[i]);
}
function* selectorMax(I, X3) {
  yield greatest2(I, (i) => X3[i]);
}
function selectChannel(v2, selector, options) {
  if (v2 != null) {
    if (options[v2] == null) throw new Error(`missing channel: ${v2}`);
    v2 = options[v2];
  }
  const z = maybeZ(options);
  return basic(options, (data, facets) => {
    const Z = valueof(data, z);
    const V = valueof(data, v2);
    const selectFacets = [];
    for (const facet of facets) {
      const selectFacet = [];
      for (const I of Z ? group(facet, (i) => Z[i]).values() : [facet]) {
        for (const i of selector(I, V)) {
          selectFacet.push(i);
        }
      }
      selectFacets.push(selectFacet);
    }
    return { data, facets: selectFacets };
  });
}

// ../../../node_modules/@observablehq/plot/src/index.js
Mark.prototype.plot = function({ marks: marks2 = [], ...options } = {}) {
  return plot({ ...options, marks: [...marks2, this] });
};

// ../plot/src/plot-attributes.js
var attributeMap = /* @__PURE__ */ new Map([
  ["style", "style"],
  ["width", "width"],
  ["height", "height"],
  ["margin", "margin"],
  ["marginLeft", "marginLeft"],
  ["marginRight", "marginRight"],
  ["marginTop", "marginTop"],
  ["marginBottom", "marginBottom"],
  ["align", "align"],
  ["aspectRatio", "aspectRatio"],
  ["axis", "axis"],
  ["inset", "inset"],
  ["grid", "grid"],
  ["label", "label"],
  ["padding", "padding"],
  ["xScale", "x.type"],
  ["xDomain", "x.domain"],
  ["xRange", "x.range"],
  ["xNice", "x.nice"],
  ["xInset", "x.inset"],
  ["xInsetLeft", "x.insetLeft"],
  ["xInsetRight", "x.insetRight"],
  ["xClamp", "x.clamp"],
  ["xRound", "x.round"],
  ["xAlign", "x.align"],
  ["xPadding", "x.padding"],
  ["xPaddingInner", "x.paddingInner"],
  ["xPaddingOuter", "x.paddingOuter"],
  ["xAxis", "x.axis"],
  ["xTicks", "x.ticks"],
  ["xTickSize", "x.tickSize"],
  ["xTickSpacing", "x.tickSpacing"],
  ["xTickPadding", "x.tickPadding"],
  ["xTickFormat", "x.tickFormat"],
  ["xTickRotate", "x.tickRotate"],
  ["xGrid", "x.grid"],
  ["xLine", "x.line"],
  ["xLabel", "x.label"],
  ["xLabelAnchor", "x.labelAnchor"],
  ["xLabelArrow", "x.labelArrow"],
  ["xLabelOffset", "x.labelOffset"],
  ["xFontVariant", "x.fontVariant"],
  ["xAriaLabel", "x.ariaLabel"],
  ["xAriaDescription", "x.ariaDescription"],
  ["xPercent", "x.percent"],
  ["xReverse", "x.reverse"],
  ["xZero", "x.zero"],
  ["xBase", "x.base"],
  ["xExponent", "x.exponent"],
  ["xConstant", "x.constant"],
  ["yScale", "y.type"],
  ["yDomain", "y.domain"],
  ["yRange", "y.range"],
  ["yNice", "y.nice"],
  ["yInset", "y.inset"],
  ["yInsetTop", "y.insetTop"],
  ["yInsetBottom", "y.insetBottom"],
  ["yClamp", "y.clamp"],
  ["yRound", "y.round"],
  ["yAlign", "y.align"],
  ["yPadding", "y.padding"],
  ["yPaddingInner", "y.paddingInner"],
  ["yPaddingOuter", "y.paddingOuter"],
  ["yAxis", "y.axis"],
  ["yTicks", "y.ticks"],
  ["yTickSize", "y.tickSize"],
  ["yTickSpacing", "y.tickSpacing"],
  ["yTickPadding", "y.tickPadding"],
  ["yTickFormat", "y.tickFormat"],
  ["yTickRotate", "y.tickRotate"],
  ["yGrid", "y.grid"],
  ["yLine", "y.line"],
  ["yLabel", "y.label"],
  ["yLabelAnchor", "y.labelAnchor"],
  ["yLabelArrow", "y.labelArrow"],
  ["yLabelOffset", "y.labelOffset"],
  ["yFontVariant", "y.fontVariant"],
  ["yAriaLabel", "y.ariaLabel"],
  ["yAriaDescription", "y.ariaDescription"],
  ["yPercent", "y.percent"],
  ["yReverse", "y.reverse"],
  ["yZero", "y.zero"],
  ["yBase", "y.base"],
  ["yExponent", "y.exponent"],
  ["yConstant", "y.constant"],
  ["facetMargin", "facet.margin"],
  ["facetMarginTop", "facet.marginTop"],
  ["facetMarginBottom", "facet.marginBottom"],
  ["facetMarginLeft", "facet.marginLeft"],
  ["facetMarginRight", "facet.marginRight"],
  ["facetGrid", "facet.grid"],
  ["facetLabel", "facet.label"],
  ["fxDomain", "fx.domain"],
  ["fxRange", "fx.range"],
  ["fxInset", "fx.inset"],
  ["fxInsetLeft", "fx.insetLeft"],
  ["fxInsetRight", "fx.insetRight"],
  ["fxRound", "fx.round"],
  ["fxAlign", "fx.align"],
  ["fxPadding", "fx.padding"],
  ["fxPaddingInner", "fx.paddingInner"],
  ["fxPaddingOuter", "fx.paddingOuter"],
  ["fxAxis", "fx.axis"],
  ["fxTicks", "fx.ticks"],
  ["fxTickSize", "fx.tickSize"],
  ["fxTickSpacing", "fx.tickSpacing"],
  ["fxTickPadding", "fx.tickPadding"],
  ["fxTickFormat", "fx.tickFormat"],
  ["fxTickRotate", "fx.tickRotate"],
  ["fxGrid", "fx.grid"],
  ["fxLine", "fx.line"],
  ["fxLabel", "fx.label"],
  ["fxLabelAnchor", "fx.labelAnchor"],
  ["fxLabelOffset", "fx.labelOffset"],
  ["fxFontVariant", "fx.fontVariant"],
  ["fxAriaLabel", "fx.ariaLabel"],
  ["fxAriaDescription", "fx.ariaDescription"],
  ["fxReverse", "fx.reverse"],
  ["fyDomain", "fy.domain"],
  ["fyRange", "fy.range"],
  ["fyInset", "fy,inset"],
  ["fyInsetTop", "fy.insetTop"],
  ["fyInsetBottom", "fy.insetBottom"],
  ["fyRound", "fy.round"],
  ["fyAlign", "fy.align"],
  ["fyPadding", "fy.padding"],
  ["fyPaddingInner", "fy.paddingInner"],
  ["fyPaddingOuter", "fy.paddingOuter"],
  ["fyAxis", "fy.axis"],
  ["fyTicks", "fy.ticks"],
  ["fyTickSize", "fy.tickSize"],
  ["fyTickSpacing", "fy.tickSpacing"],
  ["fyTickPadding", "fy.tickPadding"],
  ["fyTickFormat", "fy.tickFormat"],
  ["fyTickRotate", "fy.tickRotate"],
  ["fyGrid", "fy.grid"],
  ["fyLine", "fy.line"],
  ["fyLabel", "fy.label"],
  ["fyLabelAnchor", "fy.labelAnchor"],
  ["fyLabelOffset", "fy.labelOffset"],
  ["fyFontVariant", "fy.fontVariant"],
  ["fyAriaLabel", "fy.ariaLabel"],
  ["fyAriaDescription", "fy.ariaDescription"],
  ["fyReverse", "fy.reverse"],
  ["colorScale", "color.type"],
  ["colorDomain", "color.domain"],
  ["colorRange", "color.range"],
  ["colorClamp", "color.clamp"],
  ["colorN", "color.n"],
  ["colorNice", "color.nice"],
  ["colorScheme", "color.scheme"],
  ["colorInterpolate", "color.interpolate"],
  ["colorPivot", "color.pivot"],
  ["colorSymmetric", "color.symmetric"],
  ["colorLabel", "color.label"],
  ["colorPercent", "color.percent"],
  ["colorReverse", "color.reverse"],
  ["colorZero", "color.zero"],
  ["colorTickFormat", "color.tickFormat"],
  ["colorBase", "color.base"],
  ["colorExponent", "color.exponent"],
  ["colorConstant", "color.constant"],
  ["opacityScale", "opacity.type"],
  ["opacityDomain", "opacity.domain"],
  ["opacityRange", "opacity.range"],
  ["opacityClamp", "opacity.clamp"],
  ["opacityNice", "opacity.nice"],
  ["opacityLabel", "opacity.label"],
  ["opacityPercent", "opacity.percent"],
  ["opacityReverse", "opacity.reverse"],
  ["opacityZero", "opacity.zero"],
  ["opacityTickFormat", "opacity.tickFormat"],
  ["opacityBase", "opacity.base"],
  ["opacityExponent", "opacity.exponent"],
  ["opacityConstant", "opacity.constant"],
  ["symbolScale", "symbol.type"],
  ["symbolDomain", "symbol.domain"],
  ["symbolRange", "symbol.range"],
  ["rScale", "r.type"],
  ["rDomain", "r.domain"],
  ["rRange", "r.range"],
  ["rClamp", "r.clamp"],
  ["rNice", "r.nice"],
  ["rLabel", "r.label"],
  ["rPercent", "r.percent"],
  ["rZero", "r.zero"],
  ["rBase", "r.base"],
  ["rExponent", "r.exponent"],
  ["rConstant", "r.constant"],
  ["lengthScale", "length.type"],
  ["lengthDomain", "length.domain"],
  ["lengthRange", "length.range"],
  ["lengthClamp", "length.clamp"],
  ["lengthNice", "length.nice"],
  ["lengthPercent", "length.percent"],
  ["lengthZero", "length.zero"],
  ["lengthBase", "length.base"],
  ["lengthExponent", "length.exponent"],
  ["lengthConstant", "length.constant"],
  ["projectionType", "projection.type"],
  ["projectionParallels", "projection.parallels"],
  ["projectionPrecision", "projection.precision"],
  ["projectionRotate", "projection.rotate"],
  ["projectionDomain", "projection.domain"],
  ["projectionInset", "projection.inset"],
  ["projectionInsetLeft", "projection.insetLeft"],
  ["projectionInsetRight", "projection.insetRight"],
  ["projectionInsetTop", "projection.insetTop"],
  ["projectionInsetBottom", "projection.insetBottom"],
  ["projectionClip", "projection.clip"]
]);
function setProperty(object, path2, value) {
  for (let i = 0; i < path2.length; ++i) {
    const key = path2[i];
    if (i === path2.length - 1) {
      object[key] = value;
    } else {
      object = object[key] || (object[key] = {});
    }
  }
}
function setAttributes(attributes2, spec, symbols3) {
  for (const key in attributes2) {
    const specKey = attributeMap.get(key);
    if (specKey == null) {
      throw new Error(`Unrecognized plot attribute: ${key}`);
    }
    const value = attributes2[key];
    if (typeof value === "symbol") {
      symbols3.push(key);
    } else if (value !== void 0) {
      setProperty(spec, specKey.split("."), value);
    }
  }
}

// ../plot/src/plot-renderer.js
var OPTIONS_ONLY_MARKS = /* @__PURE__ */ new Set([
  "frame",
  "hexgrid",
  "sphere",
  "graticule"
]);
var SELECT_TRANSFORMS = /* @__PURE__ */ new Map([
  ["first", selectFirst],
  ["last", selectLast],
  ["maxX", selectMaxX],
  ["maxY", selectMaxY],
  ["minX", selectMinX],
  ["minY", selectMinY],
  ["nearest", pointer],
  ["nearestX", pointerX],
  ["nearestXY", pointerY]
]);
async function plotRenderer(plot3) {
  const spec = { marks: [] };
  const symbols3 = [];
  const { attributes: attributes2, marks: marks2 } = plot3;
  setAttributes(attributes2, spec, symbols3);
  const indices2 = [];
  for (const mark2 of marks2) {
    for (const { type: type2, data, options } of mark2.plotSpecs()) {
      const { select: select2, ...rest } = options;
      const opt = SELECT_TRANSFORMS.get(select2)?.(rest) ?? rest;
      const arg = OPTIONS_ONLY_MARKS.has(type2) ? [opt] : [data, opt];
      spec.marks.push(src_exports[type2](...arg));
      indices2.push(mark2.index);
    }
  }
  inferLabels(spec, plot3);
  const svg = plot(spec);
  annotatePlot(svg, indices2);
  setSymbolAttributes(plot3, svg, attributes2, symbols3);
  for (const interactor2 of plot3.interactors) {
    await interactor2.init(svg);
  }
  return svg;
}
function setSymbolAttributes(plot3, svg, attributes2, symbols3) {
  symbols3.forEach((key) => {
    const value = attributes2[key];
    if (value === Fixed) {
      if (!key.endsWith("Domain")) {
        throw new Error(`Unsupported fixed attribute: ${key}`);
      }
      const type2 = key.slice(0, -"Domain".length);
      const scale3 = svg.scale(type2);
      if (scale3?.domain) {
        plot3.setAttribute(key, attributes2[`${type2}Reverse`] ? scale3.domain.slice().reverse() : scale3.domain);
      }
    } else {
      throw new Error(`Unrecognized symbol: ${value}`);
    }
  });
}
function inferLabels(spec, plot3) {
  const { marks: marks2 } = plot3;
  inferLabel("x", spec, marks2);
  inferLabel("y", spec, marks2);
  inferLabel("fx", spec, marks2);
  inferLabel("fy", spec, marks2);
}
function inferLabel(key, spec, marks2) {
  const scale3 = spec[key] || {};
  if (scale3.axis === null || scale3.label !== void 0) return;
  const fields = marks2.map((mark2) => mark2.channelField(key)?.field);
  if (fields.every((x3) => x3 == null)) return;
  let candidate;
  for (let i = 0; i < fields.length; ++i) {
    const label = fieldLabel(fields[i]);
    if (label === void 0) {
      continue;
    } else if (candidate === void 0) {
      candidate = label;
    } else if (candidate !== label) {
      candidate = void 0;
    }
  }
  if (candidate === void 0) return;
  spec[key] = { ...scale3, label: candidate };
}
function fieldLabel(field3) {
  if (!field3) return void 0;
  switch (field3.type) {
    case "COLUMN_REF":
      return field3.column;
    case "CAST":
      return fieldLabel(field3.expr);
    case "FUNCTION":
      if (field3.name === "make_date") return "date";
      break;
  }
  return exprLabel(field3);
}
function exprLabel(field3) {
  const s2 = `${field3}`.replaceAll('"', "").replaceAll("(*)", "()");
  return s2.endsWith("()") ? s2.slice(0, -2) : s2;
}
function annotatePlot(svg, indices2) {
  let index2 = -1;
  for (const child of svg.children) {
    const aria = child.getAttribute("aria-label") || "";
    const skip = child.nodeName === "style" || aria.includes("-axis") || aria.includes("-grid");
    if (!skip) {
      child.setAttribute("data-index", indices2[++index2]);
    }
  }
}

// ../plot/src/plot.js
var DEFAULT_ATTRIBUTES = {
  width: 640,
  marginLeft: 40,
  marginRight: 20,
  marginTop: 20,
  marginBottom: 30
};
var Plot = class {
  /**
   * @param {HTMLElement} [element]
   */
  constructor(element) {
    this.attributes = { ...DEFAULT_ATTRIBUTES };
    this.listeners = null;
    this.interactors = [];
    this.legends = [];
    this.marks = [];
    this.markset = null;
    this.params = /* @__PURE__ */ new Map();
    this.synch = new Synchronizer();
    this.element = element || document.createElement("div");
    this.element.setAttribute("class", "plot");
    this.element.style.display = "flex";
    Object.assign(this.element, { value: this });
  }
  margins() {
    return {
      left: this.getAttribute("marginLeft"),
      top: this.getAttribute("marginTop"),
      bottom: this.getAttribute("marginBottom"),
      right: this.getAttribute("marginRight")
    };
  }
  innerWidth() {
    const { left: left2, right: right2 } = this.margins();
    return this.getAttribute("width") - left2 - right2;
  }
  innerHeight(defaultValue = 400) {
    const { top: top2, bottom: bottom2 } = this.margins();
    let h = this.getAttribute("height");
    if (h == null) {
      h = maybeAspectRatio(this, top2, bottom2) || defaultValue;
      this.setAttribute("height", h, { silent: true });
    }
    return h - top2 - bottom2;
  }
  pending(mark2) {
    this.synch.pending(mark2);
  }
  update(mark2) {
    if (this.synch.ready(mark2) && !this.pendingRender) {
      this.pendingRender = true;
      requestAnimationFrame(() => this.render());
    }
    return this.synch.promise;
  }
  async render() {
    this.pendingRender = false;
    const svg = await plotRenderer(this);
    const legends = this.legends.flatMap(({ legend: legend3, include }) => {
      const el = legend3.init(svg);
      return include ? el : [];
    });
    this.element.replaceChildren(svg, ...legends);
    this.synch.resolve();
  }
  /**
   * @param {string} name The attribute to return.
   * @returns {*} The value of the attribute.
   */
  getAttribute(name2) {
    return this.attributes[name2];
  }
  /**
   * @param {string} name The name of the attribute to set.
   * @param {*} value The value to set.
   * @param {{silent: boolean}} [options] Options for setting the attribute.
   * @returns {boolean} whether the value changed.
   */
  setAttribute(name2, value, options) {
    if (distinct(this.attributes[name2], value)) {
      if (value === void 0) {
        delete this.attributes[name2];
      } else {
        this.attributes[name2] = value;
      }
      if (!options?.silent) {
        this.listeners?.get(name2)?.forEach((cb) => cb(name2, value));
      }
      return true;
    }
    return false;
  }
  /**
   * @param {string} name The attribute name.
   * @param {*} callback The function to call when the attribute changes.
   * @returns {this}
   */
  addAttributeListener(name2, callback) {
    const map5 = this.listeners || (this.listeners = /* @__PURE__ */ new Map());
    if (!map5.has(name2)) map5.set(name2, /* @__PURE__ */ new Set());
    map5.get(name2).add(callback);
    return this;
  }
  /**
   * @param {string} name The attribute name.
   * @param {*} callback The function to call when the attribute changes.
   * @returns {void}
   */
  removeAttributeListener(name2, callback) {
    return this.listeners?.get(name2)?.delete(callback);
  }
  addParams(mark2, paramSet) {
    const { params } = this;
    for (const param of paramSet) {
      if (params.has(param)) {
        params.get(param).push(mark2);
      } else {
        params.set(param, [mark2]);
        param.addEventListener("value", () => {
          return Promise.allSettled(
            params.get(param).map((mark3) => mark3.initialize())
          );
        });
      }
    }
  }
  addMark(mark2) {
    mark2.setPlot(this, this.marks.length);
    this.marks.push(mark2);
    this.markset = null;
    return this;
  }
  get markSet() {
    return this.markset || (this.markset = new Set(this.marks));
  }
  addInteractor(sel) {
    this.interactors.push(sel);
    return this;
  }
  addLegend(legend3, include = true) {
    legend3.setPlot(this);
    this.legends.push({ legend: legend3, include });
  }
};
function maybeAspectRatio(plot3, top2, bottom2) {
  const ar = plot3.getAttribute("aspectRatio");
  if (ar == null) return;
  const x3 = plot3.getAttribute("xDomain");
  const y3 = plot3.getAttribute("yDomain");
  if (!x3 || !y3) return;
  const dx = Math.abs(x3[1] - x3[0]);
  const dy = Math.abs(y3[1] - y3[0]);
  return dy * plot3.innerWidth() / (ar * dx) + top2 + bottom2;
}

// ../plot/src/marks/util/is-color.js
function isColor2(value) {
  if (typeof value !== "string") return false;
  value = value.toLowerCase().trim();
  return value === "none" || value === "currentcolor" || value.startsWith("url(") && value.endsWith(")") || // <funciri>, e.g. pattern or gradient
  value.startsWith("var(") && value.endsWith(")") || // CSS variable
  color(value) !== null;
}

// ../plot/src/marks/util/is-constant-option.js
var constantOptions = /* @__PURE__ */ new Set([
  "offset",
  "order",
  "reverse",
  "sort",
  "label",
  "anchor",
  "curve",
  "tension",
  "marker",
  "markerStart",
  "markerMid",
  "markerEnd",
  "textAnchor",
  "lineAnchor",
  "lineHeight",
  "textOverflow",
  "monospace",
  "fontFamily",
  "fontSize",
  "fontStyle",
  "fontVariant",
  "fontWeight",
  "frameAnchor",
  "strokeLinejoin",
  "strokeLinecap",
  "strokeMiterlimit",
  "strokeDasharray",
  "strokeDashoffset",
  "mixBlendMode",
  "shapeRendering",
  "imageRendering",
  "preserveAspectRatio",
  "interpolate",
  "crossOrigin",
  "paintOrder",
  "pointerEvents",
  "target",
  "select"
]);
function isConstantOption(value) {
  return constantOptions.has(value);
}

// ../plot/src/marks/util/is-symbol.js
var symbols2 = /* @__PURE__ */ new Set([
  "asterisk",
  "circle",
  "cross",
  "diamond",
  "diamond2",
  "hexagon",
  "plus",
  "square",
  "square2",
  "star",
  "times",
  "triangle",
  "triangle2",
  "wye"
]);
function isSymbol2(value) {
  return symbols2.has(`${value}`.toLowerCase());
}

// ../plot/src/marks/Mark.js
var isColorChannel = (channel) => channel === "stroke" || channel === "fill";
var isOpacityChannel = (channel) => /opacity$/i.test(channel);
var isSymbolChannel = (channel) => channel === "symbol";
var isFieldObject = (channel, field3) => {
  return channel !== "sort" && channel !== "tip" && field3 != null && !Array.isArray(field3);
};
var fieldEntry = (channel, field3) => ({
  channel,
  field: field3,
  as: isColumnRef(field3) && !isColumnParam(field3) ? field3.column : channel
});
var valueEntry = (channel, value) => ({ channel, value });
var isDataArray = (source) => Array.isArray(source);
var Mark2 = class extends MosaicClient {
  constructor(type2, source, encodings, reqs = {}) {
    super(source?.options?.filterBy);
    this.type = type2;
    this.reqs = reqs;
    this.source = source;
    const channels = this.channels = [];
    const detail = this.detail = /* @__PURE__ */ new Set();
    const params = this.params = /* @__PURE__ */ new Set();
    if (isDataArray(source)) {
      this.data = toDataColumns(source);
    } else if (isParam(source?.table)) {
      params.add(source.table);
    }
    const process = (channel, entry) => {
      const type3 = typeof entry;
      if (channel === "channels") {
        for (const name2 in entry) {
          detail.add(name2);
          process(name2, entry[name2]);
        }
      } else if (type3 === "function" && entry[Transform]) {
        const enc = entry(this, channel);
        for (const key in enc) {
          process(key, enc[key]);
        }
      } else if (type3 === "string") {
        if (isConstantOption(channel) || isColorChannel(channel) && isColor2(entry) || isSymbolChannel(channel) && isSymbol2(entry)) {
          channels.push(valueEntry(channel, entry));
        } else {
          channels.push(fieldEntry(channel, column(entry)));
        }
      } else if (isParamLike(entry)) {
        const c4 = valueEntry(channel, entry.value);
        channels.push(c4);
        entry.addEventListener("value", (value) => {
          c4.value = value;
          return this.update();
        });
      } else if (isNode(entry)) {
        collectParams(entry).forEach((p) => params.add(p));
        channels.push(fieldEntry(channel, entry));
      } else if (type3 === "object" && isFieldObject(channel, entry)) {
        channels.push(fieldEntry(channel, entry));
      } else if (entry !== void 0) {
        channels.push(valueEntry(channel, entry));
      }
    };
    for (const channel in encodings) {
      process(channel, encodings[channel]);
    }
  }
  /**
   * @param {import('../plot.js').Plot} plot The plot.
   * @param {number} index
   */
  setPlot(plot3, index2) {
    this.plot = plot3;
    this.index = index2;
    plot3.addParams(this, this.params);
    if (this.source?.table) this.queryPending();
  }
  sourceTable() {
    const table3 = this.source?.table;
    return table3 ? isParam(table3) ? table3.value : table3 : null;
  }
  hasOwnData() {
    return this.source == null || isDataArray(this.source);
  }
  hasFieldInfo() {
    return !!this._fieldInfo;
  }
  channel(channel) {
    return this.channels.find((c4) => c4.channel === channel);
  }
  channelField(channel, { exact = false } = {}) {
    const c4 = exact ? this.channel(channel) : this.channels.find((c5) => c5.channel.startsWith(channel));
    return c4?.field ? c4 : null;
  }
  async prepare() {
    if (this.hasOwnData()) return null;
    const { channels, reqs } = this;
    const fields = /* @__PURE__ */ new Map();
    for (const { channel, field: field3 } of channels) {
      if (!field3) continue;
      const stats = field3.stats?.stats || [];
      const key = field3.stats?.column ?? field3;
      const entry = fields.get(key) ?? fields.set(key, /* @__PURE__ */ new Set()).get(key);
      stats.forEach((s2) => entry.add(s2));
      reqs[channel]?.forEach((s2) => entry.add(s2));
    }
    const table3 = this.sourceTable();
    const info = await queryFieldInfo(
      this.coordinator,
      Array.from(fields, ([c4, s2]) => ({ table: table3, column: c4, stats: Array.from(s2) }))
    );
    const lookup = Object.fromEntries(info.map((x3) => [x3.column, x3]));
    for (const entry of this.channels) {
      const { field: field3 } = entry;
      if (field3) {
        Object.assign(entry, lookup[field3.stats?.column ?? field3]);
      }
    }
    this._fieldInfo = true;
  }
  /**
   * Return a query specifying the data needed by this Mark client.
   * @param {*} [filter] The filtering criteria to apply in the query.
   * @returns {*} The client query
   */
  query(filter3 = []) {
    if (this.hasOwnData()) return null;
    return markQuery(this.channels, this.sourceTable()).where(filter3);
  }
  queryPending() {
    this.plot.pending(this);
    return this;
  }
  /**
   * Provide query result data to the mark.
   */
  queryResult(data) {
    this.data = toDataColumns(data);
    return this;
  }
  update() {
    return this.plot.update(this);
  }
  /**
   * Generate an array of Plot mark specifications.
   * @returns {object[]}
   */
  plotSpecs() {
    const { type: type2, data, detail, channels } = this;
    return markPlotSpec(type2, detail, channels, data);
  }
};
function channelOption(c4, columns) {
  const value = columns?.[c4.as] ?? c4.as;
  return Object.hasOwn(c4, "value") ? c4.value : isColorChannel(c4.channel) ? { value, scale: "color" } : isOpacityChannel(c4.channel) ? { value, scale: "opacity" } : value;
}
function markQuery(channels, table3, skip = []) {
  const q = Query.from({ source: table3 });
  const dims = /* @__PURE__ */ new Set();
  let aggr = false;
  for (const c4 of channels) {
    const { channel, field: field3, as } = c4;
    if (skip.includes(channel)) continue;
    if (channel === "orderby") {
      q.orderby(c4.value ?? field3);
    } else if (field3) {
      if (isAggregateExpression(field3)) {
        aggr = true;
      } else {
        if (dims.has(as)) continue;
        dims.add(as);
      }
      q.select({ [as]: field3 });
    }
  }
  if (aggr) {
    q.groupby(Array.from(dims));
  }
  return q;
}
function markPlotSpec(type2, detail, channels, data, options = {}) {
  const { numRows: length4, values: values2, columns } = data ?? {};
  const side = {};
  for (const c4 of channels) {
    const obj = detail.has(c4.channel) ? side : options;
    obj[c4.channel] = channelOption(c4, columns);
  }
  if (detail.size) options.channels = side;
  const specData = values2 ?? (data ? { length: length4 } : null);
  const spec = [{ type: type2, data: specData, options }];
  return spec;
}

// ../plot/src/marks/util/channel-scale.js
function channelScale(mark2, channel) {
  const { plot: plot3 } = mark2;
  let scaleType = plot3.getAttribute(`${channel}Scale`);
  if (!scaleType) {
    const { type: type2 } = mark2.channelField(channel);
    scaleType = type2 === "date" ? "time" : "linear";
  }
  const options = { type: scaleType };
  switch (scaleType) {
    case "log":
      options.base = plot3.getAttribute(`${channel}Base`) ?? 10;
      break;
    case "pow":
      options.exponent = plot3.getAttribute(`${channel}Exponent`) ?? 1;
      break;
    case "symlog":
      options.constant = plot3.getAttribute(`${channel}Constant`) ?? 1;
      break;
  }
  return scaleTransform(options);
}

// ../plot/src/marks/util/bin-expr.js
function binExpr(mark2, channel, n, extent4, pad4 = 1, expr) {
  const { field: field3 } = mark2.channelField(channel);
  expr = expr ?? field3;
  const { type: type2, apply: apply2, sqlApply } = channelScale(mark2, channel);
  const reverse3 = !!mark2.plot.getAttribute(`${channel}Reverse`);
  const [lo, hi] = extent4.map((v3) => apply2(v3));
  const v2 = sqlApply(expr);
  const f = type2 === "time" || type2 === "utc" ? v2 : expr;
  return [bin1d(v2, lo, hi, n - pad4, reverse3), f];
}

// ../plot/src/marks/util/extent.js
var xext = { x: ["min", "max"] };
var yext = { y: ["min", "max"] };
var xyext = { ...xext, ...yext };
function plotExtent(mark2, filter3, channel, domainAttr, niceAttr) {
  const { plot: plot3 } = mark2;
  const domain = plot3.getAttribute(domainAttr);
  const nice3 = plot3.getAttribute(niceAttr);
  if (Array.isArray(domain) && !domain[Transient]) {
    return domain;
  } else {
    const { column: column3, min: min5, max: max4 } = mark2.channelField(channel);
    const dom = filteredExtent(filter3, column3) || (nice3 ? linear2().domain([min5, max4]).nice().domain() : [min5, max4]);
    if (domain !== Fixed) dom[Transient] = true;
    plot3.setAttribute(domainAttr, dom, { silent: true });
    return dom;
  }
}
function extentX(mark2, filter3) {
  return plotExtent(mark2, filter3, "x", "xDomain", "xNice");
}
function extentY(mark2, filter3) {
  return plotExtent(mark2, filter3, "y", "yDomain", "yNice");
}
function filteredExtent(filter3, column3) {
  if (!filter3) return;
  let lo;
  let hi;
  [filter3].flat().forEach((p) => walk(p, (node) => {
    if (node instanceof BetweenOpNode && `${node.expr}` === column3) {
      const extent4 = (node.extent ?? []).map((v2) => v2?.value ?? v2);
      if (lo == null || extent4[0] < lo) lo = extent4[0];
      if (hi == null || extent4[1] > hi) hi = extent4[1];
    }
  }));
  return lo != null && hi != null && lo !== hi ? [lo, hi] : void 0;
}

// ../plot/src/marks/ConnectedMark.js
var ConnectedMark = class extends Mark2 {
  constructor(type2, source, encodings) {
    const dim = type2.endsWith("X") ? "y" : type2.endsWith("Y") ? "x" : null;
    const req = dim ? { [dim]: ["count", "min", "max"] } : void 0;
    super(type2, source, encodings, req);
    this.dim = dim;
  }
  /**
   * Return a query specifying the data needed by this Mark client.
   * @param {*} [filter] The filtering criteria to apply in the query.
   * @returns {*} The client query
   */
  query(filter3 = []) {
    const { plot: plot3, dim, source } = this;
    let optimize = source.options?.optimize;
    const q = super.query(filter3);
    if (!dim) return q;
    const ortho = dim === "x" ? "y" : "x";
    const value = this.channelField(ortho, { exact: true })?.as;
    const { field: field3, as, type: type2, count: count4, min: min5, max: max4 } = this.channelField(dim);
    const isContinuous = type2 === "date" || type2 === "number";
    const size = dim === "x" ? plot3.innerWidth() : plot3.innerHeight();
    optimize ??= count4 / size > 10;
    if (optimize && isContinuous && value) {
      const [lo, hi] = filteredExtent(filter3, field3) || [min5, max4];
      const [expr] = binExpr(this, dim, size, [lo, hi], 1, as);
      const cols = q._select.map((c4) => c4.alias).filter((c4) => c4 !== as && c4 !== value);
      return m4(q, expr, as, value, cols);
    } else {
      return q.orderby(as);
    }
  }
};

// ../plot/src/marks/util/grid.js
function array3(size, proto = []) {
  return new proto.constructor(size);
}
function grid1d(size, index2, value, columns, groupby) {
  if (!index2?.length) return { numRows: 0, columns: {} };
  const numRows = index2.length;
  const result = {};
  const cells = [];
  if (groupby?.length) {
    const group3 = new Int32Array(numRows);
    const gvalues = groupby.map((name2) => columns[name2]);
    const cellMap = {};
    for (let row = 0; row < numRows; ++row) {
      const key = gvalues.map((group4) => group4[row]);
      group3[row] = cellMap[key] ??= cells.push(key) - 1;
    }
    for (let i = 0; i < groupby.length; ++i) {
      result[groupby[i]] = cells.map((cell3) => cell3[i]);
    }
    const G = result._grid = cells.map(() => array3(size, value));
    for (let row = 0; row < numRows; ++row) {
      G[group3[row]][index2[row]] = value[row];
    }
  } else {
    cells.push([]);
    const [G] = result._grid = [array3(size, value)];
    for (let row = 0; row < numRows; ++row) {
      G[index2[row]] = value[row];
    }
  }
  return { numRows: cells.length, columns: result };
}
function grid2d(w, h, index2, columns, aggregates, groupby, interpolate) {
  if (!index2?.length) return { numRows: 0, columns: {} };
  const numRows = index2.length;
  const size = w * h;
  const values2 = aggregates.map((name2) => columns[name2]);
  const result = {};
  const cells = [];
  const group3 = new Int32Array(numRows);
  if (groupby?.length) {
    const gvalues = groupby.map((name2) => columns[name2]);
    const cellMap = {};
    for (let row = 0; row < numRows; ++row) {
      const key = gvalues.map((group4) => group4[row]);
      group3[row] = cellMap[key] ??= cells.push(key) - 1;
    }
    for (let i = 0; i < groupby.length; ++i) {
      result[groupby[i]] = cells.map((cell3) => cell3[i]);
    }
  } else {
    cells.push([]);
  }
  if (interpolate) {
    const X3 = index2.map((k2) => k2 % w);
    const Y3 = index2.map((k2) => Math.floor(k2 / w));
    const I = cells.map(() => []);
    for (let row = 0; row < numRows; ++row) {
      I[group3[row]].push(row);
    }
    aggregates.forEach((name2, i) => {
      const V = values2[i];
      result[name2] = cells.map((_, j) => interpolate(I[j], w, h, X3, Y3, V));
    });
  } else {
    aggregates.forEach((name2, i) => {
      const V = values2[i];
      const G = result[name2] = cells.map(() => array3(size, V));
      for (let row = 0; row < numRows; ++row) {
        G[group3[row]][index2[row]] = V[row];
      }
    });
  }
  return { numRows: cells.length, columns: result };
}
function gridDomainContinuous(grids) {
  let lo = Infinity, hi = -Infinity;
  grids.forEach((G) => {
    const n = G.length;
    for (let i = 0; i < n; ++i) {
      const v2 = G[i];
      if (v2 < lo) lo = v2;
      if (v2 > hi) hi = v2;
    }
  });
  return Number.isFinite(lo) && Number.isFinite(hi) ? [lo, hi] : [0, 1];
}
function gridDomainDiscrete(grids) {
  const values2 = new InternSet();
  grids.forEach((G) => {
    const n = G.length;
    for (let i = 0; i < n; ++i) {
      values2.add(G[i]);
    }
  });
  return Array.from(values2).sort(ascending);
}

// ../plot/src/marks/util/handle-param.js
function handleParam(value, update) {
  return isParam(value) ? (value.addEventListener("value", update), value.value) : value;
}

// ../plot/src/marks/util/density.js
function dericheConfig(sigma, negative2 = false) {
  const a2 = new Float64Array(5);
  const bc4 = new Float64Array(4);
  dericheCausalCoeff(a2, bc4, sigma);
  const ba = Float64Array.of(
    0,
    bc4[1] - a2[1] * bc4[0],
    bc4[2] - a2[2] * bc4[0],
    bc4[3] - a2[3] * bc4[0],
    -a2[4] * bc4[0]
  );
  const accum_denom = 1 + a2[1] + a2[2] + a2[3] + a2[4];
  const sum_causal = (bc4[0] + bc4[1] + bc4[2] + bc4[3]) / accum_denom;
  const sum_anticausal = (ba[1] + ba[2] + ba[3] + ba[4]) / accum_denom;
  return {
    sigma,
    negative: negative2,
    a: a2,
    b_causal: bc4,
    b_anticausal: ba,
    sum_causal,
    sum_anticausal
  };
}
function dericheCausalCoeff(a_out, b_out, sigma) {
  const K2 = 4;
  const alpha = Float64Array.of(
    0.84,
    1.8675,
    0.84,
    -1.8675,
    -0.34015,
    -0.1299,
    -0.34015,
    0.1299
  );
  const x12 = Math.exp(-1.783 / sigma);
  const x22 = Math.exp(-1.723 / sigma);
  const y12 = 0.6318 / sigma;
  const y22 = 1.997 / sigma;
  const beta = Float64Array.of(
    -x12 * Math.cos(y12),
    x12 * Math.sin(y12),
    -x12 * Math.cos(-y12),
    x12 * Math.sin(-y12),
    -x22 * Math.cos(y22),
    x22 * Math.sin(y22),
    -x22 * Math.cos(-y22),
    x22 * Math.sin(-y22)
  );
  const denom = sigma * 2.5066282746310007;
  const b = Float64Array.of(alpha[0], alpha[1], 0, 0, 0, 0, 0, 0);
  const a2 = Float64Array.of(1, 0, beta[0], beta[1], 0, 0, 0, 0, 0, 0);
  let j, k2;
  for (k2 = 2; k2 < 8; k2 += 2) {
    b[k2] = beta[k2] * b[k2 - 2] - beta[k2 + 1] * b[k2 - 1];
    b[k2 + 1] = beta[k2] * b[k2 - 1] + beta[k2 + 1] * b[k2 - 2];
    for (j = k2 - 2; j > 0; j -= 2) {
      b[j] += beta[k2] * b[j - 2] - beta[k2 + 1] * b[j - 1];
      b[j + 1] += beta[k2] * b[j - 1] + beta[k2 + 1] * b[j - 2];
    }
    for (j = 0; j <= k2; j += 2) {
      b[j] += alpha[k2] * a2[j] - alpha[k2 + 1] * a2[j + 1];
      b[j + 1] += alpha[k2] * a2[j + 1] + alpha[k2 + 1] * a2[j];
    }
    a2[k2 + 2] = beta[k2] * a2[k2] - beta[k2 + 1] * a2[k2 + 1];
    a2[k2 + 3] = beta[k2] * a2[k2 + 1] + beta[k2 + 1] * a2[k2];
    for (j = k2; j > 0; j -= 2) {
      a2[j] += beta[k2] * a2[j - 2] - beta[k2 + 1] * a2[j - 1];
      a2[j + 1] += beta[k2] * a2[j - 1] + beta[k2 + 1] * a2[j - 2];
    }
  }
  for (k2 = 0; k2 < K2; ++k2) {
    j = k2 << 1;
    b_out[k2] = b[j] / denom;
    a_out[k2 + 1] = a2[j + 2];
  }
}
function dericheConv2d(cx, cy, grid2, [nx, ny]) {
  const yc = new Float64Array(Math.max(nx, ny));
  const ya = new Float64Array(Math.max(nx, ny));
  const h = new Float64Array(5);
  const d = new Float64Array(grid2.length);
  for (let row = 0, r0 = 0; row < ny; ++row, r0 += nx) {
    const dx = d.subarray(r0);
    dericheConv1d(cx, grid2.subarray(r0), nx, 1, yc, ya, h, dx);
  }
  for (let c0 = 0; c0 < nx; ++c0) {
    const dy = d.subarray(c0);
    dericheConv1d(cy, dy, ny, nx, yc, ya, h, dy);
  }
  return d;
}
function dericheConv1d(c4, src, N, stride = 1, y_causal = new Float64Array(N), y_anticausal = new Float64Array(N), h = new Float64Array(5), d = y_causal, init2 = dericheInitZeroPad) {
  const stride_2 = stride * 2;
  const stride_3 = stride * 3;
  const stride_4 = stride * 4;
  const stride_N = stride * N;
  let i, n;
  init2(
    y_causal,
    src,
    N,
    stride,
    c4.b_causal,
    3,
    c4.a,
    4,
    c4.sum_causal,
    h,
    c4.sigma
  );
  for (n = 4, i = stride_4; n < N; ++n, i += stride) {
    y_causal[n] = c4.b_causal[0] * src[i] + c4.b_causal[1] * src[i - stride] + c4.b_causal[2] * src[i - stride_2] + c4.b_causal[3] * src[i - stride_3] - c4.a[1] * y_causal[n - 1] - c4.a[2] * y_causal[n - 2] - c4.a[3] * y_causal[n - 3] - c4.a[4] * y_causal[n - 4];
  }
  init2(
    y_anticausal,
    src,
    N,
    -stride,
    c4.b_anticausal,
    4,
    c4.a,
    4,
    c4.sum_anticausal,
    h,
    c4.sigma
  );
  for (n = 4, i = stride_N - stride * 5; n < N; ++n, i -= stride) {
    y_anticausal[n] = c4.b_anticausal[1] * src[i + stride] + c4.b_anticausal[2] * src[i + stride_2] + c4.b_anticausal[3] * src[i + stride_3] + c4.b_anticausal[4] * src[i + stride_4] - c4.a[1] * y_anticausal[n - 1] - c4.a[2] * y_anticausal[n - 2] - c4.a[3] * y_anticausal[n - 3] - c4.a[4] * y_anticausal[n - 4];
  }
  if (c4.negative) {
    for (n = 0, i = 0; n < N; ++n, i += stride) {
      d[i] = y_causal[n] + y_anticausal[N - n - 1];
    }
  } else {
    for (n = 0, i = 0; n < N; ++n, i += stride) {
      d[i] = Math.max(0, y_causal[n] + y_anticausal[N - n - 1]);
    }
  }
  return d;
}
function dericheInitZeroPad(dest, src, N, stride, b, p, a2, q, sum4, h, sigma, tol = 0.5) {
  const stride_N = Math.abs(stride) * N;
  const off = stride < 0 ? stride_N + stride : 0;
  let i, n, m;
  for (n = 0; n <= q; ++n) {
    h[n] = n <= p ? b[n] : 0;
    for (m = 1; m <= q && m <= n; ++m) {
      h[n] -= a2[m] * h[n - m];
    }
  }
  for (m = 0; m < q; ++m) {
    for (dest[m] = 0, n = 1; n <= m; ++n) {
      i = off + stride * n;
      if (i >= 0 && i < stride_N) {
        dest[m] += h[m - n] * src[i];
      }
    }
  }
  const cur = src[off];
  const max_iter = Math.ceil(sigma * 10);
  for (n = 0; n < max_iter; ++n) {
    for (m = 0; m < q; ++m) {
      dest[m] += h[m] * cur;
    }
    sum4 -= Math.abs(h[0]);
    if (sum4 <= tol) break;
    h[q] = n + q <= p ? b[n + q] : 0;
    for (m = 1; m <= q; ++m) {
      h[q] -= a2[m] * h[q - m];
    }
    for (m = 0; m < q; ++m) {
      h[m] = h[m + 1];
    }
  }
  return;
}

// ../plot/src/marks/Grid2DMark.js
var DENSITY = "density";
var Grid2DMark = class extends Mark2 {
  constructor(type2, source, options) {
    const {
      bandwidth = 0,
      interpolate = "none",
      pixelSize = 1,
      pad: pad4 = 1,
      width: width2,
      height: height2,
      ...channels
    } = options;
    const densityMap = createDensityMap(channels);
    super(type2, source, channels, xyext);
    this.densityMap = densityMap;
    this.bandwidth = handleParam(bandwidth, (value) => {
      this.bandwidth = value;
      return this.grids ? this.convolve().update() : null;
    });
    this.interpolate = handleParam(interpolate, (value) => {
      return this.interpolate = value, this.requestUpdate();
    });
    this.pixelSize = handleParam(pixelSize, (value) => {
      return this.pixelSize = value, this.requestUpdate();
    });
    this.pad = handleParam(pad4, (value) => {
      return this.pad = value, this.requestUpdate();
    });
    this.width = handleParam(width2, (value) => {
      return this.width = value, this.requestUpdate();
    });
    this.height = handleParam(height2, (value) => {
      return this.height = value, this.requestUpdate();
    });
  }
  /**
   * @param {import('../plot.js').Plot} plot The plot.
   * @param {number} index
   */
  setPlot(plot3, index2) {
    const update = () => {
      if (this.hasFieldInfo()) this.requestUpdate();
    };
    plot3.addAttributeListener("xDomain", update);
    plot3.addAttributeListener("yDomain", update);
    super.setPlot(plot3, index2);
  }
  get filterStable() {
    const xdom = this.plot.getAttribute("xDomain");
    const ydom = this.plot.getAttribute("yDomain");
    return xdom && ydom && !xdom[Transient] && !ydom[Transient];
  }
  query(filter3 = []) {
    const { interpolate, pad: pad4, channels, densityMap } = this;
    const [x06, x12] = this.extentX = extentX(this, filter3);
    const [y06, y12] = this.extentY = extentY(this, filter3);
    const [nx, ny] = this.bins = this.binDimensions();
    const [x3, bx] = binExpr(this, "x", nx, [x06, x12], pad4);
    const [y3, by] = binExpr(this, "y", ny, [y06, y12], pad4);
    const bounds = pad4 ? [isBetween(bx, [+x06, +x12]), isBetween(by, [+y06, +y12])] : [lte(+x06, bx), lt(bx, +x12), lte(+y06, by), lt(by, +y12)];
    const q = Query.from(this.sourceTable()).where(filter3.concat(bounds));
    const groupby = this.groupby = [];
    const aggrMap = {};
    for (const c4 of channels) {
      if (Object.hasOwn(c4, "field")) {
        const { as, channel, field: field3 } = c4;
        if (isAggregateExpression(field3)) {
          aggrMap[channel] = field3;
          densityMap[channel] = true;
        } else if (channel === "weight") {
          aggrMap[DENSITY] = sum(field3);
        } else if (channel !== "x" && channel !== "y") {
          q.select({ [as]: field3 });
          groupby.push(as);
        }
      }
    }
    const aggr = this.aggr = Object.keys(aggrMap);
    if (aggrMap.density && aggr.length > 1) {
      throw new Error("Weight option can not be used with custom aggregates.");
    }
    if (!aggr.length) {
      aggr.push(DENSITY);
      aggrMap[DENSITY] = count();
    }
    if (interpolate === "linear") {
      if (aggr.length > 1) {
        throw new Error("Linear binning not applicable to multiple aggregates.");
      }
      if (!aggrMap[DENSITY]) {
        throw new Error("Linear binning not applicable to custom aggregates.");
      }
      const weight = collectColumns(aggrMap[DENSITY])[0];
      return binLinear2d(q, x3, y3, weight, nx, groupby);
    } else {
      return bin2d(q, x3, y3, aggrMap, nx, groupby);
    }
  }
  /**
   * @returns {[number, number]} The bin dimensions.
   */
  binDimensions() {
    const { plot: plot3, pixelSize, width: width2, height: height2 } = this;
    return [
      width2 ?? Math.round(plot3.innerWidth() / pixelSize),
      height2 ?? Math.round(plot3.innerHeight() / pixelSize)
    ];
  }
  queryResult(data) {
    const [w, h] = this.bins;
    const interp = maybeInterpolate2(this.interpolate);
    const { columns } = toDataColumns(data);
    this.grids0 = grid2d(w, h, columns.index, columns, this.aggr, this.groupby, interp);
    return this.convolve();
  }
  convolve() {
    const { aggr, bandwidth, bins, grids0, plot: plot3 } = this;
    this.grids = grids0;
    if (bandwidth > 0 && grids0.numRows > 0) {
      const prop = aggr.length === 1 ? aggr[0] : aggr.includes(DENSITY) ? DENSITY : null;
      if (!prop) {
        console.warn("No compatible grid found for smoothing.");
        return this;
      }
      const g = grids0.columns[prop];
      const w = plot3.innerWidth();
      const h = plot3.innerHeight();
      const [nx, ny] = bins;
      const neg = g.some((grid2) => grid2.some((v2) => v2 < 0));
      const configX = dericheConfig(bandwidth * (nx - 1) / w, neg);
      const configY = dericheConfig(bandwidth * (ny - 1) / h, neg);
      this.grids = {
        numRows: grids0.numRows,
        columns: {
          ...grids0.columns,
          // @ts-expect-error array types
          [prop]: g.map((grid2) => dericheConv2d(configX, configY, grid2, bins))
        }
      };
    }
    return this;
  }
};
function createDensityMap(channels) {
  const densityMap = {};
  for (const key in channels) {
    if (channels[key] === "density") {
      delete channels[key];
      densityMap[key] = true;
    }
  }
  return densityMap;
}
function maybeInterpolate2(interpolate = "none") {
  if (typeof interpolate === "function") return interpolate;
  switch (interpolate.toLowerCase()) {
    case "none":
    case "linear":
      return void 0;
    // no special interpolation need
    case "nearest":
      return interpolateNearest;
    case "barycentric":
      return interpolatorBarycentric();
    case "random-walk":
      return interpolatorRandomWalk();
  }
  throw new Error(`invalid interpolate: ${interpolate}`);
}

// ../plot/src/marks/ContourMark.js
var ContourMark = class extends Grid2DMark {
  constructor(source, options) {
    const { thresholds = 10, ...channels } = options;
    super("geo", source, {
      bandwidth: 20,
      interpolate: "linear",
      pixelSize: 2,
      ...channels
    });
    this.thresholds = handleParam(thresholds, (value) => {
      this.thresholds = value;
      return this.grids ? this.contours().update() : null;
    });
  }
  convolve() {
    return super.convolve().contours();
  }
  contours() {
    const { bins, densityMap, grids, thresholds, plot: plot3 } = this;
    const { numRows, columns } = grids;
    let t = thresholds;
    let tz;
    if (Array.isArray(t)) {
      tz = t;
    } else {
      const [, hi] = gridDomainContinuous(columns.density);
      tz = Array.from({ length: t - 1 }, (_, i) => hi * (i + 1) / t);
    }
    if (densityMap.fill || densityMap.stroke) {
      if (this.plot.getAttribute("colorScale") !== "log") {
        this.plot.setAttribute("colorZero", true);
      }
    }
    const [nx, ny] = bins;
    const [x06, x12] = plot3.getAttribute("xDomain");
    const [y06, y12] = plot3.getAttribute("yDomain");
    const sx = (x12 - x06) / nx;
    const sy = (y12 - y06) / ny;
    const xo = +x06;
    const yo = +y06;
    const x3 = (v2) => xo + v2 * sx;
    const y3 = (v2) => yo + v2 * sy;
    const contour3 = contours_default().size(bins);
    const data = this.contourData = Array(numRows * tz.length);
    const { density: density3, ...groupby } = columns;
    const groups2 = Object.entries(groupby);
    for (let i = 0, k2 = 0; i < numRows; ++i) {
      const grid2 = density3[i];
      const rest = groups2.reduce((o, [name2, col]) => (o[name2] = col[i], o), {});
      for (let j = 0; j < tz.length; ++j, ++k2) {
        data[k2] = Object.assign(
          transform2(contour3.contour(grid2, tz[j]), x3, y3),
          rest
        );
      }
    }
    return this;
  }
  plotSpecs() {
    const { type: type2, channels, densityMap, contourData: data } = this;
    const options = {};
    for (const c4 of channels) {
      const { channel } = c4;
      if (channel !== "x" && channel !== "y") {
        options[channel] = channelOption(c4);
      }
    }
    for (const channel in densityMap) {
      if (!densityMap[channel]) continue;
      options[channel] = channelOption({ channel, as: "value" });
    }
    return [{ type: type2, data, options }];
  }
};
function transform2(geometry, x3, y3) {
  function transformPolygon(coordinates) {
    coordinates.forEach(transformRing);
  }
  function transformRing(coordinates) {
    coordinates.forEach(transformPoint);
  }
  function transformPoint(coordinates) {
    coordinates[0] = x3(coordinates[0]);
    coordinates[1] = y3(coordinates[1]);
  }
  geometry.coordinates.forEach(transformPolygon);
  return geometry;
}

// ../plot/src/marks/util/permute.js
function indices(length4) {
  return Array.from({ length: length4 }, (_, i) => i);
}
function permute2(data, order) {
  const ord = order.reduce((acc, val, i) => (acc[val] = i, acc), {});
  const idx = indices(data.length);
  idx.sort((a2, b) => ord[data[a2]] - ord[data[b]]);
  return idx;
}

// ../plot/src/marks/util/raster.js
function createCanvas(w, h) {
  if (typeof document !== "undefined") {
    const c4 = document.createElement("canvas");
    c4.setAttribute("width", w);
    c4.setAttribute("height", h);
    return c4;
  }
  throw new Error("Can not create a canvas instance.");
}
function alphaConstant(v2 = 1) {
  const a2 = 255 * v2 | 0;
  return (data, w, h) => {
    for (let j = 0, k2 = 0; j < h; ++j) {
      for (let i = 0; i < w; ++i, k2 += 4) {
        data[k2 + 3] = a2;
      }
    }
  };
}
function alphaScheme(scale3) {
  const { apply: apply2 } = scale3;
  return (data, w, h, grid2) => {
    for (let j = 0, k2 = 0; j < h; ++j) {
      for (let i = 0, row = (h - j - 1) * w; i < w; ++i, k2 += 4) {
        data[k2 + 3] = 255 * apply2(grid2[i + row]) | 0;
      }
    }
  };
}
function colorConstant(v2 = {}) {
  const { r = 0, g = 0, b = 0, opacity: opacity2 = 1 } = typeof v2 === "string" ? rgb(v2) : v2;
  const c4 = new Uint8ClampedArray([r, g, b, 255 * opacity2 | 0]);
  return (data, w, h) => {
    for (let j = 0, k2 = 0; j < h; ++j) {
      for (let i = 0; i < w; ++i, k2 += 4) {
        data[k2 + 0] = c4[0];
        data[k2 + 1] = c4[1];
        data[k2 + 2] = c4[2];
        data[k2 + 3] = c4[3];
      }
    }
  };
}
function colorCategory(scale3) {
  const { domain, range: range3 } = scale3;
  const idx = /* @__PURE__ */ Object.create(null);
  const p = new Uint8ClampedArray(4 * domain.length);
  const n = domain.length - 1;
  const m = range3.length;
  for (let i = 0; i <= n; ++i) {
    const v2 = range3[i % m];
    const { r, g, b, opacity: opacity2 = 1 } = typeof v2 === "string" ? rgb(v2) : v2;
    const k2 = i << 2;
    p[k2 + 0] = r;
    p[k2 + 1] = g;
    p[k2 + 2] = b;
    p[k2 + 3] = 255 * opacity2 | 0;
    idx[domain[i]] = k2;
  }
  return (data, w, h, grid2) => {
    if (grid2.map) {
      for (let j = 0, k2 = 0; j < h; ++j) {
        for (let i = 0, row = (h - j - 1) * w; i < w; ++i, k2 += 4) {
          const c4 = idx[grid2[i + row]];
          data[k2 + 0] = p[c4 + 0];
          data[k2 + 1] = p[c4 + 1];
          data[k2 + 2] = p[c4 + 2];
          data[k2 + 3] = p[c4 + 3];
        }
      }
    } else {
      const c4 = idx[grid2];
      for (let j = 0, k2 = 0; j < h; ++j) {
        for (let i = 0; i < w; ++i, k2 += 4) {
          data[k2 + 0] = p[c4 + 0];
          data[k2 + 1] = p[c4 + 1];
          data[k2 + 2] = p[c4 + 2];
          data[k2 + 3] = p[c4 + 3];
        }
      }
    }
  };
}
function colorScheme(size, scale3, frac) {
  const { interpolate } = scale3;
  const p = new Uint8ClampedArray(4 * size);
  const n = size - 1;
  for (let i = 0; i <= n; ++i) {
    const v2 = interpolate(i / n);
    const { r, g, b, opacity: opacity2 = 1 } = typeof v2 === "string" ? rgb(v2) : v2;
    const k2 = i << 2;
    p[k2 + 0] = r;
    p[k2 + 1] = g;
    p[k2 + 2] = b;
    p[k2 + 3] = 255 * opacity2 | 0;
  }
  return (data, w, h, grid2) => {
    for (let j = 0, k2 = 0; j < h; ++j) {
      for (let i = 0, row = (h - j - 1) * w; i < w; ++i, k2 += 4) {
        const c4 = n * frac(grid2[i + row]) << 2;
        data[k2 + 0] = p[c4 + 0];
        data[k2 + 1] = p[c4 + 1];
        data[k2 + 2] = p[c4 + 2];
        data[k2 + 3] = p[c4 + 3];
      }
    }
  };
}

// ../plot/src/marks/RasterMark.js
var RasterMark = class extends Grid2DMark {
  constructor(source, options) {
    super("image", source, options);
    this.image = null;
  }
  setPlot(plot3, index2) {
    const update = () => {
      if (this.hasFieldInfo()) this.rasterize();
    };
    plot3.addAttributeListener("schemeColor", update);
    super.setPlot(plot3, index2);
  }
  convolve() {
    return super.convolve().rasterize();
  }
  rasterize() {
    const { bins, grids } = this;
    const [w, h] = bins;
    const { numRows, columns } = grids;
    const { canvas, ctx, img } = imageData(this, w, h);
    const { alpha, alphaProp, color: color3, colorProp } = rasterEncoding(this);
    const alphaData = columns[alphaProp] ?? [];
    const colorData = columns[colorProp] ?? [];
    const idx = numRows > 1 && colorProp && this.groupby?.includes(colorProp) ? permute2(colorData, this.plot.getAttribute("colorDomain")) : indices(numRows);
    this.data = {
      numRows,
      columns: {
        src: Array.from({ length: numRows }, (_, i) => {
          color3?.(img.data, w, h, colorData[idx[i]]);
          alpha?.(img.data, w, h, alphaData[idx[i]]);
          ctx.putImageData(img, 0, 0);
          return canvas.toDataURL();
        })
      }
    };
    return this;
  }
  plotSpecs() {
    const { type: type2, plot: plot3, data: { numRows: length4, columns } } = this;
    const options = {
      src: columns.src,
      width: plot3.innerWidth(),
      height: plot3.innerHeight(),
      preserveAspectRatio: "none",
      imageRendering: this.channel("imageRendering")?.value,
      frameAnchor: "middle"
    };
    return [{ type: type2, data: { length: length4 }, options }];
  }
};
var HeatmapMark = class extends RasterMark {
  constructor(source, options) {
    super(source, {
      bandwidth: 20,
      interpolate: "linear",
      pixelSize: 2,
      ...options
    });
  }
};
function rasterEncoding(mark2) {
  const { aggr, densityMap, groupby, plot: plot3 } = mark2;
  const hasDensity = aggr.includes(DENSITY);
  const hasFillOpacity = aggr.includes("fillOpacity");
  const fillEntry = mark2.channel("fill");
  const opacEntry = mark2.channel("fillOpacity");
  if (aggr.length > 2 || hasDensity && hasFillOpacity) {
    throw new Error("Invalid raster encodings. Try dropping an aggregate?");
  }
  if (groupby.includes(opacEntry?.as)) {
    throw new Error("Raster fillOpacity must be an aggregate or constant.");
  }
  const fill = densityMap.fill || aggr.includes("fill") ? "grid" : groupby.includes(fillEntry?.as) ? "group" : isColor2(fillEntry?.value) ? fillEntry.value : hasDensity && plot3.getAttribute("colorScheme") ? "grid" : void 0;
  const opac = densityMap.fillOpacity || aggr.includes("fillOpacity") ? "grid" : typeof opacEntry?.value === "number" ? opacEntry.value : hasDensity && fill !== "grid" ? "grid" : void 0;
  if (fill !== "grid" && opac !== "grid") {
    throw new Error("Raster mark missing density values.");
  }
  const colorProp = fillEntry?.as ?? (fill === "grid" ? DENSITY : null);
  const alphaProp = opacEntry?.as ?? (opac === "grid" ? DENSITY : null);
  const color3 = fill !== "grid" && fill !== "group" ? colorConstant(fill) : colorScale(mark2, colorProp);
  const alpha = opac !== "grid" ? alphaConstant(opac) : alphaScale(mark2, alphaProp);
  return { alphaProp, colorProp, alpha, color: color3 };
}
function alphaScale(mark2, prop) {
  const { plot: plot3, grids } = mark2;
  const domainAttr = plot3.getAttribute("opacityDomain");
  const domainFixed = domainAttr === Fixed;
  const domainTransient = domainAttr?.[Transient];
  const domain = !domainFixed && !domainTransient && domainAttr || gridDomainContinuous(grids.columns[prop]);
  if (domainFixed || domainTransient || !domainAttr) {
    if (!domainFixed) domain[Transient] = true;
    plot3.setAttribute("opacityDomain", domain);
  }
  const s2 = scale2({
    opacity: {
      type: plot3.getAttribute("opacityScale"),
      domain,
      range: plot3.getAttribute("opacityRange"),
      clamp: plot3.getAttribute("opacityClamp"),
      nice: plot3.getAttribute("opacityNice"),
      reverse: plot3.getAttribute("opacityReverse"),
      zero: plot3.getAttribute("opacityZero"),
      base: plot3.getAttribute("opacityBase"),
      exponent: plot3.getAttribute("opacityExponent"),
      constant: plot3.getAttribute("opacityConstant")
    }
  });
  return alphaScheme(s2);
}
function colorScale(mark2, prop) {
  const { plot: plot3, grids } = mark2;
  const data = grids.columns[prop] ?? [];
  const flat = !data[0]?.map;
  const discrete = flat || Array.isArray(data[0]);
  const domainAttr = plot3.getAttribute("colorDomain");
  const domainFixed = domainAttr === Fixed;
  const domainTransient = domainAttr?.[Transient];
  const domain = !domainFixed && !domainTransient && domainAttr || (flat ? data.slice().sort(ascending) : discrete ? gridDomainDiscrete(data) : gridDomainContinuous(data));
  if (domainFixed || domainTransient || !domainAttr) {
    if (!domainFixed) domain[Transient] = true;
    plot3.setAttribute("colorDomain", domain);
  }
  const s2 = scale2({
    color: {
      type: plot3.getAttribute("colorScale"),
      domain,
      range: plot3.getAttribute("colorRange"),
      clamp: plot3.getAttribute("colorClamp"),
      n: plot3.getAttribute("colorN"),
      nice: plot3.getAttribute("colorNice"),
      reverse: plot3.getAttribute("colorReverse"),
      scheme: plot3.getAttribute("colorScheme"),
      interpolate: plot3.getAttribute("colorInterpolate"),
      pivot: plot3.getAttribute("colorPivot"),
      symmetric: plot3.getAttribute("colorSymmetric"),
      zero: plot3.getAttribute("colorZero"),
      base: plot3.getAttribute("colorBase"),
      exponent: plot3.getAttribute("colorExponent"),
      constant: plot3.getAttribute("colorConstant")
    }
  });
  if (discrete) {
    return colorCategory(s2);
  } else {
    const frac = scale2({
      x: {
        type: inferScaleType2(s2.type),
        domain: s2.domain,
        reverse: s2.reverse,
        range: [0, 1],
        clamp: s2.clamp,
        base: s2.base,
        exponent: s2.exponent,
        constant: s2.constant
      }
    });
    return colorScheme(1024, s2, frac.apply);
  }
}
function inferScaleType2(type2) {
  if (type2.endsWith("symlog")) return "symlog";
  if (type2.endsWith("log")) return "log";
  if (type2.endsWith("pow")) return "pow";
  if (type2.endsWith("sqrt")) return "sqrt";
  if (type2 === "diverging") return "linear";
  return type2;
}
function imageData(mark2, w, h) {
  if (!mark2.image || mark2.image.w !== w || mark2.image.h !== h) {
    const canvas = createCanvas(w, h);
    const ctx = canvas.getContext("2d", { willReadFrequently: true });
    const img = ctx.getImageData(0, 0, w, h);
    mark2.image = { canvas, ctx, img, w, h };
  }
  return mark2.image;
}

// ../plot/src/marks/DenseLineMark.js
var DenseLineMark = class extends RasterMark {
  constructor(source, options) {
    const { normalize: normalize4 = true, ...rest } = options;
    super(source, rest);
    this.normalize = handleParam(normalize4, (value) => {
      return this.normalize = value, this.requestUpdate();
    });
  }
  query(filter3 = []) {
    const { channels, normalize: normalize4, pad: pad4 } = this;
    const [nx, ny] = this.bins = this.binDimensions();
    const [x3] = binExpr(this, "x", nx, extentX(this, filter3), pad4);
    const [y3] = binExpr(this, "y", ny, extentY(this, filter3), pad4);
    const q = Query.from(this.sourceTable()).where(stripXY(this, filter3));
    this.aggr = ["density"];
    const groupby = this.groupby = [];
    const z = [];
    for (const c4 of channels) {
      if (Object.hasOwn(c4, "field")) {
        const { channel, field: field3 } = c4;
        if (channel === "z") {
          q.select({ [channel]: field3 });
          z.push("z");
        } else if (channel !== "x" && channel !== "y") {
          q.select({ [channel]: field3 });
          groupby.push(channel);
        }
      }
    }
    return lineDensity(q, x3, y3, z, nx, ny, groupby, normalize4);
  }
};
function stripXY(mark2, filter3) {
  if (Array.isArray(filter3) && !filter3.length) return filter3;
  const xc = mark2.channelField("x").column;
  const yc = mark2.channelField("y").column;
  const test = (p) => {
    const col = `${p.expr}`;
    return p.type !== "BETWEEN" || col !== xc && col !== yc;
  };
  const filterAnd = (p) => p.op === "AND" ? and(p.clauses.filter((c4) => test(c4))) : p;
  return Array.isArray(filter3) ? filter3.filter((p) => test(p)).map((p) => filterAnd(p)) : filterAnd(filter3);
}

// ../plot/src/marks/Density1DMark.js
var GROUPBY = { fill: 1, stroke: 1, z: 1 };
var Density1DMark = class extends Mark2 {
  constructor(type2, source, options) {
    const {
      bins = 1024,
      bandwidth = 20,
      normalize: normalize4 = false,
      stack: stack2 = false,
      ...channels
    } = options;
    const dim = type2.endsWith("X") ? "y" : "x";
    super(type2, source, channels, dim === "x" ? xext : yext);
    this.dim = dim;
    this.bins = handleParam(bins, (value) => {
      return this.bins = value, this.requestUpdate();
    });
    this.bandwidth = handleParam(bandwidth, (value) => {
      this.bandwidth = value;
      return this.grids ? this.convolve().update() : null;
    });
    this.normalize = handleParam(normalize4, (value) => {
      return this.normalize = value, this.convolve().update();
    });
    this.stack = handleParam(stack2, (value) => {
      return this.stack = value, this.update();
    });
  }
  get filterStable() {
    const name2 = this.dim === "x" ? "xDomain" : "yDomain";
    const dom = this.plot.getAttribute(name2);
    return dom && !dom[Transient];
  }
  query(filter3 = []) {
    if (this.hasOwnData()) throw new Error("Density1DMark requires a data source");
    const { bins, channels, dim } = this;
    const extent4 = this.extent = (dim === "x" ? extentX : extentY)(this, filter3);
    const [x3, bx] = binExpr(this, dim, bins, extent4);
    const q = markQuery(channels, this.sourceTable(), [dim]).where(filter3.concat(isBetween(bx, extent4)));
    const v2 = this.channelField("weight") ? "weight" : null;
    const g = this.groupby = channels.flatMap((c4) => {
      return GROUPBY[c4.channel] && c4.field ? c4.as : [];
    });
    return binLinear1d(q, x3, v2, g);
  }
  queryResult(data) {
    const c4 = toDataColumns(data).columns;
    this.grids = grid1d(this.bins, c4.index, c4.density, c4, this.groupby);
    return this.convolve();
  }
  convolve() {
    const {
      bins,
      bandwidth,
      normalize: normalize4,
      dim,
      grids,
      groupby,
      plot: plot3,
      extent: [lo, hi]
    } = this;
    const cols = grids.columns;
    const numGrids = grids.numRows;
    const b = this.channelField(dim).as;
    const v2 = dim === "x" ? "y" : "x";
    const size = dim === "x" ? plot3.innerWidth() : plot3.innerHeight();
    const neg = cols._grid.some((grid2) => grid2.some((v3) => v3 < 0));
    const config = dericheConfig(bandwidth * (bins - 1) / size, neg);
    const b0 = +lo;
    const delta = (hi - b0) / (bins - 1);
    const numRows = bins * numGrids;
    const _b = new Float64Array(numRows);
    const _v = new Float64Array(numRows);
    const _g = groupby.reduce((m, name2) => (m[name2] = Array(numRows), m), {});
    for (let k2 = 0, g = 0; g < numGrids; ++g) {
      groupby.forEach((name2) => _g[name2].fill(cols[name2][g], k2, k2 + bins));
      const grid2 = cols._grid[g];
      const result = dericheConv1d(config, grid2, bins);
      const scale3 = 1 / norm(grid2, result, delta, normalize4);
      for (let i = 0; i < bins; ++i, ++k2) {
        _b[k2] = b0 + i * delta;
        _v[k2] = result[i] * scale3;
      }
    }
    this.data = { numRows, columns: { [b]: _b, [v2]: _v, ..._g } };
    return this;
  }
  plotSpecs() {
    const { type: type2, data: { numRows: length4, columns }, channels, dim, stack: stack2 } = this;
    const _ = type2.startsWith("area") && !stack2 ? "2" : "";
    const options = dim === "x" ? { [`y${_}`]: columns.y } : { [`x${_}`]: columns.x };
    for (const c4 of channels) {
      options[c4.channel] = channelOption(c4, columns);
    }
    return [{ type: type2, data: { length: length4 }, options }];
  }
};
function norm(grid2, smoothed, delta, type2) {
  const value = type2 === true || type2 === "sum" ? sum2(grid2) : type2 === "max" ? max2(smoothed) : delta;
  return value || 1;
}

// ../plot/src/marks/Density2DMark.js
var Density2DMark = class extends Grid2DMark {
  constructor(source, options) {
    const { type: type2 = "dot", ...channels } = options;
    super(type2, source, {
      bandwidth: 20,
      interpolate: "linear",
      pad: 0,
      pixelSize: 2,
      ...channels
    });
  }
  convolve() {
    super.convolve();
    const { bins, pad: pad4, extentX: extentX2, extentY: extentY2 } = this;
    const [nx, ny] = bins;
    const scaleX = channelScale(this, "x");
    const scaleY = channelScale(this, "y");
    const [x06, x12] = extentX2.map((v2) => scaleX.apply(v2));
    const [y06, y12] = extentY2.map((v2) => scaleY.apply(v2));
    const deltaX = (x12 - x06) / (nx - pad4);
    const deltaY = (y12 - y06) / (ny - pad4);
    const offset2 = pad4 ? 0 : 0.5;
    this.data = points(
      this.grids,
      bins,
      x06,
      y06,
      deltaX,
      deltaY,
      scaleX.invert,
      scaleY.invert,
      offset2
    );
    return this;
  }
  plotSpecs() {
    const { type: type2, channels, densityMap, data: { numRows: length4, columns } } = this;
    const options = {};
    for (const c4 of channels) {
      const { channel } = c4;
      options[channel] = channel === "x" || channel === "y" ? columns[channel] : channelOption(c4, columns);
    }
    for (const channel in densityMap) {
      if (densityMap[channel]) {
        options[channel] = columns.density;
      }
    }
    return [{ type: type2, data: { length: length4 }, options }];
  }
};
function points(data, bins, x06, y06, deltaX, deltaY, invertX, invertY, offset2) {
  const scale3 = 1 / (deltaX * deltaY);
  const [nx, ny] = bins;
  const batch = nx * ny;
  const numRows = batch * data.numRows;
  const x3 = new Float64Array(numRows);
  const y3 = new Float64Array(numRows);
  const density3 = new Float64Array(numRows);
  const columns = { x: x3, y: y3, density: density3 };
  const { density: grids, ...rest } = data.columns;
  for (const name2 in rest) {
    columns[name2] = new rest[name2].constructor(numRows);
  }
  let r = 0;
  for (let row = 0; row < data.numRows; ++row) {
    for (const name2 in rest) {
      columns[name2].fill(rest[name2][row], r, r + batch);
    }
    const grid2 = grids[row];
    for (let k2 = 0, j = 0; j < ny; ++j) {
      for (let i = 0; i < nx; ++i, ++r, ++k2) {
        x3[r] = invertX(x06 + (i + offset2) * deltaX);
        y3[r] = invertY(y06 + (j + offset2) * deltaY);
        density3[r] = grid2[k2] * scale3;
      }
    }
  }
  return { numRows, columns };
}

// ../plot/src/marks/util/stats.js
function ibetainv2(p, a2, b) {
  var EPS2 = 1e-8;
  var a1 = a2 - 1;
  var b1 = b - 1;
  var j = 0;
  var lna, lnb, pp, t, u4, err, x3, al, h, w, afac;
  if (p <= 0) return 0;
  if (p >= 1) return 1;
  if (a2 >= 1 && b >= 1) {
    pp = p < 0.5 ? p : 1 - p;
    t = Math.sqrt(-2 * Math.log(pp));
    x3 = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;
    if (p < 0.5) x3 = -x3;
    al = (x3 * x3 - 3) / 6;
    h = 2 / (1 / (2 * a2 - 1) + 1 / (2 * b - 1));
    w = x3 * Math.sqrt(al + h) / h - (1 / (2 * b - 1) - 1 / (2 * a2 - 1)) * (al + 5 / 6 - 2 / (3 * h));
    x3 = a2 / (a2 + b * Math.exp(2 * w));
  } else {
    lna = Math.log(a2 / (a2 + b));
    lnb = Math.log(b / (a2 + b));
    t = Math.exp(a2 * lna) / a2;
    u4 = Math.exp(b * lnb) / b;
    w = t + u4;
    if (p < t / w) x3 = Math.pow(a2 * w * p, 1 / a2);
    else x3 = 1 - Math.pow(b * w * (1 - p), 1 / b);
  }
  afac = -gammaln2(a2) - gammaln2(b) + gammaln2(a2 + b);
  for (; j < 10; j++) {
    if (x3 === 0 || x3 === 1) return x3;
    err = ibeta2(x3, a2, b) - p;
    t = Math.exp(a1 * Math.log(x3) + b1 * Math.log(1 - x3) + afac);
    u4 = err / t;
    x3 -= t = u4 / (1 - 0.5 * Math.min(1, u4 * (a1 / x3 - b1 / (1 - x3))));
    if (x3 <= 0) x3 = 0.5 * (x3 + t);
    if (x3 >= 1) x3 = 0.5 * (x3 + t + 1);
    if (Math.abs(t) < EPS2 * x3 && j > 0) break;
  }
  return x3;
}
function ibeta2(x3, a2, b) {
  var bt = x3 === 0 || x3 === 1 ? 0 : Math.exp(gammaln2(a2 + b) - gammaln2(a2) - gammaln2(b) + a2 * Math.log(x3) + b * Math.log(1 - x3));
  if (x3 < 0 || x3 > 1) return 0;
  if (x3 < (a2 + 1) / (a2 + b + 2))
    return bt * betacf2(x3, a2, b) / a2;
  return 1 - bt * betacf2(1 - x3, b, a2) / b;
}
function betacf2(x3, a2, b) {
  var fpmin = 1e-30;
  var m = 1;
  var qab = a2 + b;
  var qap = a2 + 1;
  var qam = a2 - 1;
  var c4 = 1;
  var d = 1 - qab * x3 / qap;
  var m2, aa2, del, h;
  if (Math.abs(d) < fpmin) d = fpmin;
  d = 1 / d;
  h = d;
  for (; m <= 100; m++) {
    m2 = 2 * m;
    aa2 = m * (b - m) * x3 / ((qam + m2) * (a2 + m2));
    d = 1 + aa2 * d;
    if (Math.abs(d) < fpmin) d = fpmin;
    c4 = 1 + aa2 / c4;
    if (Math.abs(c4) < fpmin) c4 = fpmin;
    d = 1 / d;
    h *= d * c4;
    aa2 = -(a2 + m) * (qab + m) * x3 / ((a2 + m2) * (qap + m2));
    d = 1 + aa2 * d;
    if (Math.abs(d) < fpmin) d = fpmin;
    c4 = 1 + aa2 / c4;
    if (Math.abs(c4) < fpmin) c4 = fpmin;
    d = 1 / d;
    del = d * c4;
    h *= del;
    if (Math.abs(del - 1) < 3e-7) break;
  }
  return h;
}
function gammaln2(x3) {
  var j = 0;
  var cof = [
    76.18009172947146,
    -86.5053203294167,
    24.01409824083091,
    -1.231739572450155,
    0.001208650973866179,
    -5395239384953e-18
  ];
  var ser = 1.000000000190015;
  var xx, y3, tmp;
  tmp = (y3 = xx = x3) + 5.5;
  tmp -= (xx + 0.5) * Math.log(tmp);
  for (; j < 6; j++) ser += cof[j] / ++y3;
  return Math.log(2.506628274631 * ser / xx) - tmp;
}
function qt2(p, dof) {
  var x3 = ibetainv2(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);
  x3 = Math.sqrt(dof * (1 - x3) / x3);
  return p > 0.5 ? x3 : -x3;
}
function erfinv(x3) {
  let w = -Math.log((1 - x3) * (1 + x3));
  let p;
  if (w < 6.25) {
    w -= 3.125;
    p = -364441206401782e-35;
    p = -16850591381820166e-35 + p * w;
    p = 128584807152564e-32 + p * w;
    p = 11157877678025181e-33 + p * w;
    p = -1333171662854621e-31 + p * w;
    p = 20972767875968562e-33 + p * w;
    p = 6637638134358324e-30 + p * w;
    p = -4054566272975207e-29 + p * w;
    p = -8151934197605472e-29 + p * w;
    p = 26335093153082323e-28 + p * w;
    p = -12975133253453532e-27 + p * w;
    p = -5415412054294628e-26 + p * w;
    p = 10512122733215323e-25 + p * w;
    p = -4112633980346984e-24 + p * w;
    p = -29070369957882005e-24 + p * w;
    p = 42347877827932404e-23 + p * w;
    p = -13654692000834679e-22 + p * w;
    p = -13882523362786469e-21 + p * w;
    p = 18673420803405714e-20 + p * w;
    p = -740702534166267e-18 + p * w;
    p = -0.006033670871430149 + p * w;
    p = 0.24015818242558962 + p * w;
    p = 1.6536545626831027 + p * w;
  } else if (w < 16) {
    w = Math.sqrt(w) - 3.25;
    p = 22137376921775787e-25;
    p = 9075656193888539e-23 + p * w;
    p = -27517406297064545e-23 + p * w;
    p = 18239629214389228e-24 + p * w;
    p = 15027403968909828e-22 + p * w;
    p = -4013867526981546e-21 + p * w;
    p = 29234449089955446e-22 + p * w;
    p = 12475304481671779e-21 + p * w;
    p = -47318229009055734e-21 + p * w;
    p = 6828485145957318e-20 + p * w;
    p = 24031110387097894e-21 + p * w;
    p = -3550375203628475e-19 + p * w;
    p = 9532893797373805e-19 + p * w;
    p = -0.0016882755560235047 + p * w;
    p = 0.002491442096107851 + p * w;
    p = -0.003751208507569241 + p * w;
    p = 0.005370914553590064 + p * w;
    p = 1.0052589676941592 + p * w;
    p = 3.0838856104922208 + p * w;
  } else if (Number.isFinite(w)) {
    w = Math.sqrt(w) - 5;
    p = -27109920616438573e-27;
    p = -2555641816996525e-25 + p * w;
    p = 15076572693500548e-25 + p * w;
    p = -3789465440126737e-24 + p * w;
    p = 761570120807834e-23 + p * w;
    p = -1496002662714924e-23 + p * w;
    p = 2914795345090108e-23 + p * w;
    p = -6771199775845234e-23 + p * w;
    p = 22900482228026655e-23 + p * w;
    p = -99298272942317e-20 + p * w;
    p = 4526062597223154e-21 + p * w;
    p = -1968177810553167e-20 + p * w;
    p = 7599527703001776e-20 + p * w;
    p = -21503011930044477e-20 + p * w;
    p = -13871931833623122e-20 + p * w;
    p = 1.0103004648645344 + p * w;
    p = 4.849906401408584 + p * w;
  } else {
    p = Infinity;
  }
  return p * x3;
}

// ../plot/src/marks/ErrorBarMark.js
var ErrorBarMark = class extends Mark2 {
  constructor(type2, source, options) {
    const dim = type2.endsWith("X") ? "y" : "x";
    const { ci = 0.95, ...channels } = options;
    super(type2, source, channels);
    this.dim = dim;
    this.field = this.channelField(dim).field;
    this.channels = this.channels.filter((c4) => c4.channel !== dim);
    this.ci = handleParam(ci, (value) => {
      return this.ci = value, this.update();
    });
  }
  query(filter3 = []) {
    const { channels, field: field3 } = this;
    const fields = channels.concat([
      { field: avg(field3), as: "__avg__" },
      { field: div(stddev(field3), sqrt(count(field3))), as: "__se__" }
    ]);
    return markQuery(fields, this.sourceTable()).where(filter3);
  }
  queryResult(data) {
    this.data = toDataColumns(data);
    return this;
  }
  plotSpecs() {
    const { type: type2, dim, detail, data, ci, channels } = this;
    const p = Math.SQRT2 * erfinv(ci);
    const { columns: { __avg__: u4, __se__: s2 } } = data;
    const options = {
      [`${dim}1`]: u4.map((u5, i) => u5 - p * s2[i]),
      [`${dim}2`]: u4.map((u5, i) => u5 + p * s2[i])
    };
    return markPlotSpec(type2, detail, channels, data, options);
  }
};

// ../plot/src/marks/GeoMark.js
var DEFAULT_GEOMETRY_COLUMN = "geom";
var GeoMark = class extends Mark2 {
  constructor(source, encodings = {}, reqs) {
    if (!isDataArray(source) && !encodings?.geometry) {
      encodings.geometry = geojson(DEFAULT_GEOMETRY_COLUMN);
    }
    super("geo", source, encodings, reqs);
  }
  queryResult(data) {
    super.queryResult(data);
    const geom = this.channelField("geometry")?.as;
    if (geom) {
      const { columns } = this.data;
      if (typeof columns[geom][0] === "string") {
        columns[geom] = columns[geom].map((s2) => JSON.parse(s2));
      }
    }
    return this;
  }
};

// ../plot/src/marks/HexbinMark.js
var HexbinMark = class extends Mark2 {
  constructor(source, options) {
    const { type: type2 = "hexagon", binWidth = 20, ...channels } = options;
    super(type2, source, { r: binWidth / 2, clip: true, ...channels }, xyext);
    this.binWidth = handleParam(binWidth, (value) => {
      return this.binWidth = value, this.requestUpdate();
    });
  }
  get filterStable() {
    const xdom = this.plot.getAttribute("xDomain");
    const ydom = this.plot.getAttribute("yDomain");
    return xdom && ydom && !xdom[Transient] && !ydom[Transient];
  }
  query(filter3 = []) {
    if (this.hasOwnData()) return null;
    const { plot: plot3, binWidth, channels } = this;
    let xc, yc;
    const dims = /* @__PURE__ */ new Set();
    const cols = {};
    for (const c4 of channels) {
      if (c4.channel === "orderby") {
      } else if (c4.channel === "x") {
        xc = c4;
      } else if (c4.channel === "y") {
        yc = c4;
      } else if (Object.hasOwn(c4, "field")) {
        const { as, field: field3 } = c4;
        cols[as] = field3;
        if (!isAggregateExpression(field3)) {
          dims.add(as);
        }
      }
    }
    const [x12, x22] = extentX(this, filter3);
    const [y12, y22] = extentY(this, filter3);
    const ox2 = 0.5 - plot3.getAttribute("marginLeft");
    const oy2 = 0 - plot3.getAttribute("marginTop");
    const dx = float642(binWidth);
    const dy = float642(binWidth * (1.5 / Math.sqrt(3)));
    const xr = float642(plot3.innerWidth() / (x22 - x12));
    const yr = float642(plot3.innerHeight() / (y22 - y12));
    const x3 = "_x";
    const y3 = "_y";
    const px = "_px";
    const py = "_py";
    const pi5 = "_pi";
    const pj = "_pj";
    const tt = "_tt";
    return Query.select({
      [xc.as]: add(
        float642(x12),
        div(add(mul(add(x3, mul(0.5, bitAnd(y3, 1))), dx), ox2), xr)
      ),
      [yc.as]: sub(
        float642(y22),
        div(add(mul(y3, dy), oy2), yr)
      ),
      ...cols
    }).groupby(x3, y3, ...dims).from(
      // Subquery performs hex binning in screen space and also passes
      // original columns through (the DB should optimize this).
      Query.select({
        [py]: div(sub(mul(yr, sub(y22, yc.field)), oy2), dy),
        [pj]: int322(round(py)),
        [px]: sub(
          div(sub(mul(xr, sub(xc.field, x12)), ox2), dx),
          mul(0.5, bitAnd(pj, 1))
        ),
        [pi5]: int322(round(px)),
        [tt]: and(
          gt(mul(abs(sub(py, pj)), 3), 1),
          gt(
            add(pow(sub(px, pi5), 2), pow(sub(py, pj), 2)),
            add(
              pow(sub(sub(px, pi5), mul(0.5, cond(lt(px, pi5), -1, 1))), 2),
              pow(sub(sub(py, pj), cond(lt(py, pj), -1, 1)), 2)
            )
          )
        ),
        [x3]: cond(
          tt,
          int322(add(
            add(pi5, cond(lt(px, pi5), -0.5, 0.5)),
            cond(neq(bitAnd(pj, 1), 0), 0.5, -0.5)
          )),
          pi5
        ),
        [y3]: cond(tt, int322(add(pj, cond(lt(py, pj), -1, 1))), pj)
      }, "*").from(this.sourceTable()).where(isNotNull(xc.field), isNotNull(yc.field), filter3)
    );
  }
};

// ../plot/src/marks/RasterTileMark.js
var RasterTileMark = class extends Grid2DMark {
  constructor(source, options) {
    const { origin = [0, 0], dim = "xy", ...markOptions2 } = options;
    super("image", source, markOptions2);
    this.image = null;
    this.origin = origin;
    this.tileX = dim.toLowerCase().includes("x");
    this.tileY = dim.toLowerCase().includes("y");
  }
  setPlot(plot3, index2) {
    const update = () => {
      if (this.hasFieldInfo()) this.rasterize();
    };
    plot3.addAttributeListener("schemeColor", update);
    super.setPlot(plot3, index2);
  }
  requestQuery() {
    return this.requestTiles();
  }
  query(filter3 = []) {
    this._filter = filter3;
    return null;
  }
  tileQuery(extent4) {
    const { interpolate, pad: pad4, channels, densityMap } = this;
    const [[x06, x12], [y06, y12]] = extent4;
    const [nx, ny] = this.bins;
    const [x3, bx] = binExpr(this, "x", nx, [x06, x12], pad4);
    const [y3, by] = binExpr(this, "y", ny, [y06, y12], pad4);
    const bounds = pad4 ? [isBetween(bx, [+x06, +x12]), isBetween(by, [+y06, +y12])] : [lte(+x06, bx), lt(bx, +x12), lte(+y06, by), lt(by, +y12)];
    const q = Query.from(this.sourceTable()).where(bounds);
    const groupby = this.groupby = [];
    const aggrMap = {};
    for (const c4 of channels) {
      if (Object.hasOwn(c4, "field")) {
        const { as, channel, field: field3 } = c4;
        if (field3.aggregate) {
          aggrMap[channel] = field3;
          densityMap[channel] = true;
        } else if (channel === "weight") {
          aggrMap.density = sum(field3);
        } else if (channel !== "x" && channel !== "y") {
          q.select({ [as]: field3 });
          groupby.push(as);
        }
      }
    }
    const aggr = this.aggr = Object.keys(aggrMap);
    if (aggrMap.density && aggr.length > 1) {
      throw new Error("Weight option can not be used with custom aggregates.");
    }
    if (!aggr.length) {
      aggr.push("density");
      aggrMap.density = count();
    }
    if (interpolate === "linear") {
      if (aggr.length > 1) {
        throw new Error("Linear binning not applicable to multiple aggregates.");
      }
      if (!aggrMap.density) {
        throw new Error("Linear binning not applicable to custom aggregates.");
      }
      return binLinear2d2(q, x3, y3, aggrMap.density, nx, groupby);
    } else {
      return bin2d2(q, x3, y3, aggrMap, nx, groupby);
    }
  }
  async requestTiles() {
    const mc = coordinator();
    if (this.prefetch) mc.cancel(this.prefetch);
    const { pad: pad4, tileX, tileY, origin: [tx, ty] } = this;
    const [m, n] = this.bins = this.binDimensions();
    const [x06, x12] = extentX(this, this._filter);
    const [y06, y12] = extentY(this, this._filter);
    const xspan = x12 - x06;
    const yspan = y12 - y06;
    const xx = Math.floor((x06 - tx) * (m - pad4) / xspan);
    const yy = Math.floor((y06 - ty) * (n - pad4) / yspan);
    const tileExtent = (i, j) => [
      [tx + i * xspan, tx + (i + 1) * xspan],
      [ty + j * yspan, ty + (j + 1) * yspan]
    ];
    const i0 = Math.floor((x06 - tx) / xspan);
    const i1 = tileX ? tileFloor((x12 - tx) / xspan) : i0;
    const j0 = Math.floor((y06 - ty) / yspan);
    const j1 = tileY ? tileFloor((y12 - ty) / yspan) : j0;
    const coords = [];
    for (let i = i0; i <= i1; ++i) {
      for (let j = j0; j <= j1; ++j) {
        coords.push([i, j]);
      }
    }
    const queries = coords.map(
      ([i, j]) => mc.query(this.tileQuery(tileExtent(i, j)))
    );
    const prefetchCoords = [];
    if (tileX) {
      for (let j = j0; j <= j1; ++j) {
        prefetchCoords.push([i1 + 1, j]);
        prefetchCoords.push([i0 - 1, j]);
      }
    }
    if (tileY) {
      const x07 = tileX ? i0 - 1 : i0;
      const x13 = tileX ? i1 + 1 : i1;
      for (let i = x07; i <= x13; ++i) {
        prefetchCoords.push([i, j1 + 1]);
        prefetchCoords.push([i, j0 - 1]);
      }
    }
    this.prefetch = prefetchCoords.map(
      ([i, j]) => mc.prefetch(this.tileQuery(tileExtent(i, j)))
    );
    const tiles = await Promise.all(queries);
    const density3 = processTiles(m, n, xx, yy, coords, tiles);
    this.grids0 = {
      numRows: density3.length,
      columns: { density: [density3] }
    };
    this.convolve().update();
  }
  convolve() {
    return super.convolve().rasterize();
  }
  rasterize() {
    const { bins, grids } = this;
    const [w, h] = bins;
    const { numRows, columns } = grids;
    const { canvas, ctx, img } = imageData2(this, w, h);
    const { alpha, alphaProp, color: color3, colorProp } = rasterEncoding(this);
    const alphaData = columns[alphaProp] ?? [];
    const colorData = columns[colorProp] ?? [];
    const idx = numRows > 1 && colorProp && this.groupby?.includes(colorProp) ? permute2(colorData, this.plot.getAttribute("colorDomain")) : indices(numRows);
    this.data = {
      numRows,
      columns: {
        src: Array.from({ length: numRows }, (_, i) => {
          color3?.(img.data, w, h, colorData[idx[i]]);
          alpha?.(img.data, w, h, alphaData[idx[i]]);
          ctx.putImageData(img, 0, 0);
          return canvas.toDataURL();
        })
      }
    };
    return this;
  }
  plotSpecs() {
    const { type: type2, plot: plot3, data: { numRows: length4, columns } } = this;
    const options = {
      src: columns.src,
      width: plot3.innerWidth(),
      height: plot3.innerHeight(),
      preserveAspectRatio: "none",
      imageRendering: this.channel("imageRendering")?.value,
      frameAnchor: "middle"
    };
    return [{ type: type2, data: { length: length4 }, options }];
  }
};
function processTiles(m, n, x3, y3, coords, tiles) {
  const grid2 = new Float64Array(m * n);
  tiles.forEach((data, index2) => {
    const [i, j] = coords[index2];
    const tx = i * m - x3;
    const ty = j * n - y3;
    copy3(m, n, grid2, data, tx, ty);
  });
  return grid2;
}
function copy3(m, n, grid2, values2, tx, ty) {
  const num = values2.numRows;
  if (num === 0) return;
  const index2 = values2.getChild("index").toArray();
  const value = values2.getChild("density").toArray();
  for (let row = 0; row < num; ++row) {
    const idx = index2[row];
    const i = tx + idx % m;
    const j = ty + Math.floor(idx / m);
    if (0 <= i && i < m && 0 <= j && j < n) {
      grid2[i + j * m] = value[row];
    }
  }
}
function imageData2(mark2, w, h) {
  if (!mark2.image || mark2.image.w !== w || mark2.image.h !== h) {
    const canvas = createCanvas(w, h);
    const ctx = canvas.getContext("2d", { willReadFrequently: true });
    const img = ctx.getImageData(0, 0, w, h);
    mark2.image = { canvas, ctx, img, w, h };
  }
  return mark2.image;
}
function bin2d2(q, xp, yp, aggs, xn, groupby) {
  return q.select({
    index: sql`FLOOR(${xp})::INTEGER + FLOOR(${yp})::INTEGER * ${xn}`,
    ...aggs
  }).groupby("index", groupby);
}
function binLinear2d2(q, xp, yp, value, xn, groupby) {
  const w = value.column ? `* ${value.column}` : "";
  const subq = (i, w2) => q.clone().select({ xp, yp, i, w: w2 });
  const a2 = subq(
    sql`FLOOR(xp)::INTEGER + FLOOR(yp)::INTEGER * ${xn}`,
    sql`(FLOOR(xp)::INTEGER + 1 - xp) * (FLOOR(yp)::INTEGER + 1 - yp)${w}`
  );
  const b = subq(
    sql`FLOOR(xp)::INTEGER + (FLOOR(yp)::INTEGER + 1) * ${xn}`,
    sql`(FLOOR(xp)::INTEGER + 1 - xp) * (yp - FLOOR(yp)::INTEGER)${w}`
  );
  const c4 = subq(
    sql`FLOOR(xp)::INTEGER + 1 + FLOOR(yp)::INTEGER * ${xn}`,
    sql`(xp - FLOOR(xp)::INTEGER) * (FLOOR(yp)::INTEGER + 1 - yp)${w}`
  );
  const d = subq(
    sql`FLOOR(xp)::INTEGER + 1 + (FLOOR(yp)::INTEGER + 1) * ${xn}`,
    sql`(xp - FLOOR(xp)::INTEGER) * (yp - FLOOR(yp)::INTEGER)${w}`
  );
  return Query.from(Query.unionAll(a2, b, c4, d)).select({ index: "i", density: sum("w") }, groupby).groupby("index", groupby).having(neq("density", 0));
}
function tileFloor(value) {
  const floored = Math.floor(value);
  return floored === value ? floored - 1 : floored;
}

// ../plot/src/marks/RegressionMark.js
var RegressionMark = class extends Mark2 {
  constructor(source, options) {
    const { ci = 0.95, precision = 4, ...channels } = options;
    super("line", source, channels);
    const update = () => this.modelFit ? this.confidenceBand().update() : null;
    this.ci = handleParam(ci, (value) => {
      return this.ci = value, update();
    });
    this.precision = handleParam(precision, (value) => {
      return this.precision = value, update();
    });
  }
  query(filter3 = []) {
    const x3 = this.channelField("x").as;
    const y3 = this.channelField("y").as;
    const groupby = Array.from(new Set(
      ["stroke", "z", "fx", "fy"].flatMap((c4) => this.channelField(c4)?.as || [])
    ));
    return Query.from(super.query(filter3)).select({
      intercept: regrIntercept(y3, x3),
      slope: regrSlope(y3, x3),
      n: regrCount(y3, x3),
      ssy: regrSYY(y3, x3),
      ssx: regrSXX(y3, x3),
      xm: regrAvgX(y3, x3),
      x0: float642(min(x3).where(isNotNull(y3))),
      x1: float642(max(x3).where(isNotNull(y3)))
    }).select(groupby).groupby(groupby);
  }
  queryResult(data) {
    this.modelFit = toDataColumns(data);
    this.lineData = linePoints(this.modelFit);
    return this.confidenceBand();
  }
  confidenceBand() {
    const { ci, modelFit, precision, plot: plot3 } = this;
    const width2 = plot3.innerWidth();
    this.areaData = ci ? areaPoints(modelFit, ci, precision, width2) : null;
    return this;
  }
  plotSpecs() {
    const { lineData, areaData, channels, ci } = this;
    const lcols = lineData.columns;
    const acols = ci ? areaData.columns : {};
    const lopt = { x: lcols.x, y: lcols.y };
    const aopt = { x: acols.x, y1: acols.y1, y2: acols.y2, fillOpacity: 0.1 };
    for (const c4 of channels) {
      switch (c4.channel) {
        case "x":
        case "y":
        case "fill":
          break;
        case "tip":
          aopt.tip = channelOption(c4, acols);
          break;
        case "stroke":
          lopt.stroke = channelOption(c4, lcols);
          aopt.fill = channelOption(c4, acols);
          break;
        case "strokeOpacity":
          lopt.strokeOpacity = channelOption(c4, lcols);
          break;
        case "fillOpacity":
          aopt.fillOpacity = channelOption(c4, acols);
          break;
        default:
          lopt[c4.channel] = channelOption(c4, lcols);
          aopt[c4.channel] = channelOption(c4, acols);
          break;
      }
    }
    return [
      ...ci ? [{ type: "areaY", data: { length: areaData.numRows }, options: aopt }] : [],
      { type: "line", data: { length: lineData.numRows }, options: lopt }
    ];
  }
};
function concat(a2, b) {
  if (a2.concat) return a2.concat(b);
  const array4 = new a2.constructor(a2.length + b.length);
  array4.set(a2, 0);
  array4.set(b, a2.length);
  return array4;
}
function linePoints(fit2) {
  const { x0: x06 = [], x1: x12 = [], xm, intercept, slope, n, ssx, ssy, ...rest } = fit2.columns;
  const predict = (x4, i) => intercept[i] + x4 * slope[i];
  const x3 = concat(x06, x12);
  const y3 = concat(x06.map(predict), x12.map(predict));
  for (const name2 in rest) {
    rest[name2] = concat(rest[name2], rest[name2]);
  }
  return { numRows: x3.length, columns: { x: x3, y: y3, ...rest } };
}
function areaPoints(fit2, ci, precision, width2) {
  const len = fit2.numRows;
  const { x0: x06, x1: x12, xm, intercept, slope, n, ssx, ssy, ...rest } = fit2.columns;
  const other = Object.keys(rest);
  const columns = { x: [], y1: [], y2: [] };
  other.forEach((name2) => columns[name2] = []);
  for (let i = 0; i < len; ++i) {
    const pp = precision * (x12[i] - x06[i]) / width2;
    const t_sy = qt2((1 - ci) / 2, n[i] - 2) * Math.sqrt(ssy[i] / (n[i] - 2));
    range(x06[i], x12[i] - pp / 2, pp).concat(x12[i]).forEach((x3) => {
      const y3 = intercept[i] + x3 * slope[i];
      const ye = t_sy * Math.sqrt(1 / n[i] + (x3 - xm[i]) ** 2 / ssx[i]);
      columns.x.push(x3);
      columns.y1.push(y3 - ye);
      columns.y2.push(y3 + ye);
      other.forEach((name2) => columns[name2].push(rest[name2][i]));
    });
  }
  return { numRows: columns.x.length, columns };
}

// ../plot/src/interactors/util/get-datum.js
function getDatum(el) {
  if (el.tagName === "a") {
    el = el.children[0];
  }
  const data = el.__data__;
  return Array.isArray(data) ? data[0] : data;
}

// ../plot/src/interactors/util/to-kebab-case.js
function toKebabCase(cc2) {
  const lc = cc2.toLowerCase();
  const n = cc2.length;
  let kc = "";
  for (let i = 0; i < n; ++i) {
    kc += (cc2[i] !== lc[i] ? "-" : "") + lc[i];
  }
  return kc;
}

// ../plot/src/interactors/util/sanitize-styles.js
function sanitizeStyles(styles2) {
  const s2 = {};
  for (const name2 in styles2) {
    s2[toKebabCase(name2)] = styles2[name2];
  }
  return s2;
}

// ../plot/src/interactors/Highlight.js
function configureMark(mark2) {
  const { channels } = mark2;
  const dims = /* @__PURE__ */ new Set();
  let ordered = false;
  let aggregate = false;
  for (const c4 of channels) {
    const { channel, field: field3, as } = c4;
    if (channel === "orderby") {
      ordered = true;
    } else if (field3) {
      if (isAggregateExpression(field3)) {
        aggregate = true;
      } else {
        if (dims.has(as)) continue;
        dims.add(as);
      }
    }
  }
  if (!ordered && aggregate && dims.size) {
    mark2.channels.push({ channel: "orderby", value: Array.from(dims) });
  }
  return mark2;
}
var Highlight = class {
  constructor(mark2, {
    selection: selection2,
    channels = {}
  }) {
    this.mark = configureMark(mark2);
    this.selection = selection2;
    const c4 = Object.entries(sanitizeStyles(channels));
    this.channels = c4.length ? c4 : [["opacity", 0.2]];
    this.selection.addEventListener("value", throttle(() => this.update()));
  }
  init(svg) {
    this.svg = svg;
    const values2 = this.values = [];
    const index2 = this.mark.index;
    const g = `g[data-index="${index2}"]`;
    const selector = `${g} > *:not(g), ${g} > g > *`;
    const nodes = this.nodes = svg.querySelectorAll(selector);
    const { channels } = this;
    for (let i = 0; i < nodes.length; ++i) {
      const node = nodes[i];
      values2.push(channels.map((c4) => node.getAttribute(c4[0])));
    }
    return this.update();
  }
  async update() {
    const { svg, nodes, channels, values: values2, mark: mark2, selection: selection2 } = this;
    if (!svg) return;
    const test = await predicateFunction(mark2, selection2);
    for (let i = 0; i < nodes.length; ++i) {
      const node = nodes[i];
      const base = values2[i];
      const t = test(getDatum(node));
      for (let j = 0; j < channels.length; ++j) {
        const [attr, value] = channels[j];
        node.setAttribute(attr, t ? base[j] : value);
      }
    }
  }
};
async function predicateFunction(mark2, selection2) {
  const pred = selection2?.predicate(mark2);
  if (!pred || pred.length === 0) {
    return () => true;
  }
  const filter3 = mark2.filterBy?.predicate(mark2, true);
  const s2 = { __: and(pred) };
  const q = mark2.query(filter3);
  (q.queries || [q]).forEach((q2) => {
    q2._groupby.length ? q2.select(s2) : q2.setSelect(s2);
  });
  const data = await mark2.coordinator.query(q);
  const v2 = data.getChild?.("__");
  return !(data.numRows || data.length) ? (() => false) : v2 ? ((i) => v2.at(i)) : ((i) => data[i].__);
}

// ../plot/src/interactors/util/patchScreenCTM.js
function patchScreenCTM() {
  const node = this;
  const getScreenCTM = node.getScreenCTM;
  let memo2;
  node.getScreenCTM = () => {
    return node.isConnected ? memo2 = getScreenCTM.call(node) : memo2;
  };
}

// ../plot/src/interactors/util/brush.js
function wrap2(brush3) {
  const brushOn = brush3.on;
  let enabled = true;
  function silence(callback) {
    enabled = false;
    callback();
    enabled = true;
  }
  brush3.reset = (...args) => {
    silence(() => brush3.clear(...args));
  };
  brush3.moveSilent = (...args) => {
    silence(() => brush3.move(...args));
  };
  brush3.on = (...args) => {
    if (args.length > 1 && args[1]) {
      const callback = args[1];
      args[1] = (...event) => enabled && callback(...event);
    }
    return brushOn(...args);
  };
  return brush3;
}
function brush2() {
  return wrap2(brush_default());
}
function brushX2() {
  return wrap2(brushX());
}
function brushY2() {
  return wrap2(brushY());
}
function brushGroups(svg, root2, dx, dy, className) {
  let groups2 = select_default2(root2 ?? svg).append("g").attr("class", className);
  const fx = svg.scale("fx");
  const fy = svg.scale("fy");
  if (fx || fy) {
    const X3 = fx?.domain.map((v2) => fx.apply(v2) - dx);
    const Y3 = fy?.domain.map((v2) => fy.apply(v2) - dy);
    if (X3 && Y3) {
      for (let i = 0; i < X3.length; ++i) {
        for (let j = 0; j < Y3.length; ++j) {
          groups2.append("g").attr("transform", `translate(${X3[i]}, ${Y3[j]})`);
        }
      }
    } else if (X3) {
      for (let i = 0; i < X3.length; ++i) {
        groups2.append("g").attr("transform", `translate(${X3[i]}, 0})`);
      }
    } else if (Y3) {
      for (let j = 0; j < Y3.length; ++j) {
        groups2.append("g").attr("transform", `translate(0, ${Y3[j]})`);
      }
    }
    groups2 = groups2.selectAll("g");
  }
  return groups2.each(patchScreenCTM);
}

// ../plot/src/interactors/util/close-to.js
var EPS = 1e-12;
function closeTo(a2, b) {
  return a2 === b || a2 && b && Math.abs(a2[0] - b[0]) < EPS && Math.abs(a2[1] - b[1]) < EPS || false;
}

// ../plot/src/interactors/util/get-field.js
function extractField(field3) {
  if (isNode(field3)) {
    if (field3.type === "COLUMN_REF") {
      return field3.column;
    } else if (field3.type === "AGGREGATE") {
      return field3.args[0] ?? field3;
    }
  }
  return field3;
}
function getField(mark2, channel) {
  return extractField(mark2.channelField(channel)?.field);
}
function getFields(mark2, channels) {
  const fields = [];
  const as = [];
  channels.forEach((c4) => {
    const q = c4 === "color" ? ["color", "fill", "stroke"] : c4 === "x" ? ["x", "x1", "x2"] : c4 === "y" ? ["y", "y1", "y2"] : [c4];
    for (let i = 0; i < q.length; ++i) {
      const f = mark2.channelField(q[i], { exact: true });
      if (f) {
        fields.push(extractField(f.field));
        as.push(f.as);
        return;
      }
    }
    throw new Error(`Missing channel: ${c4}`);
  });
  return { fields, as };
}

// ../plot/src/interactors/util/invert.js
function invert(value, scale3, pixelSize = 1) {
  return scale3.invert(pixelSize * Math.floor(value / pixelSize));
}

// ../plot/src/interactors/Interval1D.js
var Interval1D = class {
  constructor(mark2, {
    channel,
    selection: selection2,
    field: field3 = void 0,
    pixelSize = 1,
    peers = true,
    brush: style2
  }) {
    this.mark = mark2;
    this.channel = channel;
    this.pixelSize = pixelSize || 1;
    this.selection = selection2;
    this.peers = peers;
    this.field = field3 || getField(mark2, channel);
    this.style = style2 && sanitizeStyles(style2);
    this.brush = channel === "y" ? brushY2() : brushX2();
    this.brush.on("brush end", ({ selection: selection3 }) => this.publish(selection3));
  }
  reset() {
    this.value = void 0;
    if (this.g) this.brush.reset(this.g);
  }
  activate() {
    this.selection.activate(this.clause(this.value || [0, 1]));
  }
  publish(extent4) {
    let range3 = void 0;
    if (extent4) {
      range3 = extent4.map((v2) => invert(v2, this.scale, this.pixelSize)).sort((a2, b) => a2 - b);
    }
    if (!closeTo(range3, this.value)) {
      this.value = range3;
      this.g.call(this.brush.moveSilent, extent4);
      this.selection.update(this.clause(range3));
    }
  }
  clause(value) {
    const { mark: mark2, pixelSize, field: field3, scale: scale3 } = this;
    return clauseInterval(field3, value, {
      source: this,
      clients: this.peers ? mark2.plot.markSet : (/* @__PURE__ */ new Set()).add(mark2),
      scale: scale3,
      pixelSize
    });
  }
  init(svg, root2) {
    const { brush: brush3, channel, style: style2 } = this;
    this.scale = svg.scale(channel);
    const range3 = this.value?.map(this.scale.apply).sort(ascending);
    const rx = svg.scale("x").range;
    const ry = svg.scale("y").range;
    brush3.extent([[min2(rx), min2(ry)], [max2(rx), max2(ry)]]);
    this.g = brushGroups(svg, root2, min2(rx), min2(ry), `interval-${channel}`).call(brush3).call(brush3.moveSilent, range3);
    if (style2) {
      const brushes = this.g.selectAll("rect.selection");
      for (const name2 in style2) {
        brushes.attr(name2, style2[name2]);
      }
    }
    svg.addEventListener("pointerenter", (evt) => {
      if (!evt.buttons) this.activate();
    });
  }
};

// ../plot/src/interactors/Interval2D.js
var Interval2D = class {
  constructor(mark2, {
    selection: selection2,
    xfield,
    yfield,
    pixelSize = 1,
    peers = true,
    brush: style2
  }) {
    this.mark = mark2;
    this.pixelSize = pixelSize || 1;
    this.selection = selection2;
    this.peers = peers;
    this.xfield = xfield || getField(mark2, "x");
    this.yfield = yfield || getField(mark2, "y");
    this.style = style2 && sanitizeStyles(style2);
    this.brush = brush2();
    this.brush.on("brush end", ({ selection: selection3 }) => this.publish(selection3));
  }
  reset() {
    this.value = void 0;
    if (this.g) this.brush.reset(this.g);
  }
  activate() {
    this.selection.activate(this.clause(this.value || [[0, 1], [0, 1]]));
  }
  publish(extent4) {
    const { value, pixelSize, xscale, yscale } = this;
    let xr = void 0;
    let yr = void 0;
    if (extent4) {
      const [a2, b] = extent4;
      xr = [a2[0], b[0]].map((v2) => invert(v2, xscale, pixelSize)).sort(ascending);
      yr = [a2[1], b[1]].map((v2) => invert(v2, yscale, pixelSize)).sort(ascending);
    }
    if (!closeTo(xr, value?.[0]) || !closeTo(yr, value?.[1])) {
      this.value = extent4 ? [xr, yr] : void 0;
      this.g.call(this.brush.moveSilent, extent4);
      this.selection.update(this.clause(this.value));
    }
  }
  clause(value) {
    const { mark: mark2, pixelSize, xfield, yfield, xscale, yscale } = this;
    return clauseIntervals([xfield, yfield], value, {
      source: this,
      clients: this.peers ? mark2.plot.markSet : (/* @__PURE__ */ new Set()).add(mark2),
      scales: [xscale, yscale],
      pixelSize
    });
  }
  init(svg) {
    const { brush: brush3, style: style2, value } = this;
    const xscale = this.xscale = svg.scale("x");
    const yscale = this.yscale = svg.scale("y");
    const rx = xscale.range;
    const ry = yscale.range;
    brush3.extent([[min2(rx), min2(ry)], [max2(rx), max2(ry)]]);
    this.g = brushGroups(svg, null, min2(rx), min2(ry), "interval-xy").call(brush3);
    if (style2) {
      const brushes = this.g.selectAll("rect.selection");
      for (const name2 in style2) {
        brushes.attr(name2, style2[name2]);
      }
    }
    if (value) {
      const [x12, x22] = value[0].map(xscale.apply).sort(ascending);
      const [y12, y22] = value[1].map(yscale.apply).sort(ascending);
      this.g.call(brush3.moveSilent, [[x12, y12], [x22, y22]]);
    }
    svg.addEventListener("pointerenter", (evt) => {
      if (!evt.buttons) this.activate();
    });
  }
};

// ../plot/src/interactors/Nearest.js
var Nearest = class {
  constructor(mark2, {
    selection: selection2,
    pointer: pointer2,
    channels,
    fields,
    maxRadius = 40
  }) {
    this.mark = mark2;
    this.selection = selection2;
    this.clients = (/* @__PURE__ */ new Set()).add(mark2);
    this.pointer = pointer2;
    this.channels = channels || (pointer2 === "x" ? ["x"] : pointer2 === "y" ? ["y"] : ["x", "y"]);
    this.fields = fields || this.channels.map((c4) => getField(mark2, [c4]));
    this.maxRadius = maxRadius;
    this.valueIndex = -1;
  }
  clause(value) {
    const { clients, fields } = this;
    const opt = { source: (
      /** @type {ClauseSource} */
      this
    ), clients };
    return fields.length > 1 ? clausePoints(fields, value ? [value] : value, opt) : clausePoint(fields[0], value?.[0], opt);
  }
  init(svg) {
    const that = this;
    const { mark: mark2, channels, selection: selection2, maxRadius } = this;
    const { data: { columns } } = mark2;
    const keys = channels.map((c4) => mark2.channelField(c4).as);
    const param = !isSelection(selection2);
    const [X3, Y3] = calculateXY(svg, mark2);
    const sx = this.pointer === "y" ? 0.01 : 1;
    const sy = this.pointer === "x" ? 0.01 : 1;
    const root2 = select_default2(svg);
    root2.on("pointerenter pointerdown pointermove", function(evt) {
      const [px, py] = pointer_default(evt, this);
      const i = findNearest(X3, Y3, px, py, sx, sy, maxRadius);
      if (i !== this.valueIndex) {
        this.valueIndex = i;
        const v2 = i < 0 ? void 0 : keys.map((k2) => columns[k2][i]);
        selection2.update(
          // provide value for param, clause for selection
          param ? !v2 || v2.length > 1 ? v2 : v2[0] : that.clause(v2)
        );
      }
    });
    if (param) return;
    root2.on("pointerleave", () => {
      selection2.update(that.clause(void 0));
    });
    svg.addEventListener("pointerenter", (evt) => {
      if (!evt.buttons) this.activate();
    });
  }
  activate() {
    const v2 = this.channels.map(() => 0);
    this.selection.activate(this.clause(v2));
  }
};
function calculateXY(svg, mark2) {
  const { data: { columns } } = mark2;
  const data = (c4) => columns[mark2.channelField(c4)?.as];
  const scale3 = (c4) => svg.scale(c4);
  const sx = svg.scale("x");
  const sy = svg.scale("y");
  const sfx = scale3("fx")?.apply;
  const sfy = scale3("fy")?.apply;
  const X3 = Array.from(data("x"), sx.apply);
  const Y3 = Array.from(data("y"), sy.apply);
  if (sfx) {
    const dx = min2(sx.range);
    const FX = data("fx");
    for (let i = 0; i < FX.length; ++i) {
      X3[i] += sfx(FX[i]) - dx;
    }
  }
  if (sfy) {
    const dy = min2(sy.range);
    const FY = data("fy");
    for (let i = 0; i < FY.length; ++i) {
      Y3[i] += sfy(FY[i]) - dy;
    }
  }
  return [X3, Y3];
}
function findNearest(x3, y3, px, py, sx, sy, maxRadius) {
  let dist2 = maxRadius * maxRadius;
  let nearest2 = -1;
  for (let i = 0; i < x3.length; ++i) {
    const dx = sx * (x3[i] - px);
    const dy = sy * (y3[i] - py);
    const dd = dx * dx + dy * dy;
    if (dd <= dist2) {
      dist2 = dd;
      nearest2 = i;
    }
  }
  return nearest2;
}

// ../plot/src/interactors/PanZoom.js
var asc2 = (a2, b) => a2 - b;
var PanZoom = class {
  constructor(mark2, {
    x: x3 = new Selection(),
    y: y3 = new Selection(),
    xfield,
    yfield,
    zoom: zoom2 = true,
    panx = true,
    pany = true
  }) {
    this.mark = mark2;
    this.xsel = x3;
    this.ysel = y3;
    this.xfield = xfield || getField(mark2, "x");
    this.yfield = yfield || getField(mark2, "y");
    this.zoom = extent3(zoom2, [0, Infinity], [1, 1]);
    this.panx = this.xsel && panx;
    this.pany = this.ysel && pany;
    const { plot: plot3 } = mark2;
    if (panx) {
      this.xsel.addEventListener("value", (value) => {
        if (plot3.setAttribute("xDomain", value)) plot3.update();
      });
    }
    if (pany) {
      this.ysel.addEventListener("value", (value) => {
        if (plot3.setAttribute("yDomain", value)) plot3.update();
      });
    }
  }
  publish(transform3) {
    if (this.panx) {
      const xdom = rescaleX(transform3, this.xscale);
      this.xsel.update(this.clause(xdom, this.xfield, this.xscale));
    }
    if (this.pany) {
      const ydom = rescaleY(transform3, this.yscale);
      this.ysel.update(this.clause(ydom, this.yfield, this.yscale));
    }
  }
  clause(value, field3, scale3) {
    return clauseInterval(field3, value, {
      source: (
        /** @type {ClauseSource} */
        this
      ),
      clients: this.mark.plot.markSet,
      scale: scale3
    });
  }
  init(svg) {
    this.svg = svg;
    if (this.initialized) return;
    else this.initialized = true;
    const { panx, pany, mark: { plot: { element } } } = this;
    this.xscale = svg.scale("x");
    this.yscale = svg.scale("y");
    const rx = this.xscale.range.slice().sort(asc2);
    const ry = this.yscale.range.slice().sort(asc2);
    const tx = extent3(panx, [-Infinity, Infinity], rx);
    const ty = extent3(pany, [-Infinity, Infinity], ry);
    const z = zoom_default2().extent([[rx[0], ry[0]], [rx[1], ry[1]]]).scaleExtent(this.zoom).translateExtent([[tx[0], ty[0]], [tx[1], ty[1]]]).on("start", () => {
      this.xscale = this.svg.scale("x");
      this.yscale = this.svg.scale("y");
    }).on("end", () => element.__zoom = new Transform2(1, 0, 0)).on("zoom", ({ transform: transform3 }) => this.publish(transform3));
    select_default2(element).call(z);
    if (panx || pany) {
      let enter = false;
      element.addEventListener("pointerenter", (evt) => {
        if (enter) return;
        else enter = true;
        if (!evt.buttons) this.activate();
      });
      element.addEventListener("pointerleave", () => enter = false);
    }
  }
  activate() {
    if (this.panx) {
      const { xscale, xfield } = this;
      this.xsel.activate(this.clause(xscale.domain, xfield, xscale));
    }
    if (this.pany) {
      const { yscale, yfield } = this;
      this.ysel.activate(this.clause(yscale.domain, yfield, yscale));
    }
  }
};
function extent3(ext, defaultTrue, defaultFalse) {
  return ext ? Array.isArray(ext) ? ext : defaultTrue : defaultFalse;
}
function rescaleX(transform3, scale3) {
  return scale3.range.map(transform3.invertX, transform3).map(scale3.invert, scale3);
}
function rescaleY(transform3, scale3) {
  return scale3.range.map(transform3.invertY, transform3).map(scale3.invert, scale3);
}

// ../plot/src/interactors/util/parse-path.js
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]/;
var errmsg = (attr) => `Invalid SVG path, incorrect parameter ${attr}`;
function parsePath(path2) {
  const commands = [];
  const matches = path2.match(commandPattern) || [];
  matches.forEach((str) => {
    let cmd = str[0];
    const type2 = cmd.toLowerCase();
    const paramCount = paramCounts[type2];
    const params = parseParams(type2, paramCount, str.slice(1).trim());
    const count4 = params.length;
    if (count4 < paramCount || count4 && count4 % paramCount !== 0) {
      throw new Error(errmsg("count"));
    }
    commands.push([cmd, ...params.slice(0, paramCount)]);
    if (count4 === paramCount) {
      return;
    }
    if (type2 === "m") {
      cmd = cmd === "M" ? "L" : "l";
    }
    for (let i = paramCount; i < count4; i += paramCount) {
      commands.push([cmd, ...params.slice(i, i + paramCount)]);
    }
  });
  return commands;
}
function parseParams(type2, paramCount, segment) {
  const params = [];
  for (let index2 = 0; paramCount && index2 < segment.length; ) {
    for (let i = 0; i < paramCount; ++i) {
      const pattern = type2 === "a" && (i === 3 || i === 4) ? flagPattern : numberPattern;
      const match = segment.slice(index2).match(pattern);
      if (match === null) {
        throw new Error(errmsg("type"));
      }
      index2 += match[0].length;
      params.push(+match[0]);
      const ws = segment.slice(index2).match(spacePattern);
      if (ws !== null) {
        index2 += ws[0].length;
      }
    }
  }
  return params;
}

// ../plot/src/interactors/util/intersect.js
function intersect(svg, el, extent4) {
  const { x: x3, y: y3 } = svg.getBoundingClientRect();
  const identity10 = svg.createSVGMatrix();
  const list3 = [];
  for (const child of el.children) {
    if (child.tagName === "g") {
      const matrix = getTransformMatrix(child) ?? identity10;
      for (const grandchild of child.children) {
        if (intersects(extent4, x3, y3, grandchild, matrix)) {
          list3.push(grandchild);
        }
      }
    } else if (intersects(extent4, x3, y3, child, identity10)) {
      list3.push(child);
    }
  }
  return list3;
}
function intersects(sel, ox2, oy2, el, matrix) {
  let [[l, t], [r, b]] = sel;
  const { e: tx, f: ty } = matrix;
  const c4 = el.getBoundingClientRect();
  const cl = c4.left - ox2;
  const cr = c4.right - ox2;
  const ct = c4.top - oy2;
  const cb = c4.bottom - oy2;
  if (cl >= l && cr <= r && ct >= t && cb <= b) {
    return true;
  } else if (cl <= r && cr >= l && ct <= b && cb >= t) {
    let tag = el.tagName;
    if (tag === "a") {
      el = el.children[0];
      tag = el.tagName;
    }
    if (tag === "rect" || tag === "text" || tag === "image") {
      return true;
    }
    l -= tx;
    t -= ty;
    r -= tx;
    b -= ty;
    switch (tag) {
      case "circle":
        return intersectCircle(l, t, r, b, $(el.cx), $(el.cy), $(el.r));
      case "line":
        return intersectLine(l, t, r, b, $(el.x1), $(el.y1), $(el.x2), $(el.y2));
      case "path":
        return intersectPath(l, t, r, b, el);
    }
  }
  return false;
}
function $(attr) {
  return attr.baseVal.value;
}
function getTransformMatrix(el) {
  const transform3 = el.transform.baseVal;
  const n = transform3.length;
  let m = transform3[0]?.matrix;
  for (let i = 1; i < n; ++i) {
    m = m.multiply(transform3[i].matrix);
  }
  return m;
}
function intersectCircle(l, t, r, b, cx, cy, cr) {
  const h = l <= cx && cx <= r;
  const v2 = t <= cy && cy <= b;
  if (h && v2) return true;
  const dx = Math.min(Math.abs(l - cx), Math.abs(r - cx));
  if (v2 && dx <= cr) return true;
  const dy = Math.min(Math.abs(t - cy), Math.abs(b - cy));
  return h && dy <= cr || dx * dx + dy * dy <= cr * cr;
}
function intersectLine(l, t, r, b, x12, y12, x22, y22) {
  const xmin = Math.max(Math.min(x12, x22), l);
  const xmax = Math.min(Math.max(x12, x22), r);
  if (xmin > xmax) return false;
  let yl1 = y12;
  let yl2 = y22;
  const dx = x22 - x12;
  if (Math.abs(dx) > 1e-8) {
    const a2 = (y22 - y12) / dx;
    const b2 = y12 - a2 * x12;
    yl1 = a2 * xmin + b2;
    yl2 = a2 * xmax + b2;
  }
  const ymin = Math.max(Math.min(yl1, yl2), t);
  const ymax = Math.min(Math.max(yl1, yl2), b);
  return ymin <= ymax;
}
function intersectPath(l, t, r, b, el) {
  const cmds = el.__path__ || (el.__path__ = parsePath(el.getAttribute("d")));
  let anchorX3 = 0;
  let anchorY3 = 0;
  let x3 = 0;
  let y3 = 0;
  let hit = false;
  let poly = [0, 0];
  let n = 2;
  const matrix = getTransformMatrix(el);
  const setAnchor = (ax, ay) => {
    poly.length = n = 2;
    poly[0] = x3 = anchorX3 = ax;
    poly[1] = y3 = anchorY3 = ay;
  };
  const anchor = matrix ? (x4, y4) => setAnchor(multiplyX(matrix, x4, y4), multiplyY(matrix, x4, y4)) : (x4, y4) => setAnchor(x4, y4);
  const test = (x22, y22) => {
    poly[n] = x22;
    poly[n + 1] = y22;
    n += 2;
    return intersectLine(l, t, r, b, poly[n - 4], poly[n - 3], x22, y22);
  };
  const lineTo = matrix ? (x22, y22) => {
    hit = test(
      multiplyX(matrix, x3 = x22, y3 = y22),
      multiplyY(matrix, x22, y22)
    );
  } : (x22, y22) => {
    hit = test(x3 = x22, y3 = y22);
  };
  for (let i = 0; i < cmds.length; ++i) {
    const cmd = cmds[i];
    switch (cmd[0]) {
      case "M":
        anchor(cmd[1], cmd[2]);
        break;
      case "m":
        anchor(x3 + cmd[1], y3 + cmd[2]);
        break;
      case "L":
      case "T":
        lineTo(cmd[1], cmd[2]);
        break;
      case "H":
        lineTo(cmd[1], y3);
        break;
      case "V":
        lineTo(x3, cmd[1]);
        break;
      case "l":
      case "t":
        lineTo(x3 + cmd[1], y3 + cmd[2]);
        break;
      case "h":
        lineTo(x3 + cmd[1], y3);
        break;
      case "v":
        lineTo(x3, y3 + cmd[1]);
        break;
      // approximate bezier curve as line for now
      case "C":
        lineTo(cmd[5], cmd[6]);
        break;
      case "c":
        lineTo(x3 + cmd[5], y3 + cmd[6]);
        break;
      case "S":
      case "Q":
        lineTo(cmd[3], cmd[4]);
        break;
      case "s":
      case "q":
        lineTo(x3 + cmd[3], y3 + cmd[4]);
        break;
      // we don't expect to see arcs other than geo point circles
      // but just in case, approximate via straight line for now
      case "A":
        lineTo(cmd[6], cmd[7]);
        break;
      case "a":
        if (isCircle(cmds, i)) {
          return intersectCircle(l, t, r, b, x3, y3 - cmd[2], cmd[2]);
        } else {
          lineTo(x3 + cmd[6], x3 + cmd[7]);
        }
        break;
      case "z":
      case "Z":
        lineTo(anchorX3, anchorY3);
        if (pointInPolygon(l, t, poly) > 0) return true;
        anchor(anchorX3, anchorY3);
        break;
      default:
        console.warn("SVG path command not supported: ", cmd[0]);
        return false;
    }
    if (hit) return true;
  }
  return false;
}
function multiplyX(m, x3, y3) {
  return m.a * x3 + m.c * y3 + m.e;
}
function multiplyY(m, x3, y3) {
  return m.b * x3 + m.d * y3 + m.f;
}
function isCircle(cmds, i) {
  const a2 = cmds[i];
  const b = cmds[i + 1];
  return b && b[0] === "a" && cmds[i + 2]?.[0] === "z" && a2[1] === a2[2] && b[1] === b[2] && a2[1] === b[1] && a2[7] === -b[7];
}
function pointInPolygon(x3, y3, poly) {
  let wn = 0;
  const n = poly.length - 2;
  for (let i = 0; i < n; i += 2) {
    if (poly[i + 1] <= y3) {
      if (poly[i + 3] > y3 && isLeft(x3, y3, poly, i) > 0)
        ++wn;
    } else if (poly[i + 3] <= y3 && isLeft(x3, y3, poly[i]) < 0) {
      --wn;
    }
  }
  return wn;
}
function isLeft(x3, y3, p, i) {
  return (p[i + 2] - p[i]) * (y3 - p[i + 1]) - (x3 - p[i]) * (p[i + 3] - p[i + 1]);
}

// ../plot/src/interactors/util/neq.js
function neqSome(a2, b) {
  return a2 == null || b == null ? a2 != null || b != null : a2.length !== b.length || a2.some((x3, i) => neq2(x3, b[i]));
}
function neq2(a2, b) {
  const n = a2.length;
  if (b.length !== n) return true;
  for (let i = 0; i < n; ++i) {
    if (a2[i] !== b[i]) return true;
  }
  return false;
}

// ../plot/src/interactors/Region.js
var Region = class {
  constructor(mark2, {
    channels,
    selection: selection2,
    peers = true,
    brush: style2 = {
      fill: "none",
      stroke: "currentColor",
      strokeDasharray: "1,1"
    }
  }) {
    this.mark = mark2;
    this.selection = selection2;
    this.peers = peers;
    this.style = style2 && sanitizeStyles(style2);
    this.brush = brush2();
    this.brush.on("brush end", (evt) => this.publish(evt.selection));
    this.extent = null;
    this.groups = null;
    const { fields, as } = getFields(mark2, channels);
    this.fields = fields;
    this.as = as;
  }
  reset() {
    this.value = void 0;
    this.extent = null;
    if (this.g) this.brush.reset(this.g);
  }
  activate() {
    this.selection.activate(this.clause([this.fields.map(() => 0)]));
  }
  clause(value) {
    const { fields, mark: mark2 } = this;
    return clausePoints(fields, value, {
      source: this,
      clients: this.peers ? mark2.plot.markSet : (/* @__PURE__ */ new Set()).add(mark2)
    });
  }
  publish(extent4) {
    const { as, group: group3, mark: mark2, svg } = this;
    let value;
    if (extent4) {
      const { data: { columns = {} } = {} } = mark2;
      const map5 = /* @__PURE__ */ new Map();
      intersect(svg, group3, extent4).forEach((el) => {
        const index2 = getDatum(el);
        const vals = as.map((name2) => columns[name2][index2]);
        map5.set(vals.join("|"), vals);
      });
      value = Array.from(map5.values());
    }
    this.extent = extent4;
    if (neqSome(value, this.value)) {
      this.value = value;
      this.selection.update(this.clause(value));
    }
  }
  init(svg) {
    const { brush: brush3, extent: extent4, mark: mark2, style: style2 } = this;
    this.svg = svg;
    const w = svg.width.baseVal.value;
    const h = svg.height.baseVal.value;
    brush3.extent([[0, 0], [w, h]]);
    this.group = svg.querySelector(`[data-index="${mark2.index}"]`);
    this.g = select_default2(svg).append("g").attr("class", `region-xy`).each(patchScreenCTM).call(brush3).call(brush3.moveSilent, extent4);
    if (style2) {
      const brushes = this.g.selectAll("rect.selection");
      for (const name2 in style2) {
        brushes.attr(name2, style2[name2]);
      }
    }
    svg.addEventListener("pointerenter", (evt) => {
      if (!evt.buttons) this.activate();
    });
  }
};

// ../plot/src/interactors/Toggle.js
var Toggle = class {
  /**
   * @param {*} mark The mark to interact with.
   * @param {*} options The interactor options.
   */
  constructor(mark2, {
    selection: selection2,
    channels,
    peers = true
  }) {
    this.mark = mark2;
    this.value = null;
    this.selection = selection2;
    this.peers = peers;
    const fields = this.fields = [];
    const as = this.as = [];
    channels.forEach((c4) => {
      const q = c4 === "color" ? ["color", "fill", "stroke"] : c4 === "x" ? ["x", "x1", "x2"] : c4 === "y" ? ["y", "y1", "y2"] : [c4];
      for (let i = 0; i < q.length; ++i) {
        const f = mark2.channelField(q[i], { exact: true });
        if (f) {
          fields.push(f.field?.basis || f.field);
          as.push(f.as);
          return;
        }
      }
      throw new Error(`Missing channel: ${c4}`);
    });
  }
  clause(value) {
    const { fields, mark: mark2 } = this;
    return clausePoints(fields, value, {
      source: (
        /** @type {ClauseSource} */
        this
      ),
      clients: this.peers ? mark2.plot.markSet : (/* @__PURE__ */ new Set()).add(mark2)
    });
  }
  init(svg, selector, accessor) {
    const { mark: mark2, as, selection: selection2 } = this;
    const { data: { columns = {} } = {} } = mark2;
    accessor ??= (target) => as.map((name2) => columns[name2][getDatum(target)]);
    selector ??= `[data-index="${mark2.index}"]`;
    const groups2 = Array.from(svg.querySelectorAll(selector));
    svg.addEventListener("pointerdown", (evt) => {
      const state = selection2.single ? selection2.value : this.value;
      const target = evt.target;
      let value = null;
      if (isTargetElement(groups2, target)) {
        const point6 = accessor(target);
        if ((evt.shiftKey || evt.metaKey) && state?.length) {
          value = state.filter((s2) => neq2(s2, point6));
          if (value.length === state.length) value.push(point6);
        } else if (state?.length === 1 && !neq2(state[0], point6)) {
          value = null;
        } else {
          value = [point6];
        }
      }
      this.value = value;
      if (neqSome(state, value)) {
        selection2.update(this.clause(value));
      }
    });
    svg.addEventListener("pointerenter", (evt) => {
      if (!evt.buttons) this.activate();
    });
  }
  activate() {
    this.selection.activate(this.clause([this.fields.map(() => 0)]));
  }
};
function isTargetElement(groups2, node) {
  return groups2.some((g) => g.contains(node));
}

// ../plot/src/legend.js
var TOGGLE_SELECTOR = ":scope > div, :scope > span";
var SWATCH = "swatch";
var RAMP = "ramp";
var Legend = class {
  constructor(channel, options) {
    const { as, field: field3, ...rest } = options;
    this.channel = channel;
    this.options = rest;
    this.type = null;
    this.handler = null;
    this.selection = as;
    this.field = field3;
    this.legend = null;
    this.element = document.createElement("div");
    this.element.setAttribute("class", "legend");
    Object.defineProperty(this.element, "value", { value: this });
  }
  setPlot(plot3) {
    this.plot = plot3;
  }
  init(svg) {
    const el = createLegend(this, svg);
    this.element.replaceChildren(el);
    return this.element;
  }
  update() {
    if (!this.legend) return;
    const { selection: selection2, handler } = this;
    const { single, value } = selection2;
    const vals = single ? value : selection2.valueFor(handler);
    const curr = vals && vals.length ? new Set(vals.map((v2) => v2[0])) : null;
    const nodes = this.legend.querySelectorAll(TOGGLE_SELECTOR);
    for (const node of nodes) {
      const selected = curr ? curr.has(node.__data__) : true;
      node.style.opacity = selected ? 1 : 0.2;
    }
  }
};
function createLegend(legend3, svg) {
  const { channel, plot: plot3, selection: selection2 } = legend3;
  const scale3 = svg.scale(channel);
  const type2 = scale3.type === "ordinal" ? SWATCH : RAMP;
  const options = {
    label: plot3.getAttribute(`${channel}Label`) ?? null,
    ...legend3.options
  };
  const opt = type2 === SWATCH ? options : options.label ? { tickSize: 2, ...options } : { tickSize: 2, marginTop: 1, height: 29, ...options };
  const el = svg.legend(channel, opt);
  legend3.legend = el;
  let interactive = !!selection2;
  if (interactive && type2 === RAMP) {
    const width2 = opt.width ?? 240;
    const spatial = spatialScale(scale3, width2);
    if (spatial) {
      el.scale = function(type3) {
        return type3 === "x" ? { range: [0, width2] } : type3 === "y" ? { range: [-10, 0] } : type3 === channel ? spatial : void 0;
      };
    } else {
      interactive = false;
    }
  }
  if (interactive) {
    const handler = getInteractor(legend3, type2);
    if (type2 === SWATCH) {
      handler.init(el, TOGGLE_SELECTOR, (el2) => [el2.__data__]);
      legend3.update();
    } else {
      handler.init(el, el.querySelector("g:last-of-type"));
    }
  }
  return el;
}
function getInteractor(legend3, type2) {
  const { channel, handler, selection: selection2 } = legend3;
  if (handler) return handler;
  const mark2 = interactorMark(legend3);
  if (type2 === SWATCH) {
    legend3.handler = new Toggle(mark2, {
      selection: selection2,
      channels: [channel],
      peers: false
    });
    selection2.addEventListener("value", () => legend3.update());
  } else {
    legend3.handler = new Interval1D(mark2, {
      selection: selection2,
      channel,
      brush: { fill: "none", stroke: "currentColor" },
      peers: false
    });
  }
  return legend3.handler;
}
function interactorMark(legend3) {
  const { channel, plot: plot3 } = legend3;
  const field3 = legend3.field ?? findField(plot3.marks, channel) ?? "value";
  if (field3) {
    const f = { field: field3 };
    return { plot: plot3, channelField: (c4) => channel === c4 ? f : void 0 };
  }
}
function findField(marks2, channel) {
  const channels = channel === "color" ? ["fill", "stroke"] : channel === "opacity" ? ["opacity", "fillOpacity", "strokeOpacity"] : null;
  if (channels == null) return null;
  for (let i = marks2.length - 1; i > -1; --i) {
    for (const c4 of channels) {
      const field3 = marks2[i].channelField(c4, { exact: true });
      if (field3) return field3.field;
    }
  }
  return null;
}
function spatialScale(sourceScale, width2) {
  const { apply: apply2, invert: invert2, interpolate, ...rest } = sourceScale;
  let src = sourceScale.type;
  if (src.startsWith("diverging-")) src = src.slice(11);
  let type2;
  switch (src) {
    case "log":
    case "pow":
    case "sqrt":
    case "symlog":
      type2 = src;
      break;
    case "threshold":
    case "quantize":
    case "quantile":
      console.warn(`Legends do not yet support ${src} scales.`);
      return null;
    default:
      type2 = "linear";
  }
  return scale2({ x: { ...rest, type: type2, range: [0, width2] } });
}

// ../plot/src/transforms/bin.js
var EXTENT = /* @__PURE__ */ new Set([
  "rectY-x",
  "rectX-y",
  "rect-x",
  "rect-y",
  "ruleY-x",
  "ruleX-y"
]);
function hasExtent(mark2, channel) {
  return EXTENT.has(`${mark2.type}-${channel}`);
}
function bin2(field3, options = {}) {
  const fn2 = (mark2, channel) => {
    if (hasExtent(mark2, channel)) {
      return {
        [`${channel}1`]: binNode(mark2, channel, field3, options),
        [`${channel}2`]: binNode(mark2, channel, field3, { ...options, offset: 1 })
      };
    } else {
      return {
        [channel]: binNode(mark2, channel, field3, options)
      };
    }
  };
  fn2[Transform] = true;
  return fn2;
}
function binNode(mark2, channel, column3, options) {
  return new BinTransformNode(column3, mark2, channel, options);
}
function hasTimeScale(mark2, channel) {
  const scale3 = mark2.plot.getAttribute(`${channel}Scale`);
  return scale3 === "utc" || scale3 === "time";
}
var BinTransformNode = class extends ExprNode {
  constructor(column3, mark2, channel, options) {
    super("COLUMN_REF");
    this.column = column3;
    this.mark = mark2;
    this.channel = channel;
    this.options = options;
  }
  get stats() {
    return { column: this.column, stats: ["min", "max"] };
  }
  toString() {
    const { mark: mark2, channel, column: column3, options } = this;
    const { type: type2, min: min5, max: max4 } = mark2.channelField(channel);
    const isDate2 = options.interval || type2 === "date" || hasTimeScale(mark2, channel);
    const result = isDate2 ? binDate(column3, [min5, max4], options) : binHistogram(column3, [min5, max4], options, channelScale(mark2, channel));
    return `${result}`;
  }
};

// ../inputs/src/input.js
var Input = class extends MosaicClient {
  /**
   * Create a new input instance.
   * @param {import('@uwdata/mosaic-core').Selection} [filterBy] A selection
   *  with which to filter backing data that parameterizes this input.
   * @param {HTMLElement} [element] Optional container HTML element to use.
   * @param {string} [className] A class name to set on the container element.
   */
  constructor(filterBy, element, className = "input") {
    super(filterBy);
    this.element = element || document.createElement("div");
    if (className) this.element.setAttribute("class", className);
    Object.defineProperty(this.element, "value", { value: this });
  }
  activate() {
  }
};

// ../inputs/src/Menu.js
var isObject2 = (v2) => {
  return v2 && typeof v2 === "object" && !Array.isArray(v2);
};
var Menu = class extends Input {
  /**
   * Create a new menu input.
   * @param {object} [options] Options object
   * @param {HTMLElement} [options.element] The parent DOM element in which to
   *  place the menu elements. If undefined, a new `div` element is created.
   * @param {Selection} [options.filterBy] A selection to filter the database
   *  table indicated by the *from* option.
   * @param {Param} [options.as] The output param or selection. A selection
   *  clause is added for the currently selected menu option.
   * @param {string} [options.field] The database column name to use within
   *  generated selection clause predicates. Defaults to the *column* option.
   * @param {(any | { value: any, label?: string })[]} [options.options] An
   *  array of menu options, as literal values or option objects. Option
   *  objects have a `value` property and an optional `label` property. If no
   *  label or *format* function is provided, the string-coerced value is used.
   * @param {(value: any) => string} [options.format] A format function that
   *  takes an option value as input and generates a string label. The format
   *  function is not applied when an explicit label is provided in an option
   *  object.
   * @param {*} [options.value] The initial selected menu value.
   * @param {string} [options.from] The name of a database table to use as a data
   *  source for this widget. Used in conjunction with the *column* option.
   * @param {string} [options.column] The name of a database column from which
   *  to pull menu options. The unique column values are used as menu options.
   *  Used in conjunction with the *from* option.
   * @param {string} [options.label] A text label for this input.
   * @param {'any' | 'all'} [options.listMatch] The list match mode.
   */
  constructor({
    element,
    filterBy,
    as,
    from: from2,
    column: column3,
    label = column3,
    format: format3 = (x3) => x3,
    // TODO
    options,
    value,
    field: field3 = column3,
    listMatch
  } = {}) {
    super(filterBy, element);
    this.from = from2;
    this.column = column3;
    this.format = format3;
    this.field = field3;
    this.listMatch = listMatch;
    const selection2 = this.selection = as;
    const lab3 = document.createElement("label");
    lab3.innerText = label || column3;
    this.element.appendChild(lab3);
    this.select = document.createElement("select");
    this.element.appendChild(this.select);
    if (options) {
      this.data = options.map((opt) => isObject2(opt) ? opt : { value: opt });
      this.selectedValue(value === void 0 ? "" : value);
      this.update();
    }
    if (selection2) {
      const isParam2 = !isSelection(selection2);
      if (value != null && (!isParam2 || selection2.value === void 0)) {
        this.publish(value);
      }
      this.select.addEventListener("input", () => {
        this.publish(this.selectedValue() ?? null);
      });
      if (isParam2) {
        this.selection.addEventListener("value", (value2) => {
          if (value2 !== this.select.value) {
            this.selectedValue(value2);
          }
        });
      } else {
        this.select.addEventListener("pointerenter", (evt) => {
          if (!evt.buttons) this.activate();
        });
        this.select.addEventListener("focus", () => this.activate());
      }
    }
  }
  selectedValue(value) {
    if (arguments.length === 0) {
      const index2 = this.select.selectedIndex;
      return this.data[index2].value;
    } else {
      const index2 = this.data?.findIndex((opt) => opt.value === value);
      if (index2 >= 0) {
        this.select.selectedIndex = index2;
      } else {
        this.select.value = String(value);
      }
    }
  }
  reset() {
    this.select.selectedIndex = this.from ? 0 : -1;
  }
  activate() {
    if (isSelection(this.selection)) {
      this.selection.activate(clausePoint(this.field, 0, { source: this }));
    }
  }
  publish(value) {
    const { selection: selection2, field: field3, listMatch } = this;
    if (isSelection(selection2)) {
      if (value === "") value = void 0;
      const clause = listMatch ? clauseList(field3, value, { source: this, listMatch }) : clausePoint(field3, value, { source: this });
      selection2.update(clause);
    } else if (isParam(selection2)) {
      selection2.update(value);
    }
  }
  query(filter3 = []) {
    const { from: from2, column: column3, listMatch } = this;
    if (!from2) return null;
    return Query.from(from2).select({ value: listMatch ? unnest(column3) : column3 }).distinct().where(filter3).orderby(column3);
  }
  queryResult(data) {
    this.data = [{ value: "", label: "All" }, ...data];
    return this;
  }
  update() {
    const { data, format: format3, select: select2, selection: selection2 } = this;
    select2.replaceChildren();
    for (const { value, label } of data) {
      const opt = document.createElement("option");
      opt.setAttribute("value", value);
      opt.innerText = label ?? format3(value);
      this.select.appendChild(opt);
    }
    if (selection2) {
      const value = isSelection(selection2) ? selection2.valueFor(this) : selection2.value;
      this.selectedValue(value === void 0 ? "" : value);
    }
    return this;
  }
};

// ../inputs/src/Search.js
var _id = 0;
var Search = class extends Input {
  /**
   * Create a new text search input.
   * @param {object} [options] Options object
   * @param {HTMLElement} [options.element] The parent DOM element in which to
   *  place the search elements. If undefined, a new `div` element is created.
   * @param {Selection} [options.filterBy] A selection to filter the database
   *  table indicated by the *from* option.
   * @param {Param} [options.as] The output param or selection. A selection
   *  clause is added based on the current text search query.
   * @param {string} [options.field] The database column name to use within
   *  generated selection clause predicates. Defaults to the *column* option.
   * @param {'contains' | 'prefix' | 'suffix' | 'regexp'} [options.type] The
   *  type of text search query to perform. One of:
   *  - `"contains"` (default): the query string may appear anywhere in the text
   *  - `"prefix"`: the query string must appear at the start of the text
   *  - `"suffix"`: the query string must appear at the end of the text
   *  - `"regexp"`: the query string is a regular expression the text must match
   * @param {string} [options.from] The name of a database table to use as an
   *  autocomplete data source for this widget. Used in conjunction with the
   *  *column* option.
   * @param {string} [options.column] The name of a database column from which
   *  to pull valid search results. The unique column values are used as search
   *  autocomplete values. Used in conjunction with the *from* option.
   * @param {string} [options.label] A text label for this input.
   */
  constructor({
    element,
    filterBy,
    from: from2,
    column: column3,
    label,
    type: type2 = "contains",
    field: field3 = column3,
    as
  } = {}) {
    super(filterBy, element);
    this.id = "search_" + ++_id;
    this.type = type2;
    this.from = from2;
    this.column = column3;
    this.selection = as;
    this.field = field3;
    if (label) {
      const lab3 = document.createElement("label");
      lab3.setAttribute("for", this.id);
      lab3.innerText = label;
      this.element.appendChild(lab3);
    }
    this.searchbox = document.createElement("input");
    this.searchbox.setAttribute("id", this.id);
    this.searchbox.setAttribute("type", "text");
    this.searchbox.setAttribute("placeholder", "Query");
    this.element.appendChild(this.searchbox);
    if (this.selection) {
      this.searchbox.addEventListener("input", () => {
        this.publish(this.searchbox.value || null);
      });
      if (!isSelection(this.selection)) {
        this.selection.addEventListener("value", (value) => {
          if (value !== this.searchbox.value) {
            this.searchbox.value = value;
          }
        });
      } else {
        this.searchbox.addEventListener("pointerenter", (evt) => {
          if (!evt.buttons) this.activate();
        });
        this.searchbox.addEventListener("focus", () => this.activate());
      }
    }
  }
  reset() {
    this.searchbox.value = "";
  }
  clause(value) {
    const { field: field3, type: type2 } = this;
    return clauseMatch(field3, value, { source: this, method: type2 });
  }
  activate() {
    if (isSelection(this.selection)) {
      this.selection.activate(this.clause(""));
    }
  }
  publish(value) {
    const { selection: selection2 } = this;
    if (isSelection(selection2)) {
      selection2.update(this.clause(value));
    } else if (isParam(selection2)) {
      selection2.update(value);
    }
  }
  query(filter3 = []) {
    const { from: from2, column: column3 } = this;
    if (!from2) return null;
    return Query.from(from2).select({ list: column3 }).distinct().where(filter3);
  }
  queryResult(data) {
    this.data = data;
    return this;
  }
  update() {
    const list3 = document.createElement("datalist");
    const id2 = `${this.id}_list`;
    list3.setAttribute("id", id2);
    for (const d of this.data) {
      const opt = document.createElement("option");
      opt.setAttribute("value", d.list);
      list3.append(opt);
    }
    if (this.datalist) this.datalist.remove();
    this.element.appendChild(this.datalist = list3);
    this.searchbox.setAttribute("list", id2);
    return this;
  }
};

// ../inputs/src/Slider.js
var _id2 = 0;
var Slider = class extends Input {
  /**
   * Create a new slider input.
   * @param {object} [options] Options object
   * @param {HTMLElement} [options.element] The parent DOM element in which to
   *  place the slider elements. If undefined, a new `div` element is created.
   * @param {Selection} [options.filterBy] A selection to filter the database
   *  table indicated by the *from* option.
   * @param {Param} [options.as] The output param or selection. A selection
   *  clause is added based on the currently selected slider option.
   * @param {string} [options.field] The database column name to use within
   *  generated selection clause predicates. Defaults to the *column* option.
   * @param {'point' | 'interval'} [options.select] The type of selection clause
   *  predicate to generate if the **as** option is a Selection.  If `'point'`
   *  (the default), the selection predicate is an equality check for the slider
   *  value. If `'interval'`, the predicate checks an interval from the minimum
   *  to the current slider value.
   * @param {number} [options.min] The minimum slider value.
   * @param {number} [options.max] The maximum slider value.
   * @param {number} [options.step] The slider step, the amount to increment
   *  between consecutive values.
   * @param {number} [options.value] The initial slider value.
   * @param {string} [options.from] The name of a database table to use as a data
   *  source for this widget. Used in conjunction with the *column* option.
   *  The minimum and maximum values of the column determine the slider range.
   * @param {string} [options.column] The name of a database column whose values
   *  determine the slider range. Used in conjunction with the *from* option.
   *  The minimum and maximum values of the column determine the slider range.
   * @param {string} [options.label] A text label for this input.
   * @param {number} [options.width] The width of the slider in screen pixels.
   */
  constructor({
    element,
    filterBy,
    as,
    min: min5,
    max: max4,
    step,
    from: from2,
    column: column3,
    label = column3,
    value = as?.value,
    select: select2 = "point",
    field: field3 = column3,
    width: width2
  } = {}) {
    super(filterBy, element);
    this.id = "slider_" + ++_id2;
    this.from = from2;
    this.column = column3 || "value";
    this.selection = as;
    this.selectionType = select2;
    this.field = field3;
    this.min = min5;
    this.max = max4;
    this.step = step;
    if (label) {
      const desc2 = document.createElement("label");
      desc2.setAttribute("for", this.id);
      desc2.innerText = label;
      this.element.appendChild(desc2);
    }
    this.slider = document.createElement("input");
    this.slider.setAttribute("id", this.id);
    this.slider.setAttribute("type", "range");
    if (width2 != null) this.slider.style.width = `${+width2}px`;
    if (min5 != null) this.slider.setAttribute("min", `${min5}`);
    if (max4 != null) this.slider.setAttribute("max", `${max4}`);
    if (step != null) this.slider.setAttribute("step", `${step}`);
    this.element.appendChild(this.slider);
    this.curval = document.createElement("label");
    this.curval.setAttribute("for", this.id);
    this.curval.setAttribute("class", "value");
    this.element.appendChild(this.curval);
    if (value != null) {
      this.slider.setAttribute("value", `${value}`);
      if (this.selection?.value === void 0) this.publish(value);
    }
    this.curval.innerText = this.slider.value;
    this.slider.addEventListener("input", () => {
      const { value: value2 } = this.slider;
      this.curval.innerText = value2;
      if (this.selection) this.publish(+value2);
    });
    if (this.selection) {
      if (!isSelection(this.selection)) {
        this.selection.addEventListener("value", (value2) => {
          if (value2 !== +this.slider.value) {
            this.slider.value = value2;
            this.curval.innerText = value2;
          }
        });
      } else {
        this.slider.addEventListener("pointerenter", (evt) => {
          if (!evt.buttons) this.activate();
        });
        this.slider.addEventListener("focus", () => this.activate());
      }
    }
  }
  query(filter3 = []) {
    const { from: from2, column: column3 } = this;
    if (!from2 || this.min != null && this.max != null) return null;
    return Query.select({ min: min(column3), max: max(column3) }).from(from2).where(filter3);
  }
  queryResult(data) {
    const { min: min5, max: max4 } = Array.from(data)[0];
    if (this.min == null) {
      this.min = min5;
      this.slider.setAttribute("min", `${min5}`);
    }
    if (this.max == null) {
      this.max = max4;
      this.slider.setAttribute("max", `${max4}`);
    }
    if (this.step == null) {
      this.step = (max4 - min5) / 500;
      this.slider.setAttribute("step", `${this.step}`);
    }
    return this;
  }
  clause(value) {
    const { field: field3, selectionType } = this;
    if (selectionType === "interval") {
      const domain = [this.min ?? 0, value];
      return clauseInterval(field3, domain, {
        source: (
          /** @type {ClauseSource} */
          this
        ),
        bin: "ceil",
        scale: { type: "identity", domain },
        pixelSize: this.step
      });
    } else {
      return clausePoint(field3, value, { source: (
        /** @type {ClauseSource} */
        this
      ) });
    }
  }
  activate() {
    if (isSelection(this.selection)) {
      this.selection.activate(this.clause(0));
    }
  }
  publish(value) {
    const { selection: selection2 } = this;
    if (isSelection(selection2)) {
      selection2.update(this.clause(value));
    } else if (isParam(this.selection)) {
      selection2.update(value);
    }
  }
};

// ../inputs/src/util/format.js
var formatLocaleAuto = localize((locale3) => {
  const formatNumber3 = formatLocaleNumber(locale3);
  return (value) => value == null ? "" : typeof value === "number" ? formatNumber3(value) : value instanceof Date ? formatDate(value) : `${value}`;
});
var formatLocaleNumber = localize((locale3) => {
  return (value) => value === 0 ? "0" : value.toLocaleString(locale3);
});
var formatAuto2 = formatLocaleAuto();
var formatNumber2 = formatLocaleNumber();
function formatDate(date3) {
  return isoformat(date3, "Invalid Date");
}
function localize(f) {
  let key = null;
  let value;
  return (locale3 = "en") => locale3 === key ? value : value = f(key = locale3);
}
function isoformat(date3, fallback) {
  if (!(date3 instanceof Date)) date3 = /* @__PURE__ */ new Date(+date3);
  if (isNaN(+date3)) return typeof fallback === "function" ? fallback(date3) : fallback;
  const hours2 = date3.getUTCHours();
  const minutes2 = date3.getUTCMinutes();
  const seconds3 = date3.getUTCSeconds();
  const milliseconds3 = date3.getUTCMilliseconds();
  return `${formatYear3(date3.getUTCFullYear())}-${pad3(date3.getUTCMonth() + 1, 2)}-${pad3(date3.getUTCDate(), 2)}${hours2 || minutes2 || seconds3 || milliseconds3 ? `T${pad3(hours2, 2)}:${pad3(minutes2, 2)}${seconds3 || milliseconds3 ? `:${pad3(seconds3, 2)}${milliseconds3 ? `.${pad3(milliseconds3, 3)}` : ``}` : ``}Z` : ``}`;
}
function formatYear3(year) {
  return year < 0 ? `-${pad3(-year, 6)}` : year > 9999 ? `+${pad3(year, 6)}` : pad3(year, 4);
}
function pad3(value, width2) {
  return `${value}`.padStart(width2, "0");
}

// ../inputs/src/Table.js
var _id3 = -1;
var Table2 = class extends Input {
  /**
   * Create a new Table instance.
   * @param {object} options Options object
   * @param {HTMLElement} [options.element] The parent DOM element in which to
   *  place the table element. If undefined, a new `div` element is created.
   * @param {Selection} [options.filterBy] A selection to filter the database
   *  table indicated by the *from* option.
   * @param {Selection} [options.as] The output selection. A selection
   *  clause is added for the currently selected table row.
   * @param {{ [name: string]: 'left' | 'right' | 'center' }} [options.align]
   *  An object that maps column names to horiztonal text alignment values. If
   *  unspecified, alignment is determined based on the column data type.
   * @param {{ [name: string]: (value: any) => string }} [options.format] An
   *  object that maps column names to format functions to use for that
   *  column's data. Each format function takes a value as input and generates
   *  formatted text to show in the table.
   * @param {string} [options.from] The name of a database table to use as a data
   *  source for this widget. Used in conjunction with the *columns* option.
   * @param {string[]} [options.columns] The name of database columns to include
   *  in the table component. If unspecified, all columns are included.
   *  Used in conjunction with the *from* option.
   * @param {number | { [name: string]: number }} [options.width] If a number,
   *  sets the desired width of the table, in pixels. If an object, is used to
   *  set explicit pixel widts for each named column included in the object.
   * @param {number} [options.maxWidth] The maximum width of the table, in pixels.
   * @param {number} [options.height] The desired height of the table, in pixels.
   * @param {number} [options.rowBatch] The number of rows to request per query
   *  batch. The batch size will be used to prefetch data beyond the currently
   *  visible range.
   */
  constructor({
    element,
    filterBy,
    from: from2,
    columns = ["*"],
    align: align3 = {},
    format: format3,
    width: width2,
    maxWidth,
    height: height2 = 500,
    rowBatch = 100,
    as
  } = {}) {
    super(filterBy, element, null);
    this.id = `table-${++_id3}`;
    this.element.setAttribute("id", this.id);
    this.from = from2;
    this.columns = columns;
    this.format = format3;
    this.align = align3;
    this.widths = typeof width2 === "object" ? width2 : {};
    if (isParam(from2)) {
      from2.addEventListener("value", () => this.initialize());
    }
    this.offset = 0;
    this.limit = +rowBatch;
    this.isPending = false;
    this.selection = as;
    this.currentRow = -1;
    this.sortHeader = null;
    this.sortColumn = null;
    this.sortDesc = false;
    if (typeof width2 === "number") this.element.style.width = `${width2}px`;
    if (maxWidth) this.element.style.maxWidth = `${maxWidth}px`;
    this.element.style.maxHeight = `${height2}px`;
    this.element.style.overflow = "auto";
    let prevScrollTop = -1;
    this.element.addEventListener("scroll", (evt) => {
      const { isPending, loaded } = this;
      const { scrollHeight, scrollTop, clientHeight } = evt.target;
      const back = scrollTop < prevScrollTop;
      prevScrollTop = scrollTop;
      if (back || isPending || loaded) return;
      if (scrollHeight - scrollTop < 2 * clientHeight) {
        this.isPending = true;
        this.requestData(this.offset + this.limit);
      }
    });
    this.tbl = document.createElement("table");
    this.element.appendChild(this.tbl);
    this.head = document.createElement("thead");
    this.tbl.appendChild(this.head);
    this.body = document.createElement("tbody");
    this.tbl.appendChild(this.body);
    if (this.selection) {
      this.body.addEventListener("pointerover", (evt) => {
        const row = resolveRow(evt.target);
        if (row > -1 && row !== this.currentRow) {
          this.currentRow = row;
          this.selection.update(this.clause([row]));
        }
      });
      this.body.addEventListener("pointerleave", () => {
        this.currentRow = -1;
        this.selection.update(this.clause());
      });
    }
    this.style = document.createElement("style");
    this.element.appendChild(this.style);
  }
  sourceTable() {
    return isParam(this.from) ? this.from.value : this.from;
  }
  clause(rows = []) {
    const { data, limit, schema } = this;
    const fields = schema.map((s2) => s2.column);
    const values2 = rows.map((row) => {
      const { columns } = data[~~(row / limit)];
      return fields.map((f) => columns[f][row % limit]);
    });
    return clausePoints(fields, values2, { source: this });
  }
  requestData(offset2 = 0) {
    this.offset = offset2;
    const query = this.query(this.filterBy?.predicate(this));
    this.requestQuery(query);
    coordinator().prefetch(query.clone().offset(offset2 + this.limit));
  }
  async prepare() {
    const table3 = this.sourceTable();
    const fields = this.columns.map((column3) => ({ column: column3, table: table3 }));
    const schema = await queryFieldInfo(this.coordinator, fields);
    this.schema = schema;
    const thead = this.head;
    thead.innerHTML = "";
    const tr = document.createElement("tr");
    for (const { column: column3 } of schema) {
      const th = document.createElement("th");
      th.addEventListener("click", (evt) => this.sort(evt, column3));
      th.appendChild(document.createElement("span"));
      th.appendChild(document.createTextNode(column3));
      tr.appendChild(th);
    }
    thead.appendChild(tr);
    this.formats = formatof(this.format, schema);
    this.style.innerText = tableCSS(
      this.id,
      alignof(this.align, schema),
      widthof(this.widths, schema)
    );
  }
  /**
   * @param {FilterExpr} filter
   */
  query(filter3 = []) {
    const { limit, offset: offset2, schema, sortColumn, sortDesc } = this;
    return Query.from(this.sourceTable()).select(schema.map((s2) => s2.column)).where(filter3).orderby(sortColumn ? sortDesc ? desc(sortColumn) : sortColumn : []).limit(limit).offset(offset2);
  }
  queryResult(data) {
    if (!this.isPending) {
      this.loaded = false;
      this.data = [];
      this.body.replaceChildren();
      this.offset = 0;
    }
    this.data.push(toDataColumns(data));
    return this;
  }
  update() {
    const { body, formats, data, schema, limit } = this;
    const nf = schema.length;
    const n = data.length - 1;
    const rowCount = limit * n;
    const { numRows, columns } = data[n];
    const cols = schema.map((s2) => columns[s2.column]);
    for (let i = 0; i < numRows; ++i) {
      const tr = document.createElement("tr");
      Object.assign(tr, { __row__: rowCount + i });
      for (let j = 0; j < nf; ++j) {
        const value = cols[j][i];
        const td = document.createElement("td");
        td.innerText = value == null ? "" : formats[j](value);
        tr.appendChild(td);
      }
      body.appendChild(tr);
    }
    if (numRows < limit) {
      this.loaded = true;
    }
    this.isPending = false;
    return this;
  }
  activate() {
    if (isSelection(this.selection)) {
      this.selection.activate(this.clause([]));
    }
  }
  sort(event, column3) {
    if (column3 === this.sortColumn) {
      this.sortDesc = !this.sortDesc;
    } else {
      this.sortColumn = column3;
      this.sortDesc = false;
    }
    const th = event.currentTarget;
    const currentHeader = this.sortHeader;
    if (currentHeader === th && event.metaKey) {
      currentHeader.firstChild.textContent = "";
      this.sortHeader = null;
      this.sortColumn = null;
    } else {
      if (currentHeader) currentHeader.firstChild.textContent = "";
      this.sortHeader = th;
      th.firstChild.textContent = this.sortDesc ? "\u25BE" : "\u25B4";
    }
    this.requestData();
  }
};
function resolveRow(element) {
  const p = element.parentElement;
  return Object.hasOwn(p, "__row__") ? +p.__row__ : -1;
}
function formatof(base = {}, schema, locale3) {
  return schema.map(({ column: column3, type: type2 }) => {
    if (column3 in base) {
      return base[column3];
    } else {
      switch (type2) {
        case "number":
          return formatLocaleNumber(locale3);
        case "date":
          return formatDate;
        default:
          return formatLocaleAuto(locale3);
      }
    }
  });
}
function alignof(base = {}, schema) {
  return schema.map(({ column: column3, type: type2 }) => {
    if (column3 in base) {
      return base[column3];
    } else if (type2 === "number") {
      return "right";
    } else {
      return "left";
    }
  });
}
function widthof(base = {}, schema) {
  return schema.map(({ column: column3 }) => base[column3]);
}
function tableCSS(id2, aligns, widths) {
  const styles2 = [];
  aligns.forEach((a2, i) => {
    const w = +widths[i];
    if (a2 !== "left" || w) {
      const align3 = a2 !== "left" ? `text-align:${a2};` : "";
      const width2 = w ? `width:${w}px;max-width:${w}px;` : "";
      styles2.push(`#${id2} tr>:nth-child(${i + 1}) {${align3}${width2}}`);
    }
  });
  return styles2.join(" ");
}

// ../vgplot/src/connect.js
function connect(ctx, ...clients) {
  const coord = ctx?.context?.coordinator ?? coordinator();
  for (const client of clients) {
    coord.connect(client);
  }
}

// ../vgplot/src/inputs.js
function input2(ctx, InputClass, options) {
  const input3 = new InputClass(options);
  connect(ctx, input3);
  return input3.element;
}
function menu2(options) {
  return input2(this, Menu, options);
}
function search2(options) {
  return input2(this, Search, options);
}
function slider2(options) {
  return input2(this, Slider, options);
}
function table2(options) {
  return input2(this, Table2, options);
}

// ../vgplot/src/layout/concat.js
function concat2({ direction = "vertical", wrap: wrap3 = false }, children2) {
  const div2 = document.createElement("div");
  div2.style.display = "flex";
  div2.style.flexDirection = direction === "vertical" ? "column" : "row";
  div2.style.flexWrap = !wrap3 ? "nowrap" : wrap3 === true ? "wrap" : wrap3;
  div2.style.justifyContent = "flex-start";
  div2.style.alignItems = "flex-start";
  children2.forEach((child) => div2.appendChild(child));
  Object.assign(div2, { value: { element: div2 } });
  return div2;
}
function vconcat(...plots) {
  return concat2({ direction: "vertical" }, plots.flat());
}
function hconcat(...plots) {
  return concat2({ direction: "horizontal" }, plots.flat());
}

// ../vgplot/src/layout/space.js
function space({ dim = "width", size = 10 }) {
  const span = document.createElement("span");
  span.style.display = "inline-block";
  span.style[dim] = Number.isNaN(+size) ? size : `${size}px`;
  return Object.assign(span, { value: { element: span } });
}
function vspace(size) {
  return space({ dim: "height", size });
}
function hspace(size) {
  return space({ dim: "width", size });
}

// ../vgplot/src/plot/attributes.js
var attributes_exports = {};
__export(attributes_exports, {
  align: () => align2,
  ariaDescription: () => ariaDescription,
  ariaLabel: () => ariaLabel,
  aspectRatio: () => aspectRatio,
  axis: () => axis2,
  clip: () => clip,
  colorBase: () => colorBase,
  colorClamp: () => colorClamp,
  colorConstant: () => colorConstant2,
  colorDomain: () => colorDomain,
  colorExponent: () => colorExponent,
  colorInterpolate: () => colorInterpolate,
  colorLabel: () => colorLabel,
  colorN: () => colorN,
  colorNice: () => colorNice,
  colorPercent: () => colorPercent,
  colorPivot: () => colorPivot,
  colorRange: () => colorRange,
  colorReverse: () => colorReverse,
  colorScale: () => colorScale2,
  colorScheme: () => colorScheme2,
  colorSymmetric: () => colorSymmetric,
  colorTickFormat: () => colorTickFormat,
  colorZero: () => colorZero,
  facetGrid: () => facetGrid,
  facetLabel: () => facetLabel,
  facetMargin: () => facetMargin,
  facetMarginBottom: () => facetMarginBottom,
  facetMarginLeft: () => facetMarginLeft,
  facetMarginRight: () => facetMarginRight,
  facetMarginTop: () => facetMarginTop,
  fxAlign: () => fxAlign,
  fxAriaDescription: () => fxAriaDescription,
  fxAriaLabel: () => fxAriaLabel,
  fxAxis: () => fxAxis,
  fxDomain: () => fxDomain,
  fxFontVariant: () => fxFontVariant,
  fxGrid: () => fxGrid,
  fxInset: () => fxInset,
  fxInsetLeft: () => fxInsetLeft,
  fxInsetRight: () => fxInsetRight,
  fxLabel: () => fxLabel,
  fxLabelAnchor: () => fxLabelAnchor,
  fxLabelOffset: () => fxLabelOffset,
  fxLine: () => fxLine,
  fxPadding: () => fxPadding,
  fxPaddingInner: () => fxPaddingInner,
  fxPaddingOuter: () => fxPaddingOuter,
  fxRange: () => fxRange,
  fxReverse: () => fxReverse,
  fxRound: () => fxRound,
  fxTickFormat: () => fxTickFormat,
  fxTickPadding: () => fxTickPadding,
  fxTickRotate: () => fxTickRotate,
  fxTickSize: () => fxTickSize,
  fxTickSpacing: () => fxTickSpacing,
  fxTicks: () => fxTicks,
  fyAlign: () => fyAlign,
  fyAriaDescription: () => fyAriaDescription,
  fyAriaLabel: () => fyAriaLabel,
  fyAxis: () => fyAxis,
  fyDomain: () => fyDomain,
  fyFontVariant: () => fyFontVariant,
  fyGrid: () => fyGrid,
  fyInset: () => fyInset,
  fyInsetBottom: () => fyInsetBottom,
  fyInsetTop: () => fyInsetTop,
  fyLabel: () => fyLabel,
  fyLabelAnchor: () => fyLabelAnchor,
  fyLabelOffset: () => fyLabelOffset,
  fyLine: () => fyLine,
  fyPadding: () => fyPadding,
  fyPaddingInner: () => fyPaddingInner,
  fyPaddingOuter: () => fyPaddingOuter,
  fyRange: () => fyRange,
  fyReverse: () => fyReverse,
  fyRound: () => fyRound,
  fyTickFormat: () => fyTickFormat,
  fyTickPadding: () => fyTickPadding,
  fyTickRotate: () => fyTickRotate,
  fyTickSize: () => fyTickSize,
  fyTickSpacing: () => fyTickSpacing,
  fyTicks: () => fyTicks,
  grid: () => grid,
  height: () => height,
  inset: () => inset,
  lengthBase: () => lengthBase,
  lengthClamp: () => lengthClamp,
  lengthConstant: () => lengthConstant,
  lengthDomain: () => lengthDomain,
  lengthExponent: () => lengthExponent,
  lengthNice: () => lengthNice,
  lengthPercent: () => lengthPercent,
  lengthRange: () => lengthRange,
  lengthScale: () => lengthScale,
  lengthZero: () => lengthZero,
  margin: () => margin,
  marginBottom: () => marginBottom,
  marginLeft: () => marginLeft,
  marginRight: () => marginRight,
  marginTop: () => marginTop,
  margins: () => margins,
  name: () => name,
  opacityBase: () => opacityBase,
  opacityClamp: () => opacityClamp,
  opacityConstant: () => opacityConstant,
  opacityDomain: () => opacityDomain,
  opacityExponent: () => opacityExponent,
  opacityLabel: () => opacityLabel,
  opacityNice: () => opacityNice,
  opacityPercent: () => opacityPercent,
  opacityRange: () => opacityRange,
  opacityReverse: () => opacityReverse,
  opacityScale: () => opacityScale,
  opacityTickFormat: () => opacityTickFormat,
  opacityZero: () => opacityZero,
  padding: () => padding,
  projectionClip: () => projectionClip,
  projectionDomain: () => projectionDomain,
  projectionInset: () => projectionInset,
  projectionInsetBottom: () => projectionInsetBottom,
  projectionInsetLeft: () => projectionInsetLeft,
  projectionInsetRight: () => projectionInsetRight,
  projectionInsetTop: () => projectionInsetTop,
  projectionParallels: () => projectionParallels,
  projectionPrecision: () => projectionPrecision,
  projectionRotate: () => projectionRotate,
  projectionType: () => projectionType,
  rBase: () => rBase,
  rClamp: () => rClamp,
  rConstant: () => rConstant,
  rDomain: () => rDomain,
  rExponent: () => rExponent,
  rLabel: () => rLabel,
  rNice: () => rNice,
  rPercent: () => rPercent,
  rRange: () => rRange,
  rScale: () => rScale,
  rZero: () => rZero,
  style: () => style,
  symbolDomain: () => symbolDomain,
  symbolRange: () => symbolRange,
  symbolScale: () => symbolScale,
  width: () => width,
  xAlign: () => xAlign,
  xAriaDescription: () => xAriaDescription,
  xAriaLabel: () => xAriaLabel,
  xAxis: () => xAxis,
  xBase: () => xBase,
  xClamp: () => xClamp,
  xConstant: () => xConstant,
  xDomain: () => xDomain,
  xExponent: () => xExponent,
  xFontVariant: () => xFontVariant,
  xGrid: () => xGrid,
  xInset: () => xInset,
  xInsetLeft: () => xInsetLeft,
  xInsetRight: () => xInsetRight,
  xLabel: () => xLabel,
  xLabelAnchor: () => xLabelAnchor,
  xLabelArrow: () => xLabelArrow,
  xLabelOffset: () => xLabelOffset,
  xLine: () => xLine,
  xNice: () => xNice,
  xPadding: () => xPadding,
  xPaddingInner: () => xPaddingInner,
  xPaddingOuter: () => xPaddingOuter,
  xPercent: () => xPercent,
  xRange: () => xRange,
  xReverse: () => xReverse,
  xRound: () => xRound,
  xScale: () => xScale,
  xTickFormat: () => xTickFormat,
  xTickPadding: () => xTickPadding,
  xTickRotate: () => xTickRotate,
  xTickSize: () => xTickSize,
  xTickSpacing: () => xTickSpacing,
  xTicks: () => xTicks,
  xZero: () => xZero,
  xyDomain: () => xyDomain,
  yAlign: () => yAlign,
  yAriaDescription: () => yAriaDescription,
  yAriaLabel: () => yAriaLabel,
  yAxis: () => yAxis,
  yBase: () => yBase,
  yClamp: () => yClamp,
  yConstant: () => yConstant,
  yDomain: () => yDomain,
  yExponent: () => yExponent,
  yFontVariant: () => yFontVariant,
  yGrid: () => yGrid,
  yInset: () => yInset,
  yInsetBottom: () => yInsetBottom,
  yInsetTop: () => yInsetTop,
  yLabel: () => yLabel,
  yLabelAnchor: () => yLabelAnchor,
  yLabelArrow: () => yLabelArrow,
  yLabelOffset: () => yLabelOffset,
  yLine: () => yLine,
  yNice: () => yNice,
  yPadding: () => yPadding,
  yPaddingInner: () => yPaddingInner,
  yPaddingOuter: () => yPaddingOuter,
  yPercent: () => yPercent,
  yRange: () => yRange,
  yReverse: () => yReverse,
  yRound: () => yRound,
  yScale: () => yScale,
  yTickFormat: () => yTickFormat,
  yTickPadding: () => yTickPadding,
  yTickRotate: () => yTickRotate,
  yTickSize: () => yTickSize,
  yTickSpacing: () => yTickSpacing,
  yTicks: () => yTicks,
  yZero: () => yZero
});

// ../vgplot/src/plot/named-plots.js
var NamedPlots = class extends Map {
  request(name2, callback) {
    if (this.has(name2)) {
      callback(this.get(name2));
    } else {
      const waiting = this.waiting || (this.waiting = /* @__PURE__ */ new Map());
      const list3 = waiting.get(name2) || [];
      waiting.set(name2, list3.concat(callback));
    }
  }
  set(name2, plot3) {
    if (this.has(name2)) {
      console.warn(`Overwriting named plot "${name2}".`);
    }
    const { waiting } = this;
    if (waiting?.has(name2)) {
      waiting.get(name2).forEach((fn2) => fn2(plot3));
      waiting.delete(name2);
    }
    return super.set(name2, plot3);
  }
  clear() {
    this.waiting?.clear();
    return super.clear();
  }
};
var namedPlots = new NamedPlots();
function requestNamedPlot(ctx, name2, callback) {
  const map5 = ctx?.context?.namedPlots ?? namedPlots;
  map5.request(name2, callback);
}
function setNamedPlot(ctx, name2, plot3) {
  const map5 = ctx?.context?.namedPlots ?? namedPlots;
  map5.set(name2, plot3);
}

// ../vgplot/src/plot/attributes.js
function name(name2) {
  return (plot3) => setNamedPlot(this, name2, plot3);
}
function setAttribute(plot3, name2, value) {
  if (isParam(value)) {
    value.addEventListener("value", (value2) => {
      plot3.setAttribute(name2, value2);
      plot3.update();
    });
    if (value.value !== void 0) {
      plot3.setAttribute(name2, value.value);
    }
  } else {
    plot3.setAttribute(name2, value);
  }
}
function attribute(name2, value) {
  return (plot3) => {
    setAttribute(plot3, name2, value);
  };
}
function attributes(values2) {
  return (plot3) => {
    for (const [name2, value] of Object.entries(values2)) {
      setAttribute(plot3, name2, value);
    }
  };
}
function margins(object) {
  const { top: top2, bottom: bottom2, left: left2, right: right2 } = object;
  const attr = {};
  if (top2 !== void 0) attr.marginTop = top2;
  if (bottom2 !== void 0) attr.marginBottom = bottom2;
  if (left2 !== void 0) attr.marginLeft = left2;
  if (right2 !== void 0) attr.marginRight = right2;
  return attributes(attr);
}
function margin(value) {
  return attributes({
    marginTop: value,
    marginBottom: value,
    marginLeft: value,
    marginRight: value
  });
}
function xyDomain(value) {
  return attributes({ xDomain: value, yDomain: value });
}
var attrf = (name2) => (value) => attribute(name2, value);
var style = attrf("style");
var width = attrf("width");
var height = attrf("height");
var marginLeft = attrf("marginLeft");
var marginRight = attrf("marginRight");
var marginTop = attrf("marginTop");
var marginBottom = attrf("marginBottom");
var align2 = attrf("align");
var aspectRatio = attrf("aspectRatio");
var axis2 = attrf("axis");
var inset = attrf("inset");
var grid = attrf("grid");
var clip = attrf("clip");
var padding = attrf("padding");
var ariaLabel = attrf("ariaLabel");
var ariaDescription = attrf("ariaDescription");
var xScale = attrf("xScale");
var xDomain = attrf("xDomain");
var xRange = attrf("xRange");
var xNice = attrf("xNice");
var xInset = attrf("xInset");
var xInsetLeft = attrf("xInsetLeft");
var xInsetRight = attrf("xInsetRight");
var xClamp = attrf("xClamp");
var xRound = attrf("xRound");
var xAlign = attrf("xAlign");
var xPadding = attrf("xPadding");
var xPaddingInner = attrf("xPaddingInner");
var xPaddingOuter = attrf("xPaddingOuter");
var xAxis = attrf("xAxis");
var xTicks = attrf("xTicks");
var xTickSize = attrf("xTickSize");
var xTickSpacing = attrf("xTickSpacing");
var xTickPadding = attrf("xTickPadding");
var xTickFormat = attrf("xTickFormat");
var xTickRotate = attrf("xTickRotate");
var xGrid = attrf("xGrid");
var xLine = attrf("xLine");
var xLabel = attrf("xLabel");
var xLabelAnchor = attrf("xLabelAnchor");
var xLabelArrow = attrf("xLabelArrow");
var xLabelOffset = attrf("xLabelOffset");
var xFontVariant = attrf("xFontVariant");
var xAriaLabel = attrf("xAriaLabel");
var xAriaDescription = attrf("xAriaDescription");
var xPercent = attrf("xPercent");
var xReverse = attrf("xReverse");
var xZero = attrf("xZero");
var xBase = attrf("xBase");
var xExponent = attrf("xExponent");
var xConstant = attrf("xConstant");
var yScale = attrf("yScale");
var yDomain = attrf("yDomain");
var yRange = attrf("yRange");
var yNice = attrf("yNice");
var yInset = attrf("yInset");
var yInsetTop = attrf("yInsetTop");
var yInsetBottom = attrf("yInsetBottom");
var yClamp = attrf("yClamp");
var yRound = attrf("yRound");
var yAlign = attrf("yAlign");
var yPadding = attrf("yPadding");
var yPaddingInner = attrf("yPaddingInner");
var yPaddingOuter = attrf("yPaddingOuter");
var yAxis = attrf("yAxis");
var yTicks = attrf("yTicks");
var yTickSize = attrf("yTickSize");
var yTickSpacing = attrf("yTickSpacing");
var yTickPadding = attrf("yTickPadding");
var yTickFormat = attrf("yTickFormat");
var yTickRotate = attrf("yTickRotate");
var yGrid = attrf("yGrid");
var yLine = attrf("yLine");
var yLabel = attrf("yLabel");
var yLabelAnchor = attrf("yLabelAnchor");
var yLabelArrow = attrf("yLabelArrow");
var yLabelOffset = attrf("yLabelOffset");
var yFontVariant = attrf("yFontVariant");
var yAriaLabel = attrf("yAriaLabel");
var yAriaDescription = attrf("yAriaDescription");
var yPercent = attrf("yPercent");
var yReverse = attrf("yReverse");
var yZero = attrf("yZero");
var yBase = attrf("yBase");
var yExponent = attrf("yExponent");
var yConstant = attrf("yConstant");
var facetMargin = attrf("facetMargin");
var facetMarginTop = attrf("facetMarginTop");
var facetMarginBottom = attrf("facetMarginBottom");
var facetMarginLeft = attrf("facetMarginLeft");
var facetMarginRight = attrf("facetMarginRight");
var facetGrid = attrf("facetGrid");
var facetLabel = attrf("facetLabel");
var fxDomain = attrf("fxDomain");
var fxRange = attrf("fxRange");
var fxInset = attrf("fxInset");
var fxInsetLeft = attrf("fxInsetLeft");
var fxInsetRight = attrf("fxInsetRight");
var fxRound = attrf("fxRound");
var fxAlign = attrf("fxAlign");
var fxPadding = attrf("fxPadding");
var fxPaddingInner = attrf("fxPaddingInner");
var fxPaddingOuter = attrf("fxPaddingOuter");
var fxAxis = attrf("fxAxis");
var fxTicks = attrf("fxTicks");
var fxTickSize = attrf("fxTickSize");
var fxTickSpacing = attrf("fxTickSpacing");
var fxTickPadding = attrf("fxTickPadding");
var fxTickFormat = attrf("fxTickFormat");
var fxTickRotate = attrf("fxTickRotate");
var fxGrid = attrf("fxGrid");
var fxLine = attrf("fxLine");
var fxLabel = attrf("fxLabel");
var fxLabelAnchor = attrf("fxLabelAnchor");
var fxLabelOffset = attrf("fxLabelOffset");
var fxFontVariant = attrf("fxFontVariant");
var fxAriaLabel = attrf("fxAriaLabel");
var fxAriaDescription = attrf("fxAriaDescription");
var fxReverse = attrf("fxReverse");
var fyDomain = attrf("fyDomain");
var fyRange = attrf("fyRange");
var fyInset = attrf("fyInset");
var fyInsetTop = attrf("fyInsetTop");
var fyInsetBottom = attrf("fyInsetBottom");
var fyRound = attrf("fyRound");
var fyAlign = attrf("fyAlign");
var fyPadding = attrf("fyPadding");
var fyPaddingInner = attrf("fyPaddingInner");
var fyPaddingOuter = attrf("fyPaddingOuter");
var fyAxis = attrf("fyAxis");
var fyTicks = attrf("fyTicks");
var fyTickSize = attrf("fyTickSize");
var fyTickSpacing = attrf("fyTickSpacing");
var fyTickPadding = attrf("fyTickPadding");
var fyTickFormat = attrf("fyTickFormat");
var fyTickRotate = attrf("fyTickRotate");
var fyGrid = attrf("fyGrid");
var fyLine = attrf("fyLine");
var fyLabel = attrf("fyLabel");
var fyLabelAnchor = attrf("fyLabelAnchor");
var fyLabelOffset = attrf("fyLabelOffset");
var fyFontVariant = attrf("fyFontVariant");
var fyAriaLabel = attrf("fyAriaLabel");
var fyAriaDescription = attrf("fyAriaDescription");
var fyReverse = attrf("fyReverse");
var colorScale2 = attrf("colorScale");
var colorDomain = attrf("colorDomain");
var colorRange = attrf("colorRange");
var colorClamp = attrf("colorClamp");
var colorN = attrf("colorN");
var colorNice = attrf("colorNice");
var colorScheme2 = attrf("colorScheme");
var colorInterpolate = attrf("colorInterpolate");
var colorPivot = attrf("colorPivot");
var colorSymmetric = attrf("colorSymmetric");
var colorLabel = attrf("colorLabel");
var colorPercent = attrf("colorPercent");
var colorReverse = attrf("colorReverse");
var colorZero = attrf("colorZero");
var colorTickFormat = attrf("colorTickFormat");
var colorBase = attrf("colorBase");
var colorExponent = attrf("colorExponent");
var colorConstant2 = attrf("colorConstant");
var opacityScale = attrf("opacityScale");
var opacityDomain = attrf("opacityDomain");
var opacityRange = attrf("opacityRange");
var opacityClamp = attrf("opacityClamp");
var opacityNice = attrf("opacityNice");
var opacityLabel = attrf("opacityLabel");
var opacityPercent = attrf("opacityPercent");
var opacityReverse = attrf("opacityReverse");
var opacityZero = attrf("opacityZero");
var opacityTickFormat = attrf("opacityTickFormat");
var opacityBase = attrf("opacityBase");
var opacityExponent = attrf("opacityExponent");
var opacityConstant = attrf("opacityConstant");
var symbolScale = attrf("symbolScale");
var symbolDomain = attrf("symbolDomain");
var symbolRange = attrf("symbolRange");
var rScale = attrf("rScale");
var rDomain = attrf("rDomain");
var rRange = attrf("rRange");
var rClamp = attrf("rClamp");
var rNice = attrf("rNice");
var rLabel = attrf("rLabel");
var rPercent = attrf("rPercent");
var rZero = attrf("rZero");
var rBase = attrf("rBase");
var rExponent = attrf("rExponent");
var rConstant = attrf("rConstant");
var lengthScale = attrf("lengthScale");
var lengthDomain = attrf("lengthDomain");
var lengthRange = attrf("lengthRange");
var lengthClamp = attrf("lengthClamp");
var lengthNice = attrf("lengthNice");
var lengthPercent = attrf("lengthPercent");
var lengthZero = attrf("lengthZero");
var lengthBase = attrf("lengthBase");
var lengthExponent = attrf("lengthExponent");
var lengthConstant = attrf("lengthConstant");
var projectionType = attrf("projectionType");
var projectionParallels = attrf("projectionParallels");
var projectionPrecision = attrf("projectionPrecision");
var projectionRotate = attrf("projectionRotate");
var projectionDomain = attrf("projectionDomain");
var projectionInset = attrf("projectionInset");
var projectionInsetLeft = attrf("projectionInsetLeft");
var projectionInsetRight = attrf("projectionInsetRight");
var projectionInsetTop = attrf("projectionInsetTop");
var projectionInsetBottom = attrf("projectionInsetBottom");
var projectionClip = attrf("projectionClip");

// ../vgplot/src/plot/data.js
function from(table3, options = void 0) {
  return { table: table3, options };
}

// ../vgplot/src/plot/marks.js
var marks_exports = {};
__export(marks_exports, {
  area: () => area2,
  areaX: () => areaX2,
  areaY: () => areaY2,
  arrow: () => arrow2,
  axisFx: () => axisFx2,
  axisFy: () => axisFy2,
  axisX: () => axisX2,
  axisY: () => axisY2,
  barX: () => barX2,
  barY: () => barY2,
  cell: () => cell2,
  cellX: () => cellX2,
  cellY: () => cellY2,
  circle: () => circle2,
  contour: () => contour2,
  delaunayLink: () => delaunayLink2,
  delaunayMesh: () => delaunayMesh2,
  denseLine: () => denseLine,
  density: () => density2,
  densityX: () => densityX,
  densityY: () => densityY,
  dot: () => dot2,
  dotX: () => dotX2,
  dotY: () => dotY2,
  errorbarX: () => errorbarX,
  errorbarY: () => errorbarY,
  frame: () => frame3,
  geo: () => geo2,
  graticule: () => graticule3,
  gridFx: () => gridFx2,
  gridFy: () => gridFy2,
  gridX: () => gridX2,
  gridY: () => gridY2,
  heatmap: () => heatmap,
  hexagon: () => hexagon2,
  hexbin: () => hexbin2,
  hexgrid: () => hexgrid2,
  hull: () => hull2,
  image: () => image2,
  line: () => line2,
  lineX: () => lineX2,
  lineY: () => lineY2,
  link: () => link3,
  raster: () => raster2,
  rasterTile: () => rasterTile,
  rect: () => rect2,
  rectX: () => rectX2,
  rectY: () => rectY2,
  regressionY: () => regressionY,
  ruleX: () => ruleX2,
  ruleY: () => ruleY2,
  sphere: () => sphere3,
  spike: () => spike2,
  text: () => text2,
  textX: () => textX2,
  textY: () => textY2,
  tickX: () => tickX2,
  tickY: () => tickY2,
  vector: () => vector2,
  vectorX: () => vectorX2,
  vectorY: () => vectorY2,
  voronoi: () => voronoi2,
  voronoiMesh: () => voronoiMesh2,
  waffleX: () => waffleX2,
  waffleY: () => waffleY2
});
var decorators = /* @__PURE__ */ new Set([
  "frame",
  "axisX",
  "axisY",
  "axisFx",
  "axisFy",
  "gridX",
  "gridY",
  "gridFx",
  "gridFy",
  "hexgrid",
  "graticule",
  "sphere"
]);
function mark(type2, data, channels = {}) {
  if (arguments.length === 2 && !Array.isArray(data)) {
    channels = data;
    data = decorators.has(type2) ? null : [{}];
  }
  const MarkClass = type2.startsWith("area") || type2.startsWith("line") ? ConnectedMark : Mark2;
  return explicitType(MarkClass, type2, data, channels);
}
function explicitType(MarkClass, type2, data, channels) {
  return (plot3) => {
    plot3.addMark(new MarkClass(type2, data, channels));
  };
}
function implicitType(MarkClass, data, channels) {
  return (plot3) => {
    plot3.addMark(new MarkClass(data, channels));
  };
}
var area2 = (...args) => mark("area", ...args);
var areaX2 = (...args) => mark("areaX", ...args);
var areaY2 = (...args) => mark("areaY", ...args);
var line2 = (...args) => mark("line", ...args);
var lineX2 = (...args) => mark("lineX", ...args);
var lineY2 = (...args) => mark("lineY", ...args);
var barX2 = (...args) => mark("barX", ...args);
var barY2 = (...args) => mark("barY", ...args);
var cell2 = (...args) => mark("cell", ...args);
var cellX2 = (...args) => mark("cellX", ...args);
var cellY2 = (...args) => mark("cellY", ...args);
var rect2 = (...args) => mark("rect", ...args);
var rectX2 = (...args) => mark("rectX", ...args);
var rectY2 = (...args) => mark("rectY", ...args);
var dot2 = (...args) => mark("dot", ...args);
var dotX2 = (...args) => mark("dotX", ...args);
var dotY2 = (...args) => mark("dotY", ...args);
var circle2 = (...args) => mark("circle", ...args);
var hexagon2 = (...args) => mark("hexagon", ...args);
var text2 = (...args) => mark("text", ...args);
var textX2 = (...args) => mark("textX", ...args);
var textY2 = (...args) => mark("textY", ...args);
var ruleX2 = (...args) => mark("ruleX", ...args);
var ruleY2 = (...args) => mark("ruleY", ...args);
var tickX2 = (...args) => mark("tickX", ...args);
var tickY2 = (...args) => mark("tickY", ...args);
var vector2 = (...args) => mark("vector", ...args);
var vectorX2 = (...args) => mark("vectoX", ...args);
var vectorY2 = (...args) => mark("vectorY", ...args);
var spike2 = (...args) => mark("spike", ...args);
var image2 = (...args) => mark("image", ...args);
var densityX = (...args) => explicitType(Density1DMark, "areaX", ...args);
var densityY = (...args) => explicitType(Density1DMark, "areaY", ...args);
var density2 = (...args) => implicitType(Density2DMark, ...args);
var denseLine = (...args) => implicitType(DenseLineMark, ...args);
var contour2 = (...args) => implicitType(ContourMark, ...args);
var heatmap = (...args) => implicitType(HeatmapMark, ...args);
var raster2 = (...args) => implicitType(RasterMark, ...args);
var rasterTile = (...args) => implicitType(RasterTileMark, ...args);
var hexbin2 = (...args) => implicitType(HexbinMark, ...args);
var hexgrid2 = (...args) => mark("hexgrid", ...args);
var regressionY = (...args) => implicitType(RegressionMark, ...args);
var errorbarX = (...args) => explicitType(ErrorBarMark, "ruleY", ...args);
var errorbarY = (...args) => explicitType(ErrorBarMark, "ruleX", ...args);
var voronoi2 = (...args) => mark("voronoi", ...args);
var voronoiMesh2 = (...args) => mark("voronoiMesh", ...args);
var delaunayLink2 = (...args) => mark("delaunayLink", ...args);
var delaunayMesh2 = (...args) => mark("delaunayMesh", ...args);
var hull2 = (...args) => mark("hull", ...args);
var arrow2 = (...args) => mark("arrow", ...args);
var link3 = (...args) => mark("link", ...args);
var frame3 = (...args) => mark("frame", ...args);
var axisX2 = (...args) => mark("axisX", ...args);
var axisY2 = (...args) => mark("axisY", ...args);
var axisFx2 = (...args) => mark("axisFx", ...args);
var axisFy2 = (...args) => mark("axisFy", ...args);
var gridX2 = (...args) => mark("gridX", ...args);
var gridY2 = (...args) => mark("gridY", ...args);
var gridFx2 = (...args) => mark("gridFx", ...args);
var gridFy2 = (...args) => mark("gridFy", ...args);
var geo2 = (...args) => implicitType(GeoMark, ...args);
var sphere3 = (...args) => mark("sphere", ...args);
var graticule3 = (...args) => mark("graticule", ...args);
var waffleX2 = (...args) => mark("waffleX", ...args);
var waffleY2 = (...args) => mark("waffleY", ...args);

// ../vgplot/src/plot/interactors.js
var interactors_exports = {};
__export(interactors_exports, {
  highlight: () => highlight,
  intervalX: () => intervalX,
  intervalXY: () => intervalXY,
  intervalY: () => intervalY,
  nearest: () => nearest,
  nearestX: () => nearestX,
  nearestY: () => nearestY,
  pan: () => pan,
  panX: () => panX,
  panY: () => panY,
  panZoom: () => panZoom,
  panZoomX: () => panZoomX,
  panZoomY: () => panZoomY,
  region: () => region,
  toggle: () => toggle,
  toggleColor: () => toggleColor,
  toggleX: () => toggleX,
  toggleY: () => toggleY,
  toggleZ: () => toggleZ
});
function interactor(InteractorClass, options) {
  return (plot3) => {
    const mark2 = plot3.marks[plot3.marks.length - 1];
    plot3.addInteractor(new InteractorClass(mark2, options));
  };
}
function highlight({ by, ...channels }) {
  return interactor(Highlight, { selection: by, channels });
}
function intervalX({ as, ...rest }) {
  return interactor(Interval1D, { ...rest, selection: as, channel: "x" });
}
function intervalY({ as, ...rest }) {
  return interactor(Interval1D, { ...rest, selection: as, channel: "y" });
}
function intervalXY({ as, ...rest }) {
  return interactor(Interval2D, { ...rest, selection: as });
}
function nearest({ as, ...rest }) {
  return interactor(Nearest, { ...rest, selection: as, pointer: "xy" });
}
function nearestX({ as, ...rest }) {
  return interactor(Nearest, { ...rest, selection: as, pointer: "x" });
}
function nearestY({ as, ...rest }) {
  return interactor(Nearest, { ...rest, selection: as, pointer: "y" });
}
function region({ as, ...rest }) {
  return interactor(Region, { ...rest, selection: as });
}
function toggle({ as, ...rest }) {
  return interactor(Toggle, { ...rest, selection: as });
}
function toggleX(options) {
  return toggle({ ...options, channels: ["x"] });
}
function toggleY(options) {
  return toggle({ ...options, channels: ["y"] });
}
function toggleZ(options) {
  return toggle({ ...options, channels: ["z"] });
}
function toggleColor(options) {
  return toggle({ ...options, channels: ["color"] });
}
function zoom(options) {
  return interactor(PanZoom, options);
}
function pan(options = {}) {
  return zoom({ ...options, zoom: false });
}
function panX(options = {}) {
  return zoom({ ...options, zoom: false, pany: false });
}
function panY(options = {}) {
  return zoom({ ...options, zoom: false, panx: false });
}
function panZoom(options = {}) {
  return zoom(options);
}
function panZoomX(options = {}) {
  return zoom({ ...options, pany: false });
}
function panZoomY(options = {}) {
  return zoom({ ...options, panx: false });
}

// ../vgplot/src/plot/legends.js
var legends_exports = {};
__export(legends_exports, {
  colorLegend: () => colorLegend,
  opacityLegend: () => opacityLegend,
  symbolLegend: () => symbolLegend
});
function legend2(channel, options = {}) {
  if (options.for) {
    const { for: maybePlot, ...rest } = options;
    const legend3 = new Legend(channel, rest);
    const type2 = typeof maybePlot;
    const add3 = (plot3) => plot3.addLegend(legend3, false);
    if (type2 === "string") {
      requestNamedPlot(this, maybePlot, add3);
    } else if (maybePlot.value) {
      add3(maybePlot.value);
    }
    return legend3.element;
  } else {
    return (plot3) => plot3.addLegend(new Legend(channel, options));
  }
}
function colorLegend(options) {
  return legend2.call(this, "color", options);
}
function opacityLegend(options) {
  return legend2.call(this, "opacity", options);
}
function symbolLegend(options) {
  return legend2.call(this, "symbol", options);
}

// ../vgplot/src/plot/plot.js
function plot2(...directives) {
  const p = new Plot();
  directives.flat().forEach((dir) => dir(p));
  connect(this, ...p.marks);
  p.update();
  return p.element;
}

// ../vgplot/src/context.js
function createAPIContext({
  coordinator: coordinator2 = coordinator(),
  namedPlots: namedPlots2 = new NamedPlots(),
  extensions = null,
  ...options
} = {}) {
  return {
    ...api_exports,
    ...extensions,
    context: {
      coordinator: coordinator2,
      namedPlots: namedPlots2,
      ...options
    }
  };
}

// ../spec/src/constants.js
var SPEC = "spec";
var LITERAL2 = "literal";
var OPTIONS = "options";
var SELECTION = "selection";
var PARAMREF = "paramref";
var COLUMPARAMREF = "columnparamref";
var PARAM2 = "param";
var INCLUDE = "include";
var SELECT = "select";
var VALUE = "value";
var CROSSFILTER = "crossfilter";
var INTERSECT = "intersect";
var UNION = "union";
var SINGLE = "single";
var DATA = "data";
var EXPRESSION2 = "expression";
var SQL = "sql";
var INPUT = "input";
var HCONCAT = "hconcat";
var VCONCAT = "vconcat";
var HSPACE = "hspace";
var VSPACE = "vspace";
var MARK = "mark";
var FROM = "from";
var PLOT = "plot";
var LEGEND = "legend";
var ATTRIBUTE = "attribute";
var TRANSFORM = "transform";
var WINDOW_FRAME2 = "windowframe";
var INTERACTOR = "interactor";
var FIXED = "Fixed";

// ../spec/src/util.js
function paramRef(value) {
  const type2 = typeof value;
  return type2 === "object" ? value?.param : type2 === "string" ? paramStr(value) : null;
}
function paramStr(value) {
  return value?.[0] === "$" ? value.slice(1) : null;
}
function toParamRef(name2) {
  return `$${name2}`;
}
function toArray(value) {
  return [value].flat();
}
function isArray4(value) {
  return Array.isArray(value);
}
function isObject3(value) {
  return value !== null && typeof value === "object" && !isArray4(value);
}
function isString2(value) {
  return typeof value === "string";
}
function error(message, data) {
  throw Object.assign(Error(message), { data });
}
var re3 = /^(?:[-+]\d{2})?\d{4}(?:-\d{2}(?:-\d{2})?)?(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d{3})?)?(?:Z|[-+]\d{2}:?\d{2})?)?$/;
function isoparse(string2, fallback) {
  if (!re3.test(string2 += "")) return fallback;
  return new Date(string2);
}

// ../spec/src/ast/ASTNode.js
var ASTNode = class {
  constructor(type2, children2 = null) {
    this.type = type2;
    this.children = children2;
  }
  /**
   * Instantiate this AST node to use in a live web application.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {*} The instantiated value of this node.
   */
  instantiate(ctx) {
    throw Error("instantiate not implemented");
  }
  /**
   * Generate ESM code for this AST node.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated ESM code for the node.
   */
  codegen(ctx) {
    return Error("codegen not implemented");
  }
  /**
   * @returns {*} This AST node in JSON specification format.
   */
  toJSON() {
    return Error("toJSON not implemented");
  }
};

// ../spec/src/ast/OptionsNode.js
function parseOptions(spec, ctx) {
  const options = {};
  for (const key in spec) {
    options[key] = ctx.maybeSelection(spec[key]);
  }
  return new OptionsNode(options);
}
var OptionsNode = class _OptionsNode extends ASTNode {
  constructor(options) {
    super(OPTIONS);
    this.options = options;
  }
  filter(predicate) {
    const opt = Object.fromEntries(
      Object.entries(this.options).filter(([key, value]) => predicate(key, value))
    );
    return new _OptionsNode(opt);
  }
  instantiate(ctx) {
    const { options } = this;
    const opt = {};
    for (const key in options) {
      opt[key] = options[key].instantiate(ctx);
    }
    return opt;
  }
  codegen(ctx) {
    const { options } = this;
    const opt = [];
    for (const key in options) {
      opt.push(`${key}: ${options[key].codegen(ctx)}`);
    }
    return opt.length ? `{${ctx.maybeLineWrap(opt)}}` : "";
  }
  toJSON() {
    const { options } = this;
    const opt = {};
    for (const key in options) {
      opt[key] = options[key].toJSON();
    }
    return opt;
  }
};

// ../spec/src/ast/DataNode.js
var TABLE_DATA = "table";
var PARQUET_DATA = "parquet";
var CSV_DATA = "csv";
var JSON_DATA = "json";
var SPATIAL_DATA = "spatial";
var dataFormats = /* @__PURE__ */ new Map([
  [TABLE_DATA, parseTableData],
  [PARQUET_DATA, parseParquetData],
  [CSV_DATA, parseCSVData],
  [JSON_DATA, parseJSONData],
  [SPATIAL_DATA, parseSpatialData]
]);
function parseData(name2, spec, ctx) {
  const def = resolveDataSpec(spec);
  if (dataFormats.has(def.type)) {
    const parse2 = dataFormats.get(def.type);
    return parse2(name2, def, ctx);
  } else {
    ctx.error(`Unrecognized data format type.`, spec);
  }
}
function resolveDataSpec(spec) {
  if (isArray4(spec)) spec = { type: "json", data: spec };
  if (isString2(spec)) spec = { type: "table", query: spec };
  return { ...spec, type: inferType2(spec) };
}
function inferType2(spec) {
  return spec.type || fileExtension(spec.file) || "table";
}
function fileExtension(file) {
  const idx = file?.lastIndexOf(".");
  return idx > 0 ? file.slice(idx + 1) : null;
}
function parseTableData(name2, spec, ctx) {
  const { query, type: type2, ...options } = spec;
  return new TableDataNode(name2, query, parseOptions(options, ctx));
}
function parseParquetData(name2, spec, ctx) {
  const { file, type: type2, ...options } = spec;
  return new ParquetDataNode(name2, file, parseOptions(options, ctx));
}
function parseCSVData(name2, spec, ctx) {
  const { file, type: type2, ...options } = spec;
  return new CSVDataNode(name2, file, parseOptions(options, ctx));
}
function parseJSONData(name2, spec, ctx) {
  const { data, file, type: type2, ...options } = spec;
  const opt = parseOptions(options, ctx);
  return data ? new LiteralJSONDataNode(name2, data, opt) : new JSONDataNode(name2, file, opt);
}
function parseSpatialData(name2, spec, ctx) {
  const { file, type: type2, ...options } = spec;
  return new SpatialDataNode(name2, file, parseOptions(options, ctx));
}
function resolveFileURL(file, baseURL) {
  return baseURL ? new URL(file, baseURL).toString() : file;
}
function codegenOptions(options, ctx) {
  const code = options?.codegen(ctx);
  return code ? `, ${code}` : "";
}
var DataNode = class extends ASTNode {
  constructor(name2, format3) {
    super(DATA);
    this.name = name2;
    this.format = format3;
  }
};
var QueryDataNode = class extends DataNode {
  constructor(name2, format3) {
    super(name2, format3);
  }
  /**
   * Instantiate a table creation query.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {string|void} The instantiated query.
   */
  instantiateQuery(ctx) {
    ctx.error("instantiateQuery not implemented");
  }
  /**
   * Code generate a table creation query.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated query code.
   */
  codegenQuery(ctx) {
    ctx.error("codegenQuery not implemented");
  }
  /**
   * Instantiate this AST node to use in a live web application.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {*} The instantiated value of this node.
   */
  instantiate(ctx) {
    const query = this.instantiateQuery(ctx);
    if (query) return query;
  }
  /**
   * Generate ESM code for this AST node.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated ESM code for the node.
   */
  codegen(ctx) {
    const query = this.codegenQuery(ctx);
    if (query) return query;
  }
};
var TableDataNode = class extends QueryDataNode {
  constructor(name2, query, options) {
    super(name2, TABLE_DATA);
    this.query = query?.trim();
    this.options = options;
  }
  /**
   * Instantiate a table creation query.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {string|void} The instantiated query.
   */
  instantiateQuery(ctx) {
    const { name: name2, query, options } = this;
    if (query) {
      return ctx.api.createTable(name2, query, options.instantiate(ctx));
    }
  }
  /**
   * Code generate a table creation query.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated query code.
   */
  codegenQuery(ctx) {
    const { name: name2, query, options } = this;
    if (query) {
      return `\`${createTable2(name2, query, options.instantiate(ctx))}\``;
    }
  }
  toJSON() {
    const { format: format3, query, options } = this;
    return { type: format3, query, ...options.toJSON() };
  }
};
var FileDataNode = class extends QueryDataNode {
  constructor(name2, format3, method, file, options) {
    super(name2, format3);
    this.file = file;
    this.method = method;
    this.options = options;
  }
  /**
   * Instantiate a table creation query.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {string|void} The instantiated query.
   */
  instantiateQuery(ctx) {
    const { name: name2, method, file, options } = this;
    const url = resolveFileURL(file, ctx.baseURL);
    const opt = options?.instantiate(ctx);
    return ctx.api[method](name2, url, opt);
  }
  /**
   * Code generate a table creation query.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated query code.
   */
  codegenQuery(ctx) {
    const { name: name2, method, file, options } = this;
    const url = resolveFileURL(file, ctx.baseURL);
    const opt = codegenOptions(options, ctx);
    return `${ctx.ns()}${method}("${name2}", "${url}"${opt})`;
  }
  toJSON() {
    const { format: format3, file, options } = this;
    return { type: format3, file, ...options.toJSON() };
  }
};
var SpatialDataNode = class extends FileDataNode {
  constructor(name2, file, options) {
    super(name2, SPATIAL_DATA, "loadSpatial", file, options);
  }
};
var ParquetDataNode = class extends FileDataNode {
  constructor(name2, file, options) {
    super(name2, PARQUET_DATA, "loadParquet", file, options);
  }
};
var CSVDataNode = class extends FileDataNode {
  constructor(name2, file, options) {
    super(name2, CSV_DATA, "loadCSV", file, options);
  }
};
var JSONDataNode = class extends FileDataNode {
  constructor(name2, file, options) {
    super(name2, JSON_DATA, "loadJSON", file, options);
  }
};
var LiteralJSONDataNode = class extends QueryDataNode {
  constructor(name2, data, options) {
    super(name2, JSON_DATA);
    this.data = data;
    this.options = options;
  }
  /**
   * Instantiate a table creation query.
   * @param {import('../ast-to-dom.js').InstantiateContext} ctx The instantiation context.
   * @returns {string|void} The instantiated query.
   */
  instantiateQuery(ctx) {
    const { name: name2, data, options } = this;
    return ctx.api.loadObjects(name2, data, options.instantiate(ctx));
  }
  /**
   * Code generate a table creation query.
   * @param {import('../ast-to-esm.js').CodegenContext} ctx The code generator context.
   * @returns {string|void} The generated query code.
   */
  codegenQuery(ctx) {
    const { name: name2, data, options } = this;
    const opt = options ? "," + options.codegen(ctx) : "";
    const d = "[\n    " + data.map((d2) => JSON.stringify(d2)).join(",\n    ") + "\n  ]";
    return `${ctx.ns()}loadObjects("${name2}", ${d}${opt})`;
  }
  toJSON() {
    const { format: format3, data, options } = this;
    return { type: format3, data, ...options.toJSON() };
  }
};

// ../spec/src/config/extensions.js
function resolveExtensions(ast) {
  const spec = ast.config?.extensions;
  const exts = new Set(spec ? toArray(spec) : []);
  for (const def of Object.values(ast.data)) {
    if (def.format === SPATIAL_DATA) {
      exts.add("spatial");
    }
  }
  return exts;
}

// ../spec/src/ast-to-dom.js
async function astToDOM(ast, options) {
  const { data, params, plotDefaults } = ast;
  const ctx = new InstantiateContext({ plotDefaults, ...options });
  const queries = [];
  const exts = resolveExtensions(ast);
  queries.push(...Array.from(exts).map((name2) => loadExtension(name2)));
  for (const node of Object.values(data)) {
    const query = node.instantiate(ctx);
    if (query) queries.push(query);
  }
  if (queries.length > 0) {
    await ctx.coordinator.exec(queries);
  }
  for (const [name2, node] of Object.entries(params)) {
    if (!ctx.activeParams.has(name2)) {
      const param = node.instantiate(ctx);
      ctx.activeParams.set(name2, param);
    }
  }
  return {
    element: ast.root.instantiate(ctx),
    params: ctx.activeParams
  };
}
var InstantiateContext = class {
  /**
   * Create a new InstantiateContext instance.
   * @param {object} options Optional instantiation options.
   * @param {string} [options.baseURL] The base URL for loading data files.
   * @param {any[]} [options.plotDefaults] Array of default plot attributes.
   * @param {Map<string, Param>} [options.params] A map of predefined Params/Selections.
   * @param {ReturnType<typeof createAPIContext>} [options.api] The context to be used for vgplot API methods.
   */
  constructor({
    api = createAPIContext(),
    plotDefaults = [],
    params = /* @__PURE__ */ new Map(),
    baseURL = null
  } = {}) {
    this.api = api;
    this.plotDefaults = plotDefaults;
    this.activeParams = params;
    this.baseURL = baseURL;
    this.coordinator = api.context.coordinator;
  }
  error(message, data) {
    error(message, data);
  }
};

// ../spec/src/ast/LiteralNode.js
var LiteralNode2 = class extends ASTNode {
  constructor(value) {
    super(LITERAL2);
    this.value = value;
  }
  instantiate() {
    return this.value;
  }
  codegen(ctx) {
    return ctx.stringify(this.value);
  }
  toJSON() {
    return this.value;
  }
};

// ../spec/src/ast/SelectionNode.js
function parseSelection(spec, ctx) {
  const { select: select2, include, ...options } = spec;
  const opt = parseOptions(options, ctx);
  if (include) {
    opt.options.include = new IncludeNode(
      toArray(include).map((ref) => ctx.selectionRef(paramRef(ref)))
    );
  }
  return new SelectionNode(select2, opt);
}
var SelectionNode = class extends ASTNode {
  /**
   * Create a Selection AST node.
   * @param {string} select The selection type.
   * @param {OptionsNode} options Selection options.
   */
  constructor(select2 = INTERSECT, options = new OptionsNode({})) {
    super(SELECTION);
    this.select = select2;
    this.options = options;
  }
  instantiate(ctx) {
    const { select: select2, options } = this;
    return ctx.api.Selection[select2](options.instantiate(ctx));
  }
  codegen(ctx) {
    const { select: select2, options } = this;
    return `${ctx.ns()}Selection.${select2}(${options.codegen(ctx)})`;
  }
  toJSON() {
    const { select: select2, options } = this;
    return { select: select2, ...options.toJSON() };
  }
};
var IncludeNode = class extends ASTNode {
  constructor(refs) {
    super(INCLUDE);
    this.refs = refs;
  }
  instantiate(ctx) {
    return this.refs.map((ref) => ref.instantiate(ctx));
  }
  codegen(ctx) {
    return `[${this.refs.map((ref) => ref.codegen(ctx)).join(", ")}]`;
  }
  toJSON() {
    return this.refs.map((ref) => ref.toJSON());
  }
};

// ../spec/src/ast/ParamNode.js
var paramTypes = /* @__PURE__ */ new Set([VALUE, SINGLE, CROSSFILTER, INTERSECT, UNION]);
function parseParam(spec, ctx) {
  const param = isObject3(spec) ? spec : { value: spec };
  const { select: select2 = VALUE, value, date: date3 } = param;
  if (!paramTypes.has(select2)) {
    ctx.error(`Unrecognized param type: ${select2}`, param);
  }
  if (select2 !== VALUE) {
    return parseSelection(spec, ctx);
  } else if (isArray4(value)) {
    return new ParamNode2(value.map((v2) => ctx.maybeParam(v2)));
  } else {
    return new ParamNode2(value, date3);
  }
}
var ParamNode2 = class extends ASTNode {
  constructor(value, date3) {
    super(PARAM2);
    this.value = value;
    this.date = date3;
  }
  instantiate(ctx) {
    const { date: date3, value } = this;
    const { Param: Param2 } = ctx.api;
    return isArray4(value) ? Param2.array(value.map((v2) => v2.instantiate(ctx))) : Param2.value(isoparse(date3, value));
  }
  codegen(ctx) {
    const { value, date: date3 } = this;
    const prefix2 = `${ctx.ns()}Param.`;
    return isArray4(value) ? `${prefix2}array([${value.map((v2) => v2.codegen(ctx)).join(", ")}])` : date3 ? `${prefix2}value(new Date(${JSON.stringify(date3)}))` : `${prefix2}value(${JSON.stringify(value)})`;
  }
  toJSON() {
    const { date: date3, value } = this;
    return isArray4(value) ? value.map((v2) => v2.toJSON()) : date3 ? { date: date3 } : value;
  }
};

// ../spec/src/ast/ParamRefNode.js
var ParamRefNode = class extends ASTNode {
  constructor(name2) {
    super(PARAMREF);
    this.name = name2;
  }
  instantiate(ctx) {
    return ctx.activeParams?.get(this.name);
  }
  codegen(ctx) {
    return toParamRef(this.name);
  }
  toJSON() {
    return toParamRef(this.name);
  }
};

// ../spec/src/ast/PlotAttributeNode.js
function parseAttribute(key, value, ctx) {
  if (!ctx.plot?.attributes?.has(key)) {
    ctx.error(`Unrecognized attribute: ${key}`);
  }
  return new PlotAttributeNode(
    key,
    value === FIXED ? new PlotFixedNode() : ctx.maybeParam(value)
  );
}
var PlotAttributeNode = class extends ASTNode {
  constructor(name2, value) {
    super(ATTRIBUTE);
    this.name = name2;
    this.value = value;
  }
  instantiate(ctx) {
    const { name: name2, value } = this;
    return ctx.api[name2](value.instantiate(ctx));
  }
  codegen(ctx) {
    const { name: name2, value } = this;
    return `${ctx.tab()}${ctx.ns()}${name2}(${value.codegen(ctx)})`;
  }
  toJSON() {
    const { name: name2, value } = this;
    return { [name2]: value.toJSON() };
  }
};
var PlotFixedNode = class extends ASTNode {
  constructor() {
    super(LITERAL2);
    this.value = FIXED;
  }
  instantiate(ctx) {
    return ctx.api[FIXED];
  }
  codegen(ctx) {
    return `${ctx.ns()}${FIXED}`;
  }
  toJSON() {
    return this.value;
  }
};

// ../spec/src/ast/SpecNode.js
var SpecNode = class extends ASTNode {
  constructor(root2, meta, config, data, params, plotDefaults) {
    super(SPEC, [root2]);
    this.root = root2;
    this.meta = meta;
    this.config = config;
    this.data = data;
    this.params = params;
    this.plotDefaults = plotDefaults;
  }
  toJSON() {
    const { root: root2, meta, config, plotDefaults } = this;
    const dataDefs = new Map(Object.entries(this.data));
    const paramDefs = new Map(Object.entries(this.params));
    const spec = {};
    if (meta) spec.meta = { ...meta };
    if (config) spec.config = { ...config };
    if (dataDefs?.size) {
      const data = spec.data = {};
      for (const [name2, node] of dataDefs) {
        data[name2] = node.toJSON();
      }
    }
    if (paramDefs?.size) {
      const params = spec.params = {};
      for (const [name2, node] of paramDefs) {
        params[name2] = node.toJSON();
      }
    }
    if (plotDefaults?.length) {
      const defaults22 = spec.plotDefaults = {};
      for (const node of plotDefaults) {
        Object.assign(defaults22, node.toJSON());
      }
    }
    return Object.assign(spec, root2.toJSON());
  }
};

// ../spec/src/ast/HConcatNode.js
function parseHConcat(spec, ctx) {
  const children2 = spec[HCONCAT].map((s2) => ctx.parseComponent(s2));
  return new HConcatNode(children2);
}
var HConcatNode = class extends ASTNode {
  constructor(children2) {
    super(HCONCAT, children2);
  }
  instantiate(ctx) {
    return ctx.api[HCONCAT](this.children.map((c4) => c4.instantiate(ctx)));
  }
  codegen(ctx) {
    ctx.indent();
    const items = this.children.map((c4) => c4.codegen(ctx));
    ctx.undent();
    return `${ctx.tab()}${ctx.ns()}${this.type}(
${items.join(",\n")}
${ctx.tab()})`;
  }
  toJSON() {
    return { [this.type]: this.children.map((c4) => c4.toJSON()) };
  }
};

// ../spec/src/ast/HSpaceNode.js
function parseHSpace(spec) {
  return new HSpaceNode(spec[HSPACE]);
}
var HSpaceNode = class extends ASTNode {
  constructor(value) {
    super(HSPACE);
    this.value = value;
  }
  instantiate(ctx) {
    return ctx.api[HSPACE](this.value);
  }
  codegen(ctx) {
    return `${ctx.tab()}${ctx.ns()}${this.type}(${ctx.stringify(this.value)})`;
  }
  toJSON() {
    return { [this.type]: this.value };
  }
};

// ../spec/src/ast/InputNode.js
function parseInput(spec, ctx) {
  const { [INPUT]: name2, ...options } = spec;
  if (!ctx.inputs?.has(name2)) {
    ctx.error(`Unrecognized input type: ${name2}`, spec);
  }
  return new InputNode(name2, parseOptions(options, ctx));
}
var InputNode = class extends ASTNode {
  constructor(name2, options) {
    super(INPUT);
    this.name = name2;
    this.options = options;
  }
  instantiate(ctx) {
    return ctx.api[this.name](this.options.instantiate(ctx));
  }
  codegen(ctx) {
    const opt = this.options.codegen(ctx);
    return `${ctx.tab()}${ctx.ns()}${this.name}(${opt})`;
  }
  toJSON() {
    const { type: type2, name: name2, options } = this;
    return { [type2]: name2, ...options.toJSON() };
  }
};

// ../spec/src/ast/PlotLegendNode.js
function parseLegend(spec, ctx) {
  const { [LEGEND]: name2, ...options } = spec;
  const key = `${name2}Legend`;
  if (!ctx.plot?.legends?.has(key)) {
    ctx.error(`Unrecognized legend type: ${name2}`, spec);
  }
  return new PlotLegendNode(key, name2, parseOptions(options, ctx));
}
var PlotLegendNode = class extends ASTNode {
  constructor(key, name2, options) {
    super(LEGEND);
    this.key = key;
    this.name = name2;
    this.options = options;
  }
  instantiate(ctx) {
    return ctx.api[this.key](this.options.instantiate(ctx));
  }
  codegen(ctx) {
    const opt = this.options.codegen(ctx);
    return `${ctx.tab()}${ctx.ns()}${this.key}(${opt})`;
  }
  toJSON() {
    const { type: type2, name: name2, options } = this;
    return { [type2]: name2, ...options.toJSON() };
  }
};

// ../spec/src/ast/PlotInteractorNode.js
function parseInteractor(spec, ctx) {
  const { [SELECT]: name2, ...options } = spec;
  if (!ctx.plot?.interactors?.has(name2)) {
    ctx.error(`Unrecognized interactor type: ${name2}`, spec);
  }
  return new PlotInteractorNode(name2, parseOptions(options, ctx));
}
var PlotInteractorNode = class extends ASTNode {
  constructor(name2, options) {
    super(INTERACTOR);
    this.name = name2;
    this.options = options;
  }
  instantiate(ctx) {
    return ctx.api[this.name](this.options.instantiate(ctx));
  }
  codegen(ctx) {
    const opt = this.options.codegen(ctx);
    return `${ctx.tab()}${ctx.ns()}${this.name}(${opt})`;
  }
  toJSON() {
    const { name: name2, options } = this;
    return { [SELECT]: name2, ...options.toJSON() };
  }
};

// ../spec/src/ast/ColumnParamRefNode.js
var ColumnParamRefNode = class extends ASTNode {
  constructor(param) {
    super(COLUMPARAMREF);
    this.param = param;
  }
  instantiate(ctx) {
    return ctx.api.column(this.param.instantiate(ctx));
  }
  codegen(ctx) {
    return `${ctx.ns()}column(${this.param.codegen(ctx)})`;
  }
  toJSON() {
    return `$${this.param.toJSON}`;
  }
};

// ../spec/src/ast/ExpressionNode.js
var tokenRegExp = /(\\'|\\"|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\${1,2}\w+)/g;
function parseExpression(spec, ctx) {
  const expr = spec[SQL];
  const tokens = expr.split(tokenRegExp);
  const spans = [""];
  const params = [];
  for (let i = 0, k2 = 0; i < tokens.length; ++i) {
    const tok = tokens[i];
    if (tok.startsWith("$")) {
      params[k2] = tok.startsWith("$$") ? new ColumnParamRefNode(ctx.paramRef(tok.slice(2))) : ctx.maybeParam(tok);
      spans[++k2] = "";
    } else {
      spans[k2] += tok;
    }
  }
  return new ExpressionNode(expr, spans, params);
}
var ExpressionNode = class extends ASTNode {
  constructor(value, spans, params) {
    super(EXPRESSION2);
    this.value = value;
    this.spans = spans;
    this.params = params;
  }
  instantiate(ctx) {
    const { spans, params } = this;
    const tag = ctx.api[SQL];
    const args = params.map((e) => e.instantiate(ctx));
    return tag(spans, ...args);
  }
  codegen(ctx) {
    const { spans, params } = this;
    let str = "";
    const n = params.length;
    for (let i = 0; i < n; ++i) {
      str += spans[i] + "${" + params[i].codegen(ctx) + "}";
    }
    str += spans[n];
    return `${ctx.ns()}${SQL}\`${str}\``;
  }
  toJSON() {
    return { [SQL]: this.value };
  }
};

// ../spec/src/ast/PlotFromNode.js
function parseMarkData(spec, ctx) {
  if (!spec) {
    return null;
  }
  if (isArray4(spec)) {
    return new LiteralNode2(spec);
  }
  const { from: table3, ...options } = spec;
  return new PlotFromNode(ctx.maybeParam(table3), parseOptions(options, ctx));
}
var PlotFromNode = class extends ASTNode {
  constructor(table3, options) {
    super(FROM);
    this.table = table3;
    this.options = options;
  }
  instantiate(ctx) {
    const { table: table3, options } = this;
    return ctx.api[FROM](table3.instantiate(ctx), options.instantiate(ctx));
  }
  codegen(ctx) {
    const table3 = this.table.codegen(ctx);
    const opt = this.options.codegen(ctx);
    return `${ctx.ns()}${this.type}(${table3}${opt ? ", " + opt : ""})`;
  }
  toJSON() {
    const { type: type2, table: table3, options } = this;
    return { [type2]: table3.toJSON(), ...options.toJSON() };
  }
};

// ../spec/src/ast/WindowFrameNode.js
function parseWindowFrame(spec, ctx) {
  const type2 = spec.rows ? "ROWS" : spec.range ? "RANGE" : spec.groups ? "GROUPS" : null;
  if (!type2) return null;
  const value = spec[type2.toLowerCase()];
  const name2 = paramRef(value);
  const extent4 = name2 ? ctx.paramRef(name2) : value.map(
    (v2) => isObject3(v2) ? parseTransform(v2, ctx) : new LiteralNode(v2)
  );
  return new WindowFrameNode2(type2, extent4, spec.exclude);
}
var WindowFrameNode2 = class extends ASTNode {
  constructor(type2, extent4, exclude) {
    super(WINDOW_FRAME2);
    this.type = type2;
    this.extent = extent4;
    this.exclude = exclude?.toUpperCase();
  }
  instantiate(ctx) {
    const { type: type2, extent: extent4, exclude } = this;
    const ex = Array.isArray(extent4) ? extent4.map((v2) => v2.instantiate(ctx)) : extent4.instantiate(ctx);
    return new WindowFrameNode(type2, ex, exclude?.toUpperCase());
  }
  codegen(ctx) {
    const { type: type2, extent: extent4, exclude } = this;
    const fn2 = `frame${type2[0].toUpperCase()}${type2.slice(1).toLowerCase()}`;
    const ex = Array.isArray(extent4) ? `[${extent4.map((v2) => v2.codegen(ctx)).join(", ")}]` : extent4.codegen(ctx);
    const cl = exclude ? `, '${exclude.toUpperCase()}'` : "";
    return `${ctx.ns()}${fn2}(${ex}${cl})`;
  }
  toJSON() {
    const { type: type2, extent: extent4, exclude } = this;
    const key = type2.toLowerCase();
    const ex = Array.isArray(extent4) ? extent4.map((v2) => v2.toJSON()) : extent4.toJSON();
    return { [key]: ex, exclude };
  }
};

// ../spec/src/ast/TransformNode.js
function toArray2(value, ctx) {
  return value == null ? [] : [value].flat().map((v2) => ctx.maybeParam(v2));
}
function parseTransform(spec, ctx) {
  let name2;
  for (const key in spec) {
    if (ctx.transforms.has(key)) {
      name2 = key;
    }
  }
  if (!name2) {
    return;
  }
  if (name2 === "bin") {
    const { bin: bin3, ...options } = spec;
    const [arg] = toArray2(bin3, ctx);
    return new BinTransformNode2(name2, arg, parseOptions(options, ctx));
  } else {
    const args = name2 === "count" && !spec[name2] ? [] : toArray2(spec[name2], ctx);
    const options = {
      distinct: spec.distinct,
      orderby: toArray2(spec.orderby, ctx),
      partitionby: toArray2(spec.partitionby, ctx),
      frame: parseWindowFrame(spec, ctx)
    };
    return new TransformNode(name2, args, options);
  }
}
var TransformNode = class extends ASTNode {
  constructor(name2, args, options) {
    super(TRANSFORM);
    this.name = name2;
    this.args = args;
    this.options = options;
  }
  instantiate(ctx) {
    const { name: name2, args, options } = this;
    const { distinct: distinct2, orderby, partitionby, frame: frame4 } = options;
    let expr = ctx.api[name2](...args.map((a2) => a2.instantiate(ctx)));
    if (distinct2) {
      expr = expr.distinct();
    }
    if (orderby.length) {
      expr = expr.orderby(orderby.map((v2) => v2.instantiate(ctx)));
    }
    if (partitionby.length) {
      expr = expr.partitionby(partitionby.map((v2) => v2.instantiate(ctx)));
    }
    if (frame4) {
      expr = expr.frame(frame4.instantiate(ctx));
    }
    return expr;
  }
  codegen(ctx) {
    const { name: name2, args, options } = this;
    const { distinct: distinct2, orderby, partitionby, frame: frame4 } = options;
    let str = `${ctx.ns()}${name2}(` + args.map((v2) => v2.codegen(ctx)).join(", ") + ")";
    if (distinct2) {
      str += ".distinct()";
    }
    if (orderby.length) {
      const p = orderby.map((v2) => v2.codegen(ctx));
      str += `.orderby(${p.join(", ")})`;
    }
    if (partitionby.length) {
      const p = partitionby.map((v2) => v2.codegen(ctx));
      str += `.partitionby(${p.join(", ")})`;
    }
    if (frame4) {
      str += `.frame(${frame4.codegen(ctx)})`;
    }
    return str;
  }
  toJSON() {
    const { name: name2, args, options } = this;
    const { distinct: distinct2, orderby, partitionby, frame: frame4 } = options;
    const json = { [name2]: simplify(args.map((v2) => v2.toJSON())) };
    if (distinct2) {
      json.distinct = true;
    }
    if (orderby.length) {
      json.orderby = simplify(orderby.map((v2) => v2.toJSON()));
    }
    if (partitionby.length) {
      json.partitionby = simplify(partitionby.map((v2) => v2.toJSON()));
    }
    if (frame4) {
      Object.assign(json, frame4.toJSON());
    }
    return json;
  }
};
var BinTransformNode2 = class extends ASTNode {
  constructor(name2, arg, options) {
    super(TRANSFORM);
    this.name = name2;
    this.arg = arg;
    this.options = options;
  }
  instantiate(ctx) {
    const { name: name2, arg, options } = this;
    return ctx.api[name2](arg.instantiate(ctx), options.instantiate(ctx));
  }
  codegen(ctx) {
    const { name: name2, arg, options } = this;
    const opt = options.codegen(ctx);
    return `${ctx.ns()}${name2}(` + arg.codegen(ctx) + (opt ? `, ${opt}` : "") + ")";
  }
  toJSON() {
    const { name: name2, arg, options } = this;
    return { [name2]: arg.toJSON(), ...options.toJSON() };
  }
};
function simplify(array4) {
  return array4.length === 0 ? "" : array4.length === 1 ? array4[0] : array4;
}

// ../spec/src/ast/PlotMarkNode.js
function maybeTransform(value, ctx) {
  if (isObject3(value)) {
    return value[SQL] ? parseExpression(value, ctx) : parseTransform(value, ctx);
  }
}
function parseMark(spec, ctx) {
  const { mark: mark2, data, ...options } = spec;
  if (!ctx.plot?.marks?.has(mark2)) {
    ctx.error(`Unrecognized mark type: ${mark2}`, spec);
  }
  const input3 = parseMarkData(data, ctx);
  const opt = {};
  for (const key in options) {
    const value = options[key];
    opt[key] = maybeTransform(value, ctx) || ctx.maybeParam(value);
  }
  return new PlotMarkNode(mark2, input3, new OptionsNode(opt));
}
var PlotMarkNode = class extends ASTNode {
  constructor(name2, data, options) {
    super(MARK);
    this.name = name2;
    this.data = data;
    this.options = options;
  }
  instantiate(ctx) {
    const { name: name2, data, options } = this;
    const opt = options.instantiate(ctx);
    return data ? ctx.api[name2](data.instantiate(ctx), opt) : ctx.api[name2](opt);
  }
  codegen(ctx) {
    const { name: name2, data, options } = this;
    const d = data ? data.codegen(ctx) : "";
    const o = options.codegen(ctx);
    let arg;
    if (d && o) {
      ctx.indent();
      const opt = options.codegen(ctx);
      arg = `
${ctx.tab()}${d},
${ctx.tab()}${opt}
`;
      ctx.undent();
      arg += ctx.tab();
    } else {
      arg = `${d}${o}`;
    }
    return `${ctx.tab()}${ctx.ns()}${name2}(${arg})`;
  }
  toJSON() {
    const { type: type2, name: name2, data, options } = this;
    return {
      [type2]: name2,
      ...data ? { data: data.toJSON() } : {},
      ...options.toJSON()
    };
  }
};

// ../spec/src/ast/PlotNode.js
function parseTopLevelMark(spec, ctx) {
  return parsePlot({ plot: [spec] }, ctx);
}
function parsePlot(spec, ctx) {
  const { [PLOT]: entries, ...attrs } = spec;
  const attributes2 = Object.entries(attrs).map(([key, value]) => parseAttribute(key, value, ctx));
  const children2 = entries.map((spec2) => {
    return isString2(spec2.mark) ? parseMark(spec2, ctx) : isString2(spec2.legend) ? parseLegend(spec2, ctx) : isString2(spec2.select) ? parseInteractor(spec2, ctx) : ctx.error(`Invalid plot entry.`, spec2);
  });
  return new PlotNode(children2, attributes2);
}
var PlotNode = class extends ASTNode {
  constructor(children2, attributes2) {
    super(PLOT, children2);
    this.attributes = attributes2;
  }
  instantiate(ctx) {
    const attrs = [
      ...ctx.plotDefaults || [],
      ...this.attributes || []
    ];
    return ctx.api[PLOT](
      this.children.map((c4) => c4.instantiate(ctx)),
      attrs.map((a2) => a2.instantiate(ctx))
    );
  }
  codegen(ctx) {
    const { type: type2, children: children2, attributes: attributes2 } = this;
    ctx.indent();
    const entries = [
      ...children2.map((c4) => c4.codegen(ctx)),
      ...ctx.plotDefaults?.length ? [`${ctx.tab()}...defaultAttributes`] : [],
      ...attributes2.map((a2) => a2.codegen(ctx))
    ].join(",\n");
    ctx.undent();
    return `${ctx.tab()}${ctx.ns()}${type2}(
${entries}
${ctx.tab()})`;
  }
  toJSON() {
    const { type: type2, children: children2, attributes: attributes2 } = this;
    const plot3 = { [type2]: children2.map((c4) => c4.toJSON()) };
    for (const a2 of attributes2) {
      Object.assign(plot3, a2.toJSON());
    }
    return plot3;
  }
};

// ../spec/src/ast/VConcatNode.js
function parseVConcat(spec, ctx) {
  const children2 = spec[VCONCAT].map((s2) => ctx.parseComponent(s2));
  return new VConcatNode(children2);
}
var VConcatNode = class extends ASTNode {
  constructor(children2) {
    super(VCONCAT, children2);
  }
  instantiate(ctx) {
    return ctx.api[VCONCAT](this.children.map((c4) => c4.instantiate(ctx)));
  }
  codegen(ctx) {
    ctx.indent();
    const items = this.children.map((c4) => c4.codegen(ctx));
    ctx.undent();
    return `${ctx.tab()}${ctx.ns()}${this.type}(
${items.join(",\n")}
${ctx.tab()})`;
  }
  toJSON() {
    return { [this.type]: this.children.map((c4) => c4.toJSON()) };
  }
};

// ../spec/src/ast/VSpaceNode.js
function parseVSpace(spec) {
  return new VSpaceNode(spec[VSPACE]);
}
var VSpaceNode = class extends ASTNode {
  constructor(value) {
    super(VSPACE);
    this.value = value;
  }
  instantiate(ctx) {
    return ctx.api[VSPACE](this.value);
  }
  codegen(ctx) {
    return `${ctx.tab()}${ctx.ns()}${this.type}(${ctx.stringify(this.value)})`;
  }
  toJSON() {
    return { [this.type]: this.value };
  }
};

// ../spec/src/config/components.js
function componentMap(overrides = []) {
  return new Map([
    [PLOT, parsePlot],
    [MARK, parseTopLevelMark],
    [LEGEND, parseLegend],
    [INPUT, parseInput],
    [HCONCAT, parseHConcat],
    [VCONCAT, parseVConcat],
    [HSPACE, parseHSpace],
    [VSPACE, parseVSpace],
    ...overrides
  ]);
}

// ../spec/src/config/inputs.js
function inputNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    "menu",
    "search",
    "slider",
    "table",
    ...overrides
  ]);
}

// ../spec/src/config/plots.js
function plotNames({
  attributes: attributes2 = plotAttributeNames(),
  interactors = plotInteractorNames(),
  legends = plotLegendNames(),
  marks: marks2 = plotMarkNames()
} = {}) {
  return { attributes: attributes2, interactors, legends, marks: marks2 };
}
function plotAttributeNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    ...Object.keys(attributes_exports),
    ...overrides
  ]);
}
function plotInteractorNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    ...Object.keys(interactors_exports),
    ...overrides
  ]);
}
function plotLegendNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    ...Object.keys(legends_exports),
    ...overrides
  ]);
}
function plotMarkNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    ...Object.keys(marks_exports),
    ...overrides
  ]);
}

// ../spec/src/config/transforms.js
function transformNames(overrides = []) {
  return /* @__PURE__ */ new Set([
    "argmin",
    "argmax",
    "avg",
    "bin",
    "centroid",
    "centroidX",
    "centroidY",
    "column",
    "count",
    "covariance",
    "covarPop",
    "dateMonth",
    "dateMonthDay",
    "dateDay",
    "first",
    "geomean",
    "geojson",
    "last",
    "max",
    "median",
    "min",
    "mode",
    "product",
    "quantile",
    "stddev",
    "stddevPop",
    "sum",
    "variance",
    "varPop",
    "row_number",
    "rank",
    "dense_rank",
    "percent_rank",
    "cume_dist",
    "ntile",
    "lag",
    "lead",
    "first_value",
    "last_value",
    "nth_value",
    "years",
    "months",
    "days",
    "hours",
    "minutes",
    "seconds",
    "milliseconds",
    "microseconds",
    ...overrides
  ]);
}

// ../spec/src/parse-spec.js
function parseSpec(spec, options) {
  return new ParseContext(options).parse(spec);
}
var ParseContext = class {
  /**
   * Create a new parser context.
   * @param {object} [options]
   * @param {Map<string, Function>} [options.components] Map of component names to parse functions.
   * @param {Set<string>} [options.transforms] The names of allowed transform functions.
   * @param {Set<string>} [options.inputs] The names of supported input widgets.
   * @param {PlotNames} [options.plot] The names of supported plot elements.
   * @param {any[]} [options.params] An array of [name, node] pairs of pre-parsed
   *  Param or Selection AST nodes.
   * @param {any[]} [options.datasets] An array of [name, node] pairs of pre-parsed
   *  dataset definition AST nodes.
   */
  constructor({
    components = componentMap(),
    transforms = transformNames(),
    inputs = inputNames(),
    plot: plot3 = plotNames(),
    params = [],
    datasets = []
  } = {}) {
    this.components = components;
    this.transforms = transforms;
    this.inputs = inputs;
    this.plot = plot3;
    this.params = new Map(params);
    this.datasets = new Map(datasets);
  }
  parse(spec) {
    const {
      meta,
      config,
      data = {},
      params,
      plotDefaults = {},
      ...root2
    } = spec;
    for (const name2 in data) {
      this.datasets.set(name2, parseData(name2, data[name2], this));
    }
    this.plotDefaults = Object.entries(plotDefaults).map(([key, value]) => parseAttribute(key, value, this));
    for (const name2 in params) {
      this.params.set(name2, parseParam(params[name2], this));
    }
    return new SpecNode(
      this.parseComponent(root2),
      meta ? { ...meta } : void 0,
      config ? { ...config } : void 0,
      Object.fromEntries(this.datasets),
      Object.fromEntries(this.params),
      this.plotDefaults
    );
  }
  parseComponent(spec) {
    for (const [key, parse2] of this.components) {
      const value = spec[key];
      if (value != null) {
        return parse2(spec, this);
      }
    }
    this.error(`Invalid specification.`, spec);
  }
  /**
   * Test if a value is a param reference, if so, generates a parameter
   * definition as needed and returns a new ParamRefNode. Otherwise,
   * returns a LiteralNode for the given value.
   * @param {*} value The value to test.
   * @returns {ParamRefNode|LiteralNode} An AST node for the input value.
   */
  maybeParam(value) {
    const name2 = paramRef(value);
    return name2 ? this.paramRef(name2) : new LiteralNode2(value);
  }
  /**
   * Test if a value is a param reference, if so, generates a selection
   * definition as needed and returns a new ParamRefNode. Otherwise,
   * returns a LiteralNode for the given value.
   * @param {*} value The value to test.
   * @returns {ParamRefNode|LiteralNode} An AST node for the input value.
   */
  maybeSelection(value) {
    const name2 = paramRef(value);
    return name2 ? this.selectionRef(name2) : new LiteralNode2(value);
  }
  /**
   * Create a parameter reference. Generates a parameter definition if needed
   * and returns a new ParamRefNode.
   * @param {string} name The parameter name.
   * @param {() => ParamNode | SelectionNode} [makeNode] A Param or Selection AST
   *  node constructor.
   * @returns {ParamRefNode|null} A node referring to the param or selection.
   */
  paramRef(name2, makeNode = () => new ParamNode2()) {
    const { params } = this;
    if (!name2) return null;
    let p = params.get(name2);
    if (!p) {
      p = makeNode();
      params.set(name2, p);
    }
    return new ParamRefNode(name2);
  }
  /**
   * Create a selection reference. Generates a selection definition if needed
   * and returns a new ParamRefNode. Returns null if a non-selection parameter
   * with the same name already exists and *strict* is true.
   * @param {string} name The selection name.
   * @param {boolean} [strict=false] Indicates if this method may return param
   *  references (false, default) or only selection references (true).
   * @returns {ParamRefNode|null} A node referring to the param or selection.
   */
  selectionRef(name2, strict = false) {
    const p = this.params.get(name2);
    if (strict && p && !(p instanceof SelectionNode)) {
      return null;
    }
    return this.paramRef(name2, () => new SelectionNode());
  }
  error(message, data) {
    error(message, data);
  }
};

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

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

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

// node_modules/uuid/dist/v4.js
function _v4(options, buf2, offset2) {
  options = options || {};
  const rnds = options.random ?? options.rng?.() ?? rng();
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf2) {
    offset2 = offset2 || 0;
    if (offset2 < 0 || offset2 + 16 > buf2.length) {
      throw new RangeError(`UUID byte range ${offset2}:${offset2 + 15} is out of buffer bounds`);
    }
    for (let i = 0; i < 16; ++i) {
      buf2[offset2 + i] = rnds[i];
    }
    return buf2;
  }
  return unsafeStringify(rnds);
}
function v4(options, buf2, offset2) {
  if (native_default.randomUUID && !buf2 && !options) {
    return native_default.randomUUID();
  }
  return _v4(options, buf2, offset2);
}
var v4_default = v4;

// src/index.js
var index_default = {
  /** @type {import('anywidget/types').Initialize<Model>} */
  initialize(view) {
    view.model.set("preagg_schema", coordinator().preaggregator.schema);
  },
  /** @type {import('anywidget/types').Render<Model>} */
  render(view) {
    view.el.classList.add("mosaic-widget");
    const getSpec = () => view.model.get("spec");
    const getPreaggSchema = () => view.model.get("preagg_schema");
    const logger = coordinator().logger();
    const openQueries = /* @__PURE__ */ new Map();
    function send(query, resolve, reject) {
      const uuid = v4_default();
      openQueries.set(uuid, {
        query,
        startTime: performance.now(),
        resolve,
        reject
      });
      view.model.send({ ...query, uuid });
    }
    const connector = {
      query(query) {
        return new Promise((resolve, reject) => send(query, resolve, reject));
      }
    };
    function reset() {
      coordinator().clear();
    }
    async function updateSpec() {
      const spec = getSpec();
      reset();
      logger.log("Setting spec:", spec);
      const dom = await instantiateSpec(spec);
      view.el.replaceChildren(dom.element);
      let params = {};
      for (const [name2, param] of dom.params) {
        params[name2] = {
          value: param.value,
          ...isSelection(param) ? { predicate: String(param.predicate(void 0)) } : {}
        };
        param.addEventListener("value", (value) => {
          params = Object.freeze({
            ...params,
            [name2]: {
              value,
              ...isSelection(param) ? { predicate: String(param.predicate(void 0)) } : {}
            }
          });
          view.model.set("params", params);
          view.model.save_changes();
        });
      }
      params = Object.freeze(params);
      view.model.set("params", params);
      view.model.save_changes();
    }
    view.model.on("change:spec", () => updateSpec());
    function configureCoordinator() {
      coordinator().preaggregator.schema = getPreaggSchema();
    }
    view.model.on("change:preagg_schema", () => configureCoordinator());
    view.model.on("msg:custom", (msg, buffers) => {
      logger.group(`query ${msg.uuid}`);
      logger.log("received message", msg, buffers);
      const query = openQueries.get(msg.uuid);
      openQueries.delete(msg.uuid);
      logger.log(query.query.sql, (performance.now() - query.startTime).toFixed(1));
      if (msg.error) {
        query.reject(msg.error);
        logger.error(msg.error);
      } else {
        switch (msg.type) {
          case "arrow": {
            const table3 = decodeIPC2(buffers[0].buffer);
            logger.log("table", table3);
            query.resolve(table3);
            break;
          }
          case "json": {
            logger.log("json", msg.result);
            query.resolve(msg.result);
            break;
          }
          default: {
            query.resolve({});
            break;
          }
        }
      }
      logger.groupEnd();
    });
    coordinator().databaseConnector(connector);
    configureCoordinator();
    updateSpec();
    return () => {
      reset();
    };
  }
};
function instantiateSpec(spec) {
  return astToDOM(parseSpec(spec));
}
export {
  index_default as default
};
