var ol = (function () {
  'use strict';

  /**
   * @module ol/CollectionEventType
   */

  /**
   * @enum {string}
   */
  var CollectionEventType = {
    /**
     * Triggered when an item is added to the collection.
     * @event module:ol/Collection.CollectionEvent#add
     * @api
     */
    ADD: 'add',
    /**
     * Triggered when an item is removed from the collection.
     * @event module:ol/Collection.CollectionEvent#remove
     * @api
     */
    REMOVE: 'remove',
  };

  /**
   * @module ol/ObjectEventType
   */

  /**
   * @enum {string}
   */
  var ObjectEventType = {
    /**
     * Triggered when a property is changed.
     * @event module:ol/Object.ObjectEvent#propertychange
     * @api
     */
    PROPERTYCHANGE: 'propertychange',
  };

  /**
   * @typedef {'propertychange'} Types
   */

  /**
   * @module ol/events/EventType
   */

  /**
   * @enum {string}
   * @const
   */
  var EventType = {
    /**
     * Generic change event. Triggered when the revision counter is increased.
     * @event module:ol/events/Event~BaseEvent#change
     * @api
     */
    CHANGE: 'change',

    /**
     * Generic error event. Triggered when an error occurs.
     * @event module:ol/events/Event~BaseEvent#error
     * @api
     */
    ERROR: 'error',

    CONTEXTMENU: 'contextmenu',
    CLICK: 'click',
    DBLCLICK: 'dblclick',
    DRAGENTER: 'dragenter',
    DRAGOVER: 'dragover',
    DROP: 'drop',
    KEYDOWN: 'keydown',
    KEYPRESS: 'keypress',
    LOAD: 'load',
    TOUCHMOVE: 'touchmove',
    WHEEL: 'wheel',
  };

  /**
   * @module ol/Disposable
   */

  /**
   * @classdesc
   * Objects that need to clean up after themselves.
   */
  class Disposable {
    constructor() {
      /**
       * The object has already been disposed.
       * @type {boolean}
       * @protected
       */
      this.disposed = false;
    }

    /**
     * Clean up.
     */
    dispose() {
      if (!this.disposed) {
        this.disposed = true;
        this.disposeInternal();
      }
    }

    /**
     * Extension point for disposable objects.
     * @protected
     */
    disposeInternal() {}
  }

  /**
   * @module ol/array
   */

  /**
   * Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1.
   * https://github.com/darkskyapp/binary-search
   *
   * @param {Array<*>} haystack Items to search through.
   * @param {*} needle The item to look for.
   * @param {Function} [comparator] Comparator function.
   * @return {number} The index of the item if found, -1 if not.
   */
  function binarySearch$1(haystack, needle, comparator) {
    let mid, cmp;
    comparator = comparator || ascending;
    let low = 0;
    let high = haystack.length;
    let found = false;

    while (low < high) {
      /* Note that "(low + high) >>> 1" may overflow, and results in a typecast
       * to double (which gives the wrong results). */
      mid = low + ((high - low) >> 1);
      cmp = +comparator(haystack[mid], needle);

      if (cmp < 0.0) {
        /* Too low. */
        low = mid + 1;
      } else {
        /* Key found or too high */
        high = mid;
        found = !cmp;
      }
    }

    /* Key not found. */
    return found ? low : ~low;
  }

  /**
   * Compare function sorting arrays in ascending order.  Safe to use for numeric values.
   * @param {*} a The first object to be compared.
   * @param {*} b The second object to be compared.
   * @return {number} A negative number, zero, or a positive number as the first
   *     argument is less than, equal to, or greater than the second.
   */
  function ascending(a, b) {
    return a > b ? 1 : a < b ? -1 : 0;
  }

  /**
   * Compare function sorting arrays in descending order.  Safe to use for numeric values.
   * @param {*} a The first object to be compared.
   * @param {*} b The second object to be compared.
   * @return {number} A negative number, zero, or a positive number as the first
   *     argument is greater than, equal to, or less than the second.
   */
  function descending(a, b) {
    return a < b ? 1 : a > b ? -1 : 0;
  }

  /**
   * {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution} can use a function
   * of this type to determine which nearest resolution to use.
   *
   * This function takes a `{number}` representing a value between two array entries,
   * a `{number}` representing the value of the nearest higher entry and
   * a `{number}` representing the value of the nearest lower entry
   * as arguments and returns a `{number}`. If a negative number or zero is returned
   * the lower value will be used, if a positive number is returned the higher value
   * will be used.
   * @typedef {function(number, number, number): number} NearestDirectionFunction
   * @api
   */

  /**
   * @param {Array<number>} arr Array in descending order.
   * @param {number} target Target.
   * @param {number|NearestDirectionFunction} direction
   *    0 means return the nearest,
   *    > 0 means return the largest nearest,
   *    < 0 means return the smallest nearest.
   * @return {number} Index.
   */
  function linearFindNearest(arr, target, direction) {
    if (arr[0] <= target) {
      return 0;
    }

    const n = arr.length;
    if (target <= arr[n - 1]) {
      return n - 1;
    }

    if (typeof direction === 'function') {
      for (let i = 1; i < n; ++i) {
        const candidate = arr[i];
        if (candidate === target) {
          return i;
        }
        if (candidate < target) {
          if (direction(target, arr[i - 1], candidate) > 0) {
            return i - 1;
          }
          return i;
        }
      }
      return n - 1;
    }

    if (direction > 0) {
      for (let i = 1; i < n; ++i) {
        if (arr[i] < target) {
          return i - 1;
        }
      }
      return n - 1;
    }

    if (direction < 0) {
      for (let i = 1; i < n; ++i) {
        if (arr[i] <= target) {
          return i;
        }
      }
      return n - 1;
    }

    for (let i = 1; i < n; ++i) {
      if (arr[i] == target) {
        return i;
      }
      if (arr[i] < target) {
        if (arr[i - 1] - target < target - arr[i]) {
          return i - 1;
        }
        return i;
      }
    }
    return n - 1;
  }

  /**
   * @param {Array<*>} arr Array.
   * @param {number} begin Begin index.
   * @param {number} end End index.
   */
  function reverseSubArray(arr, begin, end) {
    while (begin < end) {
      const tmp = arr[begin];
      arr[begin] = arr[end];
      arr[end] = tmp;
      ++begin;
      --end;
    }
  }

  /**
   * @param {Array<VALUE>} arr The array to modify.
   * @param {!Array<VALUE>|VALUE} data The elements or arrays of elements to add to arr.
   * @template VALUE
   */
  function extend$2(arr, data) {
    const extension = Array.isArray(data) ? data : [data];
    const length = extension.length;
    for (let i = 0; i < length; i++) {
      arr[arr.length] = extension[i];
    }
  }

  /**
   * @param {Array<any>|Uint8ClampedArray} arr1 The first array to compare.
   * @param {Array<any>|Uint8ClampedArray} arr2 The second array to compare.
   * @return {boolean} Whether the two arrays are equal.
   */
  function equals$2(arr1, arr2) {
    const len1 = arr1.length;
    if (len1 !== arr2.length) {
      return false;
    }
    for (let i = 0; i < len1; i++) {
      if (arr1[i] !== arr2[i]) {
        return false;
      }
    }
    return true;
  }

  /**
   * @param {Array<*>} arr The array to test.
   * @param {Function} [func] Comparison function.
   * @param {boolean} [strict] Strictly sorted (default false).
   * @return {boolean} Return index.
   */
  function isSorted(arr, func, strict) {
    const compare = func || ascending;
    return arr.every(function (currentVal, index) {
      if (index === 0) {
        return true;
      }
      const res = compare(arr[index - 1], currentVal);
      return !(res > 0 || (res === 0));
    });
  }

  /**
   * @module ol/functions
   */


  /**
   * Always returns true.
   * @return {boolean} true.
   */
  function TRUE() {
    return true;
  }

  /**
   * Always returns false.
   * @return {boolean} false.
   */
  function FALSE() {
    return false;
  }

  /**
   * A reusable function, used e.g. as a default for callbacks.
   *
   * @return {void} Nothing.
   */
  function VOID() {}

  /**
   * Wrap a function in another function that remembers the last return.  If the
   * returned function is called twice in a row with the same arguments and the same
   * this object, it will return the value from the first call in the second call.
   *
   * @param {function(...any): ReturnType} fn The function to memoize.
   * @return {function(...any): ReturnType} The memoized function.
   * @template ReturnType
   */
  function memoizeOne(fn) {
    /** @type {ReturnType} */
    let lastResult;

    /** @type {Array<any>|undefined} */
    let lastArgs;

    let lastThis;

    /**
     * @this {*} Only need to know if `this` changed, don't care what type
     * @return {ReturnType} Memoized value
     */
    return function () {
      const nextArgs = Array.prototype.slice.call(arguments);
      if (!lastArgs || this !== lastThis || !equals$2(nextArgs, lastArgs)) {
        lastThis = this;
        lastArgs = nextArgs;
        lastResult = fn.apply(this, arguments);
      }
      return lastResult;
    };
  }

  /**
   * @template T
   * @param {function(): (T | Promise<T>)} getter A function that returns a value or a promise for a value.
   * @return {Promise<T>} A promise for the value.
   */
  function toPromise(getter) {
    function promiseGetter() {
      let value;
      try {
        value = getter();
      } catch (err) {
        return Promise.reject(err);
      }
      if (value instanceof Promise) {
        return value;
      }
      return Promise.resolve(value);
    }
    return promiseGetter();
  }

  /**
   * @module ol/obj
   */

  /**
   * Removes all properties from an object.
   * @param {Object<string, unknown>} object The object to clear.
   */
  function clear$2(object) {
    for (const property in object) {
      delete object[property];
    }
  }

  /**
   * Determine if an object has any properties.
   * @param {Object} object The object to check.
   * @return {boolean} The object is empty.
   */
  function isEmpty$1(object) {
    let property;
    for (property in object) {
      return false;
    }
    return !property;
  }

  /**
   * @module ol/events/Event
   */

  /**
   * @classdesc
   * Stripped down implementation of the W3C DOM Level 2 Event interface.
   * See https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface.
   *
   * This implementation only provides `type` and `target` properties, and
   * `stopPropagation` and `preventDefault` methods. It is meant as base class
   * for higher level events defined in the library, and works with
   * {@link module:ol/events/Target~Target}.
   */
  class BaseEvent {
    /**
     * @param {string} type Type.
     */
    constructor(type) {
      /**
       * @type {boolean}
       */
      this.propagationStopped;

      /**
       * @type {boolean}
       */
      this.defaultPrevented;

      /**
       * The event type.
       * @type {string}
       * @api
       */
      this.type = type;

      /**
       * The event target.
       * @type {Object}
       * @api
       */
      this.target = null;
    }

    /**
     * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events
     * will be fired.
     * @api
     */
    preventDefault() {
      this.defaultPrevented = true;
    }

    /**
     * Stop event propagation.
     * @api
     */
    stopPropagation() {
      this.propagationStopped = true;
    }
  }

  /**
   * @param {Event|import("./Event.js").default} evt Event
   */
  function stopPropagation(evt) {
    evt.stopPropagation();
  }

  /**
   * @param {Event|import("./Event.js").default} evt Event
   */
  function preventDefault(evt) {
    evt.preventDefault();
  }

  var nsEvents_Event = {
    __proto__: null,
    default: BaseEvent,
    preventDefault: preventDefault,
    stopPropagation: stopPropagation
  };

  /**
   * @module ol/events/Target
   */

  /**
   * @typedef {EventTarget|Target} EventTargetLike
   */

  /**
   * @classdesc
   * A simplified implementation of the W3C DOM Level 2 EventTarget interface.
   * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget.
   *
   * There are two important simplifications compared to the specification:
   *
   * 1. The handling of `useCapture` in `addEventListener` and
   *    `removeEventListener`. There is no real capture model.
   * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`.
   *    There is no event target hierarchy. When a listener calls
   *    `stopPropagation` or `preventDefault` on an event object, it means that no
   *    more listeners after this one will be called. Same as when the listener
   *    returns false.
   */
  class Target extends Disposable {
    /**
     * @param {*} [target] Default event target for dispatched events.
     */
    constructor(target) {
      super();

      /**
       * @private
       * @type {*}
       */
      this.eventTarget_ = target;

      /**
       * @private
       * @type {Object<string, number>|null}
       */
      this.pendingRemovals_ = null;

      /**
       * @private
       * @type {Object<string, number>|null}
       */
      this.dispatching_ = null;

      /**
       * @private
       * @type {Object<string, Array<import("../events.js").Listener>>|null}
       */
      this.listeners_ = null;
    }

    /**
     * @param {string} type Type.
     * @param {import("../events.js").Listener} listener Listener.
     */
    addEventListener(type, listener) {
      if (!type || !listener) {
        return;
      }
      const listeners = this.listeners_ || (this.listeners_ = {});
      const listenersForType = listeners[type] || (listeners[type] = []);
      if (!listenersForType.includes(listener)) {
        listenersForType.push(listener);
      }
    }

    /**
     * Dispatches an event and calls all listeners listening for events
     * of this type. The event parameter can either be a string or an
     * Object with a `type` property.
     *
     * @param {import("./Event.js").default|string} event Event object.
     * @return {boolean|undefined} `false` if anyone called preventDefault on the
     *     event object or if any of the listeners returned false.
     * @api
     */
    dispatchEvent(event) {
      const isString = typeof event === 'string';
      const type = isString ? event : event.type;
      const listeners = this.listeners_ && this.listeners_[type];
      if (!listeners) {
        return;
      }

      const evt = isString ? new BaseEvent(event) : /** @type {Event} */ (event);
      if (!evt.target) {
        evt.target = this.eventTarget_ || this;
      }
      const dispatching = this.dispatching_ || (this.dispatching_ = {});
      const pendingRemovals =
        this.pendingRemovals_ || (this.pendingRemovals_ = {});
      if (!(type in dispatching)) {
        dispatching[type] = 0;
        pendingRemovals[type] = 0;
      }
      ++dispatching[type];
      let propagate;
      for (let i = 0, ii = listeners.length; i < ii; ++i) {
        if ('handleEvent' in listeners[i]) {
          propagate = /** @type {import("../events.js").ListenerObject} */ (
            listeners[i]
          ).handleEvent(evt);
        } else {
          propagate = /** @type {import("../events.js").ListenerFunction} */ (
            listeners[i]
          ).call(this, evt);
        }
        if (propagate === false || evt.propagationStopped) {
          propagate = false;
          break;
        }
      }
      if (--dispatching[type] === 0) {
        let pr = pendingRemovals[type];
        delete pendingRemovals[type];
        while (pr--) {
          this.removeEventListener(type, VOID);
        }
        delete dispatching[type];
      }
      return propagate;
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.listeners_ && clear$2(this.listeners_);
    }

    /**
     * Get the listeners for a specified event type. Listeners are returned in the
     * order that they will be called in.
     *
     * @param {string} type Type.
     * @return {Array<import("../events.js").Listener>|undefined} Listeners.
     */
    getListeners(type) {
      return (this.listeners_ && this.listeners_[type]) || undefined;
    }

    /**
     * @param {string} [type] Type. If not provided,
     *     `true` will be returned if this event target has any listeners.
     * @return {boolean} Has listeners.
     */
    hasListener(type) {
      if (!this.listeners_) {
        return false;
      }
      return type
        ? type in this.listeners_
        : Object.keys(this.listeners_).length > 0;
    }

    /**
     * @param {string} type Type.
     * @param {import("../events.js").Listener} listener Listener.
     */
    removeEventListener(type, listener) {
      if (!this.listeners_) {
        return;
      }
      const listeners = this.listeners_[type];
      if (!listeners) {
        return;
      }
      const index = listeners.indexOf(listener);
      if (index !== -1) {
        if (this.pendingRemovals_ && type in this.pendingRemovals_) {
          // make listener a no-op, and remove later in #dispatchEvent()
          listeners[index] = VOID;
          ++this.pendingRemovals_[type];
        } else {
          listeners.splice(index, 1);
          if (listeners.length === 0) {
            delete this.listeners_[type];
          }
        }
      }
    }
  }

  /**
   * @module ol/events
   */

  /**
   * Key to use with {@link module:ol/Observable.unByKey}.
   * @typedef {Object} EventsKey
   * @property {ListenerFunction} listener Listener.
   * @property {import("./events/Target.js").EventTargetLike} target Target.
   * @property {string} type Type.
   * @api
   */

  /**
   * Listener function. This function is called with an event object as argument.
   * When the function returns `false`, event propagation will stop.
   *
   * @typedef {function((Event|import("./events/Event.js").default)): (void|boolean)} ListenerFunction
   * @api
   */

  /**
   * @typedef {Object} ListenerObject
   * @property {ListenerFunction} handleEvent HandleEvent listener function.
   */

  /**
   * @typedef {ListenerFunction|ListenerObject} Listener
   */

  /**
   * Registers an event listener on an event target. Inspired by
   * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html
   *
   * This function efficiently binds a `listener` to a `this` object, and returns
   * a key for use with {@link module:ol/events.unlistenByKey}.
   *
   * @param {import("./events/Target.js").EventTargetLike} target Event target.
   * @param {string} type Event type.
   * @param {ListenerFunction} listener Listener.
   * @param {Object} [thisArg] Object referenced by the `this` keyword in the
   *     listener. Default is the `target`.
   * @param {boolean} [once] If true, add the listener as one-off listener.
   * @return {EventsKey} Unique key for the listener.
   */
  function listen(target, type, listener, thisArg, once) {
    if (once) {
      const originalListener = listener;
      /**
       * @param {Event|import('./events/Event.js').default} event The event
       * @return {void|boolean} When the function returns `false`, event propagation will stop.
       * @this {typeof target}
       */
      listener = function (event) {
        target.removeEventListener(type, listener);
        return originalListener.call(thisArg ?? this, event);
      };
    } else if (thisArg && thisArg !== target) {
      listener = listener.bind(thisArg);
    }
    const eventsKey = {
      target: target,
      type: type,
      listener: listener,
    };
    target.addEventListener(type, listener);
    return eventsKey;
  }

  /**
   * Registers a one-off event listener on an event target. Inspired by
   * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html
   *
   * This function efficiently binds a `listener` as self-unregistering listener
   * to a `this` object, and returns a key for use with
   * {@link module:ol/events.unlistenByKey} in case the listener needs to be
   * unregistered before it is called.
   *
   * When {@link module:ol/events.listen} is called with the same arguments after this
   * function, the self-unregistering listener will be turned into a permanent
   * listener.
   *
   * @param {import("./events/Target.js").EventTargetLike} target Event target.
   * @param {string} type Event type.
   * @param {ListenerFunction} listener Listener.
   * @param {Object} [thisArg] Object referenced by the `this` keyword in the
   *     listener. Default is the `target`.
   * @return {EventsKey} Key for unlistenByKey.
   */
  function listenOnce(target, type, listener, thisArg) {
    return listen(target, type, listener, thisArg, true);
  }

  /**
   * Unregisters event listeners on an event target. Inspired by
   * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html
   *
   * The argument passed to this function is the key returned from
   * {@link module:ol/events.listen} or {@link module:ol/events.listenOnce}.
   *
   * @param {EventsKey} key The key.
   */
  function unlistenByKey(key) {
    if (key && key.target) {
      key.target.removeEventListener(key.type, key.listener);
      clear$2(key);
    }
  }

  var nsEvents = {
    __proto__: null,
    listen: listen,
    listenOnce: listenOnce,
    unlistenByKey: unlistenByKey
  };

  /**
   * @module ol/Observable
   */

  /***
   * @template {string} Type
   * @template {Event|import("./events/Event.js").default} EventClass
   * @template Return
   * @typedef {(type: Type, listener: (event: EventClass) => ?) => Return} OnSignature
   */

  /***
   * @template {string} Type
   * @template Return
   * @typedef {(type: Type[], listener: (event: Event|import("./events/Event").default) => ?) => Return extends void ? void : Return[]} CombinedOnSignature
   */

  /**
   * @typedef {'change'|'error'} EventTypes
   */

  /***
   * @template Return
   * @typedef {OnSignature<EventTypes, import("./events/Event.js").default, Return> & CombinedOnSignature<EventTypes, Return>} ObservableOnSignature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * An event target providing convenient methods for listener registration
   * and unregistration. A generic `change` event is always available through
   * {@link module:ol/Observable~Observable#changed}.
   *
   * @fires import("./events/Event.js").default
   * @api
   */
  class Observable extends Target {
    constructor() {
      super();

      this.on =
        /** @type {ObservableOnSignature<import("./events").EventsKey>} */ (
          this.onInternal
        );

      this.once =
        /** @type {ObservableOnSignature<import("./events").EventsKey>} */ (
          this.onceInternal
        );

      this.un = /** @type {ObservableOnSignature<void>} */ (this.unInternal);

      /**
       * @private
       * @type {number}
       */
      this.revision_ = 0;
    }

    /**
     * Increases the revision counter and dispatches a 'change' event.
     * @api
     */
    changed() {
      ++this.revision_;
      this.dispatchEvent(EventType.CHANGE);
    }

    /**
     * Get the version number for this object.  Each time the object is modified,
     * its version number will be incremented.
     * @return {number} Revision.
     * @api
     */
    getRevision() {
      return this.revision_;
    }

    /**
     * @param {string|Array<string>} type Type.
     * @param {function((Event|import("./events/Event").default)): ?} listener Listener.
     * @return {import("./events.js").EventsKey|Array<import("./events.js").EventsKey>} Event key.
     * @protected
     */
    onInternal(type, listener) {
      if (Array.isArray(type)) {
        const len = type.length;
        const keys = new Array(len);
        for (let i = 0; i < len; ++i) {
          keys[i] = listen(this, type[i], listener);
        }
        return keys;
      }
      return listen(this, /** @type {string} */ (type), listener);
    }

    /**
     * @param {string|Array<string>} type Type.
     * @param {function((Event|import("./events/Event").default)): ?} listener Listener.
     * @return {import("./events.js").EventsKey|Array<import("./events.js").EventsKey>} Event key.
     * @protected
     */
    onceInternal(type, listener) {
      let key;
      if (Array.isArray(type)) {
        const len = type.length;
        key = new Array(len);
        for (let i = 0; i < len; ++i) {
          key[i] = listenOnce(this, type[i], listener);
        }
      } else {
        key = listenOnce(this, /** @type {string} */ (type), listener);
      }
      /** @type {Object} */ (listener).ol_key = key;
      return key;
    }

    /**
     * Unlisten for a certain type of event.
     * @param {string|Array<string>} type Type.
     * @param {function((Event|import("./events/Event").default)): ?} listener Listener.
     * @protected
     */
    unInternal(type, listener) {
      const key = /** @type {Object} */ (listener).ol_key;
      if (key) {
        unByKey(key);
      } else if (Array.isArray(type)) {
        for (let i = 0, ii = type.length; i < ii; ++i) {
          this.removeEventListener(type[i], listener);
        }
      } else {
        this.removeEventListener(type, listener);
      }
    }
  }

  /**
   * Listen for a certain type of event.
   * @function
   * @param {string|Array<string>} type The event type or array of event types.
   * @param {function((Event|import("./events/Event").default)): ?} listener The listener function.
   * @return {import("./events.js").EventsKey|Array<import("./events.js").EventsKey>} Unique key for the listener. If
   *     called with an array of event types as the first argument, the return
   *     will be an array of keys.
   * @api
   */
  Observable.prototype.on;

  /**
   * Listen once for a certain type of event.
   * @function
   * @param {string|Array<string>} type The event type or array of event types.
   * @param {function((Event|import("./events/Event").default)): ?} listener The listener function.
   * @return {import("./events.js").EventsKey|Array<import("./events.js").EventsKey>} Unique key for the listener. If
   *     called with an array of event types as the first argument, the return
   *     will be an array of keys.
   * @api
   */
  Observable.prototype.once;

  /**
   * Unlisten for a certain type of event.
   * @function
   * @param {string|Array<string>} type The event type or array of event types.
   * @param {function((Event|import("./events/Event").default)): ?} listener The listener function.
   * @api
   */
  Observable.prototype.un;

  /**
   * Removes an event listener using the key returned by `on()` or `once()`.
   * @param {import("./events.js").EventsKey|Array<import("./events.js").EventsKey>} key The key returned by `on()`
   *     or `once()` (or an array of keys).
   * @api
   */
  function unByKey(key) {
    if (Array.isArray(key)) {
      for (let i = 0, ii = key.length; i < ii; ++i) {
        unlistenByKey(key[i]);
      }
    } else {
      unlistenByKey(/** @type {import("./events.js").EventsKey} */ (key));
    }
  }

  /**
   * @module ol/util
   */

  /**
   * @return {never} Any return.
   */
  function abstract() {
    throw new Error('Unimplemented abstract method.');
  }

  /**
   * Counter for getUid.
   * @type {number}
   * @private
   */
  let uidCounter_ = 0;

  /**
   * Gets a unique ID for an object. This mutates the object so that further calls
   * with the same object as a parameter returns the same value. Unique IDs are generated
   * as a strictly increasing sequence. Adapted from goog.getUid.
   *
   * @param {Object} obj The object to get the unique ID for.
   * @return {string} The unique ID for the object.
   * @api
   */
  function getUid(obj) {
    return obj.ol_uid || (obj.ol_uid = String(++uidCounter_));
  }

  /**
   * OpenLayers version.
   * @type {string}
   */
  const VERSION = '10.6.1';

  /**
   * @module ol/Object
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/Object~BaseObject} instances are instances of this type.
   */
  class ObjectEvent extends BaseEvent {
    /**
     * @param {string} type The event type.
     * @param {string} key The property name.
     * @param {*} oldValue The old value for `key`.
     */
    constructor(type, key, oldValue) {
      super(type);

      /**
       * The name of the property whose value is changing.
       * @type {string}
       * @api
       */
      this.key = key;

      /**
       * The old value. To get the new value use `e.target.get(e.key)` where
       * `e` is the event object.
       * @type {*}
       * @api
       */
      this.oldValue = oldValue;
    }
  }

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *    import("./Observable").OnSignature<import("./ObjectEventType").Types, ObjectEvent, Return> &
   *    import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|import("./ObjectEventType").Types, Return>} ObjectOnSignature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Most non-trivial classes inherit from this.
   *
   * This extends {@link module:ol/Observable~Observable} with observable
   * properties, where each property is observable as well as the object as a
   * whole.
   *
   * Classes that inherit from this have pre-defined properties, to which you can
   * add your owns. The pre-defined properties are listed in this documentation as
   * 'Observable Properties', and have their own accessors; for example,
   * {@link module:ol/Map~Map} has a `target` property, accessed with
   * `getTarget()` and changed with `setTarget()`. Not all properties are however
   * settable. There are also general-purpose accessors `get()` and `set()`. For
   * example, `get('target')` is equivalent to `getTarget()`.
   *
   * The `set` accessors trigger a change event, and you can monitor this by
   * registering a listener. For example, {@link module:ol/View~View} has a
   * `center` property, so `view.on('change:center', function(evt) {...});` would
   * call the function whenever the value of the center property changes. Within
   * the function, `evt.target` would be the view, so `evt.target.getCenter()`
   * would return the new center.
   *
   * You can add your own observable properties with
   * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`.
   * You can listen for changes on that property value with
   * `object.on('change:prop', listener)`. You can get a list of all
   * properties with {@link module:ol/Object~BaseObject#getProperties}.
   *
   * Note that the observable properties are separate from standard JS properties.
   * You can, for example, give your map object a title with
   * `map.title='New title'` and with `map.set('title', 'Another title')`. The
   * first will be a `hasOwnProperty`; the second will appear in
   * `getProperties()`. Only the second is observable.
   *
   * Properties can be deleted by using the unset method. E.g.
   * object.unset('foo').
   *
   * @fires ObjectEvent
   * @api
   */
  class BaseObject extends Observable {
    /**
     * @param {Object<string, *>} [values] An object with key-value pairs.
     */
    constructor(values) {
      super();

      /***
       * @type {ObjectOnSignature<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {ObjectOnSignature<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {ObjectOnSignature<void>}
       */
      this.un;

      // Call {@link module:ol/util.getUid} to ensure that the order of objects' ids is
      // the same as the order in which they were created.  This also helps to
      // ensure that object properties are always added in the same order, which
      // helps many JavaScript engines generate faster code.
      getUid(this);

      /**
       * @private
       * @type {Object<string, *>|null}
       */
      this.values_ = null;

      if (values !== undefined) {
        this.setProperties(values);
      }
    }

    /**
     * Gets a value.
     * @param {string} key Key name.
     * @return {*} Value.
     * @api
     */
    get(key) {
      let value;
      if (this.values_ && this.values_.hasOwnProperty(key)) {
        value = this.values_[key];
      }
      return value;
    }

    /**
     * Get a list of object property names.
     * @return {Array<string>} List of property names.
     * @api
     */
    getKeys() {
      return (this.values_ && Object.keys(this.values_)) || [];
    }

    /**
     * Get an object of all property names and values.
     * @return {Object<string, *>} Object.
     * @api
     */
    getProperties() {
      return (this.values_ && Object.assign({}, this.values_)) || {};
    }

    /**
     * Get an object of all property names and values.
     * @return {Object<string, *>?} Object.
     */
    getPropertiesInternal() {
      return this.values_;
    }

    /**
     * @return {boolean} The object has properties.
     */
    hasProperties() {
      return !!this.values_;
    }

    /**
     * @param {string} key Key name.
     * @param {*} oldValue Old value.
     */
    notify(key, oldValue) {
      let eventType;
      eventType = `change:${key}`;
      if (this.hasListener(eventType)) {
        this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));
      }
      eventType = ObjectEventType.PROPERTYCHANGE;
      if (this.hasListener(eventType)) {
        this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));
      }
    }

    /**
     * @param {string} key Key name.
     * @param {import("./events.js").Listener} listener Listener.
     */
    addChangeListener(key, listener) {
      this.addEventListener(`change:${key}`, listener);
    }

    /**
     * @param {string} key Key name.
     * @param {import("./events.js").Listener} listener Listener.
     */
    removeChangeListener(key, listener) {
      this.removeEventListener(`change:${key}`, listener);
    }

    /**
     * Sets a value.
     * @param {string} key Key name.
     * @param {*} value Value.
     * @param {boolean} [silent] Update without triggering an event.
     * @api
     */
    set(key, value, silent) {
      const values = this.values_ || (this.values_ = {});
      if (silent) {
        values[key] = value;
      } else {
        const oldValue = values[key];
        values[key] = value;
        if (oldValue !== value) {
          this.notify(key, oldValue);
        }
      }
    }

    /**
     * Sets a collection of key-value pairs.  Note that this changes any existing
     * properties and adds new ones (it does not remove any existing properties).
     * @param {Object<string, *>} values Values.
     * @param {boolean} [silent] Update without triggering an event.
     * @api
     */
    setProperties(values, silent) {
      for (const key in values) {
        this.set(key, values[key], silent);
      }
    }

    /**
     * Apply any properties from another object without triggering events.
     * @param {BaseObject} source The source object.
     * @protected
     */
    applyProperties(source) {
      if (!source.values_) {
        return;
      }
      Object.assign(this.values_ || (this.values_ = {}), source.values_);
    }

    /**
     * Unsets a property.
     * @param {string} key Key name.
     * @param {boolean} [silent] Unset without triggering an event.
     * @api
     */
    unset(key, silent) {
      if (this.values_ && key in this.values_) {
        const oldValue = this.values_[key];
        delete this.values_[key];
        if (isEmpty$1(this.values_)) {
          this.values_ = null;
        }
        if (!silent) {
          this.notify(key, oldValue);
        }
      }
    }
  }

  /**
   * @module ol/Collection
   */

  /**
   * @enum {string}
   * @private
   */
  const Property$5 = {
    LENGTH: 'length',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/Collection~Collection} instances are instances of this
   * type.
   * @template T
   */
  class CollectionEvent extends BaseEvent {
    /**
     * @param {import("./CollectionEventType.js").default} type Type.
     * @param {T} element Element.
     * @param {number} index The index of the added or removed element.
     */
    constructor(type, element, index) {
      super(type);

      /**
       * The element that is added to or removed from the collection.
       * @type {T}
       * @api
       */
      this.element = element;

      /**
       * The index of the added or removed element.
       * @type {number}
       * @api
       */
      this.index = index;
    }
  }

  /***
   * @template T
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *   import("./Observable").OnSignature<import("./ObjectEventType").Types|'change:length', import("./Object").ObjectEvent, Return> &
   *   import("./Observable").OnSignature<'add'|'remove', CollectionEvent<T>, Return> &
   *   import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|import("./ObjectEventType").Types|
   *     'change:length'|'add'|'remove',Return>} CollectionOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {boolean} [unique=false] Disallow the same item from being added to
   * the collection twice.
   */

  /**
   * @classdesc
   * An expanded version of standard JS Array, adding convenience methods for
   * manipulation. Add and remove changes to the Collection trigger a Collection
   * event. Note that this does not cover changes to the objects _within_ the
   * Collection; they trigger events on the appropriate object, not on the
   * Collection as a whole.
   *
   * @fires CollectionEvent
   *
   * @template T
   * @api
   */
  class Collection extends BaseObject {
    /**
     * @param {Array<T>} [array] Array.
     * @param {Options} [options] Collection options.
     */
    constructor(array, options) {
      super();

      /***
       * @type {CollectionOnSignature<T, import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {CollectionOnSignature<T, import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {CollectionOnSignature<T, void>}
       */
      this.un;

      options = options || {};

      /**
       * @private
       * @type {boolean}
       */
      this.unique_ = !!options.unique;

      /**
       * @private
       * @type {!Array<T>}
       */
      this.array_ = array ? array : [];

      if (this.unique_) {
        for (let i = 0, ii = this.array_.length; i < ii; ++i) {
          this.assertUnique_(this.array_[i], i);
        }
      }

      this.updateLength_();
    }

    /**
     * Remove all elements from the collection.
     * @api
     */
    clear() {
      while (this.getLength() > 0) {
        this.pop();
      }
    }

    /**
     * Add elements to the collection.  This pushes each item in the provided array
     * to the end of the collection.
     * @param {!Array<T>} arr Array.
     * @return {Collection<T>} This collection.
     * @api
     */
    extend(arr) {
      for (let i = 0, ii = arr.length; i < ii; ++i) {
        this.push(arr[i]);
      }
      return this;
    }

    /**
     * Iterate over each element, calling the provided callback.
     * @param {function(T, number, Array<T>): *} f The function to call
     *     for every element. This function takes 3 arguments (the element, the
     *     index and the array). The return value is ignored.
     * @api
     */
    forEach(f) {
      const array = this.array_;
      for (let i = 0, ii = array.length; i < ii; ++i) {
        f(array[i], i, array);
      }
    }

    /**
     * Get a reference to the underlying Array object. Warning: if the array
     * is mutated, no events will be dispatched by the collection, and the
     * collection's "length" property won't be in sync with the actual length
     * of the array.
     * @return {!Array<T>} Array.
     * @api
     */
    getArray() {
      return this.array_;
    }

    /**
     * Get the element at the provided index.
     * @param {number} index Index.
     * @return {T} Element.
     * @api
     */
    item(index) {
      return this.array_[index];
    }

    /**
     * Get the length of this collection.
     * @return {number} The length of the array.
     * @observable
     * @api
     */
    getLength() {
      return this.get(Property$5.LENGTH);
    }

    /**
     * Insert an element at the provided index.
     * @param {number} index Index.
     * @param {T} elem Element.
     * @api
     */
    insertAt(index, elem) {
      if (index < 0 || index > this.getLength()) {
        throw new Error('Index out of bounds: ' + index);
      }
      if (this.unique_) {
        this.assertUnique_(elem);
      }
      this.array_.splice(index, 0, elem);
      this.updateLength_();
      this.dispatchEvent(
        new CollectionEvent(CollectionEventType.ADD, elem, index),
      );
    }

    /**
     * Remove the last element of the collection and return it.
     * Return `undefined` if the collection is empty.
     * @return {T|undefined} Element.
     * @api
     */
    pop() {
      return this.removeAt(this.getLength() - 1);
    }

    /**
     * Insert the provided element at the end of the collection.
     * @param {T} elem Element.
     * @return {number} New length of the collection.
     * @api
     */
    push(elem) {
      if (this.unique_) {
        this.assertUnique_(elem);
      }
      const n = this.getLength();
      this.insertAt(n, elem);
      return this.getLength();
    }

    /**
     * Remove the first occurrence of an element from the collection.
     * @param {T} elem Element.
     * @return {T|undefined} The removed element or undefined if none found.
     * @api
     */
    remove(elem) {
      const arr = this.array_;
      for (let i = 0, ii = arr.length; i < ii; ++i) {
        if (arr[i] === elem) {
          return this.removeAt(i);
        }
      }
      return undefined;
    }

    /**
     * Remove the element at the provided index and return it.
     * Return `undefined` if the collection does not contain this index.
     * @param {number} index Index.
     * @return {T|undefined} Value.
     * @api
     */
    removeAt(index) {
      if (index < 0 || index >= this.getLength()) {
        return undefined;
      }
      const prev = this.array_[index];
      this.array_.splice(index, 1);
      this.updateLength_();
      this.dispatchEvent(
        /** @type {CollectionEvent<T>} */ (
          new CollectionEvent(CollectionEventType.REMOVE, prev, index)
        ),
      );
      return prev;
    }

    /**
     * Set the element at the provided index.
     * @param {number} index Index.
     * @param {T} elem Element.
     * @api
     */
    setAt(index, elem) {
      const n = this.getLength();
      if (index >= n) {
        this.insertAt(index, elem);
        return;
      }
      if (index < 0) {
        throw new Error('Index out of bounds: ' + index);
      }
      if (this.unique_) {
        this.assertUnique_(elem, index);
      }
      const prev = this.array_[index];
      this.array_[index] = elem;
      this.dispatchEvent(
        /** @type {CollectionEvent<T>} */ (
          new CollectionEvent(CollectionEventType.REMOVE, prev, index)
        ),
      );
      this.dispatchEvent(
        /** @type {CollectionEvent<T>} */ (
          new CollectionEvent(CollectionEventType.ADD, elem, index)
        ),
      );
    }

    /**
     * @private
     */
    updateLength_() {
      this.set(Property$5.LENGTH, this.array_.length);
    }

    /**
     * @private
     * @param {T} elem Element.
     * @param {number} [except] Optional index to ignore.
     */
    assertUnique_(elem, except) {
      for (let i = 0, ii = this.array_.length; i < ii; ++i) {
        if (this.array_[i] === elem && i !== except) {
          throw new Error('Duplicate item added to a unique collection');
        }
      }
    }
  }

  /**
   * @module ol/asserts
   */

  /**
   * @param {*} assertion Assertion we expected to be truthy.
   * @param {string} errorMessage Error message.
   */
  function assert(assertion, errorMessage) {
    if (!assertion) {
      throw new Error(errorMessage);
    }
  }

  /**
   * @module ol/Feature
   */

  /**
   * @typedef {typeof Feature|typeof import("./render/Feature.js").default} FeatureClass
   */

  /**
   * @typedef {Feature|import("./render/Feature.js").default} FeatureLike
   */

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *   import("./Observable").OnSignature<import("./ObjectEventType").Types|'change:geometry', import("./Object").ObjectEvent, Return> &
   *   import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|import("./ObjectEventType").Types
   *     |'change:geometry', Return>} FeatureOnSignature
   */

  /***
   * @template {import("./geom/Geometry.js").default} [Geometry=import("./geom/Geometry.js").default]
   * @typedef {Object<string, *> & { geometry?: Geometry }} ObjectWithGeometry
   */

  /**
   * @classdesc
   * A vector object for geographic features with a geometry and other
   * attribute properties, similar to the features in vector file formats like
   * GeoJSON.
   *
   * Features can be styled individually with `setStyle`; otherwise they use the
   * style of their vector layer.
   *
   * Note that attribute properties are set as {@link module:ol/Object~BaseObject} properties on
   * the feature object, so they are observable, and have get/set accessors.
   *
   * Typically, a feature has a single geometry property. You can set the
   * geometry using the `setGeometry` method and get it with `getGeometry`.
   * It is possible to store more than one geometry on a feature using attribute
   * properties. By default, the geometry used for rendering is identified by
   * the property name `geometry`. If you want to use another geometry property
   * for rendering, use the `setGeometryName` method to change the attribute
   * property associated with the geometry for the feature.  For example:
   *
   * ```js
   *
   * import Feature from 'ol/Feature.js';
   * import Polygon from 'ol/geom/Polygon.js';
   * import Point from 'ol/geom/Point.js';
   *
   * const feature = new Feature({
   *   geometry: new Polygon(polyCoords),
   *   labelPoint: new Point(labelCoords),
   *   name: 'My Polygon',
   * });
   *
   * // get the polygon geometry
   * const poly = feature.getGeometry();
   *
   * // Render the feature as a point using the coordinates from labelPoint
   * feature.setGeometryName('labelPoint');
   *
   * // get the point geometry
   * const point = feature.getGeometry();
   * ```
   *
   * @api
   * @template {import("./geom/Geometry.js").default} [Geometry=import("./geom/Geometry.js").default]
   */
  class Feature extends BaseObject {
    /**
     * @param {Geometry|ObjectWithGeometry<Geometry>} [geometryOrProperties]
     *     You may pass a Geometry object directly, or an object literal containing
     *     properties. If you pass an object literal, you may include a Geometry
     *     associated with a `geometry` key.
     */
    constructor(geometryOrProperties) {
      super();

      /***
       * @type {FeatureOnSignature<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {FeatureOnSignature<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {FeatureOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {number|string|undefined}
       */
      this.id_ = undefined;

      /**
       * @type {string}
       * @private
       */
      this.geometryName_ = 'geometry';

      /**
       * User provided style.
       * @private
       * @type {import("./style/Style.js").StyleLike}
       */
      this.style_ = null;

      /**
       * @private
       * @type {import("./style/Style.js").StyleFunction|undefined}
       */
      this.styleFunction_ = undefined;

      /**
       * @private
       * @type {?import("./events.js").EventsKey}
       */
      this.geometryChangeKey_ = null;

      this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);

      if (geometryOrProperties) {
        if (
          typeof (
            /** @type {?} */ (geometryOrProperties).getSimplifiedGeometry
          ) === 'function'
        ) {
          const geometry = /** @type {Geometry} */ (geometryOrProperties);
          this.setGeometry(geometry);
        } else {
          /** @type {Object<string, *>} */
          const properties = geometryOrProperties;
          this.setProperties(properties);
        }
      }
    }

    /**
     * Clone this feature. If the original feature has a geometry it
     * is also cloned. The feature id is not set in the clone.
     * @return {Feature<Geometry>} The clone.
     * @api
     */
    clone() {
      const clone = /** @type {Feature<Geometry>} */ (
        new Feature(this.hasProperties() ? this.getProperties() : null)
      );
      clone.setGeometryName(this.getGeometryName());
      const geometry = this.getGeometry();
      if (geometry) {
        clone.setGeometry(/** @type {Geometry} */ (geometry.clone()));
      }
      const style = this.getStyle();
      if (style) {
        clone.setStyle(style);
      }
      return clone;
    }

    /**
     * Get the feature's default geometry.  A feature may have any number of named
     * geometries.  The "default" geometry (the one that is rendered by default) is
     * set when calling {@link module:ol/Feature~Feature#setGeometry}.
     * @return {Geometry|undefined} The default geometry for the feature.
     * @api
     * @observable
     */
    getGeometry() {
      return /** @type {Geometry|undefined} */ (this.get(this.geometryName_));
    }

    /**
     * Get the feature identifier.  This is a stable identifier for the feature and
     * is either set when reading data from a remote source or set explicitly by
     * calling {@link module:ol/Feature~Feature#setId}.
     * @return {number|string|undefined} Id.
     * @api
     */
    getId() {
      return this.id_;
    }

    /**
     * Get the name of the feature's default geometry.  By default, the default
     * geometry is named `geometry`.
     * @return {string} Get the property name associated with the default geometry
     *     for this feature.
     * @api
     */
    getGeometryName() {
      return this.geometryName_;
    }

    /**
     * Get the feature's style. Will return what was provided to the
     * {@link module:ol/Feature~Feature#setStyle} method.
     * @return {import("./style/Style.js").StyleLike|undefined} The feature style.
     * @api
     */
    getStyle() {
      return this.style_;
    }

    /**
     * Get the feature's style function.
     * @return {import("./style/Style.js").StyleFunction|undefined} Return a function
     * representing the current style of this feature.
     * @api
     */
    getStyleFunction() {
      return this.styleFunction_;
    }

    /**
     * @private
     */
    handleGeometryChange_() {
      this.changed();
    }

    /**
     * @private
     */
    handleGeometryChanged_() {
      if (this.geometryChangeKey_) {
        unlistenByKey(this.geometryChangeKey_);
        this.geometryChangeKey_ = null;
      }
      const geometry = this.getGeometry();
      if (geometry) {
        this.geometryChangeKey_ = listen(
          geometry,
          EventType.CHANGE,
          this.handleGeometryChange_,
          this,
        );
      }
      this.changed();
    }

    /**
     * Set the default geometry for the feature.  This will update the property
     * with the name returned by {@link module:ol/Feature~Feature#getGeometryName}.
     * @param {Geometry|undefined} geometry The new geometry.
     * @api
     * @observable
     */
    setGeometry(geometry) {
      this.set(this.geometryName_, geometry);
    }

    /**
     * Set the style for the feature to override the layer style.  This can be a
     * single style object, an array of styles, or a function that takes a
     * resolution and returns an array of styles. To unset the feature style, call
     * `setStyle()` without arguments or a falsey value.
     * @param {import("./style/Style.js").StyleLike} [style] Style for this feature.
     * @api
     * @fires module:ol/events/Event~BaseEvent#event:change
     */
    setStyle(style) {
      this.style_ = style;
      this.styleFunction_ = !style ? undefined : createStyleFunction(style);
      this.changed();
    }

    /**
     * Set the feature id.  The feature id is considered stable and may be used when
     * requesting features or comparing identifiers returned from a remote source.
     * The feature id can be used with the
     * {@link module:ol/source/Vector~VectorSource#getFeatureById} method.
     * @param {number|string|undefined} id The feature id.
     * @api
     * @fires module:ol/events/Event~BaseEvent#event:change
     */
    setId(id) {
      this.id_ = id;
      this.changed();
    }

    /**
     * Set the property name to be used when getting the feature's default geometry.
     * When calling {@link module:ol/Feature~Feature#getGeometry}, the value of the property with
     * this name will be returned.
     * @param {string} name The property name of the default geometry.
     * @api
     */
    setGeometryName(name) {
      this.removeChangeListener(this.geometryName_, this.handleGeometryChanged_);
      this.geometryName_ = name;
      this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);
      this.handleGeometryChanged_();
    }
  }

  /**
   * Convert the provided object into a feature style function.  Functions passed
   * through unchanged.  Arrays of Style or single style objects wrapped
   * in a new feature style function.
   * @param {!import("./style/Style.js").StyleFunction|!Array<import("./style/Style.js").default>|!import("./style/Style.js").default} obj
   *     A feature style function, a single style, or an array of styles.
   * @return {import("./style/Style.js").StyleFunction} A style function.
   */
  function createStyleFunction(obj) {
    if (typeof obj === 'function') {
      return obj;
    }
    /**
     * @type {Array<import("./style/Style.js").default>}
     */
    let styles;
    if (Array.isArray(obj)) {
      styles = obj;
    } else {
      assert(
        typeof (/** @type {?} */ (obj).getZIndex) === 'function',
        'Expected an `ol/style/Style` or an array of `ol/style/Style.js`',
      );
      const style = /** @type {import("./style/Style.js").default} */ (obj);
      styles = [style];
    }
    return function () {
      return styles;
    };
  }

  /**
   * @module ol/extent/Relationship
   */

  /**
   * Relationship to an extent.
   * @enum {number}
   */
  var Relationship = {
    UNKNOWN: 0,
    INTERSECTING: 1,
    ABOVE: 2,
    RIGHT: 4,
    BELOW: 8,
    LEFT: 16,
  };

  /**
   * @module ol/extent
   */

  /**
   * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`.
   * @typedef {Array<number>} Extent
   * @api
   */

  /**
   * Extent corner.
   * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} Corner
   */

  /**
   * Build an extent that includes all given coordinates.
   *
   * @param {Array<import("./coordinate.js").Coordinate>} coordinates Coordinates.
   * @return {Extent} Bounding extent.
   * @api
   */
  function boundingExtent(coordinates) {
    const extent = createEmpty();
    for (let i = 0, ii = coordinates.length; i < ii; ++i) {
      extendCoordinate(extent, coordinates[i]);
    }
    return extent;
  }

  /**
   * @param {Array<number>} xs Xs.
   * @param {Array<number>} ys Ys.
   * @param {Extent} [dest] Destination extent.
   * @private
   * @return {Extent} Extent.
   */
  function _boundingExtentXYs(xs, ys, dest) {
    const minX = Math.min.apply(null, xs);
    const minY = Math.min.apply(null, ys);
    const maxX = Math.max.apply(null, xs);
    const maxY = Math.max.apply(null, ys);
    return createOrUpdate$2(minX, minY, maxX, maxY, dest);
  }

  /**
   * Return extent increased by the provided value.
   * @param {Extent} extent Extent.
   * @param {number} value The amount by which the extent should be buffered.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   * @api
   */
  function buffer$1(extent, value, dest) {
    if (dest) {
      dest[0] = extent[0] - value;
      dest[1] = extent[1] - value;
      dest[2] = extent[2] + value;
      dest[3] = extent[3] + value;
      return dest;
    }
    return [
      extent[0] - value,
      extent[1] - value,
      extent[2] + value,
      extent[3] + value,
    ];
  }

  /**
   * Creates a clone of an extent.
   *
   * @param {Extent} extent Extent to clone.
   * @param {Extent} [dest] Extent.
   * @return {Extent} The clone.
   */
  function clone(extent, dest) {
    if (dest) {
      dest[0] = extent[0];
      dest[1] = extent[1];
      dest[2] = extent[2];
      dest[3] = extent[3];
      return dest;
    }
    return extent.slice();
  }

  /**
   * @param {Extent} extent Extent.
   * @param {number} x X.
   * @param {number} y Y.
   * @return {number} Closest squared distance.
   */
  function closestSquaredDistanceXY(extent, x, y) {
    let dx, dy;
    if (x < extent[0]) {
      dx = extent[0] - x;
    } else if (extent[2] < x) {
      dx = x - extent[2];
    } else {
      dx = 0;
    }
    if (y < extent[1]) {
      dy = extent[1] - y;
    } else if (extent[3] < y) {
      dy = y - extent[3];
    } else {
      dy = 0;
    }
    return dx * dx + dy * dy;
  }

  /**
   * Check if the passed coordinate is contained or on the edge of the extent.
   *
   * @param {Extent} extent Extent.
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
   * @return {boolean} The coordinate is contained in the extent.
   * @api
   */
  function containsCoordinate(extent, coordinate) {
    return containsXY(extent, coordinate[0], coordinate[1]);
  }

  /**
   * Check if one extent contains another.
   *
   * An extent is deemed contained if it lies completely within the other extent,
   * including if they share one or more edges.
   *
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @return {boolean} The second extent is contained by or on the edge of the
   *     first.
   * @api
   */
  function containsExtent(extent1, extent2) {
    return (
      extent1[0] <= extent2[0] &&
      extent2[2] <= extent1[2] &&
      extent1[1] <= extent2[1] &&
      extent2[3] <= extent1[3]
    );
  }

  /**
   * Check if the passed coordinate is contained or on the edge of the extent.
   *
   * @param {Extent} extent Extent.
   * @param {number} x X coordinate.
   * @param {number} y Y coordinate.
   * @return {boolean} The x, y values are contained in the extent.
   * @api
   */
  function containsXY(extent, x, y) {
    return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3];
  }

  /**
   * Get the relationship between a coordinate and extent.
   * @param {Extent} extent The extent.
   * @param {import("./coordinate.js").Coordinate} coordinate The coordinate.
   * @return {import("./extent/Relationship.js").default} The relationship (bitwise compare with
   *     import("./extent/Relationship.js").Relationship).
   */
  function coordinateRelationship(extent, coordinate) {
    const minX = extent[0];
    const minY = extent[1];
    const maxX = extent[2];
    const maxY = extent[3];
    const x = coordinate[0];
    const y = coordinate[1];
    let relationship = Relationship.UNKNOWN;
    if (x < minX) {
      relationship = relationship | Relationship.LEFT;
    } else if (x > maxX) {
      relationship = relationship | Relationship.RIGHT;
    }
    if (y < minY) {
      relationship = relationship | Relationship.BELOW;
    } else if (y > maxY) {
      relationship = relationship | Relationship.ABOVE;
    }
    if (relationship === Relationship.UNKNOWN) {
      relationship = Relationship.INTERSECTING;
    }
    return relationship;
  }

  /**
   * Create an empty extent.
   * @return {Extent} Empty extent.
   * @api
   */
  function createEmpty() {
    return [Infinity, Infinity, -Infinity, -Infinity];
  }

  /**
   * Create a new extent or update the provided extent.
   * @param {number} minX Minimum X.
   * @param {number} minY Minimum Y.
   * @param {number} maxX Maximum X.
   * @param {number} maxY Maximum Y.
   * @param {Extent} [dest] Destination extent.
   * @return {Extent} Extent.
   */
  function createOrUpdate$2(minX, minY, maxX, maxY, dest) {
    if (dest) {
      dest[0] = minX;
      dest[1] = minY;
      dest[2] = maxX;
      dest[3] = maxY;
      return dest;
    }
    return [minX, minY, maxX, maxY];
  }

  /**
   * Create a new empty extent or make the provided one empty.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function createOrUpdateEmpty(dest) {
    return createOrUpdate$2(Infinity, Infinity, -Infinity, -Infinity, dest);
  }

  /**
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function createOrUpdateFromCoordinate(coordinate, dest) {
    const x = coordinate[0];
    const y = coordinate[1];
    return createOrUpdate$2(x, y, x, y, dest);
  }

  /**
   * @param {Array<import("./coordinate.js").Coordinate>} coordinates Coordinates.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function createOrUpdateFromCoordinates(coordinates, dest) {
    const extent = createOrUpdateEmpty(dest);
    return extendCoordinates(extent, coordinates);
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function createOrUpdateFromFlatCoordinates(
    flatCoordinates,
    offset,
    end,
    stride,
    dest,
  ) {
    const extent = createOrUpdateEmpty(dest);
    return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride);
  }

  /**
   * @param {Array<Array<import("./coordinate.js").Coordinate>>} rings Rings.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function createOrUpdateFromRings(rings, dest) {
    const extent = createOrUpdateEmpty(dest);
    return extendRings(extent, rings);
  }

  /**
   * Determine if two extents are equivalent.
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @return {boolean} The two extents are equivalent.
   * @api
   */
  function equals$1(extent1, extent2) {
    return (
      extent1[0] == extent2[0] &&
      extent1[2] == extent2[2] &&
      extent1[1] == extent2[1] &&
      extent1[3] == extent2[3]
    );
  }

  /**
   * Determine if two extents are approximately equivalent.
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @param {number} tolerance Tolerance in extent coordinate units.
   * @return {boolean} The two extents differ by less than the tolerance.
   */
  function approximatelyEquals(extent1, extent2, tolerance) {
    return (
      Math.abs(extent1[0] - extent2[0]) < tolerance &&
      Math.abs(extent1[2] - extent2[2]) < tolerance &&
      Math.abs(extent1[1] - extent2[1]) < tolerance &&
      Math.abs(extent1[3] - extent2[3]) < tolerance
    );
  }

  /**
   * Modify an extent to include another extent.
   * @param {Extent} extent1 The extent to be modified.
   * @param {Extent} extent2 The extent that will be included in the first.
   * @return {Extent} A reference to the first (extended) extent.
   * @api
   */
  function extend$1(extent1, extent2) {
    if (extent2[0] < extent1[0]) {
      extent1[0] = extent2[0];
    }
    if (extent2[2] > extent1[2]) {
      extent1[2] = extent2[2];
    }
    if (extent2[1] < extent1[1]) {
      extent1[1] = extent2[1];
    }
    if (extent2[3] > extent1[3]) {
      extent1[3] = extent2[3];
    }
    return extent1;
  }

  /**
   * @param {Extent} extent Extent.
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
   */
  function extendCoordinate(extent, coordinate) {
    if (coordinate[0] < extent[0]) {
      extent[0] = coordinate[0];
    }
    if (coordinate[0] > extent[2]) {
      extent[2] = coordinate[0];
    }
    if (coordinate[1] < extent[1]) {
      extent[1] = coordinate[1];
    }
    if (coordinate[1] > extent[3]) {
      extent[3] = coordinate[1];
    }
  }

  /**
   * @param {Extent} extent Extent.
   * @param {Array<import("./coordinate.js").Coordinate>} coordinates Coordinates.
   * @return {Extent} Extent.
   */
  function extendCoordinates(extent, coordinates) {
    for (let i = 0, ii = coordinates.length; i < ii; ++i) {
      extendCoordinate(extent, coordinates[i]);
    }
    return extent;
  }

  /**
   * @param {Extent} extent Extent.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @return {Extent} Extent.
   */
  function extendFlatCoordinates(
    extent,
    flatCoordinates,
    offset,
    end,
    stride,
  ) {
    for (; offset < end; offset += stride) {
      extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]);
    }
    return extent;
  }

  /**
   * @param {Extent} extent Extent.
   * @param {Array<Array<import("./coordinate.js").Coordinate>>} rings Rings.
   * @return {Extent} Extent.
   */
  function extendRings(extent, rings) {
    for (let i = 0, ii = rings.length; i < ii; ++i) {
      extendCoordinates(extent, rings[i]);
    }
    return extent;
  }

  /**
   * @param {Extent} extent Extent.
   * @param {number} x X.
   * @param {number} y Y.
   */
  function extendXY(extent, x, y) {
    extent[0] = Math.min(extent[0], x);
    extent[1] = Math.min(extent[1], y);
    extent[2] = Math.max(extent[2], x);
    extent[3] = Math.max(extent[3], y);
  }

  /**
   * This function calls `callback` for each corner of the extent. If the
   * callback returns a truthy value the function returns that value
   * immediately. Otherwise the function returns `false`.
   * @param {Extent} extent Extent.
   * @param {function(import("./coordinate.js").Coordinate): S} callback Callback.
   * @return {S|boolean} Value.
   * @template S
   */
  function forEachCorner(extent, callback) {
    let val;
    val = callback(getBottomLeft(extent));
    if (val) {
      return val;
    }
    val = callback(getBottomRight(extent));
    if (val) {
      return val;
    }
    val = callback(getTopRight(extent));
    if (val) {
      return val;
    }
    val = callback(getTopLeft(extent));
    if (val) {
      return val;
    }
    return false;
  }

  /**
   * Get the size of an extent.
   * @param {Extent} extent Extent.
   * @return {number} Area.
   * @api
   */
  function getArea$1(extent) {
    let area = 0;
    if (!isEmpty(extent)) {
      area = getWidth(extent) * getHeight(extent);
    }
    return area;
  }

  /**
   * Get the bottom left coordinate of an extent.
   * @param {Extent} extent Extent.
   * @return {import("./coordinate.js").Coordinate} Bottom left coordinate.
   * @api
   */
  function getBottomLeft(extent) {
    return [extent[0], extent[1]];
  }

  /**
   * Get the bottom right coordinate of an extent.
   * @param {Extent} extent Extent.
   * @return {import("./coordinate.js").Coordinate} Bottom right coordinate.
   * @api
   */
  function getBottomRight(extent) {
    return [extent[2], extent[1]];
  }

  /**
   * Get the center coordinate of an extent.
   * @param {Extent} extent Extent.
   * @return {import("./coordinate.js").Coordinate} Center.
   * @api
   */
  function getCenter(extent) {
    return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];
  }

  /**
   * Get a corner coordinate of an extent.
   * @param {Extent} extent Extent.
   * @param {Corner} corner Corner.
   * @return {import("./coordinate.js").Coordinate} Corner coordinate.
   */
  function getCorner(extent, corner) {
    let coordinate;
    if (corner === 'bottom-left') {
      coordinate = getBottomLeft(extent);
    } else if (corner === 'bottom-right') {
      coordinate = getBottomRight(extent);
    } else if (corner === 'top-left') {
      coordinate = getTopLeft(extent);
    } else if (corner === 'top-right') {
      coordinate = getTopRight(extent);
    } else {
      throw new Error('Invalid corner');
    }
    return coordinate;
  }

  /**
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @return {number} Enlarged area.
   */
  function getEnlargedArea(extent1, extent2) {
    const minX = Math.min(extent1[0], extent2[0]);
    const minY = Math.min(extent1[1], extent2[1]);
    const maxX = Math.max(extent1[2], extent2[2]);
    const maxY = Math.max(extent1[3], extent2[3]);
    return (maxX - minX) * (maxY - minY);
  }

  /**
   * @param {import("./coordinate.js").Coordinate} center Center.
   * @param {number} resolution Resolution.
   * @param {number} rotation Rotation.
   * @param {import("./size.js").Size} size Size.
   * @param {Extent} [dest] Destination extent.
   * @return {Extent} Extent.
   */
  function getForViewAndSize(center, resolution, rotation, size, dest) {
    const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport(
      center,
      resolution,
      rotation,
      size,
    );
    return createOrUpdate$2(
      Math.min(x0, x1, x2, x3),
      Math.min(y0, y1, y2, y3),
      Math.max(x0, x1, x2, x3),
      Math.max(y0, y1, y2, y3),
      dest,
    );
  }

  /**
   * @param {import("./coordinate.js").Coordinate} center Center.
   * @param {number} resolution Resolution.
   * @param {number} rotation Rotation.
   * @param {import("./size.js").Size} size Size.
   * @return {Array<number>} Linear ring representing the viewport.
   */
  function getRotatedViewport(center, resolution, rotation, size) {
    const dx = (resolution * size[0]) / 2;
    const dy = (resolution * size[1]) / 2;
    const cosRotation = Math.cos(rotation);
    const sinRotation = Math.sin(rotation);
    const xCos = dx * cosRotation;
    const xSin = dx * sinRotation;
    const yCos = dy * cosRotation;
    const ySin = dy * sinRotation;
    const x = center[0];
    const y = center[1];
    return [
      x - xCos + ySin,
      y - xSin - yCos,
      x - xCos - ySin,
      y - xSin + yCos,
      x + xCos - ySin,
      y + xSin + yCos,
      x + xCos + ySin,
      y + xSin - yCos,
      x - xCos + ySin,
      y - xSin - yCos,
    ];
  }

  /**
   * Get the height of an extent.
   * @param {Extent} extent Extent.
   * @return {number} Height.
   * @api
   */
  function getHeight(extent) {
    return extent[3] - extent[1];
  }

  /**
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @return {number} Intersection area.
   */
  function getIntersectionArea(extent1, extent2) {
    const intersection = getIntersection(extent1, extent2);
    return getArea$1(intersection);
  }

  /**
   * Get the intersection of two extents.
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent 2.
   * @param {Extent} [dest] Optional extent to populate with intersection.
   * @return {Extent} Intersecting extent.
   * @api
   */
  function getIntersection(extent1, extent2, dest) {
    const intersection = dest ? dest : createEmpty();
    if (intersects$2(extent1, extent2)) {
      if (extent1[0] > extent2[0]) {
        intersection[0] = extent1[0];
      } else {
        intersection[0] = extent2[0];
      }
      if (extent1[1] > extent2[1]) {
        intersection[1] = extent1[1];
      } else {
        intersection[1] = extent2[1];
      }
      if (extent1[2] < extent2[2]) {
        intersection[2] = extent1[2];
      } else {
        intersection[2] = extent2[2];
      }
      if (extent1[3] < extent2[3]) {
        intersection[3] = extent1[3];
      } else {
        intersection[3] = extent2[3];
      }
    } else {
      createOrUpdateEmpty(intersection);
    }
    return intersection;
  }

  /**
   * @param {Extent} extent Extent.
   * @return {number} Margin.
   */
  function getMargin(extent) {
    return getWidth(extent) + getHeight(extent);
  }

  /**
   * Get the size (width, height) of an extent.
   * @param {Extent} extent The extent.
   * @return {import("./size.js").Size} The extent size.
   * @api
   */
  function getSize(extent) {
    return [extent[2] - extent[0], extent[3] - extent[1]];
  }

  /**
   * Get the top left coordinate of an extent.
   * @param {Extent} extent Extent.
   * @return {import("./coordinate.js").Coordinate} Top left coordinate.
   * @api
   */
  function getTopLeft(extent) {
    return [extent[0], extent[3]];
  }

  /**
   * Get the top right coordinate of an extent.
   * @param {Extent} extent Extent.
   * @return {import("./coordinate.js").Coordinate} Top right coordinate.
   * @api
   */
  function getTopRight(extent) {
    return [extent[2], extent[3]];
  }

  /**
   * Get the width of an extent.
   * @param {Extent} extent Extent.
   * @return {number} Width.
   * @api
   */
  function getWidth(extent) {
    return extent[2] - extent[0];
  }

  /**
   * Determine if one extent intersects another.
   * @param {Extent} extent1 Extent 1.
   * @param {Extent} extent2 Extent.
   * @return {boolean} The two extents intersect.
   * @api
   */
  function intersects$2(extent1, extent2) {
    return (
      extent1[0] <= extent2[2] &&
      extent1[2] >= extent2[0] &&
      extent1[1] <= extent2[3] &&
      extent1[3] >= extent2[1]
    );
  }

  /**
   * Determine if an extent is empty.
   * @param {Extent} extent Extent.
   * @return {boolean} Is empty.
   * @api
   */
  function isEmpty(extent) {
    return extent[2] < extent[0] || extent[3] < extent[1];
  }

  /**
   * @param {Extent} extent Extent.
   * @param {Extent} [dest] Extent.
   * @return {Extent} Extent.
   */
  function returnOrUpdate(extent, dest) {
    if (dest) {
      dest[0] = extent[0];
      dest[1] = extent[1];
      dest[2] = extent[2];
      dest[3] = extent[3];
      return dest;
    }
    return extent;
  }

  /**
   * @param {Extent} extent Extent.
   * @param {number} value Value.
   */
  function scaleFromCenter(extent, value) {
    const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1);
    const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1);
    extent[0] -= deltaX;
    extent[2] += deltaX;
    extent[1] -= deltaY;
    extent[3] += deltaY;
  }

  /**
   * Determine if the segment between two coordinates intersects (crosses,
   * touches, or is contained by) the provided extent.
   * @param {Extent} extent The extent.
   * @param {import("./coordinate.js").Coordinate} start Segment start coordinate.
   * @param {import("./coordinate.js").Coordinate} end Segment end coordinate.
   * @return {boolean} The segment intersects the extent.
   */
  function intersectsSegment(extent, start, end) {
    let intersects = false;
    const startRel = coordinateRelationship(extent, start);
    const endRel = coordinateRelationship(extent, end);
    if (
      startRel === Relationship.INTERSECTING ||
      endRel === Relationship.INTERSECTING
    ) {
      intersects = true;
    } else {
      const minX = extent[0];
      const minY = extent[1];
      const maxX = extent[2];
      const maxY = extent[3];
      const startX = start[0];
      const startY = start[1];
      const endX = end[0];
      const endY = end[1];
      const slope = (endY - startY) / (endX - startX);
      let x, y;
      if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) {
        // potentially intersects top
        x = endX - (endY - maxY) / slope;
        intersects = x >= minX && x <= maxX;
      }
      if (
        !intersects &&
        !!(endRel & Relationship.RIGHT) &&
        !(startRel & Relationship.RIGHT)
      ) {
        // potentially intersects right
        y = endY - (endX - maxX) * slope;
        intersects = y >= minY && y <= maxY;
      }
      if (
        !intersects &&
        !!(endRel & Relationship.BELOW) &&
        !(startRel & Relationship.BELOW)
      ) {
        // potentially intersects bottom
        x = endX - (endY - minY) / slope;
        intersects = x >= minX && x <= maxX;
      }
      if (
        !intersects &&
        !!(endRel & Relationship.LEFT) &&
        !(startRel & Relationship.LEFT)
      ) {
        // potentially intersects left
        y = endY - (endX - minX) * slope;
        intersects = y >= minY && y <= maxY;
      }
    }
    return intersects;
  }

  /**
   * Apply a transform function to the extent.
   * @param {Extent} extent Extent.
   * @param {import("./proj.js").TransformFunction} transformFn Transform function.
   * Called with `[minX, minY, maxX, maxY]` extent coordinates.
   * @param {Extent} [dest] Destination extent.
   * @param {number} [stops] Number of stops per side used for the transform.
   * By default only the corners are used.
   * @return {Extent} Extent.
   * @api
   */
  function applyTransform(extent, transformFn, dest, stops) {
    if (isEmpty(extent)) {
      return createOrUpdateEmpty(dest);
    }
    let coordinates = [];
    if (stops > 1) {
      const width = extent[2] - extent[0];
      const height = extent[3] - extent[1];
      for (let i = 0; i < stops; ++i) {
        coordinates.push(
          extent[0] + (width * i) / stops,
          extent[1],
          extent[2],
          extent[1] + (height * i) / stops,
          extent[2] - (width * i) / stops,
          extent[3],
          extent[0],
          extent[3] - (height * i) / stops,
        );
      }
    } else {
      coordinates = [
        extent[0],
        extent[1],
        extent[2],
        extent[1],
        extent[2],
        extent[3],
        extent[0],
        extent[3],
      ];
    }
    transformFn(coordinates, coordinates, 2);
    const xs = [];
    const ys = [];
    for (let i = 0, l = coordinates.length; i < l; i += 2) {
      xs.push(coordinates[i]);
      ys.push(coordinates[i + 1]);
    }
    return _boundingExtentXYs(xs, ys, dest);
  }

  /**
   * Modifies the provided extent in-place to be within the real world
   * extent.
   *
   * @param {Extent} extent Extent.
   * @param {import("./proj/Projection.js").default} projection Projection
   * @return {Extent} The extent within the real world extent.
   */
  function wrapX$2(extent, projection) {
    const projectionExtent = projection.getExtent();
    const center = getCenter(extent);
    if (
      projection.canWrapX() &&
      (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2])
    ) {
      const worldWidth = getWidth(projectionExtent);
      const worldsAway = Math.floor(
        (center[0] - projectionExtent[0]) / worldWidth,
      );
      const offset = worldsAway * worldWidth;
      extent[0] -= offset;
      extent[2] -= offset;
    }
    return extent;
  }

  /**
   * Fits the extent to the real world
   *
   * If the extent does not cross the anti meridian, this will return the extent in an array
   * If the extent crosses the anti meridian, the extent will be sliced, so each part fits within the
   * real world
   *
   *
   * @param {Extent} extent Extent.
   * @param {import("./proj/Projection.js").default} projection Projection
   * @param {boolean} [multiWorld] Return all worlds
   * @return {Array<Extent>} The extent within the real world extent.
   */
  function wrapAndSliceX(extent, projection, multiWorld) {
    if (projection.canWrapX()) {
      const projectionExtent = projection.getExtent();

      if (!isFinite(extent[0]) || !isFinite(extent[2])) {
        return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];
      }

      wrapX$2(extent, projection);
      const worldWidth = getWidth(projectionExtent);

      if (getWidth(extent) > worldWidth && !multiWorld) {
        // the extent wraps around on itself
        return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];
      }
      if (extent[0] < projectionExtent[0]) {
        // the extent crosses the anti meridian, so it needs to be sliced
        return [
          [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]],
          [projectionExtent[0], extent[1], extent[2], extent[3]],
        ];
      }
      if (extent[2] > projectionExtent[2]) {
        // the extent crosses the anti meridian, so it needs to be sliced
        return [
          [extent[0], extent[1], projectionExtent[2], extent[3]],
          [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]],
        ];
      }
    }

    return [extent];
  }

  var nsExtent = {
    __proto__: null,
    applyTransform: applyTransform,
    approximatelyEquals: approximatelyEquals,
    boundingExtent: boundingExtent,
    buffer: buffer$1,
    clone: clone,
    closestSquaredDistanceXY: closestSquaredDistanceXY,
    containsCoordinate: containsCoordinate,
    containsExtent: containsExtent,
    containsXY: containsXY,
    coordinateRelationship: coordinateRelationship,
    createEmpty: createEmpty,
    createOrUpdate: createOrUpdate$2,
    createOrUpdateEmpty: createOrUpdateEmpty,
    createOrUpdateFromCoordinate: createOrUpdateFromCoordinate,
    createOrUpdateFromCoordinates: createOrUpdateFromCoordinates,
    createOrUpdateFromFlatCoordinates: createOrUpdateFromFlatCoordinates,
    createOrUpdateFromRings: createOrUpdateFromRings,
    equals: equals$1,
    extend: extend$1,
    extendCoordinate: extendCoordinate,
    extendCoordinates: extendCoordinates,
    extendFlatCoordinates: extendFlatCoordinates,
    extendRings: extendRings,
    extendXY: extendXY,
    forEachCorner: forEachCorner,
    getArea: getArea$1,
    getBottomLeft: getBottomLeft,
    getBottomRight: getBottomRight,
    getCenter: getCenter,
    getCorner: getCorner,
    getEnlargedArea: getEnlargedArea,
    getForViewAndSize: getForViewAndSize,
    getHeight: getHeight,
    getIntersection: getIntersection,
    getIntersectionArea: getIntersectionArea,
    getMargin: getMargin,
    getRotatedViewport: getRotatedViewport,
    getSize: getSize,
    getTopLeft: getTopLeft,
    getTopRight: getTopRight,
    getWidth: getWidth,
    intersects: intersects$2,
    intersectsSegment: intersectsSegment,
    isEmpty: isEmpty,
    returnOrUpdate: returnOrUpdate,
    scaleFromCenter: scaleFromCenter,
    wrapAndSliceX: wrapAndSliceX,
    wrapX: wrapX$2
  };

  /**
   * @module ol/math
   */

  /**
   * Takes a number and clamps it to within the provided bounds.
   * @param {number} value The input number.
   * @param {number} min The minimum value to return.
   * @param {number} max The maximum value to return.
   * @return {number} The input number if it is within bounds, or the nearest
   *     number within the bounds.
   */
  function clamp$1(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }

  /**
   * Returns the square of the closest distance between the point (x, y) and the
   * line segment (x1, y1) to (x2, y2).
   * @param {number} x X.
   * @param {number} y Y.
   * @param {number} x1 X1.
   * @param {number} y1 Y1.
   * @param {number} x2 X2.
   * @param {number} y2 Y2.
   * @return {number} Squared distance.
   */
  function squaredSegmentDistance(x, y, x1, y1, x2, y2) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    if (dx !== 0 || dy !== 0) {
      const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
      if (t > 1) {
        x1 = x2;
        y1 = y2;
      } else if (t > 0) {
        x1 += dx * t;
        y1 += dy * t;
      }
    }
    return squaredDistance$1(x, y, x1, y1);
  }

  /**
   * Returns the square of the distance between the points (x1, y1) and (x2, y2).
   * @param {number} x1 X1.
   * @param {number} y1 Y1.
   * @param {number} x2 X2.
   * @param {number} y2 Y2.
   * @return {number} Squared distance.
   */
  function squaredDistance$1(x1, y1, x2, y2) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    return dx * dx + dy * dy;
  }

  /**
   * Solves system of linear equations using Gaussian elimination method.
   *
   * @param {Array<Array<number>>} mat Augmented matrix (n x n + 1 column)
   *                                     in row-major order.
   * @return {Array<number>|null} The resulting vector.
   */
  function solveLinearSystem(mat) {
    const n = mat.length;

    for (let i = 0; i < n; i++) {
      // Find max in the i-th column (ignoring i - 1 first rows)
      let maxRow = i;
      let maxEl = Math.abs(mat[i][i]);
      for (let r = i + 1; r < n; r++) {
        const absValue = Math.abs(mat[r][i]);
        if (absValue > maxEl) {
          maxEl = absValue;
          maxRow = r;
        }
      }

      if (maxEl === 0) {
        return null; // matrix is singular
      }

      // Swap max row with i-th (current) row
      const tmp = mat[maxRow];
      mat[maxRow] = mat[i];
      mat[i] = tmp;

      // Subtract the i-th row to make all the remaining rows 0 in the i-th column
      for (let j = i + 1; j < n; j++) {
        const coef = -mat[j][i] / mat[i][i];
        for (let k = i; k < n + 1; k++) {
          if (i == k) {
            mat[j][k] = 0;
          } else {
            mat[j][k] += coef * mat[i][k];
          }
        }
      }
    }

    // Solve Ax=b for upper triangular matrix A (mat)
    const x = new Array(n);
    for (let l = n - 1; l >= 0; l--) {
      x[l] = mat[l][n] / mat[l][l];
      for (let m = l - 1; m >= 0; m--) {
        mat[m][n] -= mat[m][l] * x[l];
      }
    }
    return x;
  }

  /**
   * Converts radians to to degrees.
   *
   * @param {number} angleInRadians Angle in radians.
   * @return {number} Angle in degrees.
   */
  function toDegrees(angleInRadians) {
    return (angleInRadians * 180) / Math.PI;
  }

  /**
   * Converts degrees to radians.
   *
   * @param {number} angleInDegrees Angle in degrees.
   * @return {number} Angle in radians.
   */
  function toRadians(angleInDegrees) {
    return (angleInDegrees * Math.PI) / 180;
  }

  /**
   * Returns the modulo of a / b, depending on the sign of b.
   *
   * @param {number} a Dividend.
   * @param {number} b Divisor.
   * @return {number} Modulo.
   */
  function modulo(a, b) {
    const r = a % b;
    return r * b < 0 ? r + b : r;
  }

  /**
   * Calculates the linearly interpolated value of x between a and b.
   *
   * @param {number} a Number
   * @param {number} b Number
   * @param {number} x Value to be interpolated.
   * @return {number} Interpolated value.
   */
  function lerp$1(a, b, x) {
    return a + x * (b - a);
  }

  /**
   * Returns a number with a limited number of decimal digits.
   * @param {number} n The input number.
   * @param {number} decimals The maximum number of decimal digits.
   * @return {number} The input number with a limited number of decimal digits.
   */
  function toFixed(n, decimals) {
    const factor = Math.pow(10, decimals);
    return Math.round(n * factor) / factor;
  }

  /**
   * Rounds a number to the nearest integer value considering only the given number
   * of decimal digits (with rounding on the final digit).
   * @param {number} n The input number.
   * @param {number} decimals The maximum number of decimal digits.
   * @return {number} The nearest integer.
   */
  function round(n, decimals) {
    return Math.round(toFixed(n, decimals));
  }

  /**
   * Rounds a number to the next smaller integer considering only the given number
   * of decimal digits (with rounding on the final digit).
   * @param {number} n The input number.
   * @param {number} decimals The maximum number of decimal digits.
   * @return {number} The next smaller integer.
   */
  function floor(n, decimals) {
    return Math.floor(toFixed(n, decimals));
  }

  /**
   * Rounds a number to the next bigger integer considering only the given number
   * of decimal digits (with rounding on the final digit).
   * @param {number} n The input number.
   * @param {number} decimals The maximum number of decimal digits.
   * @return {number} The next bigger integer.
   */
  function ceil(n, decimals) {
    return Math.ceil(toFixed(n, decimals));
  }

  /**
   * Wraps a number between some minimum and maximum values.
   * @param {number} n The number to wrap.
   * @param {number} min The minimum of the range (inclusive).
   * @param {number} max The maximum of the range (exclusive).
   * @return {number} The wrapped number.
   */
  function wrap(n, min, max) {
    if (n >= min && n < max) {
      return n;
    }
    const range = max - min;
    return ((((n - min) % range) + range) % range) + min;
  }

  /**
   * @module ol/sphere
   */

  /**
   * Object literal with options for the {@link getLength} or {@link getArea}
   * functions.
   * @typedef {Object} SphereMetricOptions
   * @property {import("./proj.js").ProjectionLike} [projection='EPSG:3857']
   * Projection of the  geometry.  By default, the geometry is assumed to be in
   * Web Mercator.
   * @property {number} [radius=6371008.8] Sphere radius.  By default, the
   * [mean Earth radius](https://en.wikipedia.org/wiki/Earth_radius#Mean_radius)
   * for the WGS84 ellipsoid is used.
   */

  /**
   * The mean Earth radius (1/3 * (2a + b)) for the WGS84 ellipsoid.
   * https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
   * @type {number}
   */
  const DEFAULT_RADIUS = 6371008.8;

  /**
   * Get the great circle distance (in meters) between two geographic coordinates.
   * @param {Array} c1 Starting coordinate.
   * @param {Array} c2 Ending coordinate.
   * @param {number} [radius] The sphere radius to use.  Defaults to the Earth's
   *     mean radius using the WGS84 ellipsoid.
   * @return {number} The great circle distance between the points (in meters).
   * @api
   */
  function getDistance(c1, c2, radius) {
    radius = radius || DEFAULT_RADIUS;
    const lat1 = toRadians(c1[1]);
    const lat2 = toRadians(c2[1]);
    const deltaLatBy2 = (lat2 - lat1) / 2;
    const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2;
    const a =
      Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +
      Math.sin(deltaLonBy2) *
        Math.sin(deltaLonBy2) *
        Math.cos(lat1) *
        Math.cos(lat2);
    return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  }

  /**
   * Get the cumulative great circle length of linestring coordinates (geographic).
   * @param {Array} coordinates Linestring coordinates.
   * @param {number} radius The sphere radius to use.
   * @return {number} The length (in meters).
   */
  function getLengthInternal(coordinates, radius) {
    let length = 0;
    for (let i = 0, ii = coordinates.length; i < ii - 1; ++i) {
      length += getDistance(coordinates[i], coordinates[i + 1], radius);
    }
    return length;
  }

  /**
   * Get the spherical length of a geometry.  This length is the sum of the
   * great circle distances between coordinates.  For polygons, the length is
   * the sum of all rings.  For points, the length is zero.  For multi-part
   * geometries, the length is the sum of the length of each part.
   * @param {import("./geom/Geometry.js").default} geometry A geometry.
   * @param {SphereMetricOptions} [options] Options for the
   * length calculation.  By default, geometries are assumed to be in 'EPSG:3857'.
   * You can change this by providing a `projection` option.
   * @return {number} The spherical length (in meters).
   * @api
   */
  function getLength(geometry, options) {
    options = options || {};
    const radius = options.radius || DEFAULT_RADIUS;
    const projection = options.projection || 'EPSG:3857';
    const type = geometry.getType();
    if (type !== 'GeometryCollection') {
      geometry = geometry.clone().transform(projection, 'EPSG:4326');
    }
    let length = 0;
    let coordinates, coords, i, ii, j, jj;
    switch (type) {
      case 'Point':
      case 'MultiPoint': {
        break;
      }
      case 'LineString':
      case 'LinearRing': {
        coordinates = /** @type {import("./geom/SimpleGeometry.js").default} */ (
          geometry
        ).getCoordinates();
        length = getLengthInternal(coordinates, radius);
        break;
      }
      case 'MultiLineString':
      case 'Polygon': {
        coordinates = /** @type {import("./geom/SimpleGeometry.js").default} */ (
          geometry
        ).getCoordinates();
        for (i = 0, ii = coordinates.length; i < ii; ++i) {
          length += getLengthInternal(coordinates[i], radius);
        }
        break;
      }
      case 'MultiPolygon': {
        coordinates = /** @type {import("./geom/SimpleGeometry.js").default} */ (
          geometry
        ).getCoordinates();
        for (i = 0, ii = coordinates.length; i < ii; ++i) {
          coords = coordinates[i];
          for (j = 0, jj = coords.length; j < jj; ++j) {
            length += getLengthInternal(coords[j], radius);
          }
        }
        break;
      }
      case 'GeometryCollection': {
        const geometries =
          /** @type {import("./geom/GeometryCollection.js").default} */ (
            geometry
          ).getGeometries();
        for (i = 0, ii = geometries.length; i < ii; ++i) {
          length += getLength(geometries[i], options);
        }
        break;
      }
      default: {
        throw new Error('Unsupported geometry type: ' + type);
      }
    }
    return length;
  }

  /**
   * Returns the spherical area for a list of coordinates.
   *
   * [Reference](https://trs.jpl.nasa.gov/handle/2014/40409)
   * Robert. G. Chamberlain and William H. Duquette, "Some Algorithms for
   * Polygons on a Sphere", JPL Publication 07-03, Jet Propulsion
   * Laboratory, Pasadena, CA, June 2007
   *
   * @param {Array<import("./coordinate.js").Coordinate>} coordinates List of coordinates of a linear
   * ring. If the ring is oriented clockwise, the area will be positive,
   * otherwise it will be negative.
   * @param {number} radius The sphere radius.
   * @return {number} Area (in square meters).
   */
  function getAreaInternal(coordinates, radius) {
    let area = 0;
    const len = coordinates.length;
    let x1 = coordinates[len - 1][0];
    let y1 = coordinates[len - 1][1];
    for (let i = 0; i < len; i++) {
      const x2 = coordinates[i][0];
      const y2 = coordinates[i][1];
      area +=
        toRadians(x2 - x1) *
        (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2)));
      x1 = x2;
      y1 = y2;
    }
    return (area * radius * radius) / 2.0;
  }

  /**
   * Get the spherical area of a geometry.  This is the area (in meters) assuming
   * that polygon edges are segments of great circles on a sphere.
   * @param {import("./geom/Geometry.js").default} geometry A geometry.
   * @param {SphereMetricOptions} [options] Options for the area
   *     calculation.  By default, geometries are assumed to be in 'EPSG:3857'.
   *     You can change this by providing a `projection` option.
   * @return {number} The spherical area (in square meters).
   * @api
   */
  function getArea(geometry, options) {
    options = options || {};
    const radius = options.radius || DEFAULT_RADIUS;
    const projection = options.projection || 'EPSG:3857';
    const type = geometry.getType();
    if (type !== 'GeometryCollection') {
      geometry = geometry.clone().transform(projection, 'EPSG:4326');
    }
    let area = 0;
    let coordinates, coords, i, ii, j, jj;
    switch (type) {
      case 'Point':
      case 'MultiPoint':
      case 'LineString':
      case 'MultiLineString':
      case 'LinearRing': {
        break;
      }
      case 'Polygon': {
        coordinates = /** @type {import("./geom/Polygon.js").default} */ (
          geometry
        ).getCoordinates();
        area = Math.abs(getAreaInternal(coordinates[0], radius));
        for (i = 1, ii = coordinates.length; i < ii; ++i) {
          area -= Math.abs(getAreaInternal(coordinates[i], radius));
        }
        break;
      }
      case 'MultiPolygon': {
        coordinates = /** @type {import("./geom/SimpleGeometry.js").default} */ (
          geometry
        ).getCoordinates();
        for (i = 0, ii = coordinates.length; i < ii; ++i) {
          coords = coordinates[i];
          area += Math.abs(getAreaInternal(coords[0], radius));
          for (j = 1, jj = coords.length; j < jj; ++j) {
            area -= Math.abs(getAreaInternal(coords[j], radius));
          }
        }
        break;
      }
      case 'GeometryCollection': {
        const geometries =
          /** @type {import("./geom/GeometryCollection.js").default} */ (
            geometry
          ).getGeometries();
        for (i = 0, ii = geometries.length; i < ii; ++i) {
          area += getArea(geometries[i], options);
        }
        break;
      }
      default: {
        throw new Error('Unsupported geometry type: ' + type);
      }
    }
    return area;
  }

  /**
   * Returns the coordinate at the given distance and bearing from `c1`.
   *
   * @param {import("./coordinate.js").Coordinate} c1 The origin point (`[lon, lat]` in degrees).
   * @param {number} distance The great-circle distance between the origin
   *     point and the target point.
   * @param {number} bearing The bearing (in radians).
   * @param {number} [radius] The sphere radius to use.  Defaults to the Earth's
   *     mean radius using the WGS84 ellipsoid.
   * @return {import("./coordinate.js").Coordinate} The target point.
   */
  function offset(c1, distance, bearing, radius) {
    radius = radius || DEFAULT_RADIUS;
    const lat1 = toRadians(c1[1]);
    const lon1 = toRadians(c1[0]);
    const dByR = distance / radius;
    const lat = Math.asin(
      Math.sin(lat1) * Math.cos(dByR) +
        Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing),
    );
    const lon =
      lon1 +
      Math.atan2(
        Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),
        Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat),
      );
    return [toDegrees(lon), toDegrees(lat)];
  }

  var nsSphere = {
    __proto__: null,
    DEFAULT_RADIUS: DEFAULT_RADIUS,
    getArea: getArea,
    getDistance: getDistance,
    getLength: getLength,
    offset: offset
  };

  /**
   * @module ol/console
   */


  /**
   * @param  {...any} args Arguments to log
   */
  function warn(...args) {
    console.warn(...args); // eslint-disable-line no-console
  }

  /**
   * @param  {...any} args Arguments to log
   */
  function error$1(...args) {
    console.error(...args); // eslint-disable-line no-console
  }

  /**
   * @module ol/string
   */

  /**
   * @param {number} number Number to be formatted
   * @param {number} width The desired width
   * @param {number} [precision] Precision of the output string (i.e. number of decimal places)
   * @return {string} Formatted string
   */
  function padNumber(number, width, precision) {
    const numberString =
      precision !== undefined ? number.toFixed(precision) : '' + number;
    let decimal = numberString.indexOf('.');
    decimal = decimal === -1 ? numberString.length : decimal;
    return decimal > width
      ? numberString
      : new Array(1 + width - decimal).join('0') + numberString;
  }

  /**
   * Adapted from https://github.com/omichelsen/compare-versions/blob/master/index.js
   * @param {string|number} v1 First version
   * @param {string|number} v2 Second version
   * @return {number} Value
   */
  function compareVersions(v1, v2) {
    const s1 = ('' + v1).split('.');
    const s2 = ('' + v2).split('.');

    for (let i = 0; i < Math.max(s1.length, s2.length); i++) {
      const n1 = parseInt(s1[i] || '0', 10);
      const n2 = parseInt(s2[i] || '0', 10);

      if (n1 > n2) {
        return 1;
      }
      if (n2 > n1) {
        return -1;
      }
    }

    return 0;
  }

  /**
   * @module ol/coordinate
   */

  /**
   * An array of numbers representing an `xy`, `xyz` or `xyzm` coordinate.
   * Example: `[16, 48]`.
   * @typedef {Array<number>} Coordinate
   * @api
   */

  /**
   * A function that takes a {@link module:ol/coordinate~Coordinate} and
   * transforms it into a `{string}`.
   *
   * @typedef {function((Coordinate|undefined)): string} CoordinateFormat
   * @api
   */

  /**
   * Add `delta` to `coordinate`. `coordinate` is modified in place and returned
   * by the function.
   *
   * Example:
   *
   *     import {add} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     add(coord, [-2, 4]);
   *     // coord is now [5.85, 51.983333]
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {Coordinate} delta Delta.
   * @return {Coordinate} The input coordinate adjusted by
   * the given delta.
   * @api
   */
  function add$2(coordinate, delta) {
    coordinate[0] += +delta[0];
    coordinate[1] += +delta[1];
    return coordinate;
  }

  /**
   * Calculates the point closest to the passed coordinate on the passed circle.
   *
   * @param {Coordinate} coordinate The coordinate.
   * @param {import("./geom/Circle.js").default} circle The circle.
   * @return {Coordinate} Closest point on the circumference.
   */
  function closestOnCircle(coordinate, circle) {
    const r = circle.getRadius();
    const center = circle.getCenter();
    const x0 = center[0];
    const y0 = center[1];
    const x1 = coordinate[0];
    const y1 = coordinate[1];

    let dx = x1 - x0;
    const dy = y1 - y0;
    if (dx === 0 && dy === 0) {
      dx = 1;
    }
    const d = Math.sqrt(dx * dx + dy * dy);

    const x = x0 + (r * dx) / d;
    const y = y0 + (r * dy) / d;

    return [x, y];
  }

  /**
   * Calculates the point closest to the passed coordinate on the passed segment.
   * This is the foot of the perpendicular of the coordinate to the segment when
   * the foot is on the segment, or the closest segment coordinate when the foot
   * is outside the segment.
   *
   * @param {Coordinate} coordinate The coordinate.
   * @param {Array<Coordinate>} segment The two coordinates
   * of the segment.
   * @return {Coordinate} The foot of the perpendicular of
   * the coordinate to the segment.
   */
  function closestOnSegment(coordinate, segment) {
    const x0 = coordinate[0];
    const y0 = coordinate[1];
    const start = segment[0];
    const end = segment[1];
    const x1 = start[0];
    const y1 = start[1];
    const x2 = end[0];
    const y2 = end[1];
    const dx = x2 - x1;
    const dy = y2 - y1;
    const along =
      dx === 0 && dy === 0
        ? 0
        : (dx * (x0 - x1) + dy * (y0 - y1)) / (dx * dx + dy * dy || 0);
    let x, y;
    if (along <= 0) {
      x = x1;
      y = y1;
    } else if (along >= 1) {
      x = x2;
      y = y2;
    } else {
      x = x1 + along * dx;
      y = y1 + along * dy;
    }
    return [x, y];
  }

  /**
   * Returns a {@link module:ol/coordinate~CoordinateFormat} function that can be
   * used to format
   * a {Coordinate} to a string.
   *
   * Example without specifying the fractional digits:
   *
   *     import {createStringXY} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const stringifyFunc = createStringXY();
   *     const out = stringifyFunc(coord);
   *     // out is now '8, 48'
   *
   * Example with explicitly specifying 2 fractional digits:
   *
   *     import {createStringXY} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const stringifyFunc = createStringXY(2);
   *     const out = stringifyFunc(coord);
   *     // out is now '7.85, 47.98'
   *
   * @param {number} [fractionDigits] The number of digits to include
   *    after the decimal point. Default is `0`.
   * @return {CoordinateFormat} Coordinate format.
   * @api
   */
  function createStringXY(fractionDigits) {
    return (
      /**
       * @param {Coordinate} coordinate Coordinate.
       * @return {string} String XY.
       */
      function (coordinate) {
        return toStringXY(coordinate, fractionDigits);
      }
    );
  }

  /**
   * @param {string} hemispheres Hemispheres.
   * @param {number} degrees Degrees.
   * @param {number} [fractionDigits] The number of digits to include
   *    after the decimal point. Default is `0`.
   * @return {string} String.
   */
  function degreesToStringHDMS(hemispheres, degrees, fractionDigits) {
    const normalizedDegrees = modulo(degrees + 180, 360) - 180;
    const x = Math.abs(3600 * normalizedDegrees);
    const decimals = fractionDigits || 0;

    let deg = Math.floor(x / 3600);
    let min = Math.floor((x - deg * 3600) / 60);
    let sec = toFixed(x - deg * 3600 - min * 60, decimals);

    if (sec >= 60) {
      sec = 0;
      min += 1;
    }

    if (min >= 60) {
      min = 0;
      deg += 1;
    }

    let hdms = deg + '\u00b0';
    if (min !== 0 || sec !== 0) {
      hdms += ' ' + padNumber(min, 2) + '\u2032';
    }
    if (sec !== 0) {
      hdms += ' ' + padNumber(sec, 2, decimals) + '\u2033';
    }
    if (normalizedDegrees !== 0) {
      hdms += ' ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0);
    }

    return hdms;
  }

  /**
   * Transforms the given {@link module:ol/coordinate~Coordinate} to a string
   * using the given string template. The strings `{x}` and `{y}` in the template
   * will be replaced with the first and second coordinate values respectively.
   *
   * Example without specifying the fractional digits:
   *
   *     import {format} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const template = 'Coordinate is ({x}|{y}).';
   *     const out = format(coord, template);
   *     // out is now 'Coordinate is (8|48).'
   *
   * Example explicitly specifying the fractional digits:
   *
   *     import {format} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const template = 'Coordinate is ({x}|{y}).';
   *     const out = format(coord, template, 2);
   *     // out is now 'Coordinate is (7.85|47.98).'
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {string} template A template string with `{x}` and `{y}` placeholders
   *     that will be replaced by first and second coordinate values.
   * @param {number} [fractionDigits] The number of digits to include
   *    after the decimal point. Default is `0`.
   * @return {string} Formatted coordinate.
   * @api
   */
  function format(coordinate, template, fractionDigits) {
    if (coordinate) {
      return template
        .replace('{x}', coordinate[0].toFixed(fractionDigits))
        .replace('{y}', coordinate[1].toFixed(fractionDigits));
    }
    return '';
  }

  /**
   * @param {Coordinate} coordinate1 First coordinate.
   * @param {Coordinate} coordinate2 Second coordinate.
   * @return {boolean} The two coordinates are equal.
   */
  function equals(coordinate1, coordinate2) {
    let equals = true;
    for (let i = coordinate1.length - 1; i >= 0; --i) {
      if (coordinate1[i] != coordinate2[i]) {
        equals = false;
        break;
      }
    }
    return equals;
  }

  /**
   * Rotate `coordinate` by `angle`. `coordinate` is modified in place and
   * returned by the function.
   *
   * Example:
   *
   *     import {rotate} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const rotateRadians = Math.PI / 2; // 90 degrees
   *     rotate(coord, rotateRadians);
   *     // coord is now [-47.983333, 7.85]
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {number} angle Angle in radian.
   * @return {Coordinate} Coordinate.
   * @api
   */
  function rotate$2(coordinate, angle) {
    const cosAngle = Math.cos(angle);
    const sinAngle = Math.sin(angle);
    const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle;
    const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle;
    coordinate[0] = x;
    coordinate[1] = y;
    return coordinate;
  }

  /**
   * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned
   * by the function.
   *
   * Example:
   *
   *     import {scale as scaleCoordinate} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const scale = 1.2;
   *     scaleCoordinate(coord, scale);
   *     // coord is now [9.42, 57.5799996]
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {number} scale Scale factor.
   * @return {Coordinate} Coordinate.
   */
  function scale$4(coordinate, scale) {
    coordinate[0] *= scale;
    coordinate[1] *= scale;
    return coordinate;
  }

  /**
   * @param {Coordinate} coord1 First coordinate.
   * @param {Coordinate} coord2 Second coordinate.
   * @return {number} Squared distance between coord1 and coord2.
   */
  function squaredDistance(coord1, coord2) {
    const dx = coord1[0] - coord2[0];
    const dy = coord1[1] - coord2[1];
    return dx * dx + dy * dy;
  }

  /**
   * @param {Coordinate} coord1 First coordinate.
   * @param {Coordinate} coord2 Second coordinate.
   * @return {number} Distance between coord1 and coord2.
   */
  function distance(coord1, coord2) {
    return Math.sqrt(squaredDistance(coord1, coord2));
  }

  /**
   * Calculate the squared distance from a coordinate to a line segment.
   *
   * @param {Coordinate} coordinate Coordinate of the point.
   * @param {Array<Coordinate>} segment Line segment (2
   * coordinates).
   * @return {number} Squared distance from the point to the line segment.
   */
  function squaredDistanceToSegment(coordinate, segment) {
    return squaredDistance(coordinate, closestOnSegment(coordinate, segment));
  }

  /**
   * Format a geographic coordinate with the hemisphere, degrees, minutes, and
   * seconds.
   *
   * Example without specifying fractional digits:
   *
   *     import {toStringHDMS} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const out = toStringHDMS(coord);
   *     // out is now '47° 58′ 60″ N 7° 50′ 60″ E'
   *
   * Example explicitly specifying 1 fractional digit:
   *
   *     import {toStringHDMS} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const out = toStringHDMS(coord, 1);
   *     // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E'
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {number} [fractionDigits] The number of digits to include
   *    after the decimal point. Default is `0`.
   * @return {string} Hemisphere, degrees, minutes and seconds.
   * @api
   */
  function toStringHDMS(coordinate, fractionDigits) {
    if (coordinate) {
      return (
        degreesToStringHDMS('NS', coordinate[1], fractionDigits) +
        ' ' +
        degreesToStringHDMS('EW', coordinate[0], fractionDigits)
      );
    }
    return '';
  }

  /**
   * Format a coordinate as a comma delimited string.
   *
   * Example without specifying fractional digits:
   *
   *     import {toStringXY} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const out = toStringXY(coord);
   *     // out is now '8, 48'
   *
   * Example explicitly specifying 1 fractional digit:
   *
   *     import {toStringXY} from 'ol/coordinate.js';
   *
   *     const coord = [7.85, 47.983333];
   *     const out = toStringXY(coord, 1);
   *     // out is now '7.8, 48.0'
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {number} [fractionDigits] The number of digits to include
   *    after the decimal point. Default is `0`.
   * @return {string} XY.
   * @api
   */
  function toStringXY(coordinate, fractionDigits) {
    return format(coordinate, '{x}, {y}', fractionDigits);
  }

  /**
   * Modifies the provided coordinate in-place to be within the real world
   * extent. The lower projection extent boundary is inclusive, the upper one
   * exclusive.
   *
   * @param {Coordinate} coordinate Coordinate.
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @return {Coordinate} The coordinate within the real world extent.
   */
  function wrapX$1(coordinate, projection) {
    if (projection.canWrapX()) {
      const worldWidth = getWidth(projection.getExtent());
      const worldsAway = getWorldsAway(coordinate, projection, worldWidth);
      if (worldsAway) {
        coordinate[0] -= worldsAway * worldWidth;
      }
    }
    return coordinate;
  }
  /**
   * @param {Coordinate} coordinate Coordinate.
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @param {number} [sourceExtentWidth] Width of the source extent.
   * @return {number} Offset in world widths.
   */
  function getWorldsAway(coordinate, projection, sourceExtentWidth) {
    const projectionExtent = projection.getExtent();
    let worldsAway = 0;
    if (
      projection.canWrapX() &&
      (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2])
    ) {
      sourceExtentWidth = sourceExtentWidth || getWidth(projectionExtent);
      worldsAway = Math.floor(
        (coordinate[0] - projectionExtent[0]) / sourceExtentWidth,
      );
    }
    return worldsAway;
  }

  var nsCoordinate = {
    __proto__: null,
    add: add$2,
    closestOnCircle: closestOnCircle,
    closestOnSegment: closestOnSegment,
    createStringXY: createStringXY,
    degreesToStringHDMS: degreesToStringHDMS,
    distance: distance,
    equals: equals,
    format: format,
    getWorldsAway: getWorldsAway,
    rotate: rotate$2,
    scale: scale$4,
    squaredDistance: squaredDistance,
    squaredDistanceToSegment: squaredDistanceToSegment,
    toStringHDMS: toStringHDMS,
    toStringXY: toStringXY,
    wrapX: wrapX$1
  };

  /**
   * @module ol/proj/Units
   */

  /**
   * @typedef {'radians' | 'degrees' | 'ft' | 'm' | 'pixels' | 'tile-pixels' | 'us-ft'} Units
   * Projection units.
   */

  /**
   * See http://duff.ess.washington.edu/data/raster/drg/docs/geotiff.txt
   * @type {Object<number, Units>}
   */
  const unitByCode = {
    '9001': 'm',
    '9002': 'ft',
    '9003': 'us-ft',
    '9101': 'radians',
    '9102': 'degrees',
  };

  /**
   * @param {number} code Unit code.
   * @return {Units} Units.
   */
  function fromCode(code) {
    return unitByCode[code];
  }

  /**
   * @typedef {Object} MetersPerUnitLookup
   * @property {number} radians Radians
   * @property {number} degrees Degrees
   * @property {number} ft  Feet
   * @property {number} m Meters
   * @property {number} us-ft US feet
   */

  /**
   * Meters per unit lookup table.
   * @const
   * @type {MetersPerUnitLookup}
   * @api
   */
  const METERS_PER_UNIT$1 = {
    // use the radius of the Normal sphere
    'radians': 6370997 / (2 * Math.PI),
    'degrees': (2 * Math.PI * 6370997) / 360,
    'ft': 0.3048,
    'm': 1,
    'us-ft': 1200 / 3937,
  };

  /**
   * @module ol/proj/Projection
   */

  /**
   * The function is called with a `number` view resolution and a
   * {@link module:ol/coordinate~Coordinate} as arguments, and returns the `number` resolution
   * in projection units at the passed coordinate.
   * @typedef {function(number, import("../coordinate.js").Coordinate):number} GetPointResolution
   * @api
   */

  /**
   * @typedef {Object} Options
   * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.
   * @property {import("./Units.js").Units} [units] Units. Required unless a
   * proj4 projection is defined for `code`.
   * @property {import("../extent.js").Extent} [extent] The validity extent for the SRS.
   * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.
   * @property {boolean} [global=false] Whether the projection is valid for the whole globe.
   * @property {number} [metersPerUnit] The meters per unit for the SRS.
   * If not provided, the `units` are used to get the meters per unit from the {@link METERS_PER_UNIT}
   * lookup table.
   * @property {import("../extent.js").Extent} [worldExtent] The world extent for the SRS.
   * @property {GetPointResolution} [getPointResolution]
   * Function to determine resolution at a point. The function is called with a
   * `number` view resolution and a {@link module:ol/coordinate~Coordinate} as arguments, and returns
   * the `number` resolution in projection units at the passed coordinate. If this is `undefined`,
   * the default {@link module:ol/proj.getPointResolution} function will be used.
   */

  /**
   * @classdesc
   * In most cases, you should not need to create instances of this class.
   * Instead, where projection information is required, you can use a string
   * projection code or identifier (e.g. `EPSG:4326`) instead of a projection
   * instance.
   *
   * The library includes support for transforming coordinates between the following
   * projections:
   *
   *  WGS 84 / Geographic - Using codes `EPSG:4326`, `CRS:84`, `urn:ogc:def:crs:EPSG:6.6:4326`,
   *    `urn:ogc:def:crs:OGC:1.3:CRS84`, `urn:ogc:def:crs:OGC:2:84`, `http://www.opengis.net/gml/srs/epsg.xml#4326`,
   *    or `urn:x-ogc:def:crs:EPSG:4326`
   *  WGS 84 / Spherical Mercator - Using codes `EPSG:3857`, `EPSG:102100`, `EPSG:102113`, `EPSG:900913`,
   *    `urn:ogc:def:crs:EPSG:6.18:3:3857`, or `http://www.opengis.net/gml/srs/epsg.xml#3857`
   *  WGS 84 / UTM zones - Using codes `EPSG:32601` through `EPSG:32660` for northern zones
   *    and `EPSG:32701` through `EPSG:32760` for southern zones. Note that the built-in UTM transforms
   *    are lower accuracy (with errors on the order of 0.1 m) than those that you might get in a
   *    library like [proj4js](https://github.com/proj4js/proj4js).
   *
   * For additional projection support, or to use higher accuracy transforms than the built-in ones, you can use
   * the [proj4js](https://github.com/proj4js/proj4js) library. With `proj4js`, after adding any new projection
   * definitions, call the {@link module:ol/proj/proj4.register} function.
   *
   * You can use the {@link module:ol/proj.get} function to retrieve a projection instance
   * for one of the registered projections.
   *
   * @api
   */
  class Projection {
    /**
     * @param {Options} options Projection options.
     */
    constructor(options) {
      /**
       * @private
       * @type {string}
       */
      this.code_ = options.code;

      /**
       * Units of projected coordinates. When set to `TILE_PIXELS`, a
       * `this.extent_` and `this.worldExtent_` must be configured properly for each
       * tile.
       * @private
       * @type {import("./Units.js").Units}
       */
      this.units_ = /** @type {import("./Units.js").Units} */ (options.units);

      /**
       * Validity extent of the projection in projected coordinates. For projections
       * with `TILE_PIXELS` units, this is the extent of the tile in
       * tile pixel space.
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.extent_ = options.extent !== undefined ? options.extent : null;

      /**
       * Extent of the world in EPSG:4326. For projections with
       * `TILE_PIXELS` units, this is the extent of the tile in
       * projected coordinate space.
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.worldExtent_ =
        options.worldExtent !== undefined ? options.worldExtent : null;

      /**
       * @private
       * @type {string}
       */
      this.axisOrientation_ =
        options.axisOrientation !== undefined ? options.axisOrientation : 'enu';

      /**
       * @private
       * @type {boolean}
       */
      this.global_ = options.global !== undefined ? options.global : false;

      /**
       * @private
       * @type {boolean}
       */
      this.canWrapX_ = !!(this.global_ && this.extent_);

      /**
       * @private
       * @type {GetPointResolution|undefined}
       */
      this.getPointResolutionFunc_ = options.getPointResolution;

      /**
       * @private
       * @type {import("../tilegrid/TileGrid.js").default}
       */
      this.defaultTileGrid_ = null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.metersPerUnit_ = options.metersPerUnit;
    }

    /**
     * @return {boolean} The projection is suitable for wrapping the x-axis
     */
    canWrapX() {
      return this.canWrapX_;
    }

    /**
     * Get the code for this projection, e.g. 'EPSG:4326'.
     * @return {string} Code.
     * @api
     */
    getCode() {
      return this.code_;
    }

    /**
     * Get the validity extent for this projection.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getExtent() {
      return this.extent_;
    }

    /**
     * Get the units of this projection.
     * @return {import("./Units.js").Units} Units.
     * @api
     */
    getUnits() {
      return this.units_;
    }

    /**
     * Get the amount of meters per unit of this projection.  If the projection is
     * not configured with `metersPerUnit` or a units identifier, the return is
     * `undefined`.
     * @return {number|undefined} Meters.
     * @api
     */
    getMetersPerUnit() {
      return this.metersPerUnit_ || METERS_PER_UNIT$1[this.units_];
    }

    /**
     * Get the world extent for this projection.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getWorldExtent() {
      return this.worldExtent_;
    }

    /**
     * Get the axis orientation of this projection.
     * Example values are:
     * enu - the default easting, northing, elevation.
     * neu - northing, easting, up - useful for "lat/long" geographic coordinates,
     *     or south orientated transverse mercator.
     * wnu - westing, northing, up - some planetary coordinate systems have
     *     "west positive" coordinate systems
     * @return {string} Axis orientation.
     * @api
     */
    getAxisOrientation() {
      return this.axisOrientation_;
    }

    /**
     * Is this projection a global projection which spans the whole world?
     * @return {boolean} Whether the projection is global.
     * @api
     */
    isGlobal() {
      return this.global_;
    }

    /**
     * Set if the projection is a global projection which spans the whole world
     * @param {boolean} global Whether the projection is global.
     * @api
     */
    setGlobal(global) {
      this.global_ = global;
      this.canWrapX_ = !!(global && this.extent_);
    }

    /**
     * @return {import("../tilegrid/TileGrid.js").default} The default tile grid.
     */
    getDefaultTileGrid() {
      return this.defaultTileGrid_;
    }

    /**
     * @param {import("../tilegrid/TileGrid.js").default} tileGrid The default tile grid.
     */
    setDefaultTileGrid(tileGrid) {
      this.defaultTileGrid_ = tileGrid;
    }

    /**
     * Set the validity extent for this projection.
     * @param {import("../extent.js").Extent} extent Extent.
     * @api
     */
    setExtent(extent) {
      this.extent_ = extent;
      this.canWrapX_ = !!(this.global_ && extent);
    }

    /**
     * Set the world extent for this projection.
     * @param {import("../extent.js").Extent} worldExtent World extent
     *     [minlon, minlat, maxlon, maxlat].
     * @api
     */
    setWorldExtent(worldExtent) {
      this.worldExtent_ = worldExtent;
    }

    /**
     * Set the getPointResolution function (see {@link module:ol/proj.getPointResolution}
     * for this projection.
     * @param {function(number, import("../coordinate.js").Coordinate):number} func Function
     * @api
     */
    setGetPointResolution(func) {
      this.getPointResolutionFunc_ = func;
    }

    /**
     * Get the custom point resolution function for this projection (if set).
     * @return {GetPointResolution|undefined} The custom point
     * resolution function (if set).
     */
    getPointResolutionFunc() {
      return this.getPointResolutionFunc_;
    }
  }

  /**
   * @module ol/proj/epsg3857
   */

  /**
   * Radius of WGS84 sphere
   *
   * @const
   * @type {number}
   */
  const RADIUS$1 = 6378137;

  /**
   * @const
   * @type {number}
   */
  const HALF_SIZE = Math.PI * RADIUS$1;

  /**
   * @const
   * @type {import("../extent.js").Extent}
   */
  const EXTENT$2 = [-HALF_SIZE, -HALF_SIZE, HALF_SIZE, HALF_SIZE];

  /**
   * @const
   * @type {import("../extent.js").Extent}
   */
  const WORLD_EXTENT = [-180, -85, 180, 85];

  /**
   * Maximum safe value in y direction
   * @const
   * @type {number}
   */
  const MAX_SAFE_Y = RADIUS$1 * Math.log(Math.tan(Math.PI / 2));

  /**
   * @classdesc
   * Projection object for web/spherical Mercator (EPSG:3857).
   */
  class EPSG3857Projection extends Projection {
    /**
     * @param {string} code Code.
     */
    constructor(code) {
      super({
        code: code,
        units: 'm',
        extent: EXTENT$2,
        global: true,
        worldExtent: WORLD_EXTENT,
        getPointResolution: function (resolution, point) {
          return resolution / Math.cosh(point[1] / RADIUS$1);
        },
      });
    }
  }

  /**
   * Projections equal to EPSG:3857.
   *
   * @const
   * @type {Array<import("./Projection.js").default>}
   */
  const PROJECTIONS$1 = [
    new EPSG3857Projection('EPSG:3857'),
    new EPSG3857Projection('EPSG:102100'),
    new EPSG3857Projection('EPSG:102113'),
    new EPSG3857Projection('EPSG:900913'),
    new EPSG3857Projection('http://www.opengis.net/def/crs/EPSG/0/3857'),
    new EPSG3857Projection('http://www.opengis.net/gml/srs/epsg.xml#3857'),
  ];

  /**
   * Transformation from EPSG:4326 to EPSG:3857.
   *
   * @param {Array<number>} input Input array of coordinate values.
   * @param {Array<number>} [output] Output array of coordinate values.
   * @param {number} [dimension] Dimension (default is `2`).
   * @param {number} [stride] Stride (default is `dimension`).
   * @return {Array<number>} Output array of coordinate values.
   */
  function fromEPSG4326(input, output, dimension, stride) {
    const length = input.length;
    dimension = dimension > 1 ? dimension : 2;
    stride = stride ?? dimension;
    if (output === undefined) {
      if (dimension > 2) {
        // preserve values beyond second dimension
        output = input.slice();
      } else {
        output = new Array(length);
      }
    }
    for (let i = 0; i < length; i += stride) {
      output[i] = (HALF_SIZE * input[i]) / 180;
      let y = RADIUS$1 * Math.log(Math.tan((Math.PI * (+input[i + 1] + 90)) / 360));
      if (y > MAX_SAFE_Y) {
        y = MAX_SAFE_Y;
      } else if (y < -MAX_SAFE_Y) {
        y = -MAX_SAFE_Y;
      }
      output[i + 1] = y;
    }
    return output;
  }

  /**
   * Transformation from EPSG:3857 to EPSG:4326.
   *
   * @param {Array<number>} input Input array of coordinate values.
   * @param {Array<number>} [output] Output array of coordinate values.
   * @param {number} [dimension] Dimension (default is `2`).
   * @param {number} [stride] Stride (default is `dimension`).
   * @return {Array<number>} Output array of coordinate values.
   */
  function toEPSG4326(input, output, dimension, stride) {
    const length = input.length;
    dimension = dimension > 1 ? dimension : 2;
    stride = stride ?? dimension;
    if (output === undefined) {
      if (dimension > 2) {
        // preserve values beyond second dimension
        output = input.slice();
      } else {
        output = new Array(length);
      }
    }
    for (let i = 0; i < length; i += stride) {
      output[i] = (180 * input[i]) / HALF_SIZE;
      output[i + 1] =
        (360 * Math.atan(Math.exp(input[i + 1] / RADIUS$1))) / Math.PI - 90;
    }
    return output;
  }

  /**
   * @module ol/proj/epsg4326
   */

  /**
   * Semi-major radius of the WGS84 ellipsoid.
   *
   * @const
   * @type {number}
   */
  const RADIUS = 6378137;

  /**
   * Extent of the EPSG:4326 projection which is the whole world.
   *
   * @const
   * @type {import("../extent.js").Extent}
   */
  const EXTENT$1 = [-180, -90, 180, 90];

  /**
   * @const
   * @type {number}
   */
  const METERS_PER_UNIT = (Math.PI * RADIUS) / 180;

  /**
   * @classdesc
   * Projection object for WGS84 geographic coordinates (EPSG:4326).
   *
   * Note that OpenLayers does not strictly comply with the EPSG definition.
   * The EPSG registry defines 4326 as a CRS for Latitude,Longitude (y,x).
   * OpenLayers treats EPSG:4326 as a pseudo-projection, with x,y coordinates.
   */
  class EPSG4326Projection extends Projection {
    /**
     * @param {string} code Code.
     * @param {string} [axisOrientation] Axis orientation.
     */
    constructor(code, axisOrientation) {
      super({
        code: code,
        units: 'degrees',
        extent: EXTENT$1,
        axisOrientation: axisOrientation,
        global: true,
        metersPerUnit: METERS_PER_UNIT,
        worldExtent: EXTENT$1,
      });
    }
  }

  /**
   * Projections equal to EPSG:4326.
   *
   * @const
   * @type {Array<import("./Projection.js").default>}
   */
  const PROJECTIONS = [
    new EPSG4326Projection('CRS:84'),
    new EPSG4326Projection('EPSG:4326', 'neu'),
    new EPSG4326Projection('urn:ogc:def:crs:OGC:1.3:CRS84'),
    new EPSG4326Projection('urn:ogc:def:crs:OGC:2:84'),
    new EPSG4326Projection('http://www.opengis.net/def/crs/OGC/1.3/CRS84'),
    new EPSG4326Projection('http://www.opengis.net/gml/srs/epsg.xml#4326', 'neu'),
    new EPSG4326Projection('http://www.opengis.net/def/crs/EPSG/0/4326', 'neu'),
  ];

  /**
   * @module ol/proj/projections
   */

  /**
   * @type {Object<string, import("./Projection.js").default>}
   */
  let cache$1 = {};

  /**
   * Clear the projections cache.
   */
  function clear$1() {
    cache$1 = {};
  }

  /**
   * Get a cached projection by code.
   * @param {string} code The code for the projection.
   * @return {import("./Projection.js").default|null} The projection (if cached).
   */
  function get$4(code) {
    return (
      cache$1[code] ||
      cache$1[code.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\w+)$/, 'EPSG:$3')] ||
      null
    );
  }

  /**
   * Add a projection to the cache.
   * @param {string} code The projection code.
   * @param {import("./Projection.js").default} projection The projection to cache.
   */
  function add$1(code, projection) {
    cache$1[code] = projection;
  }

  /**
   * @module ol/proj/transforms
   */

  /**
   * @private
   * @type {!Object<string, Object<string, import("../proj.js").TransformFunction>>}
   */
  let transforms = {};

  /**
   * Clear the transform cache.
   */
  function clear() {
    transforms = {};
  }

  /**
   * Registers a conversion function to convert coordinates from the source
   * projection to the destination projection.
   *
   * @param {import("./Projection.js").default} source Source.
   * @param {import("./Projection.js").default} destination Destination.
   * @param {import("../proj.js").TransformFunction} transformFn Transform.
   */
  function add(source, destination, transformFn) {
    const sourceCode = source.getCode();
    const destinationCode = destination.getCode();
    if (!(sourceCode in transforms)) {
      transforms[sourceCode] = {};
    }
    transforms[sourceCode][destinationCode] = transformFn;
  }

  /**
   * Get a transform given a source code and a destination code.
   * @param {string} sourceCode The code for the source projection.
   * @param {string} destinationCode The code for the destination projection.
   * @return {import("../proj.js").TransformFunction|null} The transform function (if found).
   */
  function get$3(sourceCode, destinationCode) {
    if (sourceCode in transforms && destinationCode in transforms[sourceCode]) {
      return transforms[sourceCode][destinationCode];
    }
    return null;
  }

  /**
   * @module ol/proj/utm
   */


  /**
   * @typedef {Object} UTMZone
   * @property {number} number The zone number (1 - 60).
   * @property {boolean} north The northern hemisphere.
   */

  const K0 = 0.9996;

  const E = 0.00669438;
  const E2$1 = E * E;
  const E3 = E2$1 * E;
  const E_P2 = E / (1 - E);

  const SQRT_E = Math.sqrt(1 - E);
  const _E = (1 - SQRT_E) / (1 + SQRT_E);
  const _E2 = _E * _E;
  const _E3 = _E2 * _E;
  const _E4 = _E3 * _E;
  const _E5 = _E4 * _E;

  const M1 = 1 - E / 4 - (3 * E2$1) / 64 - (5 * E3) / 256;
  const M2 = (3 * E) / 8 + (3 * E2$1) / 32 + (45 * E3) / 1024;
  const M3 = (15 * E2$1) / 256 + (45 * E3) / 1024;
  const M4 = (35 * E3) / 3072;

  const P2 = (3 / 2) * _E - (27 / 32) * _E3 + (269 / 512) * _E5;
  const P3 = (21 / 16) * _E2 - (55 / 32) * _E4;
  const P4 = (151 / 96) * _E3 - (417 / 128) * _E5;
  const P5 = (1097 / 512) * _E4;

  const R = 6378137;

  /**
   * @param {number} easting Easting value of coordinate.
   * @param {number} northing Northing value of coordinate.
   * @param {UTMZone} zone The UTM zone.
   * @return {import("../coordinate.js").Coordinate} The transformed coordinate.
   */
  function toLonLat$1(easting, northing, zone) {
    const x = easting - 500000;
    const y = zone.north ? northing : northing - 10000000;

    const m = y / K0;
    const mu = m / (R * M1);

    const pRad =
      mu +
      P2 * Math.sin(2 * mu) +
      P3 * Math.sin(4 * mu) +
      P4 * Math.sin(6 * mu) +
      P5 * Math.sin(8 * mu);

    const pSin = Math.sin(pRad);
    const pSin2 = pSin * pSin;

    const pCos = Math.cos(pRad);

    const pTan = pSin / pCos;
    const pTan2 = pTan * pTan;
    const pTan4 = pTan2 * pTan2;

    const epSin = 1 - E * pSin2;
    const epSinSqrt = Math.sqrt(1 - E * pSin2);

    const n = R / epSinSqrt;
    const r = (1 - E) / epSin;

    const c = E_P2 * pCos ** 2;
    const c2 = c * c;

    const d = x / (n * K0);
    const d2 = d * d;
    const d3 = d2 * d;
    const d4 = d3 * d;
    const d5 = d4 * d;
    const d6 = d5 * d;

    const latitude =
      pRad -
      (pTan / r) *
        (d2 / 2 - (d4 / 24) * (5 + 3 * pTan2 + 10 * c - 4 * c2 - 9 * E_P2)) +
      (d6 / 720) * (61 + 90 * pTan2 + 298 * c + 45 * pTan4 - 252 * E_P2 - 3 * c2);

    let longitude =
      (d -
        (d3 / 6) * (1 + 2 * pTan2 + c) +
        (d5 / 120) * (5 - 2 * c + 28 * pTan2 - 3 * c2 + 8 * E_P2 + 24 * pTan4)) /
      pCos;

    longitude = wrap(
      longitude + toRadians(zoneToCentralLongitude(zone.number)),
      -Math.PI,
      Math.PI,
    );

    return [toDegrees(longitude), toDegrees(latitude)];
  }

  const MIN_LATITUDE = -80;
  const MAX_LATITUDE = 84;
  const MIN_LONGITUDE = -180;
  const MAX_LONGITUDE = 180;

  /**
   * @param {number} longitude The longitude.
   * @param {number} latitude The latitude.
   * @param {UTMZone} zone The UTM zone.
   * @return {import('../coordinate.js').Coordinate} The UTM coordinate.
   */
  function fromLonLat$1(longitude, latitude, zone) {
    longitude = wrap(longitude, MIN_LONGITUDE, MAX_LONGITUDE);

    if (latitude < MIN_LATITUDE) {
      latitude = MIN_LATITUDE;
    } else if (latitude > MAX_LATITUDE) {
      latitude = MAX_LATITUDE;
    }

    const latRad = toRadians(latitude);
    const latSin = Math.sin(latRad);
    const latCos = Math.cos(latRad);

    const latTan = latSin / latCos;
    const latTan2 = latTan * latTan;
    const latTan4 = latTan2 * latTan2;

    const lonRad = toRadians(longitude);
    const centralLon = zoneToCentralLongitude(zone.number);
    const centralLonRad = toRadians(centralLon);

    const n = R / Math.sqrt(1 - E * latSin ** 2);
    const c = E_P2 * latCos ** 2;

    const a = latCos * wrap(lonRad - centralLonRad, -Math.PI, Math.PI);
    const a2 = a * a;
    const a3 = a2 * a;
    const a4 = a3 * a;
    const a5 = a4 * a;
    const a6 = a5 * a;

    const m =
      R *
      (M1 * latRad -
        M2 * Math.sin(2 * latRad) +
        M3 * Math.sin(4 * latRad) -
        M4 * Math.sin(6 * latRad));

    const easting =
      K0 *
        n *
        (a +
          (a3 / 6) * (1 - latTan2 + c) +
          (a5 / 120) * (5 - 18 * latTan2 + latTan4 + 72 * c - 58 * E_P2)) +
      500000;

    let northing =
      K0 *
      (m +
        n *
          latTan *
          (a2 / 2 +
            (a4 / 24) * (5 - latTan2 + 9 * c + 4 * c ** 2) +
            (a6 / 720) * (61 - 58 * latTan2 + latTan4 + 600 * c - 330 * E_P2)));

    if (!zone.north) {
      northing += 10000000;
    }

    return [easting, northing];
  }

  /**
   * @param {number} zone The zone number.
   * @return {number} The central longitude in degrees.
   */
  function zoneToCentralLongitude(zone) {
    return (zone - 1) * 6 - 180 + 3;
  }

  /**
   * @type {Array<RegExp>}
   */
  const epsgRegExes = [
    /^EPSG:(\d+)$/,
    /^urn:ogc:def:crs:EPSG::(\d+)$/,
    /^http:\/\/www\.opengis\.net\/def\/crs\/EPSG\/0\/(\d+)$/,
  ];

  /**
   * @param {string} code The projection code.
   * @return {UTMZone|null} The UTM zone info (or null if not UTM).
   */
  function zoneFromCode(code) {
    let epsgId = 0;
    for (const re of epsgRegExes) {
      const match = code.match(re);
      if (match) {
        epsgId = parseInt(match[1]);
        break;
      }
    }
    if (!epsgId) {
      return null;
    }

    let number = 0;
    let north = false;
    if (epsgId > 32700 && epsgId < 32761) {
      number = epsgId - 32700;
    } else if (epsgId > 32600 && epsgId < 32661) {
      north = true;
      number = epsgId - 32600;
    }
    if (!number) {
      return null;
    }

    return {number, north};
  }

  /**
   * @param {function(number, number, UTMZone): import('../coordinate.js').Coordinate} transformer The transformer.
   * @param {UTMZone} zone The UTM zone.
   * @return {import('../proj.js').TransformFunction} The transform function.
   */
  function makeTransformFunction(transformer, zone) {
    return function (input, output, dimension, stride) {
      const length = input.length;
      dimension = dimension > 1 ? dimension : 2;
      stride = stride ?? dimension;
      if (!output) {
        if (dimension > 2) {
          output = input.slice();
        } else {
          output = new Array(length);
        }
      }
      for (let i = 0; i < length; i += stride) {
        const x = input[i];
        const y = input[i + 1];
        const coord = transformer(x, y, zone);
        output[i] = coord[0];
        output[i + 1] = coord[1];
      }
      return output;
    };
  }

  /**
   * @param {string} code The projection code.
   * @return {import('./Projection.js').default|null} A projection or null if unable to create one.
   */
  function makeProjection(code) {
    const zone = zoneFromCode(code);
    if (!zone) {
      return null;
    }
    return new Projection({code, units: 'm'});
  }

  /**
   * @param {import('./Projection.js').default} projection The projection.
   * @return {import('../proj.js').Transforms|null} The transforms lookup or null if unable to handle projection.
   */
  function makeTransforms(projection) {
    const zone = zoneFromCode(projection.getCode());
    if (!zone) {
      return null;
    }

    return {
      forward: makeTransformFunction(fromLonLat$1, zone),
      inverse: makeTransformFunction(toLonLat$1, zone),
    };
  }

  /**
   * @module ol/proj
   */


  /**
   * A projection as {@link module:ol/proj/Projection~Projection}, SRS identifier
   * string or undefined.
   * @typedef {Projection|string|undefined} ProjectionLike
   * @api
   */

  /**
   * @typedef {Object} Transforms
   * @property {TransformFunction} forward The forward transform (from geographic).
   * @property {TransformFunction} inverse The inverse transform (to geographic).
   */

  /**
   * @type {Array<function(Projection): Transforms|null>}
   */
  const transformFactories = [makeTransforms];

  /**
   * @type {Array<function(string): Projection|null>}
   */
  const projectionFactories = [makeProjection];

  let showCoordinateWarning = true;

  /**
   * @param {boolean} [disable] Disable console info about `useGeographic()`
   */
  function disableCoordinateWarning(disable) {
    const hide = disable === undefined ? true : disable;
    showCoordinateWarning = !hide;
  }

  /**
   * @param {Array<number>} input Input coordinate array.
   * @param {Array<number>} [output] Output array of coordinate values.
   * @return {Array<number>} Output coordinate array (new array, same coordinate
   *     values).
   */
  function cloneTransform(input, output) {
    if (output !== undefined) {
      for (let i = 0, ii = input.length; i < ii; ++i) {
        output[i] = input[i];
      }
      output = output;
    } else {
      output = input.slice();
    }
    return output;
  }

  /**
   * @param {Array<number>} input Input coordinate array.
   * @param {Array<number>} [output] Output array of coordinate values.
   * @return {Array<number>} Input coordinate array (same array as input).
   */
  function identityTransform(input, output) {
    if (output !== undefined && input !== output) {
      for (let i = 0, ii = input.length; i < ii; ++i) {
        output[i] = input[i];
      }
      input = output;
    }
    return input;
  }

  /**
   * Add a Projection object to the list of supported projections that can be
   * looked up by their code.
   *
   * @param {Projection} projection Projection instance.
   * @api
   */
  function addProjection(projection) {
    add$1(projection.getCode(), projection);
    add(projection, projection, cloneTransform);
  }

  /**
   * @param {Array<Projection>} projections Projections.
   */
  function addProjections(projections) {
    projections.forEach(addProjection);
  }

  /**
   * Fetches a Projection object for the code specified.
   *
   * @param {ProjectionLike} projectionLike Either a code string which is
   *     a combination of authority and identifier such as "EPSG:4326", or an
   *     existing projection object, or undefined.
   * @return {Projection|null} Projection object, or null if not in list.
   * @api
   */
  function get$2(projectionLike) {
    if (!(typeof projectionLike === 'string')) {
      return projectionLike;
    }
    const projection = get$4(projectionLike);
    if (projection) {
      return projection;
    }
    for (const makeProjection of projectionFactories) {
      const projection = makeProjection(projectionLike);
      if (projection) {
        return projection;
      }
    }
    return null;
  }

  /**
   * Get the resolution of the point in degrees or distance units.
   * For projections with degrees as the unit this will simply return the
   * provided resolution. For other projections the point resolution is
   * by default estimated by transforming the `point` pixel to EPSG:4326,
   * measuring its width and height on the normal sphere,
   * and taking the average of the width and height.
   * A custom function can be provided for a specific projection, either
   * by setting the `getPointResolution` option in the
   * {@link module:ol/proj/Projection~Projection} constructor or by using
   * {@link module:ol/proj/Projection~Projection#setGetPointResolution} to change an existing
   * projection object.
   * @param {ProjectionLike} projection The projection.
   * @param {number} resolution Nominal resolution in projection units.
   * @param {import("./coordinate.js").Coordinate} point Point to find adjusted resolution at.
   * @param {import("./proj/Units.js").Units} [units] Units to get the point resolution in.
   * Default is the projection's units.
   * @return {number} Point resolution.
   * @api
   */
  function getPointResolution(projection, resolution, point, units) {
    projection = get$2(projection);
    let pointResolution;
    const getter = projection.getPointResolutionFunc();
    if (getter) {
      pointResolution = getter(resolution, point);
      if (units && units !== projection.getUnits()) {
        const metersPerUnit = projection.getMetersPerUnit();
        if (metersPerUnit) {
          pointResolution =
            (pointResolution * metersPerUnit) / METERS_PER_UNIT$1[units];
        }
      }
    } else {
      const projUnits = projection.getUnits();
      if ((projUnits == 'degrees' && !units) || units == 'degrees') {
        pointResolution = resolution;
      } else {
        // Estimate point resolution by transforming the center pixel to EPSG:4326,
        // measuring its width and height on the normal sphere, and taking the
        // average of the width and height.
        const toEPSG4326 = getTransformFromProjections(
          projection,
          get$2('EPSG:4326'),
        );
        if (!toEPSG4326 && projUnits !== 'degrees') {
          // no transform is available
          pointResolution = resolution * projection.getMetersPerUnit();
        } else {
          let vertices = [
            point[0] - resolution / 2,
            point[1],
            point[0] + resolution / 2,
            point[1],
            point[0],
            point[1] - resolution / 2,
            point[0],
            point[1] + resolution / 2,
          ];
          vertices = toEPSG4326(vertices, vertices, 2);
          const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4));
          const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8));
          pointResolution = (width + height) / 2;
        }
        const metersPerUnit = units
          ? METERS_PER_UNIT$1[units]
          : projection.getMetersPerUnit();
        if (metersPerUnit !== undefined) {
          pointResolution /= metersPerUnit;
        }
      }
    }
    return pointResolution;
  }

  /**
   * Registers transformation functions that don't alter coordinates. Those allow
   * to transform between projections with equal meaning.
   *
   * @param {Array<Projection>} projections Projections.
   * @api
   */
  function addEquivalentProjections(projections) {
    addProjections(projections);
    projections.forEach(function (source) {
      projections.forEach(function (destination) {
        if (source !== destination) {
          add(source, destination, cloneTransform);
        }
      });
    });
  }

  /**
   * Registers transformation functions to convert coordinates in any projection
   * in projection1 to any projection in projection2.
   *
   * @param {Array<Projection>} projections1 Projections with equal
   *     meaning.
   * @param {Array<Projection>} projections2 Projections with equal
   *     meaning.
   * @param {TransformFunction} forwardTransform Transformation from any
   *   projection in projection1 to any projection in projection2.
   * @param {TransformFunction} inverseTransform Transform from any projection
   *   in projection2 to any projection in projection1..
   */
  function addEquivalentTransforms(
    projections1,
    projections2,
    forwardTransform,
    inverseTransform,
  ) {
    projections1.forEach(function (projection1) {
      projections2.forEach(function (projection2) {
        add(projection1, projection2, forwardTransform);
        add(projection2, projection1, inverseTransform);
      });
    });
  }

  /**
   * Clear all cached projections and transforms.
   */
  function clearAllProjections() {
    clear$1();
    clear();
  }

  /**
   * @param {Projection|string|undefined} projection Projection.
   * @param {string} defaultCode Default code.
   * @return {Projection} Projection.
   */
  function createProjection(projection, defaultCode) {
    if (!projection) {
      return get$2(defaultCode);
    }
    if (typeof projection === 'string') {
      return get$2(projection);
    }
    return /** @type {Projection} */ (projection);
  }

  /**
   * Creates a {@link module:ol/proj~TransformFunction} from a simple 2D coordinate transform
   * function.
   * @param {function(import("./coordinate.js").Coordinate): import("./coordinate.js").Coordinate} coordTransform Coordinate
   *     transform.
   * @return {TransformFunction} Transform function.
   */
  function createTransformFromCoordinateTransform(coordTransform) {
    return (
      /**
       * @param {Array<number>} input Input.
       * @param {Array<number>} [output] Output.
       * @param {number} [dimension] Dimensions that should be transformed.
       * @param {number} [stride] Stride.
       * @return {Array<number>} Output.
       */
      function (input, output, dimension, stride) {
        const length = input.length;
        dimension = dimension !== undefined ? dimension : 2;
        stride = stride ?? dimension;
        output = output !== undefined ? output : new Array(length);
        for (let i = 0; i < length; i += stride) {
          const point = coordTransform(input.slice(i, i + dimension));
          const pointLength = point.length;
          for (let j = 0, jj = stride; j < jj; ++j) {
            output[i + j] = j >= pointLength ? input[i + j] : point[j];
          }
        }
        return output;
      }
    );
  }

  /**
   * Registers coordinate transform functions to convert coordinates between the
   * source projection and the destination projection.
   * The forward and inverse functions convert coordinate pairs; this function
   * converts these into the functions used internally which also handle
   * extents and coordinate arrays.
   *
   * @param {ProjectionLike} source Source projection.
   * @param {ProjectionLike} destination Destination projection.
   * @param {function(import("./coordinate.js").Coordinate): import("./coordinate.js").Coordinate} forward The forward transform
   *     function (that is, from the source projection to the destination
   *     projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns
   *     the transformed {@link module:ol/coordinate~Coordinate}.
   * @param {function(import("./coordinate.js").Coordinate): import("./coordinate.js").Coordinate} inverse The inverse transform
   *     function (that is, from the destination projection to the source
   *     projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns
   *     the transformed {@link module:ol/coordinate~Coordinate}. If the transform function can only
   *     transform less dimensions than the input coordinate, it is supposeed to return a coordinate
   *     with only the length it can transform. The other dimensions will be taken unchanged from the
   *     source.
   * @api
   */
  function addCoordinateTransforms(source, destination, forward, inverse) {
    const sourceProj = get$2(source);
    const destProj = get$2(destination);
    add(
      sourceProj,
      destProj,
      createTransformFromCoordinateTransform(forward),
    );
    add(
      destProj,
      sourceProj,
      createTransformFromCoordinateTransform(inverse),
    );
  }

  /**
   * Transforms a coordinate from longitude/latitude to a different projection.
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate as longitude and latitude, i.e.
   *     an array with longitude as 1st and latitude as 2nd element.
   * @param {ProjectionLike} [projection] Target projection. The
   *     default is Web Mercator, i.e. 'EPSG:3857'.
   * @return {import("./coordinate.js").Coordinate} Coordinate projected to the target projection.
   * @api
   */
  function fromLonLat(coordinate, projection) {
    disableCoordinateWarning();
    return transform(
      coordinate,
      'EPSG:4326',
      projection !== undefined ? projection : 'EPSG:3857',
    );
  }

  /**
   * Transforms a coordinate to longitude/latitude.
   * @param {import("./coordinate.js").Coordinate} coordinate Projected coordinate.
   * @param {ProjectionLike} [projection] Projection of the coordinate.
   *     The default is Web Mercator, i.e. 'EPSG:3857'.
   * @return {import("./coordinate.js").Coordinate} Coordinate as longitude and latitude, i.e. an array
   *     with longitude as 1st and latitude as 2nd element.
   * @api
   */
  function toLonLat(coordinate, projection) {
    const lonLat = transform(
      coordinate,
      projection !== undefined ? projection : 'EPSG:3857',
      'EPSG:4326',
    );
    const lon = lonLat[0];
    if (lon < -180 || lon > 180) {
      lonLat[0] = modulo(lon + 180, 360) - 180;
    }
    return lonLat;
  }

  /**
   * Checks if two projections are the same, that is every coordinate in one
   * projection does represent the same geographic point as the same coordinate in
   * the other projection.
   *
   * @param {Projection} projection1 Projection 1.
   * @param {Projection} projection2 Projection 2.
   * @return {boolean} Equivalent.
   * @api
   */
  function equivalent$1(projection1, projection2) {
    if (projection1 === projection2) {
      return true;
    }
    const equalUnits = projection1.getUnits() === projection2.getUnits();
    if (projection1.getCode() === projection2.getCode()) {
      return equalUnits;
    }
    const transformFunc = getTransformFromProjections(projection1, projection2);
    return transformFunc === cloneTransform && equalUnits;
  }

  /**
   * Searches in the list of transform functions for the function for converting
   * coordinates from the source projection to the destination projection.
   *
   * @param {Projection} source Source Projection object.
   * @param {Projection} destination Destination Projection
   *     object.
   * @return {TransformFunction|null} Transform function.
   */
  function getTransformFromProjections(source, destination) {
    const sourceCode = source.getCode();
    const destinationCode = destination.getCode();
    let transformFunc = get$3(sourceCode, destinationCode);
    if (transformFunc) {
      return transformFunc;
    }

    /**
     * @type {Transforms|null}
     */
    let sourceTransforms = null;

    /**
     * @type {Transforms|null}
     */
    let destinationTransforms = null;

    // lazily add projections if we have supported transforms
    for (const makeTransforms of transformFactories) {
      if (!sourceTransforms) {
        sourceTransforms = makeTransforms(source);
      }
      if (!destinationTransforms) {
        destinationTransforms = makeTransforms(destination);
      }
    }

    if (!sourceTransforms && !destinationTransforms) {
      return null;
    }

    const intermediateCode = 'EPSG:4326';
    if (!destinationTransforms) {
      const toDestination = get$3(intermediateCode, destinationCode);
      if (toDestination) {
        transformFunc = composeTransformFuncs(
          sourceTransforms.inverse,
          toDestination,
        );
      }
    } else if (!sourceTransforms) {
      const fromSource = get$3(sourceCode, intermediateCode);
      if (fromSource) {
        transformFunc = composeTransformFuncs(
          fromSource,
          destinationTransforms.forward,
        );
      }
    } else {
      transformFunc = composeTransformFuncs(
        sourceTransforms.inverse,
        destinationTransforms.forward,
      );
    }

    if (transformFunc) {
      addProjection(source);
      addProjection(destination);
      add(source, destination, transformFunc);
    }

    return transformFunc;
  }

  /**
   * @param {TransformFunction} t1 The first transform function.
   * @param {TransformFunction} t2 The second transform function.
   * @return {TransformFunction} The composed transform function.
   */
  function composeTransformFuncs(t1, t2) {
    return function (input, output, dimensions, stride) {
      output = t1(input, output, dimensions, stride);
      return t2(output, output, dimensions, stride);
    };
  }

  /**
   * Given the projection-like objects, searches for a transformation
   * function to convert a coordinates array from the source projection to the
   * destination projection.
   *
   * @param {ProjectionLike} source Source.
   * @param {ProjectionLike} destination Destination.
   * @return {TransformFunction} Transform function.
   * @api
   */
  function getTransform(source, destination) {
    const sourceProjection = get$2(source);
    const destinationProjection = get$2(destination);
    return getTransformFromProjections(sourceProjection, destinationProjection);
  }

  /**
   * Transforms a coordinate from source projection to destination projection.
   * This returns a new coordinate (and does not modify the original). If there
   * is no available transform between the two projection, the function will throw
   * an error.
   *
   * See {@link module:ol/proj.transformExtent} for extent transformation.
   * See the transform method of {@link module:ol/geom/Geometry~Geometry} and its
   * subclasses for geometry transforms.
   *
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
   * @param {ProjectionLike} source Source projection-like.
   * @param {ProjectionLike} destination Destination projection-like.
   * @return {import("./coordinate.js").Coordinate} Coordinate.
   * @api
   */
  function transform(coordinate, source, destination) {
    const transformFunc = getTransform(source, destination);
    if (!transformFunc) {
      const sourceCode = get$2(source).getCode();
      const destinationCode = get$2(destination).getCode();
      throw new Error(
        `No transform available between ${sourceCode} and ${destinationCode}`,
      );
    }
    return transformFunc(coordinate, undefined, coordinate.length);
  }

  /**
   * Transforms an extent from source projection to destination projection.  This
   * returns a new extent (and does not modify the original).
   *
   * @param {import("./extent.js").Extent} extent The extent to transform.
   * @param {ProjectionLike} source Source projection-like.
   * @param {ProjectionLike} destination Destination projection-like.
   * @param {number} [stops] Number of stops per side used for the transform.
   * By default only the corners are used.
   * @return {import("./extent.js").Extent} The transformed extent.
   * @api
   */
  function transformExtent(extent, source, destination, stops) {
    const transformFunc = getTransform(source, destination);
    return applyTransform(extent, transformFunc, undefined, stops);
  }

  /**
   * Transforms the given point to the destination projection.
   *
   * @param {import("./coordinate.js").Coordinate} point Point.
   * @param {Projection} sourceProjection Source projection.
   * @param {Projection} destinationProjection Destination projection.
   * @return {import("./coordinate.js").Coordinate} Point.
   */
  function transformWithProjections(
    point,
    sourceProjection,
    destinationProjection,
  ) {
    const transformFunc = getTransformFromProjections(
      sourceProjection,
      destinationProjection,
    );
    return transformFunc(point);
  }

  /**
   * @type {Projection|null}
   */
  let userProjection = null;

  /**
   * Set the projection for coordinates supplied from and returned by API methods.
   * This includes all API methods except for those interacting with tile grids,
   * plus {@link import("./Map.js").FrameState} and {@link import("./View.js").State}.
   * @param {ProjectionLike} projection The user projection.
   * @api
   */
  function setUserProjection(projection) {
    userProjection = get$2(projection);
  }

  /**
   * Clear the user projection if set.
   * @api
   */
  function clearUserProjection() {
    userProjection = null;
  }

  /**
   * Get the projection for coordinates supplied from and returned by API methods.
   * @return {Projection|null} The user projection (or null if not set).
   * @api
   */
  function getUserProjection() {
    return userProjection;
  }

  /**
   * Use geographic coordinates (WGS-84 datum) in API methods.
   * This includes all API methods except for those interacting with tile grids,
   * plus {@link import("./Map.js").FrameState} and {@link import("./View.js").State}.
   * @api
   */
  function useGeographic() {
    setUserProjection('EPSG:4326');
  }

  /**
   * Return a coordinate transformed into the user projection.  If no user projection
   * is set, the original coordinate is returned.
   * @param {Array<number>} coordinate Input coordinate.
   * @param {ProjectionLike} sourceProjection The input coordinate projection.
   * @return {Array<number>} The input coordinate in the user projection.
   */
  function toUserCoordinate(coordinate, sourceProjection) {
    if (!userProjection) {
      return coordinate;
    }
    return transform(coordinate, sourceProjection, userProjection);
  }

  /**
   * Return a coordinate transformed from the user projection.  If no user projection
   * is set, the original coordinate is returned.
   * @param {Array<number>} coordinate Input coordinate.
   * @param {ProjectionLike} destProjection The destination projection.
   * @return {Array<number>} The input coordinate transformed.
   */
  function fromUserCoordinate(coordinate, destProjection) {
    if (!userProjection) {
      if (
        showCoordinateWarning &&
        !equals(coordinate, [0, 0]) &&
        coordinate[0] >= -180 &&
        coordinate[0] <= 180 &&
        coordinate[1] >= -90 &&
        coordinate[1] <= 90
      ) {
        showCoordinateWarning = false;
        warn(
          'Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.',
        );
      }
      return coordinate;
    }
    return transform(coordinate, userProjection, destProjection);
  }

  /**
   * Return an extent transformed into the user projection.  If no user projection
   * is set, the original extent is returned.
   * @param {import("./extent.js").Extent} extent Input extent.
   * @param {ProjectionLike} sourceProjection The input extent projection.
   * @return {import("./extent.js").Extent} The input extent in the user projection.
   */
  function toUserExtent(extent, sourceProjection) {
    if (!userProjection) {
      return extent;
    }
    return transformExtent(extent, sourceProjection, userProjection);
  }

  /**
   * Return an extent transformed from the user projection.  If no user projection
   * is set, the original extent is returned.
   * @param {import("./extent.js").Extent} extent Input extent.
   * @param {ProjectionLike} destProjection The destination projection.
   * @return {import("./extent.js").Extent} The input extent transformed.
   */
  function fromUserExtent(extent, destProjection) {
    if (!userProjection) {
      return extent;
    }
    return transformExtent(extent, userProjection, destProjection);
  }

  /**
   * Return the resolution in user projection units per pixel. If no user projection
   * is set, or source or user projection are missing units, the original resolution
   * is returned.
   * @param {number} resolution Resolution in input projection units per pixel.
   * @param {ProjectionLike} sourceProjection The input projection.
   * @return {number} Resolution in user projection units per pixel.
   */
  function toUserResolution(resolution, sourceProjection) {
    if (!userProjection) {
      return resolution;
    }
    const sourceMetersPerUnit = get$2(sourceProjection).getMetersPerUnit();
    const userMetersPerUnit = userProjection.getMetersPerUnit();
    return sourceMetersPerUnit && userMetersPerUnit
      ? (resolution * sourceMetersPerUnit) / userMetersPerUnit
      : resolution;
  }

  /**
   * Return the resolution in user projection units per pixel. If no user projection
   * is set, or source or user projection are missing units, the original resolution
   * is returned.
   * @param {number} resolution Resolution in user projection units per pixel.
   * @param {ProjectionLike} destProjection The destination projection.
   * @return {number} Resolution in destination projection units per pixel.
   */
  function fromUserResolution(resolution, destProjection) {
    if (!userProjection) {
      return resolution;
    }
    const destMetersPerUnit = get$2(destProjection).getMetersPerUnit();
    const userMetersPerUnit = userProjection.getMetersPerUnit();
    return destMetersPerUnit && userMetersPerUnit
      ? (resolution * userMetersPerUnit) / destMetersPerUnit
      : resolution;
  }

  /**
   * Creates a safe coordinate transform function from a coordinate transform function.
   * "Safe" means that it can handle wrapping of x-coordinates for global projections,
   * and that coordinates exceeding the source projection validity extent's range will be
   * clamped to the validity range.
   * @param {Projection} sourceProj Source projection.
   * @param {Projection} destProj Destination projection.
   * @param {function(import("./coordinate.js").Coordinate): import("./coordinate.js").Coordinate} transform Transform function (source to destination).
   * @return {function(import("./coordinate.js").Coordinate): import("./coordinate.js").Coordinate} Safe transform function (source to destination).
   */
  function createSafeCoordinateTransform(sourceProj, destProj, transform) {
    return function (coord) {
      let transformed, worldsAway;
      if (sourceProj.canWrapX()) {
        const sourceExtent = sourceProj.getExtent();
        const sourceExtentWidth = getWidth(sourceExtent);
        coord = coord.slice(0);
        worldsAway = getWorldsAway(coord, sourceProj, sourceExtentWidth);
        if (worldsAway) {
          // Move x to the real world
          coord[0] = coord[0] - worldsAway * sourceExtentWidth;
        }
        coord[0] = clamp$1(coord[0], sourceExtent[0], sourceExtent[2]);
        coord[1] = clamp$1(coord[1], sourceExtent[1], sourceExtent[3]);
        transformed = transform(coord);
      } else {
        transformed = transform(coord);
      }
      if (worldsAway && destProj.canWrapX()) {
        // Move transformed coordinate back to the offset world
        transformed[0] += worldsAway * getWidth(destProj.getExtent());
      }
      return transformed;
    };
  }

  /**
   * Add transforms to and from EPSG:4326 and EPSG:3857.  This function is called
   * by when this module is executed and should only need to be called again after
   * `clearAllProjections()` is called (e.g. in tests).
   */
  function addCommon() {
    // Add transformations that don't alter coordinates to convert within set of
    // projections with equal meaning.
    addEquivalentProjections(PROJECTIONS$1);
    addEquivalentProjections(PROJECTIONS);
    // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like
    // coordinates and back.
    addEquivalentTransforms(
      PROJECTIONS,
      PROJECTIONS$1,
      fromEPSG4326,
      toEPSG4326,
    );
  }

  addCommon();

  var proj0 = {
    __proto__: null,
    METERS_PER_UNIT: METERS_PER_UNIT$1,
    Projection: Projection,
    addCommon: addCommon,
    addCoordinateTransforms: addCoordinateTransforms,
    addEquivalentProjections: addEquivalentProjections,
    addEquivalentTransforms: addEquivalentTransforms,
    addProjection: addProjection,
    addProjections: addProjections,
    clearAllProjections: clearAllProjections,
    clearUserProjection: clearUserProjection,
    cloneTransform: cloneTransform,
    createProjection: createProjection,
    createSafeCoordinateTransform: createSafeCoordinateTransform,
    createTransformFromCoordinateTransform: createTransformFromCoordinateTransform,
    disableCoordinateWarning: disableCoordinateWarning,
    equivalent: equivalent$1,
    fromLonLat: fromLonLat,
    fromUserCoordinate: fromUserCoordinate,
    fromUserExtent: fromUserExtent,
    fromUserResolution: fromUserResolution,
    get: get$2,
    getPointResolution: getPointResolution,
    getTransform: getTransform,
    getTransformFromProjections: getTransformFromProjections,
    getUserProjection: getUserProjection,
    identityTransform: identityTransform,
    setUserProjection: setUserProjection,
    toLonLat: toLonLat,
    toUserCoordinate: toUserCoordinate,
    toUserExtent: toUserExtent,
    toUserResolution: toUserResolution,
    transform: transform,
    transformExtent: transformExtent,
    transformWithProjections: transformWithProjections,
    useGeographic: useGeographic
  };

  /**
   * @module ol/transform
   */

  /**
   * An array representing an affine 2d transformation for use with
   * {@link module:ol/transform} functions. The array has 6 elements.
   * @typedef {!Array<number>} Transform
   * @api
   */

  /**
   * Collection of affine 2d transformation functions. The functions work on an
   * array of 6 elements. The element order is compatible with the [SVGMatrix
   * interface](https://developer.mozilla.org/en-US/docs/Web/API/SVGMatrix) and is
   * a subset (elements a to f) of a 3×3 matrix:
   * ```
   * [ a c e ]
   * [ b d f ]
   * [ 0 0 1 ]
   * ```
   */

  /**
   * @private
   * @type {Transform}
   */
  const tmp_ = new Array(6);

  /**
   * Create an identity transform.
   * @return {!Transform} Identity transform.
   */
  function create$3() {
    return [1, 0, 0, 1, 0, 0];
  }

  /**
   * Resets the given transform to an identity transform.
   * @param {!Transform} transform Transform.
   * @return {!Transform} Transform.
   */
  function reset(transform) {
    return set(transform, 1, 0, 0, 1, 0, 0);
  }

  /**
   * Multiply the underlying matrices of two transforms and return the result in
   * the first transform.
   * @param {!Transform} transform1 Transform parameters of matrix 1.
   * @param {!Transform} transform2 Transform parameters of matrix 2.
   * @return {!Transform} transform1 multiplied with transform2.
   */
  function multiply(transform1, transform2) {
    const a1 = transform1[0];
    const b1 = transform1[1];
    const c1 = transform1[2];
    const d1 = transform1[3];
    const e1 = transform1[4];
    const f1 = transform1[5];
    const a2 = transform2[0];
    const b2 = transform2[1];
    const c2 = transform2[2];
    const d2 = transform2[3];
    const e2 = transform2[4];
    const f2 = transform2[5];

    transform1[0] = a1 * a2 + c1 * b2;
    transform1[1] = b1 * a2 + d1 * b2;
    transform1[2] = a1 * c2 + c1 * d2;
    transform1[3] = b1 * c2 + d1 * d2;
    transform1[4] = a1 * e2 + c1 * f2 + e1;
    transform1[5] = b1 * e2 + d1 * f2 + f1;

    return transform1;
  }

  /**
   * Set the transform components a-f on a given transform.
   * @param {!Transform} transform Transform.
   * @param {number} a The a component of the transform.
   * @param {number} b The b component of the transform.
   * @param {number} c The c component of the transform.
   * @param {number} d The d component of the transform.
   * @param {number} e The e component of the transform.
   * @param {number} f The f component of the transform.
   * @return {!Transform} Matrix with transform applied.
   */
  function set(transform, a, b, c, d, e, f) {
    transform[0] = a;
    transform[1] = b;
    transform[2] = c;
    transform[3] = d;
    transform[4] = e;
    transform[5] = f;
    return transform;
  }

  /**
   * Set transform on one matrix from another matrix.
   * @param {!Transform} transform1 Matrix to set transform to.
   * @param {!Transform} transform2 Matrix to set transform from.
   * @return {!Transform} transform1 with transform from transform2 applied.
   */
  function setFromArray(transform1, transform2) {
    transform1[0] = transform2[0];
    transform1[1] = transform2[1];
    transform1[2] = transform2[2];
    transform1[3] = transform2[3];
    transform1[4] = transform2[4];
    transform1[5] = transform2[5];
    return transform1;
  }

  /**
   * Transforms the given coordinate with the given transform returning the
   * resulting, transformed coordinate. The coordinate will be modified in-place.
   *
   * @param {Transform} transform The transformation.
   * @param {import("./coordinate.js").Coordinate|import("./pixel.js").Pixel} coordinate The coordinate to transform.
   * @return {import("./coordinate.js").Coordinate|import("./pixel.js").Pixel} return coordinate so that operations can be
   *     chained together.
   */
  function apply(transform, coordinate) {
    const x = coordinate[0];
    const y = coordinate[1];
    coordinate[0] = transform[0] * x + transform[2] * y + transform[4];
    coordinate[1] = transform[1] * x + transform[3] * y + transform[5];
    return coordinate;
  }

  /**
   * Applies rotation to the given transform.
   * @param {!Transform} transform Transform.
   * @param {number} angle Angle in radians.
   * @return {!Transform} The rotated transform.
   */
  function rotate$1(transform, angle) {
    const cos = Math.cos(angle);
    const sin = Math.sin(angle);
    return multiply(transform, set(tmp_, cos, sin, -sin, cos, 0, 0));
  }

  /**
   * Applies scale to a given transform.
   * @param {!Transform} transform Transform.
   * @param {number} x Scale factor x.
   * @param {number} y Scale factor y.
   * @return {!Transform} The scaled transform.
   */
  function scale$3(transform, x, y) {
    return multiply(transform, set(tmp_, x, 0, 0, y, 0, 0));
  }

  /**
   * Applies translation to the given transform.
   * @param {!Transform} transform Transform.
   * @param {number} dx Translation x.
   * @param {number} dy Translation y.
   * @return {!Transform} The translated transform.
   */
  function translate$2(transform, dx, dy) {
    return multiply(transform, set(tmp_, 1, 0, 0, 1, dx, dy));
  }

  /**
   * Creates a composite transform given an initial translation, scale, rotation, and
   * final translation (in that order only, not commutative).
   * @param {!Transform} transform The transform (will be modified in place).
   * @param {number} dx1 Initial translation x.
   * @param {number} dy1 Initial translation y.
   * @param {number} sx Scale factor x.
   * @param {number} sy Scale factor y.
   * @param {number} angle Rotation (in counter-clockwise radians).
   * @param {number} dx2 Final translation x.
   * @param {number} dy2 Final translation y.
   * @return {!Transform} The composite transform.
   */
  function compose(transform, dx1, dy1, sx, sy, angle, dx2, dy2) {
    const sin = Math.sin(angle);
    const cos = Math.cos(angle);
    transform[0] = sx * cos;
    transform[1] = sy * sin;
    transform[2] = -sx * sin;
    transform[3] = sy * cos;
    transform[4] = dx2 * sx * cos - dy2 * sx * sin + dx1;
    transform[5] = dx2 * sy * sin + dy2 * sy * cos + dy1;
    return transform;
  }

  /**
   * Invert the given transform.
   * @param {!Transform} target Transform to be set as the inverse of
   *     the source transform.
   * @param {!Transform} source The source transform to invert.
   * @return {!Transform} The inverted (target) transform.
   */
  function makeInverse(target, source) {
    const det = determinant(source);
    assert(det !== 0, 'Transformation matrix cannot be inverted');

    const a = source[0];
    const b = source[1];
    const c = source[2];
    const d = source[3];
    const e = source[4];
    const f = source[5];

    target[0] = d / det;
    target[1] = -b / det;
    target[2] = -c / det;
    target[3] = a / det;
    target[4] = (c * f - d * e) / det;
    target[5] = -(a * f - b * e) / det;

    return target;
  }

  /**
   * Returns the determinant of the given matrix.
   * @param {!Transform} mat Matrix.
   * @return {number} Determinant.
   */
  function determinant(mat) {
    return mat[0] * mat[3] - mat[1] * mat[2];
  }

  /**
   * @type {Array}
   */
  const matrixPrecision = [1e5, 1e5, 1e5, 1e5, 2, 2];

  /**
   * A matrix string version of the transform.  This can be used
   * for CSS transforms.
   * @param {!Transform} mat Matrix.
   * @return {string} The transform as a string.
   */
  function toString$2(mat) {
    const transformString = 'matrix(' + mat.join(', ') + ')';
    return transformString;
  }

  /**
   * Create a transform from a CSS transform matrix string.
   * @param {string} cssTransform The CSS string to parse.
   * @return {!Transform} The transform.
   */
  function fromString$1(cssTransform) {
    const values = cssTransform.substring(7, cssTransform.length - 1).split(',');
    return values.map(parseFloat);
  }

  /**
   * Compare two matrices for equality.
   * @param {!string} cssTransform1 A CSS transform matrix string.
   * @param {!string} cssTransform2 A CSS transform matrix string.
   * @return {boolean} The two matrices are equal.
   */
  function equivalent(cssTransform1, cssTransform2) {
    const mat1 = fromString$1(cssTransform1);
    const mat2 = fromString$1(cssTransform2);
    for (let i = 0; i < 6; ++i) {
      if (Math.round((mat1[i] - mat2[i]) * matrixPrecision[i]) !== 0) {
        return false;
      }
    }
    return true;
  }

  /**
   * @module ol/geom/flat/transform
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {import("../../transform.js").Transform} transform Transform.
   * @param {Array<number>} [dest] Destination.
   * @param {number} [destinationStride] Stride of destination coordinates; if unspecified, assumed to be 2.
   * @return {Array<number>} Transformed coordinates.
   */
  function transform2D(
    flatCoordinates,
    offset,
    end,
    stride,
    transform,
    dest,
    destinationStride,
  ) {
    dest = dest ? dest : [];
    destinationStride = destinationStride ? destinationStride : 2;
    let i = 0;
    for (let j = offset; j < end; j += stride) {
      const x = flatCoordinates[j];
      const y = flatCoordinates[j + 1];
      dest[i++] = transform[0] * x + transform[2] * y + transform[4];
      dest[i++] = transform[1] * x + transform[3] * y + transform[5];

      for (let k = 2; k < destinationStride; k++) {
        dest[i++] = flatCoordinates[j + k];
      }
    }

    if (dest && dest.length != i) {
      dest.length = i;
    }
    return dest;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} angle Angle.
   * @param {Array<number>} anchor Rotation anchor point.
   * @param {Array<number>} [dest] Destination.
   * @return {Array<number>} Transformed coordinates.
   */
  function rotate(
    flatCoordinates,
    offset,
    end,
    stride,
    angle,
    anchor,
    dest,
  ) {
    dest = dest ? dest : [];
    const cos = Math.cos(angle);
    const sin = Math.sin(angle);
    const anchorX = anchor[0];
    const anchorY = anchor[1];
    let i = 0;
    for (let j = offset; j < end; j += stride) {
      const deltaX = flatCoordinates[j] - anchorX;
      const deltaY = flatCoordinates[j + 1] - anchorY;
      dest[i++] = anchorX + deltaX * cos - deltaY * sin;
      dest[i++] = anchorY + deltaX * sin + deltaY * cos;
      for (let k = j + 2; k < j + stride; ++k) {
        dest[i++] = flatCoordinates[k];
      }
    }
    if (dest && dest.length != i) {
      dest.length = i;
    }
    return dest;
  }

  /**
   * Scale the coordinates.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} sx Scale factor in the x-direction.
   * @param {number} sy Scale factor in the y-direction.
   * @param {Array<number>} anchor Scale anchor point.
   * @param {Array<number>} [dest] Destination.
   * @return {Array<number>} Transformed coordinates.
   */
  function scale$2(
    flatCoordinates,
    offset,
    end,
    stride,
    sx,
    sy,
    anchor,
    dest,
  ) {
    dest = dest ? dest : [];
    const anchorX = anchor[0];
    const anchorY = anchor[1];
    let i = 0;
    for (let j = offset; j < end; j += stride) {
      const deltaX = flatCoordinates[j] - anchorX;
      const deltaY = flatCoordinates[j + 1] - anchorY;
      dest[i++] = anchorX + sx * deltaX;
      dest[i++] = anchorY + sy * deltaY;
      for (let k = j + 2; k < j + stride; ++k) {
        dest[i++] = flatCoordinates[k];
      }
    }
    if (dest && dest.length != i) {
      dest.length = i;
    }
    return dest;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} deltaX Delta X.
   * @param {number} deltaY Delta Y.
   * @param {Array<number>} [dest] Destination.
   * @return {Array<number>} Transformed coordinates.
   */
  function translate$1(
    flatCoordinates,
    offset,
    end,
    stride,
    deltaX,
    deltaY,
    dest,
  ) {
    dest = dest ? dest : [];
    let i = 0;
    for (let j = offset; j < end; j += stride) {
      dest[i++] = flatCoordinates[j] + deltaX;
      dest[i++] = flatCoordinates[j + 1] + deltaY;
      for (let k = j + 2; k < j + stride; ++k) {
        dest[i++] = flatCoordinates[k];
      }
    }
    if (dest && dest.length != i) {
      dest.length = i;
    }
    return dest;
  }

  /**
   * @module ol/geom/Geometry
   */

  /**
   * @typedef {'XY' | 'XYZ' | 'XYM' | 'XYZM'} GeometryLayout
   * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z')
   * or measure ('M') coordinate is available.
   */

  /**
   * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString' | 'MultiPolygon' | 'GeometryCollection' | 'Circle'} Type
   * The geometry type.  One of `'Point'`, `'LineString'`, `'LinearRing'`,
   * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`,
   * `'GeometryCollection'`, or `'Circle'`.
   */

  /**
   * @type {import("../transform.js").Transform}
   */
  const tmpTransform$1 = create$3();

  /** @type {import('../coordinate.js').Coordinate} */
  const tmpPoint = [NaN, NaN];

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for vector geometries.
   *
   * To get notified of changes to the geometry, register a listener for the
   * generic `change` event on your geometry instance.
   *
   * @abstract
   * @api
   */
  class Geometry extends BaseObject {
    constructor() {
      super();

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.extent_ = createEmpty();

      /**
       * @private
       * @type {number}
       */
      this.extentRevision_ = -1;

      /**
       * @protected
       * @type {number}
       */
      this.simplifiedGeometryMaxMinSquaredTolerance = 0;

      /**
       * @protected
       * @type {number}
       */
      this.simplifiedGeometryRevision = 0;

      /**
       * Get a transformed and simplified version of the geometry.
       * @abstract
       * @param {number} revision The geometry revision.
       * @param {number} squaredTolerance Squared tolerance.
       * @param {import("../proj.js").TransformFunction} [transform] Optional transform function.
       * @return {Geometry} Simplified geometry.
       */
      this.simplifyTransformedInternal = memoizeOne(
        (revision, squaredTolerance, transform) => {
          if (!transform) {
            return this.getSimplifiedGeometry(squaredTolerance);
          }
          const clone = this.clone();
          clone.applyTransform(transform);
          return clone.getSimplifiedGeometry(squaredTolerance);
        },
      );
    }

    /**
     * Get a transformed and simplified version of the geometry.
     * @abstract
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../proj.js").TransformFunction} [transform] Optional transform function.
     * @return {Geometry} Simplified geometry.
     */
    simplifyTransformed(squaredTolerance, transform) {
      return this.simplifyTransformedInternal(
        this.getRevision(),
        squaredTolerance,
        transform,
      );
    }

    /**
     * Make a complete copy of the geometry.
     * @abstract
     * @return {!Geometry} Clone.
     */
    clone() {
      return abstract();
    }

    /**
     * @abstract
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      return abstract();
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @return {boolean} Contains (x, y).
     */
    containsXY(x, y) {
      return this.closestPointXY(x, y, tmpPoint, Number.MIN_VALUE) === 0;
    }

    /**
     * Return the closest point of the geometry to the passed point as
     * {@link module:ol/coordinate~Coordinate coordinate}.
     * @param {import("../coordinate.js").Coordinate} point Point.
     * @param {import("../coordinate.js").Coordinate} [closestPoint] Closest point.
     * @return {import("../coordinate.js").Coordinate} Closest point.
     * @api
     */
    getClosestPoint(point, closestPoint) {
      closestPoint = closestPoint ? closestPoint : [NaN, NaN];
      this.closestPointXY(point[0], point[1], closestPoint, Infinity);
      return closestPoint;
    }

    /**
     * Returns true if this geometry includes the specified coordinate. If the
     * coordinate is on the boundary of the geometry, returns false.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @return {boolean} Contains coordinate.
     * @api
     */
    intersectsCoordinate(coordinate) {
      return this.containsXY(coordinate[0], coordinate[1]);
    }

    /**
     * @abstract
     * @param {import("../extent.js").Extent} extent Extent.
     * @protected
     * @return {import("../extent.js").Extent} extent Extent.
     */
    computeExtent(extent) {
      return abstract();
    }

    /**
     * Get the extent of the geometry.
     * @param {import("../extent.js").Extent} [extent] Extent.
     * @return {import("../extent.js").Extent} extent Extent.
     * @api
     */
    getExtent(extent) {
      if (this.extentRevision_ != this.getRevision()) {
        const extent = this.computeExtent(this.extent_);
        if (isNaN(extent[0]) || isNaN(extent[1])) {
          createOrUpdateEmpty(extent);
        }
        this.extentRevision_ = this.getRevision();
      }
      return returnOrUpdate(this.extent_, extent);
    }

    /**
     * Rotate the geometry around a given coordinate. This modifies the geometry
     * coordinates in place.
     * @abstract
     * @param {number} angle Rotation angle in radians.
     * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
     * @api
     */
    rotate(angle, anchor) {
      abstract();
    }

    /**
     * Scale the geometry (with an optional origin).  This modifies the geometry
     * coordinates in place.
     * @abstract
     * @param {number} sx The scaling factor in the x-direction.
     * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).
     * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center
     *     of the geometry extent).
     * @api
     */
    scale(sx, sy, anchor) {
      abstract();
    }

    /**
     * Create a simplified version of this geometry.  For linestrings, this uses
     * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)
     * algorithm.  For polygons, a quantization-based
     * simplification is used to preserve topology.
     * @param {number} tolerance The tolerance distance for simplification.
     * @return {Geometry} A new, simplified version of the original geometry.
     * @api
     */
    simplify(tolerance) {
      return this.getSimplifiedGeometry(tolerance * tolerance);
    }

    /**
     * Create a simplified version of this geometry using the Douglas Peucker
     * algorithm.
     * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.
     * @abstract
     * @param {number} squaredTolerance Squared tolerance.
     * @return {Geometry} Simplified geometry.
     */
    getSimplifiedGeometry(squaredTolerance) {
      return abstract();
    }

    /**
     * Get the type of this geometry.
     * @abstract
     * @return {Type} Geometry type.
     */
    getType() {
      return abstract();
    }

    /**
     * Apply a transform function to the coordinates of the geometry.
     * The geometry is modified in place.
     * If you do not want the geometry modified in place, first `clone()` it and
     * then use this function on the clone.
     * @abstract
     * @param {import("../proj.js").TransformFunction} transformFn Transform function.
     * Called with a flat array of geometry coordinates.
     */
    applyTransform(transformFn) {
      abstract();
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @abstract
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     */
    intersectsExtent(extent) {
      return abstract();
    }

    /**
     * Translate the geometry.  This modifies the geometry coordinates in place.  If
     * instead you want a new geometry, first `clone()` this geometry.
     * @abstract
     * @param {number} deltaX Delta X.
     * @param {number} deltaY Delta Y.
     * @api
     */
    translate(deltaX, deltaY) {
      abstract();
    }

    /**
     * Transform each coordinate of the geometry from one coordinate reference
     * system to another. The geometry is modified in place.
     * For example, a line will be transformed to a line and a circle to a circle.
     * If you do not want the geometry modified in place, first `clone()` it and
     * then use this function on the clone.
     *
     * @param {import("../proj.js").ProjectionLike} source The current projection.  Can be a
     *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
     * @param {import("../proj.js").ProjectionLike} destination The desired projection.  Can be a
     *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
     * @return {this} This geometry.  Note that original geometry is
     *     modified in place.
     * @api
     */
    transform(source, destination) {
      /** @type {import("../proj/Projection.js").default} */
      const sourceProj = get$2(source);
      const transformFn =
        sourceProj.getUnits() == 'tile-pixels'
          ? function (inCoordinates, outCoordinates, stride) {
              const pixelExtent = sourceProj.getExtent();
              const projectedExtent = sourceProj.getWorldExtent();
              const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
              compose(
                tmpTransform$1,
                projectedExtent[0],
                projectedExtent[3],
                scale,
                -scale,
                0,
                0,
                0,
              );
              const transformed = transform2D(
                inCoordinates,
                0,
                inCoordinates.length,
                stride,
                tmpTransform$1,
                outCoordinates,
              );
              const projTransform = getTransform(sourceProj, destination);
              if (projTransform) {
                return projTransform(transformed, transformed, stride);
              }
              return transformed;
            }
          : getTransform(sourceProj, destination);
      this.applyTransform(transformFn);
      return this;
    }
  }

  /**
   * @module ol/geom/SimpleGeometry
   */

  /**
   * @classdesc
   * Abstract base class; only used for creating subclasses; do not instantiate
   * in apps, as cannot be rendered.
   *
   * @abstract
   * @api
   */
  class SimpleGeometry extends Geometry {
    constructor() {
      super();

      /**
       * @protected
       * @type {import("./Geometry.js").GeometryLayout}
       */
      this.layout = 'XY';

      /**
       * @protected
       * @type {number}
       */
      this.stride = 2;

      /**
       * @protected
       * @type {Array<number>}
       */
      this.flatCoordinates;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @protected
     * @return {import("../extent.js").Extent} extent Extent.
     * @override
     */
    computeExtent(extent) {
      return createOrUpdateFromFlatCoordinates(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        extent,
      );
    }

    /**
     * @abstract
     * @return {Array<*> | null} Coordinates.
     */
    getCoordinates() {
      return abstract();
    }

    /**
     * Return the first coordinate of the geometry.
     * @return {import("../coordinate.js").Coordinate} First coordinate.
     * @api
     */
    getFirstCoordinate() {
      return this.flatCoordinates.slice(0, this.stride);
    }

    /**
     * @return {Array<number>} Flat coordinates.
     */
    getFlatCoordinates() {
      return this.flatCoordinates;
    }

    /**
     * Return the last coordinate of the geometry.
     * @return {import("../coordinate.js").Coordinate} Last point.
     * @api
     */
    getLastCoordinate() {
      return this.flatCoordinates.slice(
        this.flatCoordinates.length - this.stride,
      );
    }

    /**
     * Return the {@link import("./Geometry.js").GeometryLayout layout} of the geometry.
     * @return {import("./Geometry.js").GeometryLayout} Layout.
     * @api
     */
    getLayout() {
      return this.layout;
    }

    /**
     * Create a simplified version of this geometry using the Douglas Peucker algorithm.
     * @param {number} squaredTolerance Squared tolerance.
     * @return {SimpleGeometry} Simplified geometry.
     * @override
     */
    getSimplifiedGeometry(squaredTolerance) {
      if (this.simplifiedGeometryRevision !== this.getRevision()) {
        this.simplifiedGeometryMaxMinSquaredTolerance = 0;
        this.simplifiedGeometryRevision = this.getRevision();
      }
      // If squaredTolerance is negative or if we know that simplification will not
      // have any effect then just return this.
      if (
        squaredTolerance < 0 ||
        (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&
          squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)
      ) {
        return this;
      }

      const simplifiedGeometry =
        this.getSimplifiedGeometryInternal(squaredTolerance);
      const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates();
      if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) {
        return simplifiedGeometry;
      }
      // Simplification did not actually remove any coordinates.  We now know
      // that any calls to getSimplifiedGeometry with a squaredTolerance less
      // than or equal to the current squaredTolerance will also not have any
      // effect.  This allows us to short circuit simplification (saving CPU
      // cycles) and prevents the cache of simplified geometries from filling
      // up with useless identical copies of this geometry (saving memory).
      this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;
      return this;
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {SimpleGeometry} Simplified geometry.
     * @protected
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      return this;
    }

    /**
     * @return {number} Stride.
     */
    getStride() {
      return this.stride;
    }

    /**
     * @param {import("./Geometry.js").GeometryLayout} layout Layout.
     * @param {Array<number>} flatCoordinates Flat coordinates.
     */
    setFlatCoordinates(layout, flatCoordinates) {
      this.stride = getStrideForLayout(layout);
      this.layout = layout;
      this.flatCoordinates = flatCoordinates;
    }

    /**
     * @abstract
     * @param {!Array<*>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    setCoordinates(coordinates, layout) {
      abstract();
    }

    /**
     * @param {import("./Geometry.js").GeometryLayout|undefined} layout Layout.
     * @param {Array<*>} coordinates Coordinates.
     * @param {number} nesting Nesting.
     * @protected
     */
    setLayout(layout, coordinates, nesting) {
      let stride;
      if (layout) {
        stride = getStrideForLayout(layout);
      } else {
        for (let i = 0; i < nesting; ++i) {
          if (coordinates.length === 0) {
            this.layout = 'XY';
            this.stride = 2;
            return;
          }
          coordinates = /** @type {Array<unknown>} */ (coordinates[0]);
        }
        stride = coordinates.length;
        layout = getLayoutForStride(stride);
      }
      this.layout = layout;
      this.stride = stride;
    }

    /**
     * Apply a transform function to the coordinates of the geometry.
     * The geometry is modified in place.
     * If you do not want the geometry modified in place, first `clone()` it and
     * then use this function on the clone.
     * @param {import("../proj.js").TransformFunction} transformFn Transform function.
     * Called with a flat array of geometry coordinates.
     * @api
     * @override
     */
    applyTransform(transformFn) {
      if (this.flatCoordinates) {
        transformFn(
          this.flatCoordinates,
          this.flatCoordinates,
          this.layout.startsWith('XYZ') ? 3 : 2,
          this.stride,
        );
        this.changed();
      }
    }

    /**
     * Rotate the geometry around a given coordinate. This modifies the geometry
     * coordinates in place.
     * @param {number} angle Rotation angle in counter-clockwise radians.
     * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
     * @api
     * @override
     */
    rotate(angle, anchor) {
      const flatCoordinates = this.getFlatCoordinates();
      if (flatCoordinates) {
        const stride = this.getStride();
        rotate(
          flatCoordinates,
          0,
          flatCoordinates.length,
          stride,
          angle,
          anchor,
          flatCoordinates,
        );
        this.changed();
      }
    }

    /**
     * Scale the geometry (with an optional origin).  This modifies the geometry
     * coordinates in place.
     * @param {number} sx The scaling factor in the x-direction.
     * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).
     * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center
     *     of the geometry extent).
     * @api
     * @override
     */
    scale(sx, sy, anchor) {
      if (sy === undefined) {
        sy = sx;
      }
      if (!anchor) {
        anchor = getCenter(this.getExtent());
      }
      const flatCoordinates = this.getFlatCoordinates();
      if (flatCoordinates) {
        const stride = this.getStride();
        scale$2(
          flatCoordinates,
          0,
          flatCoordinates.length,
          stride,
          sx,
          sy,
          anchor,
          flatCoordinates,
        );
        this.changed();
      }
    }

    /**
     * Translate the geometry.  This modifies the geometry coordinates in place.  If
     * instead you want a new geometry, first `clone()` this geometry.
     * @param {number} deltaX Delta X.
     * @param {number} deltaY Delta Y.
     * @api
     * @override
     */
    translate(deltaX, deltaY) {
      const flatCoordinates = this.getFlatCoordinates();
      if (flatCoordinates) {
        const stride = this.getStride();
        translate$1(
          flatCoordinates,
          0,
          flatCoordinates.length,
          stride,
          deltaX,
          deltaY,
          flatCoordinates,
        );
        this.changed();
      }
    }
  }

  /**
   * @param {number} stride Stride.
   * @return {import("./Geometry.js").GeometryLayout} layout Layout.
   */
  function getLayoutForStride(stride) {
    let layout;
    if (stride == 2) {
      layout = 'XY';
    } else if (stride == 3) {
      layout = 'XYZ';
    } else if (stride == 4) {
      layout = 'XYZM';
    }
    return /** @type {import("./Geometry.js").GeometryLayout} */ (layout);
  }

  /**
   * @param {import("./Geometry.js").GeometryLayout} layout Layout.
   * @return {number} Stride.
   */
  function getStrideForLayout(layout) {
    let stride;
    if (layout == 'XY') {
      stride = 2;
    } else if (layout == 'XYZ' || layout == 'XYM') {
      stride = 3;
    } else if (layout == 'XYZM') {
      stride = 4;
    }
    return /** @type {number} */ (stride);
  }

  /**
   * @param {SimpleGeometry} simpleGeometry Simple geometry.
   * @param {import("../transform.js").Transform} transform Transform.
   * @param {Array<number>} [dest] Destination.
   * @return {Array<number>} Transformed flat coordinates.
   */
  function transformGeom2D(simpleGeometry, transform, dest) {
    const flatCoordinates = simpleGeometry.getFlatCoordinates();
    if (!flatCoordinates) {
      return null;
    }
    const stride = simpleGeometry.getStride();
    return transform2D(
      flatCoordinates,
      0,
      flatCoordinates.length,
      stride,
      transform,
      dest,
    );
  }

  /**
   * @module ol/geom/flat/area
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @return {number} Area.
   */
  function linearRing(flatCoordinates, offset, end, stride) {
    let twiceArea = 0;
    const x0 = flatCoordinates[end - stride];
    const y0 = flatCoordinates[end - stride + 1];
    let dx1 = 0;
    let dy1 = 0;
    for (; offset < end; offset += stride) {
      const dx2 = flatCoordinates[offset] - x0;
      const dy2 = flatCoordinates[offset + 1] - y0;
      twiceArea += dy1 * dx2 - dx1 * dy2;
      dx1 = dx2;
      dy1 = dy2;
    }
    return twiceArea / 2;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @return {number} Area.
   */
  function linearRings(flatCoordinates, offset, ends, stride) {
    let area = 0;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      area += linearRing(flatCoordinates, offset, end, stride);
      offset = end;
    }
    return area;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @return {number} Area.
   */
  function linearRingss$1(flatCoordinates, offset, endss, stride) {
    let area = 0;
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      area += linearRings(flatCoordinates, offset, ends, stride);
      offset = ends[ends.length - 1];
    }
    return area;
  }

  /**
   * @module ol/geom/flat/closest
   */

  /**
   * Returns the point on the 2D line segment flatCoordinates[offset1] to
   * flatCoordinates[offset2] that is closest to the point (x, y).  Extra
   * dimensions are linearly interpolated.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset1 Offset 1.
   * @param {number} offset2 Offset 2.
   * @param {number} stride Stride.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {Array<number>} closestPoint Closest point.
   */
  function assignClosest(
    flatCoordinates,
    offset1,
    offset2,
    stride,
    x,
    y,
    closestPoint,
  ) {
    const x1 = flatCoordinates[offset1];
    const y1 = flatCoordinates[offset1 + 1];
    const dx = flatCoordinates[offset2] - x1;
    const dy = flatCoordinates[offset2 + 1] - y1;
    let offset;
    if (dx === 0 && dy === 0) {
      offset = offset1;
    } else {
      const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);
      if (t > 1) {
        offset = offset2;
      } else if (t > 0) {
        for (let i = 0; i < stride; ++i) {
          closestPoint[i] = lerp$1(
            flatCoordinates[offset1 + i],
            flatCoordinates[offset2 + i],
            t,
          );
        }
        closestPoint.length = stride;
        return;
      } else {
        offset = offset1;
      }
    }
    for (let i = 0; i < stride; ++i) {
      closestPoint[i] = flatCoordinates[offset + i];
    }
    closestPoint.length = stride;
  }

  /**
   * Return the squared of the largest distance between any pair of consecutive
   * coordinates.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} max Max squared delta.
   * @return {number} Max squared delta.
   */
  function maxSquaredDelta(flatCoordinates, offset, end, stride, max) {
    let x1 = flatCoordinates[offset];
    let y1 = flatCoordinates[offset + 1];
    for (offset += stride; offset < end; offset += stride) {
      const x2 = flatCoordinates[offset];
      const y2 = flatCoordinates[offset + 1];
      const squaredDelta = squaredDistance$1(x1, y1, x2, y2);
      if (squaredDelta > max) {
        max = squaredDelta;
      }
      x1 = x2;
      y1 = y2;
    }
    return max;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} max Max squared delta.
   * @return {number} Max squared delta.
   */
  function arrayMaxSquaredDelta(
    flatCoordinates,
    offset,
    ends,
    stride,
    max,
  ) {
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      max = maxSquaredDelta(flatCoordinates, offset, end, stride, max);
      offset = end;
    }
    return max;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {number} max Max squared delta.
   * @return {number} Max squared delta.
   */
  function multiArrayMaxSquaredDelta(
    flatCoordinates,
    offset,
    endss,
    stride,
    max,
  ) {
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max);
      offset = ends[ends.length - 1];
    }
    return max;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} maxDelta Max delta.
   * @param {boolean} isRing Is ring.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {Array<number>} closestPoint Closest point.
   * @param {number} minSquaredDistance Minimum squared distance.
   * @param {Array<number>} [tmpPoint] Temporary point object.
   * @return {number} Minimum squared distance.
   */
  function assignClosestPoint(
    flatCoordinates,
    offset,
    end,
    stride,
    maxDelta,
    isRing,
    x,
    y,
    closestPoint,
    minSquaredDistance,
    tmpPoint,
  ) {
    if (offset == end) {
      return minSquaredDistance;
    }
    let i, squaredDistance;
    if (maxDelta === 0) {
      // All points are identical, so just test the first point.
      squaredDistance = squaredDistance$1(
        x,
        y,
        flatCoordinates[offset],
        flatCoordinates[offset + 1],
      );
      if (squaredDistance < minSquaredDistance) {
        for (i = 0; i < stride; ++i) {
          closestPoint[i] = flatCoordinates[offset + i];
        }
        closestPoint.length = stride;
        return squaredDistance;
      }
      return minSquaredDistance;
    }
    tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];
    let index = offset + stride;
    while (index < end) {
      assignClosest(
        flatCoordinates,
        index - stride,
        index,
        stride,
        x,
        y,
        tmpPoint,
      );
      squaredDistance = squaredDistance$1(x, y, tmpPoint[0], tmpPoint[1]);
      if (squaredDistance < minSquaredDistance) {
        minSquaredDistance = squaredDistance;
        for (i = 0; i < stride; ++i) {
          closestPoint[i] = tmpPoint[i];
        }
        closestPoint.length = stride;
        index += stride;
      } else {
        // Skip ahead multiple points, because we know that all the skipped
        // points cannot be any closer than the closest point we have found so
        // far.  We know this because we know how close the current point is, how
        // close the closest point we have found so far is, and the maximum
        // distance between consecutive points.  For example, if we're currently
        // at distance 10, the best we've found so far is 3, and that the maximum
        // distance between consecutive points is 2, then we'll need to skip at
        // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of
        // finding a closer point.  We use Math.max(..., 1) to ensure that we
        // always advance at least one point, to avoid an infinite loop.
        index +=
          stride *
          Math.max(
            ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) /
              maxDelta) |
              0,
            1,
          );
      }
    }
    if (isRing) {
      // Check the closing segment.
      assignClosest(
        flatCoordinates,
        end - stride,
        offset,
        stride,
        x,
        y,
        tmpPoint,
      );
      squaredDistance = squaredDistance$1(x, y, tmpPoint[0], tmpPoint[1]);
      if (squaredDistance < minSquaredDistance) {
        minSquaredDistance = squaredDistance;
        for (i = 0; i < stride; ++i) {
          closestPoint[i] = tmpPoint[i];
        }
        closestPoint.length = stride;
      }
    }
    return minSquaredDistance;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} maxDelta Max delta.
   * @param {boolean} isRing Is ring.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {Array<number>} closestPoint Closest point.
   * @param {number} minSquaredDistance Minimum squared distance.
   * @param {Array<number>} [tmpPoint] Temporary point object.
   * @return {number} Minimum squared distance.
   */
  function assignClosestArrayPoint(
    flatCoordinates,
    offset,
    ends,
    stride,
    maxDelta,
    isRing,
    x,
    y,
    closestPoint,
    minSquaredDistance,
    tmpPoint,
  ) {
    tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      minSquaredDistance = assignClosestPoint(
        flatCoordinates,
        offset,
        end,
        stride,
        maxDelta,
        isRing,
        x,
        y,
        closestPoint,
        minSquaredDistance,
        tmpPoint,
      );
      offset = end;
    }
    return minSquaredDistance;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {number} maxDelta Max delta.
   * @param {boolean} isRing Is ring.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {Array<number>} closestPoint Closest point.
   * @param {number} minSquaredDistance Minimum squared distance.
   * @param {Array<number>} [tmpPoint] Temporary point object.
   * @return {number} Minimum squared distance.
   */
  function assignClosestMultiArrayPoint(
    flatCoordinates,
    offset,
    endss,
    stride,
    maxDelta,
    isRing,
    x,
    y,
    closestPoint,
    minSquaredDistance,
    tmpPoint,
  ) {
    tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      minSquaredDistance = assignClosestArrayPoint(
        flatCoordinates,
        offset,
        ends,
        stride,
        maxDelta,
        isRing,
        x,
        y,
        closestPoint,
        minSquaredDistance,
        tmpPoint,
      );
      offset = ends[ends.length - 1];
    }
    return minSquaredDistance;
  }

  /**
   * @module ol/geom/flat/deflate
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
   * @param {number} stride Stride.
   * @return {number} offset Offset.
   */
  function deflateCoordinate(flatCoordinates, offset, coordinate, stride) {
    for (let i = 0, ii = coordinate.length; i < ii; ++i) {
      flatCoordinates[offset++] = coordinate[i];
    }
    return offset;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<import("../../coordinate.js").Coordinate>} coordinates Coordinates.
   * @param {number} stride Stride.
   * @return {number} offset Offset.
   */
  function deflateCoordinates(
    flatCoordinates,
    offset,
    coordinates,
    stride,
  ) {
    for (let i = 0, ii = coordinates.length; i < ii; ++i) {
      const coordinate = coordinates[i];
      for (let j = 0; j < stride; ++j) {
        flatCoordinates[offset++] = coordinate[j];
      }
    }
    return offset;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<import("../../coordinate.js").Coordinate>>} coordinatess Coordinatess.
   * @param {number} stride Stride.
   * @param {Array<number>} [ends] Ends.
   * @return {Array<number>} Ends.
   */
  function deflateCoordinatesArray(
    flatCoordinates,
    offset,
    coordinatess,
    stride,
    ends,
  ) {
    ends = ends ? ends : [];
    let i = 0;
    for (let j = 0, jj = coordinatess.length; j < jj; ++j) {
      const end = deflateCoordinates(
        flatCoordinates,
        offset,
        coordinatess[j],
        stride,
      );
      ends[i++] = end;
      offset = end;
    }
    ends.length = i;
    return ends;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<Array<import("../../coordinate.js").Coordinate>>>} coordinatesss Coordinatesss.
   * @param {number} stride Stride.
   * @param {Array<Array<number>>} [endss] Endss.
   * @return {Array<Array<number>>} Endss.
   */
  function deflateMultiCoordinatesArray(
    flatCoordinates,
    offset,
    coordinatesss,
    stride,
    endss,
  ) {
    endss = endss ? endss : [];
    let i = 0;
    for (let j = 0, jj = coordinatesss.length; j < jj; ++j) {
      const ends = deflateCoordinatesArray(
        flatCoordinates,
        offset,
        coordinatesss[j],
        stride,
        endss[i],
      );
      if (ends.length === 0) {
        ends[0] = offset;
      }
      endss[i++] = ends;
      offset = ends[ends.length - 1];
    }
    endss.length = i;
    return endss;
  }

  /**
   * @module ol/geom/flat/inflate
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {Array<import("../../coordinate.js").Coordinate>} [coordinates] Coordinates.
   * @return {Array<import("../../coordinate.js").Coordinate>} Coordinates.
   */
  function inflateCoordinates(
    flatCoordinates,
    offset,
    end,
    stride,
    coordinates,
  ) {
    coordinates = coordinates !== undefined ? coordinates : [];
    let i = 0;
    for (let j = offset; j < end; j += stride) {
      coordinates[i++] = flatCoordinates.slice(j, j + stride);
    }
    coordinates.length = i;
    return coordinates;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {Array<Array<import("../../coordinate.js").Coordinate>>} [coordinatess] Coordinatess.
   * @return {Array<Array<import("../../coordinate.js").Coordinate>>} Coordinatess.
   */
  function inflateCoordinatesArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    coordinatess,
  ) {
    coordinatess = coordinatess !== undefined ? coordinatess : [];
    let i = 0;
    for (let j = 0, jj = ends.length; j < jj; ++j) {
      const end = ends[j];
      coordinatess[i++] = inflateCoordinates(
        flatCoordinates,
        offset,
        end,
        stride,
        coordinatess[i],
      );
      offset = end;
    }
    coordinatess.length = i;
    return coordinatess;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {Array<Array<Array<import("../../coordinate.js").Coordinate>>>} [coordinatesss]
   *     Coordinatesss.
   * @return {Array<Array<Array<import("../../coordinate.js").Coordinate>>>} Coordinatesss.
   */
  function inflateMultiCoordinatesArray(
    flatCoordinates,
    offset,
    endss,
    stride,
    coordinatesss,
  ) {
    coordinatesss = coordinatesss !== undefined ? coordinatesss : [];
    let i = 0;
    for (let j = 0, jj = endss.length; j < jj; ++j) {
      const ends = endss[j];
      coordinatesss[i++] =
        ends.length === 1 && ends[0] === offset
          ? []
          : inflateCoordinatesArray(
              flatCoordinates,
              offset,
              ends,
              stride,
              coordinatesss[i],
            );
      offset = ends[ends.length - 1];
    }
    coordinatesss.length = i;
    return coordinatesss;
  }

  /**
   * @module ol/geom/flat/simplify
   */
  // Based on simplify-js https://github.com/mourner/simplify-js
  // Copyright (c) 2012, Vladimir Agafonkin
  // All rights reserved.
  //
  // Redistribution and use in source and binary forms, with or without
  // modification, are permitted provided that the following conditions are met:
  //
  //    1. Redistributions of source code must retain the above copyright notice,
  //       this list of conditions and the following disclaimer.
  //
  //    2. Redistributions in binary form must reproduce the above copyright
  //       notice, this list of conditions and the following disclaimer in the
  //       documentation and/or other materials provided with the distribution.
  //
  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  // POSSIBILITY OF SUCH DAMAGE.


  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} squaredTolerance Squared tolerance.
   * @param {Array<number>} simplifiedFlatCoordinates Simplified flat
   *     coordinates.
   * @param {number} simplifiedOffset Simplified offset.
   * @return {number} Simplified offset.
   */
  function douglasPeucker(
    flatCoordinates,
    offset,
    end,
    stride,
    squaredTolerance,
    simplifiedFlatCoordinates,
    simplifiedOffset,
  ) {
    const n = (end - offset) / stride;
    if (n < 3) {
      for (; offset < end; offset += stride) {
        simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];
        simplifiedFlatCoordinates[simplifiedOffset++] =
          flatCoordinates[offset + 1];
      }
      return simplifiedOffset;
    }
    /** @type {Array<number>} */
    const markers = new Array(n);
    markers[0] = 1;
    markers[n - 1] = 1;
    /** @type {Array<number>} */
    const stack = [offset, end - stride];
    let index = 0;
    while (stack.length > 0) {
      const last = stack.pop();
      const first = stack.pop();
      let maxSquaredDistance = 0;
      const x1 = flatCoordinates[first];
      const y1 = flatCoordinates[first + 1];
      const x2 = flatCoordinates[last];
      const y2 = flatCoordinates[last + 1];
      for (let i = first + stride; i < last; i += stride) {
        const x = flatCoordinates[i];
        const y = flatCoordinates[i + 1];
        const squaredDistance = squaredSegmentDistance(x, y, x1, y1, x2, y2);
        if (squaredDistance > maxSquaredDistance) {
          index = i;
          maxSquaredDistance = squaredDistance;
        }
      }
      if (maxSquaredDistance > squaredTolerance) {
        markers[(index - offset) / stride] = 1;
        if (first + stride < index) {
          stack.push(first, index);
        }
        if (index + stride < last) {
          stack.push(index, last);
        }
      }
    }
    for (let i = 0; i < n; ++i) {
      if (markers[i]) {
        simplifiedFlatCoordinates[simplifiedOffset++] =
          flatCoordinates[offset + i * stride];
        simplifiedFlatCoordinates[simplifiedOffset++] =
          flatCoordinates[offset + i * stride + 1];
      }
    }
    return simplifiedOffset;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} squaredTolerance Squared tolerance.
   * @param {Array<number>} simplifiedFlatCoordinates Simplified flat
   *     coordinates.
   * @param {number} simplifiedOffset Simplified offset.
   * @param {Array<number>} simplifiedEnds Simplified ends.
   * @return {number} Simplified offset.
   */
  function douglasPeuckerArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    squaredTolerance,
    simplifiedFlatCoordinates,
    simplifiedOffset,
    simplifiedEnds,
  ) {
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      simplifiedOffset = douglasPeucker(
        flatCoordinates,
        offset,
        end,
        stride,
        squaredTolerance,
        simplifiedFlatCoordinates,
        simplifiedOffset,
      );
      simplifiedEnds.push(simplifiedOffset);
      offset = end;
    }
    return simplifiedOffset;
  }

  /**
   * @param {number} value Value.
   * @param {number} tolerance Tolerance.
   * @return {number} Rounded value.
   */
  function snap(value, tolerance) {
    return tolerance * Math.round(value / tolerance);
  }

  /**
   * Simplifies a line string using an algorithm designed by Tim Schaub.
   * Coordinates are snapped to the nearest value in a virtual grid and
   * consecutive duplicate coordinates are discarded.  This effectively preserves
   * topology as the simplification of any subsection of a line string is
   * independent of the rest of the line string.  This means that, for examples,
   * the common edge between two polygons will be simplified to the same line
   * string independently in both polygons.  This implementation uses a single
   * pass over the coordinates and eliminates intermediate collinear points.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} tolerance Tolerance.
   * @param {Array<number>} simplifiedFlatCoordinates Simplified flat
   *     coordinates.
   * @param {number} simplifiedOffset Simplified offset.
   * @return {number} Simplified offset.
   */
  function quantize(
    flatCoordinates,
    offset,
    end,
    stride,
    tolerance,
    simplifiedFlatCoordinates,
    simplifiedOffset,
  ) {
    // do nothing if the line is empty
    if (offset == end) {
      return simplifiedOffset;
    }
    // snap the first coordinate (P1)
    let x1 = snap(flatCoordinates[offset], tolerance);
    let y1 = snap(flatCoordinates[offset + 1], tolerance);
    offset += stride;
    // add the first coordinate to the output
    simplifiedFlatCoordinates[simplifiedOffset++] = x1;
    simplifiedFlatCoordinates[simplifiedOffset++] = y1;
    // find the next coordinate that does not snap to the same value as the first
    // coordinate (P2)
    let x2, y2;
    do {
      x2 = snap(flatCoordinates[offset], tolerance);
      y2 = snap(flatCoordinates[offset + 1], tolerance);
      offset += stride;
      if (offset == end) {
        // all coordinates snap to the same value, the line collapses to a point
        // push the last snapped value anyway to ensure that the output contains
        // at least two points
        // FIXME should we really return at least two points anyway?
        simplifiedFlatCoordinates[simplifiedOffset++] = x2;
        simplifiedFlatCoordinates[simplifiedOffset++] = y2;
        return simplifiedOffset;
      }
    } while (x2 == x1 && y2 == y1);
    while (offset < end) {
      // snap the next coordinate (P3)
      const x3 = snap(flatCoordinates[offset], tolerance);
      const y3 = snap(flatCoordinates[offset + 1], tolerance);
      offset += stride;
      // skip P3 if it is equal to P2
      if (x3 == x2 && y3 == y2) {
        continue;
      }
      // calculate the delta between P1 and P2
      const dx1 = x2 - x1;
      const dy1 = y2 - y1;
      // calculate the delta between P3 and P1
      const dx2 = x3 - x1;
      const dy2 = y3 - y1;
      // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from
      // P1 in the same direction then P2 is on the straight line between P1 and
      // P3
      if (
        dx1 * dy2 == dy1 * dx2 &&
        ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) &&
        ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1))
      ) {
        // discard P2 and set P2 = P3
        x2 = x3;
        y2 = y3;
        continue;
      }
      // either P1, P2, and P3 are not colinear, or they are colinear but P3 is
      // between P3 and P1 or on the opposite half of the line to P2.  add P2,
      // and continue with P1 = P2 and P2 = P3
      simplifiedFlatCoordinates[simplifiedOffset++] = x2;
      simplifiedFlatCoordinates[simplifiedOffset++] = y2;
      x1 = x2;
      y1 = y2;
      x2 = x3;
      y2 = y3;
    }
    // add the last point (P2)
    simplifiedFlatCoordinates[simplifiedOffset++] = x2;
    simplifiedFlatCoordinates[simplifiedOffset++] = y2;
    return simplifiedOffset;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} tolerance Tolerance.
   * @param {Array<number>} simplifiedFlatCoordinates Simplified flat
   *     coordinates.
   * @param {number} simplifiedOffset Simplified offset.
   * @param {Array<number>} simplifiedEnds Simplified ends.
   * @return {number} Simplified offset.
   */
  function quantizeArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    tolerance,
    simplifiedFlatCoordinates,
    simplifiedOffset,
    simplifiedEnds,
  ) {
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      simplifiedOffset = quantize(
        flatCoordinates,
        offset,
        end,
        stride,
        tolerance,
        simplifiedFlatCoordinates,
        simplifiedOffset,
      );
      simplifiedEnds.push(simplifiedOffset);
      offset = end;
    }
    return simplifiedOffset;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {number} tolerance Tolerance.
   * @param {Array<number>} simplifiedFlatCoordinates Simplified flat
   *     coordinates.
   * @param {number} simplifiedOffset Simplified offset.
   * @param {Array<Array<number>>} simplifiedEndss Simplified endss.
   * @return {number} Simplified offset.
   */
  function quantizeMultiArray(
    flatCoordinates,
    offset,
    endss,
    stride,
    tolerance,
    simplifiedFlatCoordinates,
    simplifiedOffset,
    simplifiedEndss,
  ) {
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      /** @type {Array<number>} */
      const simplifiedEnds = [];
      simplifiedOffset = quantizeArray(
        flatCoordinates,
        offset,
        ends,
        stride,
        tolerance,
        simplifiedFlatCoordinates,
        simplifiedOffset,
        simplifiedEnds,
      );
      simplifiedEndss.push(simplifiedEnds);
      offset = ends[ends.length - 1];
    }
    return simplifiedOffset;
  }

  /**
   * @module ol/geom/LinearRing
   */

  /**
   * @classdesc
   * Linear ring geometry. Only used as part of polygon; cannot be rendered
   * on its own.
   *
   * @api
   */
  class LinearRing extends SimpleGeometry {
    /**
     * @param {Array<import("../coordinate.js").Coordinate>|Array<number>} coordinates Coordinates.
     *     For internal use, flat coordinates in combination with `layout` are also accepted.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    constructor(coordinates, layout) {
      super();

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDeltaRevision_ = -1;

      if (layout !== undefined && !Array.isArray(coordinates[0])) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
      } else {
        this.setCoordinates(
          /** @type {Array<import("../coordinate.js").Coordinate>} */ (
            coordinates
          ),
          layout,
        );
      }
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!LinearRing} Clone.
     * @api
     * @override
     */
    clone() {
      return new LinearRing(this.flatCoordinates.slice(), this.layout);
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      if (this.maxDeltaRevision_ != this.getRevision()) {
        this.maxDelta_ = Math.sqrt(
          maxSquaredDelta(
            this.flatCoordinates,
            0,
            this.flatCoordinates.length,
            this.stride,
            0,
          ),
        );
        this.maxDeltaRevision_ = this.getRevision();
      }
      return assignClosestPoint(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        this.maxDelta_,
        true,
        x,
        y,
        closestPoint,
        minSquaredDistance,
      );
    }

    /**
     * Return the area of the linear ring on projected plane.
     * @return {number} Area (on projected plane).
     * @api
     */
    getArea() {
      return linearRing(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
      );
    }

    /**
     * Return the coordinates of the linear ring.
     * @return {Array<import("../coordinate.js").Coordinate>} Coordinates.
     * @api
     * @override
     */
    getCoordinates() {
      return inflateCoordinates(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
      );
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {LinearRing} Simplified LinearRing.
     * @protected
     * @override
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      /** @type {Array<number>} */
      const simplifiedFlatCoordinates = [];
      simplifiedFlatCoordinates.length = douglasPeucker(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        squaredTolerance,
        simplifiedFlatCoordinates,
        0,
      );
      return new LinearRing(simplifiedFlatCoordinates, 'XY');
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'LinearRing';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return false;
    }

    /**
     * Set the coordinates of the linear ring.
     * @param {!Array<import("../coordinate.js").Coordinate>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 1);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      this.flatCoordinates.length = deflateCoordinates(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
      );
      this.changed();
    }
  }

  /**
   * @module ol/geom/Point
   */

  /**
   * @classdesc
   * Point geometry.
   *
   * @api
   */
  class Point extends SimpleGeometry {
    /**
     * @param {import("../coordinate.js").Coordinate} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    constructor(coordinates, layout) {
      super();
      this.setCoordinates(coordinates, layout);
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!Point} Clone.
     * @api
     * @override
     */
    clone() {
      const point = new Point(this.flatCoordinates.slice(), this.layout);
      point.applyProperties(this);
      return point;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      const flatCoordinates = this.flatCoordinates;
      const squaredDistance = squaredDistance$1(
        x,
        y,
        flatCoordinates[0],
        flatCoordinates[1],
      );
      if (squaredDistance < minSquaredDistance) {
        const stride = this.stride;
        for (let i = 0; i < stride; ++i) {
          closestPoint[i] = flatCoordinates[i];
        }
        closestPoint.length = stride;
        return squaredDistance;
      }
      return minSquaredDistance;
    }

    /**
     * Return the coordinate of the point.
     * @return {import("../coordinate.js").Coordinate} Coordinates.
     * @api
     * @override
     */
    getCoordinates() {
      return this.flatCoordinates.slice();
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @protected
     * @return {import("../extent.js").Extent} extent Extent.
     * @override
     */
    computeExtent(extent) {
      return createOrUpdateFromCoordinate(this.flatCoordinates, extent);
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'Point';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]);
    }

    /**
     * @param {!Array<*>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 0);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      this.flatCoordinates.length = deflateCoordinate(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
      );
      this.changed();
    }
  }

  /**
   * @module ol/geom/flat/contains
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @return {boolean} Contains extent.
   */
  function linearRingContainsExtent(
    flatCoordinates,
    offset,
    end,
    stride,
    extent,
  ) {
    const outside = forEachCorner(
      extent,
      /**
       * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
       * @return {boolean} Contains (x, y).
       */
      function (coordinate) {
        return !linearRingContainsXY(
          flatCoordinates,
          offset,
          end,
          stride,
          coordinate[0],
          coordinate[1],
        );
      },
    );
    return !outside;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} x X.
   * @param {number} y Y.
   * @return {boolean} Contains (x, y).
   */
  function linearRingContainsXY(
    flatCoordinates,
    offset,
    end,
    stride,
    x,
    y,
  ) {
    // https://web.archive.org/web/20210504233957/http://geomalgorithms.com/a03-_inclusion.html
    // Copyright 2000 softSurfer, 2012 Dan Sunday
    // This code may be freely used and modified for any purpose
    // providing that this copyright notice is included with it.
    // SoftSurfer makes no warranty for this code, and cannot be held
    // liable for any real or imagined damage resulting from its use.
    // Users of this code must verify correctness for their application.
    let wn = 0;
    let x1 = flatCoordinates[end - stride];
    let y1 = flatCoordinates[end - stride + 1];
    for (; offset < end; offset += stride) {
      const x2 = flatCoordinates[offset];
      const y2 = flatCoordinates[offset + 1];
      if (y1 <= y) {
        if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) {
          wn++;
        }
      } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) {
        wn--;
      }
      x1 = x2;
      y1 = y2;
    }
    return wn !== 0;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} x X.
   * @param {number} y Y.
   * @return {boolean} Contains (x, y).
   */
  function linearRingsContainsXY(
    flatCoordinates,
    offset,
    ends,
    stride,
    x,
    y,
  ) {
    if (ends.length === 0) {
      return false;
    }
    if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) {
      return false;
    }
    for (let i = 1, ii = ends.length; i < ii; ++i) {
      if (
        linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y)
      ) {
        return false;
      }
    }
    return true;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {number} x X.
   * @param {number} y Y.
   * @return {boolean} Contains (x, y).
   */
  function linearRingssContainsXY(
    flatCoordinates,
    offset,
    endss,
    stride,
    x,
    y,
  ) {
    if (endss.length === 0) {
      return false;
    }
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {
        return true;
      }
      offset = ends[ends.length - 1];
    }
    return false;
  }

  /**
   * @module ol/geom/flat/interiorpoint
   */

  /**
   * Calculates a point that is likely to lie in the interior of the linear rings.
   * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {Array<number>} flatCenters Flat centers.
   * @param {number} flatCentersOffset Flat center offset.
   * @param {Array<number>} [dest] Destination.
   * @return {Array<number>} Destination point as XYM coordinate, where M is the
   * length of the horizontal intersection that the point belongs to.
   */
  function getInteriorPointOfArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    flatCenters,
    flatCentersOffset,
    dest,
  ) {
    let i, ii, x, x1, x2, y1, y2;
    const y = flatCenters[flatCentersOffset + 1];
    /** @type {Array<number>} */
    const intersections = [];
    // Calculate intersections with the horizontal line
    for (let r = 0, rr = ends.length; r < rr; ++r) {
      const end = ends[r];
      x1 = flatCoordinates[end - stride];
      y1 = flatCoordinates[end - stride + 1];
      for (i = offset; i < end; i += stride) {
        x2 = flatCoordinates[i];
        y2 = flatCoordinates[i + 1];
        if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) {
          x = ((y - y1) / (y2 - y1)) * (x2 - x1) + x1;
          intersections.push(x);
        }
        x1 = x2;
        y1 = y2;
      }
    }
    // Find the longest segment of the horizontal line that has its center point
    // inside the linear ring.
    let pointX = NaN;
    let maxSegmentLength = -Infinity;
    intersections.sort(ascending);
    x1 = intersections[0];
    for (i = 1, ii = intersections.length; i < ii; ++i) {
      x2 = intersections[i];
      const segmentLength = Math.abs(x2 - x1);
      if (segmentLength > maxSegmentLength) {
        x = (x1 + x2) / 2;
        if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {
          pointX = x;
          maxSegmentLength = segmentLength;
        }
      }
      x1 = x2;
    }
    if (isNaN(pointX)) {
      // There is no horizontal line that has its center point inside the linear
      // ring.  Use the center of the the linear ring's extent.
      pointX = flatCenters[flatCentersOffset];
    }
    if (dest) {
      dest.push(pointX, y, maxSegmentLength);
      return dest;
    }
    return [pointX, y, maxSegmentLength];
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {Array<number>} flatCenters Flat centers.
   * @return {Array<number>} Interior points as XYM coordinates, where M is the
   * length of the horizontal intersection that the point belongs to.
   */
  function getInteriorPointsOfMultiArray(
    flatCoordinates,
    offset,
    endss,
    stride,
    flatCenters,
  ) {
    /** @type {Array<number>} */
    let interiorPoints = [];
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      interiorPoints = getInteriorPointOfArray(
        flatCoordinates,
        offset,
        ends,
        stride,
        flatCenters,
        2 * i,
        interiorPoints,
      );
      offset = ends[ends.length - 1];
    }
    return interiorPoints;
  }

  /**
   * @module ol/geom/flat/segments
   */

  /**
   * This function calls `callback` for each segment of the flat coordinates
   * array. If the callback returns a truthy value the function returns that
   * value immediately. Otherwise the function returns `false`.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {function(import("../../coordinate.js").Coordinate, import("../../coordinate.js").Coordinate): T} callback Function
   *     called for each segment.
   * @return {T|boolean} Value.
   * @template T
   */
  function forEach(flatCoordinates, offset, end, stride, callback) {
    let ret;
    offset += stride;
    for (; offset < end; offset += stride) {
      ret = callback(
        flatCoordinates.slice(offset - stride, offset),
        flatCoordinates.slice(offset, offset + stride),
      );
      if (ret) {
        return ret;
      }
    }
    return false;
  }

  /**
   * Calculate the intersection point of two line segments.
   * Reference: https://stackoverflow.com/a/72474223/2389327
   * @param {Array<import("../../coordinate.js").Coordinate>} segment1 The first line segment as an array of two points.
   * @param {Array<import("../../coordinate.js").Coordinate>} segment2 The second line segment as an array of two points.
   * @return {import("../../coordinate.js").Coordinate|undefined} The intersection point or `undefined` if no intersection.
   */
  function getIntersectionPoint(segment1, segment2) {
    const [a, b] = segment1;
    const [c, d] = segment2;
    const t =
      ((a[0] - c[0]) * (c[1] - d[1]) - (a[1] - c[1]) * (c[0] - d[0])) /
      ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]));
    const u =
      ((a[0] - c[0]) * (a[1] - b[1]) - (a[1] - c[1]) * (a[0] - b[0])) /
      ((a[0] - b[0]) * (c[1] - d[1]) - (a[1] - b[1]) * (c[0] - d[0]));

    // Check if lines actually intersect
    if (0 <= t && t <= 1 && 0 <= u && u <= 1) {
      return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
    }
    return undefined;
  }

  /**
   * @module ol/geom/flat/intersectsextent
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @param {import('../../extent.js').Extent} [coordinatesExtent] Coordinates extent
   * @return {boolean} True if the geometry and the extent intersect.
   */
  function intersectsLineString(
    flatCoordinates,
    offset,
    end,
    stride,
    extent,
    coordinatesExtent,
  ) {
    coordinatesExtent =
      coordinatesExtent ??
      extendFlatCoordinates(createEmpty(), flatCoordinates, offset, end, stride);
    if (!intersects$2(extent, coordinatesExtent)) {
      return false;
    }
    if (
      (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) ||
      (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3])
    ) {
      return true;
    }
    return forEach(
      flatCoordinates,
      offset,
      end,
      stride,
      /**
       * @param {import("../../coordinate.js").Coordinate} point1 Start point.
       * @param {import("../../coordinate.js").Coordinate} point2 End point.
       * @return {boolean} `true` if the segment and the extent intersect,
       *     `false` otherwise.
       */
      function (point1, point2) {
        return intersectsSegment(extent, point1, point2);
      },
    );
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @return {boolean} True if the geometry and the extent intersect.
   */
  function intersectsLineStringArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    extent,
  ) {
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      if (
        intersectsLineString(flatCoordinates, offset, ends[i], stride, extent)
      ) {
        return true;
      }
      offset = ends[i];
    }
    return false;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @return {boolean} True if the geometry and the extent intersect.
   */
  function intersectsLinearRing(
    flatCoordinates,
    offset,
    end,
    stride,
    extent,
  ) {
    if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) {
      return true;
    }
    if (
      linearRingContainsXY(
        flatCoordinates,
        offset,
        end,
        stride,
        extent[0],
        extent[1],
      )
    ) {
      return true;
    }
    if (
      linearRingContainsXY(
        flatCoordinates,
        offset,
        end,
        stride,
        extent[0],
        extent[3],
      )
    ) {
      return true;
    }
    if (
      linearRingContainsXY(
        flatCoordinates,
        offset,
        end,
        stride,
        extent[2],
        extent[1],
      )
    ) {
      return true;
    }
    if (
      linearRingContainsXY(
        flatCoordinates,
        offset,
        end,
        stride,
        extent[2],
        extent[3],
      )
    ) {
      return true;
    }
    return false;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @return {boolean} True if the geometry and the extent intersect.
   */
  function intersectsLinearRingArray(
    flatCoordinates,
    offset,
    ends,
    stride,
    extent,
  ) {
    if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) {
      return false;
    }
    if (ends.length === 1) {
      return true;
    }
    for (let i = 1, ii = ends.length; i < ii; ++i) {
      if (
        linearRingContainsExtent(
          flatCoordinates,
          ends[i - 1],
          ends[i],
          stride,
          extent,
        )
      ) {
        if (
          !intersectsLineString(
            flatCoordinates,
            ends[i - 1],
            ends[i],
            stride,
            extent,
          )
        ) {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @param {import("../../extent.js").Extent} extent Extent.
   * @return {boolean} True if the geometry and the extent intersect.
   */
  function intersectsLinearRingMultiArray(
    flatCoordinates,
    offset,
    endss,
    stride,
    extent,
  ) {
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      if (
        intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent)
      ) {
        return true;
      }
      offset = ends[ends.length - 1];
    }
    return false;
  }

  /**
   * @module ol/geom/flat/reverse
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   */
  function coordinates(flatCoordinates, offset, end, stride) {
    while (offset < end - stride) {
      for (let i = 0; i < stride; ++i) {
        const tmp = flatCoordinates[offset + i];
        flatCoordinates[offset + i] = flatCoordinates[end - stride + i];
        flatCoordinates[end - stride + i] = tmp;
      }
      offset += stride;
      end -= stride;
    }
  }

  /**
   * @module ol/geom/flat/orient
   */

  /**
   * Is the linear ring oriented clockwise in a coordinate system with a bottom-left
   * coordinate origin? For a coordinate system with a top-left coordinate origin,
   * the ring's orientation is clockwise when this function returns false.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @return {boolean|undefined} Is clockwise.
   */
  function linearRingIsClockwise(flatCoordinates, offset, end, stride) {
    // https://stackoverflow.com/q/1165647/clockwise-method#1165943
    // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrlinearring.cpp
    let edge = 0;
    let x1 = flatCoordinates[end - stride];
    let y1 = flatCoordinates[end - stride + 1];
    for (; offset < end; offset += stride) {
      const x2 = flatCoordinates[offset];
      const y2 = flatCoordinates[offset + 1];
      edge += (x2 - x1) * (y2 + y1);
      x1 = x2;
      y1 = y2;
    }
    return edge === 0 ? undefined : edge > 0;
  }

  /**
   * Determines if linear rings are oriented.  By default, left-hand orientation
   * is tested (first ring must be clockwise, remaining rings counter-clockwise).
   * To test for right-hand orientation, use the `right` argument.
   *
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Array of end indexes.
   * @param {number} stride Stride.
   * @param {boolean} [right] Test for right-hand orientation
   *     (counter-clockwise exterior ring and clockwise interior rings).
   * @return {boolean} Rings are correctly oriented.
   */
  function linearRingsAreOriented(
    flatCoordinates,
    offset,
    ends,
    stride,
    right,
  ) {
    right = right !== undefined ? right : false;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      const isClockwise = linearRingIsClockwise(
        flatCoordinates,
        offset,
        end,
        stride,
      );
      if (i === 0) {
        if ((right && isClockwise) || (!right && !isClockwise)) {
          return false;
        }
      } else {
        if ((right && !isClockwise) || (!right && isClockwise)) {
          return false;
        }
      }
      offset = end;
    }
    return true;
  }

  /**
   * Determines if linear rings are oriented.  By default, left-hand orientation
   * is tested (first ring must be clockwise, remaining rings counter-clockwise).
   * To test for right-hand orientation, use the `right` argument.
   *
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Array of array of end indexes.
   * @param {number} stride Stride.
   * @param {boolean} [right] Test for right-hand orientation
   *     (counter-clockwise exterior ring and clockwise interior rings).
   * @return {boolean} Rings are correctly oriented.
   */
  function linearRingssAreOriented(
    flatCoordinates,
    offset,
    endss,
    stride,
    right,
  ) {
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) {
        return false;
      }
      if (ends.length) {
        offset = ends[ends.length - 1];
      }
    }
    return true;
  }

  /**
   * Orient coordinates in a flat array of linear rings.  By default, rings
   * are oriented following the left-hand rule (clockwise for exterior and
   * counter-clockwise for interior rings).  To orient according to the
   * right-hand rule, use the `right` argument.
   *
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {boolean} [right] Follow the right-hand rule for orientation.
   * @return {number} End.
   */
  function orientLinearRings(
    flatCoordinates,
    offset,
    ends,
    stride,
    right,
  ) {
    right = right !== undefined ? right : false;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      const isClockwise = linearRingIsClockwise(
        flatCoordinates,
        offset,
        end,
        stride,
      );
      const reverse =
        i === 0
          ? (right && isClockwise) || (!right && !isClockwise)
          : (right && !isClockwise) || (!right && isClockwise);
      if (reverse) {
        coordinates(flatCoordinates, offset, end, stride);
      }
      offset = end;
    }
    return offset;
  }

  /**
   * Orient coordinates in a flat array of linear rings.  By default, rings
   * are oriented following the left-hand rule (clockwise for exterior and
   * counter-clockwise for interior rings).  To orient according to the
   * right-hand rule, use the `right` argument.
   *
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Array of array of end indexes.
   * @param {number} stride Stride.
   * @param {boolean} [right] Follow the right-hand rule for orientation.
   * @return {number} End.
   */
  function orientLinearRingsArray(
    flatCoordinates,
    offset,
    endss,
    stride,
    right,
  ) {
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      offset = orientLinearRings(
        flatCoordinates,
        offset,
        endss[i],
        stride,
        right,
      );
    }
    return offset;
  }

  /**
   * Return a two-dimensional endss
   * @param {Array<number>} flatCoordinates Flat coordinates
   * @param {Array<number>} ends Linear ring end indexes
   * @return {Array<Array<number>>} Two dimensional endss array that can
   * be used to construct a MultiPolygon
   */
  function inflateEnds(flatCoordinates, ends) {
    const endss = [];
    let offset = 0;
    let prevEndIndex = 0;
    let startOrientation;
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      // classifies an array of rings into polygons with outer rings and holes
      const orientation = linearRingIsClockwise(flatCoordinates, offset, end, 2);
      if (startOrientation === undefined) {
        startOrientation = orientation;
      }
      if (orientation === startOrientation) {
        endss.push(ends.slice(prevEndIndex, i + 1));
      } else {
        if (endss.length === 0) {
          continue;
        }
        endss[endss.length - 1].push(ends[prevEndIndex]);
      }
      prevEndIndex = i + 1;
      offset = end;
    }
    return endss;
  }

  /**
   * @module ol/geom/Polygon
   */

  /**
   * @classdesc
   * Polygon geometry.
   *
   * @api
   */
  class Polygon extends SimpleGeometry {
    /**
     * @param {!Array<Array<import("../coordinate.js").Coordinate>>|!Array<number>} coordinates
     *     Array of linear rings that define the polygon. The first linear ring of the
     *     array defines the outer-boundary or surface of the polygon. Each subsequent
     *     linear ring defines a hole in the surface of the polygon. A linear ring is
     *     an array of vertices' coordinates where the first coordinate and the last are
     *     equivalent. (For internal use, flat coordinates in combination with
     *     `layout` and `ends` are also accepted.)
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @param {Array<number>} [ends] Ends (for internal use with flat coordinates).
     */
    constructor(coordinates, layout, ends) {
      super();

      /**
       * @type {Array<number>}
       * @private
       */
      this.ends_ = [];

      /**
       * @private
       * @type {number}
       */
      this.flatInteriorPointRevision_ = -1;

      /**
       * @private
       * @type {import("../coordinate.js").Coordinate|null}
       */
      this.flatInteriorPoint_ = null;

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDeltaRevision_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.orientedRevision_ = -1;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.orientedFlatCoordinates_ = null;

      if (layout !== undefined && ends) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
        this.ends_ = ends;
      } else {
        this.setCoordinates(
          /** @type {Array<Array<import("../coordinate.js").Coordinate>>} */ (
            coordinates
          ),
          layout,
        );
      }
    }

    /**
     * Append the passed linear ring to this polygon.
     * @param {LinearRing} linearRing Linear ring.
     * @api
     */
    appendLinearRing(linearRing) {
      if (!this.flatCoordinates) {
        this.flatCoordinates = linearRing.getFlatCoordinates().slice();
      } else {
        extend$2(this.flatCoordinates, linearRing.getFlatCoordinates());
      }
      this.ends_.push(this.flatCoordinates.length);
      this.changed();
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!Polygon} Clone.
     * @api
     * @override
     */
    clone() {
      const polygon = new Polygon(
        this.flatCoordinates.slice(),
        this.layout,
        this.ends_.slice(),
      );
      polygon.applyProperties(this);
      return polygon;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      if (this.maxDeltaRevision_ != this.getRevision()) {
        this.maxDelta_ = Math.sqrt(
          arrayMaxSquaredDelta(
            this.flatCoordinates,
            0,
            this.ends_,
            this.stride,
            0,
          ),
        );
        this.maxDeltaRevision_ = this.getRevision();
      }
      return assignClosestArrayPoint(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        this.maxDelta_,
        true,
        x,
        y,
        closestPoint,
        minSquaredDistance,
      );
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @return {boolean} Contains (x, y).
     * @override
     */
    containsXY(x, y) {
      return linearRingsContainsXY(
        this.getOrientedFlatCoordinates(),
        0,
        this.ends_,
        this.stride,
        x,
        y,
      );
    }

    /**
     * Return the area of the polygon on projected plane.
     * @return {number} Area (on projected plane).
     * @api
     */
    getArea() {
      return linearRings(
        this.getOrientedFlatCoordinates(),
        0,
        this.ends_,
        this.stride,
      );
    }

    /**
     * Get the coordinate array for this geometry.  This array has the structure
     * of a GeoJSON coordinate array for polygons.
     *
     * @param {boolean} [right] Orient coordinates according to the right-hand
     *     rule (counter-clockwise for exterior and clockwise for interior rings).
     *     If `false`, coordinates will be oriented according to the left-hand rule
     *     (clockwise for exterior and counter-clockwise for interior rings).
     *     By default, coordinate orientation will depend on how the geometry was
     *     constructed.
     * @return {Array<Array<import("../coordinate.js").Coordinate>>} Coordinates.
     * @api
     * @override
     */
    getCoordinates(right) {
      let flatCoordinates;
      if (right !== undefined) {
        flatCoordinates = this.getOrientedFlatCoordinates().slice();
        orientLinearRings(flatCoordinates, 0, this.ends_, this.stride, right);
      } else {
        flatCoordinates = this.flatCoordinates;
      }

      return inflateCoordinatesArray(flatCoordinates, 0, this.ends_, this.stride);
    }

    /**
     * @return {Array<number>} Ends.
     */
    getEnds() {
      return this.ends_;
    }

    /**
     * @return {Array<number>} Interior point.
     */
    getFlatInteriorPoint() {
      if (this.flatInteriorPointRevision_ != this.getRevision()) {
        const flatCenter = getCenter(this.getExtent());
        this.flatInteriorPoint_ = getInteriorPointOfArray(
          this.getOrientedFlatCoordinates(),
          0,
          this.ends_,
          this.stride,
          flatCenter,
          0,
        );
        this.flatInteriorPointRevision_ = this.getRevision();
      }
      return /** @type {import("../coordinate.js").Coordinate} */ (
        this.flatInteriorPoint_
      );
    }

    /**
     * Return an interior point of the polygon.
     * @return {Point} Interior point as XYM coordinate, where M is the
     * length of the horizontal intersection that the point belongs to.
     * @api
     */
    getInteriorPoint() {
      return new Point(this.getFlatInteriorPoint(), 'XYM');
    }

    /**
     * Return the number of rings of the polygon,  this includes the exterior
     * ring and any interior rings.
     *
     * @return {number} Number of rings.
     * @api
     */
    getLinearRingCount() {
      return this.ends_.length;
    }

    /**
     * Return the Nth linear ring of the polygon geometry. Return `null` if the
     * given index is out of range.
     * The exterior linear ring is available at index `0` and the interior rings
     * at index `1` and beyond.
     *
     * @param {number} index Index.
     * @return {LinearRing|null} Linear ring.
     * @api
     */
    getLinearRing(index) {
      if (index < 0 || this.ends_.length <= index) {
        return null;
      }
      return new LinearRing(
        this.flatCoordinates.slice(
          index === 0 ? 0 : this.ends_[index - 1],
          this.ends_[index],
        ),
        this.layout,
      );
    }

    /**
     * Return the linear rings of the polygon.
     * @return {Array<LinearRing>} Linear rings.
     * @api
     */
    getLinearRings() {
      const layout = this.layout;
      const flatCoordinates = this.flatCoordinates;
      const ends = this.ends_;
      const linearRings = [];
      let offset = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        const linearRing = new LinearRing(
          flatCoordinates.slice(offset, end),
          layout,
        );
        linearRings.push(linearRing);
        offset = end;
      }
      return linearRings;
    }

    /**
     * @return {Array<number>} Oriented flat coordinates.
     */
    getOrientedFlatCoordinates() {
      if (this.orientedRevision_ != this.getRevision()) {
        const flatCoordinates = this.flatCoordinates;
        if (linearRingsAreOriented(flatCoordinates, 0, this.ends_, this.stride)) {
          this.orientedFlatCoordinates_ = flatCoordinates;
        } else {
          this.orientedFlatCoordinates_ = flatCoordinates.slice();
          this.orientedFlatCoordinates_.length = orientLinearRings(
            this.orientedFlatCoordinates_,
            0,
            this.ends_,
            this.stride,
          );
        }
        this.orientedRevision_ = this.getRevision();
      }
      return /** @type {Array<number>} */ (this.orientedFlatCoordinates_);
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {Polygon} Simplified Polygon.
     * @protected
     * @override
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      /** @type {Array<number>} */
      const simplifiedFlatCoordinates = [];
      /** @type {Array<number>} */
      const simplifiedEnds = [];
      simplifiedFlatCoordinates.length = quantizeArray(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        Math.sqrt(squaredTolerance),
        simplifiedFlatCoordinates,
        0,
        simplifiedEnds,
      );
      return new Polygon(simplifiedFlatCoordinates, 'XY', simplifiedEnds);
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'Polygon';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return intersectsLinearRingArray(
        this.getOrientedFlatCoordinates(),
        0,
        this.ends_,
        this.stride,
        extent,
      );
    }

    /**
     * Set the coordinates of the polygon.
     * @param {!Array<Array<import("../coordinate.js").Coordinate>>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 2);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      const ends = deflateCoordinatesArray(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
        this.ends_,
      );
      this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];
      this.changed();
    }
  }

  /**
   * Create an approximation of a circle on the surface of a sphere.
   * @param {import("../coordinate.js").Coordinate} center Center (`[lon, lat]` in degrees).
   * @param {number} radius The great-circle distance from the center to
   *     the polygon vertices in meters.
   * @param {number} [n] Optional number of vertices for the resulting
   *     polygon. Default is `32`.
   * @param {number} [sphereRadius] Optional radius for the sphere (defaults to
   *     the Earth's mean radius using the WGS84 ellipsoid).
   * @return {Polygon} The "circular" polygon.
   * @api
   */
  function circular(center, radius, n, sphereRadius) {
    n = n ? n : 32;
    /** @type {Array<number>} */
    const flatCoordinates = [];
    for (let i = 0; i < n; ++i) {
      extend$2(
        flatCoordinates,
        offset(center, radius, (2 * Math.PI * i) / n, sphereRadius),
      );
    }
    flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);
    return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);
  }

  /**
   * Create a polygon from an extent. The layout used is `XY`.
   * @param {import("../extent.js").Extent} extent The extent.
   * @return {Polygon} The polygon.
   * @api
   */
  function fromExtent(extent) {
    if (isEmpty(extent)) {
      throw new Error('Cannot create polygon from empty extent');
    }
    const minX = extent[0];
    const minY = extent[1];
    const maxX = extent[2];
    const maxY = extent[3];
    const flatCoordinates = [
      minX,
      minY,
      minX,
      maxY,
      maxX,
      maxY,
      maxX,
      minY,
      minX,
      minY,
    ];
    return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);
  }

  /**
   * Create a regular polygon from a circle.
   * @param {import("./Circle.js").default} circle Circle geometry.
   * @param {number} [sides] Number of sides of the polygon. Default is 32.
   * @param {number} [angle] Start angle for the first vertex of the polygon in
   *     counter-clockwise radians. 0 means East. Default is 0.
   * @return {Polygon} Polygon geometry.
   * @api
   */
  function fromCircle(circle, sides, angle) {
    sides = sides ? sides : 32;
    const stride = circle.getStride();
    const layout = circle.getLayout();
    const center = circle.getCenter();
    const arrayLength = stride * (sides + 1);
    const flatCoordinates = new Array(arrayLength);
    for (let i = 0; i < arrayLength; i += stride) {
      flatCoordinates[i] = 0;
      flatCoordinates[i + 1] = 0;
      for (let j = 2; j < stride; j++) {
        flatCoordinates[i + j] = center[j];
      }
    }
    const ends = [flatCoordinates.length];
    const polygon = new Polygon(flatCoordinates, layout, ends);
    makeRegular(polygon, center, circle.getRadius(), angle);
    return polygon;
  }

  /**
   * Modify the coordinates of a polygon to make it a regular polygon.
   * @param {Polygon} polygon Polygon geometry.
   * @param {import("../coordinate.js").Coordinate} center Center of the regular polygon.
   * @param {number} radius Radius of the regular polygon.
   * @param {number} [angle] Start angle for the first vertex of the polygon in
   *     counter-clockwise radians. 0 means East. Default is 0.
   */
  function makeRegular(polygon, center, radius, angle) {
    const flatCoordinates = polygon.getFlatCoordinates();
    const stride = polygon.getStride();
    const sides = flatCoordinates.length / stride - 1;
    const startAngle = angle ? angle : 0;
    for (let i = 0; i <= sides; ++i) {
      const offset = i * stride;
      const angle = startAngle + (modulo(i, sides) * 2 * Math.PI) / sides;
      flatCoordinates[offset] = center[0] + radius * Math.cos(angle);
      flatCoordinates[offset + 1] = center[1] + radius * Math.sin(angle);
    }
    polygon.changed();
  }

  var geom_Polygon = {
    __proto__: null,
    circular: circular,
    default: Polygon,
    fromCircle: fromCircle,
    fromExtent: fromExtent,
    makeRegular: makeRegular
  };

  /**
   * @module ol/Geolocation
   */

  /**
   * @enum {string}
   */
  const Property$4 = {
    ACCURACY: 'accuracy',
    ACCURACY_GEOMETRY: 'accuracyGeometry',
    ALTITUDE: 'altitude',
    ALTITUDE_ACCURACY: 'altitudeAccuracy',
    HEADING: 'heading',
    POSITION: 'position',
    PROJECTION: 'projection',
    SPEED: 'speed',
    TRACKING: 'tracking',
    TRACKING_OPTIONS: 'trackingOptions',
  };

  /**
   * @enum string
   */
  const GeolocationErrorType = {
    /**
     * Triggered when a `GeolocationPositionError` occurs.
     * @event module:ol/Geolocation.GeolocationError#error
     * @api
     */
    ERROR: 'error',
  };

  /**
   * @classdesc
   * Events emitted on [GeolocationPositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError).
   */
  class GeolocationError extends BaseEvent {
    /**
     * @param {GeolocationPositionError} error error object.
     */
    constructor(error) {
      super(GeolocationErrorType.ERROR);

      /**
       * Code of the underlying `GeolocationPositionError`.
       * @type {number}
       * @api
       */
      this.code = error.code;

      /**
       * Message of the underlying `GeolocationPositionError`.
       * @type {string}
       * @api
       */
      this.message = error.message;
    }
  }

  /**
   * @typedef {Object} Options
   * @property {boolean} [tracking=false] Start Tracking right after
   * instantiation.
   * @property {PositionOptions} [trackingOptions] Tracking options.
   * See https://www.w3.org/TR/geolocation-API/#position_options_interface.
   * @property {import("./proj.js").ProjectionLike} [projection] The projection the position
   * is reported in.
   */

  /**
   * @typedef {import("./ObjectEventType").Types|'change:accuracy'|'change:accuracyGeometry'|'change:altitude'|
   *    'change:altitudeAccuracy'|'change:heading'|'change:position'|'change:projection'|'change:speed'|'change:tracking'|
   *    'change:trackingOptions'} GeolocationObjectEventTypes
   */

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<GeolocationObjectEventTypes, import("./Object").ObjectEvent, Return> &
   *   import("./Observable").OnSignature<'error', GeolocationError, Return> &
   *   import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|GeolocationObjectEventTypes, Return> &
   *   import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return>} GeolocationOnSignature
   */

  /**
   * @classdesc
   * Helper class for providing HTML5 Geolocation capabilities.
   * The [Geolocation API](https://www.w3.org/TR/geolocation-API/)
   * is used to locate a user's position.
   *
   * To get notified of position changes and errors, register listeners for the generic
   * `change` event and the `error` event on your instance of {@link module:ol/Geolocation~Geolocation}.
   *
   * Example:
   *
   *     const geolocation = new Geolocation({
   *       // take the projection to use from the map's view
   *       projection: view.getProjection()
   *     });
   *     // listen to changes in position
   *     geolocation.on('change', function(evt) {
   *       console.log(geolocation.getPosition());
   *     });
   *     // listen to error
   *     geolocation.on('error', function(evt) {
   *       window.console.log(evt.message);
   *     });
   *
   * @fires GeolocationError
   * @api
   */
  class Geolocation extends BaseObject {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      /***
       * @type {GeolocationOnSignature<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {GeolocationOnSignature<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {GeolocationOnSignature<void>}
       */
      this.un;

      options = options || {};

      /**
       * The unprojected (EPSG:4326) device position.
       * @private
       * @type {?import("./coordinate.js").Coordinate}
       */
      this.position_ = null;

      /**
       * @private
       * @type {import("./proj.js").TransformFunction}
       */
      this.transform_ = identityTransform;

      /**
       * @private
       * @type {number|undefined}
       */
      this.watchId_ = undefined;

      this.addChangeListener(Property$4.PROJECTION, this.handleProjectionChanged_);
      this.addChangeListener(Property$4.TRACKING, this.handleTrackingChanged_);

      if (options.projection !== undefined) {
        this.setProjection(options.projection);
      }
      if (options.trackingOptions !== undefined) {
        this.setTrackingOptions(options.trackingOptions);
      }

      this.setTracking(options.tracking !== undefined ? options.tracking : false);
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.setTracking(false);
      super.disposeInternal();
    }

    /**
     * @private
     */
    handleProjectionChanged_() {
      const projection = this.getProjection();
      if (projection) {
        this.transform_ = getTransformFromProjections(
          get$2('EPSG:4326'),
          projection,
        );
        if (this.position_) {
          this.set(Property$4.POSITION, this.transform_(this.position_));
        }
      }
    }

    /**
     * @private
     */
    handleTrackingChanged_() {
      if ('geolocation' in navigator) {
        const tracking = this.getTracking();
        if (tracking && this.watchId_ === undefined) {
          this.watchId_ = navigator.geolocation.watchPosition(
            this.positionChange_.bind(this),
            this.positionError_.bind(this),
            this.getTrackingOptions(),
          );
        } else if (!tracking && this.watchId_ !== undefined) {
          navigator.geolocation.clearWatch(this.watchId_);
          this.watchId_ = undefined;
        }
      }
    }

    /**
     * @private
     * @param {GeolocationPosition} position position event.
     */
    positionChange_(position) {
      const coords = position.coords;
      this.set(Property$4.ACCURACY, coords.accuracy);
      this.set(
        Property$4.ALTITUDE,
        coords.altitude === null ? undefined : coords.altitude,
      );
      this.set(
        Property$4.ALTITUDE_ACCURACY,
        coords.altitudeAccuracy === null ? undefined : coords.altitudeAccuracy,
      );
      this.set(
        Property$4.HEADING,
        coords.heading === null ? undefined : toRadians(coords.heading),
      );
      if (!this.position_) {
        this.position_ = [coords.longitude, coords.latitude];
      } else {
        this.position_[0] = coords.longitude;
        this.position_[1] = coords.latitude;
      }
      const projectedPosition = this.transform_(this.position_);
      this.set(Property$4.POSITION, projectedPosition.slice());
      this.set(Property$4.SPEED, coords.speed === null ? undefined : coords.speed);
      const geometry = circular(this.position_, coords.accuracy);
      geometry.applyTransform(this.transform_);
      this.set(Property$4.ACCURACY_GEOMETRY, geometry);
      this.changed();
    }

    /**
     * @private
     * @param {GeolocationPositionError} error error object.
     */
    positionError_(error) {
      this.dispatchEvent(new GeolocationError(error));
    }

    /**
     * Get the accuracy of the position in meters.
     * @return {number|undefined} The accuracy of the position measurement in
     *     meters.
     * @observable
     * @api
     */
    getAccuracy() {
      return /** @type {number|undefined} */ (this.get(Property$4.ACCURACY));
    }

    /**
     * Get a geometry of the position accuracy.
     * @return {?import("./geom/Polygon.js").default} A geometry of the position accuracy.
     * @observable
     * @api
     */
    getAccuracyGeometry() {
      return /** @type {?import("./geom/Polygon.js").default} */ (
        this.get(Property$4.ACCURACY_GEOMETRY) || null
      );
    }

    /**
     * Get the altitude associated with the position.
     * @return {number|undefined} The altitude of the position in meters above mean
     *     sea level.
     * @observable
     * @api
     */
    getAltitude() {
      return /** @type {number|undefined} */ (this.get(Property$4.ALTITUDE));
    }

    /**
     * Get the altitude accuracy of the position.
     * @return {number|undefined} The accuracy of the altitude measurement in
     *     meters.
     * @observable
     * @api
     */
    getAltitudeAccuracy() {
      return /** @type {number|undefined} */ (
        this.get(Property$4.ALTITUDE_ACCURACY)
      );
    }

    /**
     * Get the heading as radians clockwise from North.
     * Note: depending on the browser, the heading is only defined if the `enableHighAccuracy`
     * is set to `true` in the tracking options.
     * @return {number|undefined} The heading of the device in radians from north.
     * @observable
     * @api
     */
    getHeading() {
      return /** @type {number|undefined} */ (this.get(Property$4.HEADING));
    }

    /**
     * Get the position of the device.
     * @return {import("./coordinate.js").Coordinate|undefined} The current position of the device reported
     *     in the current projection.
     * @observable
     * @api
     */
    getPosition() {
      return /** @type {import("./coordinate.js").Coordinate|undefined} */ (
        this.get(Property$4.POSITION)
      );
    }

    /**
     * Get the projection associated with the position.
     * @return {import("./proj/Projection.js").default|undefined} The projection the position is
     *     reported in.
     * @observable
     * @api
     */
    getProjection() {
      return /** @type {import("./proj/Projection.js").default|undefined} */ (
        this.get(Property$4.PROJECTION)
      );
    }

    /**
     * Get the speed in meters per second.
     * @return {number|undefined} The instantaneous speed of the device in meters
     *     per second.
     * @observable
     * @api
     */
    getSpeed() {
      return /** @type {number|undefined} */ (this.get(Property$4.SPEED));
    }

    /**
     * Determine if the device location is being tracked.
     * @return {boolean} The device location is being tracked.
     * @observable
     * @api
     */
    getTracking() {
      return /** @type {boolean} */ (this.get(Property$4.TRACKING));
    }

    /**
     * Get the tracking options.
     * See https://www.w3.org/TR/geolocation-API/#position-options.
     * @return {PositionOptions|undefined} PositionOptions as defined by
     *     the [HTML5 Geolocation spec
     *     ](https://www.w3.org/TR/geolocation-API/#position_options_interface).
     * @observable
     * @api
     */
    getTrackingOptions() {
      return /** @type {PositionOptions|undefined} */ (
        this.get(Property$4.TRACKING_OPTIONS)
      );
    }

    /**
     * Set the projection to use for transforming the coordinates.
     * @param {import("./proj.js").ProjectionLike} projection The projection the position is
     *     reported in.
     * @observable
     * @api
     */
    setProjection(projection) {
      this.set(Property$4.PROJECTION, get$2(projection));
    }

    /**
     * Enable or disable tracking.
     * @param {boolean} tracking Enable tracking.
     * @observable
     * @api
     */
    setTracking(tracking) {
      this.set(Property$4.TRACKING, tracking);
    }

    /**
     * Set the tracking options.
     * See http://www.w3.org/TR/geolocation-API/#position-options.
     * @param {PositionOptions} options PositionOptions as defined by the
     *     [HTML5 Geolocation spec
     *     ](http://www.w3.org/TR/geolocation-API/#position_options_interface).
     * @observable
     * @api
     */
    setTrackingOptions(options) {
      this.set(Property$4.TRACKING_OPTIONS, options);
    }
  }

  /**
   * @module ol/geom/flat/interpolate
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} fraction Fraction.
   * @param {Array<number>} [dest] Destination.
   * @param {number} [dimension] Destination dimension (default is `2`)
   * @return {Array<number>} Destination.
   */
  function interpolatePoint(
    flatCoordinates,
    offset,
    end,
    stride,
    fraction,
    dest,
    dimension,
  ) {
    let o, t;
    const n = (end - offset) / stride;
    if (n === 1) {
      o = offset;
    } else if (n === 2) {
      o = offset;
      t = fraction;
    } else if (n !== 0) {
      let x1 = flatCoordinates[offset];
      let y1 = flatCoordinates[offset + 1];
      let length = 0;
      const cumulativeLengths = [0];
      for (let i = offset + stride; i < end; i += stride) {
        const x2 = flatCoordinates[i];
        const y2 = flatCoordinates[i + 1];
        length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
        cumulativeLengths.push(length);
        x1 = x2;
        y1 = y2;
      }
      const target = fraction * length;
      const index = binarySearch$1(cumulativeLengths, target);
      if (index < 0) {
        t =
          (target - cumulativeLengths[-index - 2]) /
          (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]);
        o = offset + (-index - 2) * stride;
      } else {
        o = offset + index * stride;
      }
    }
    dimension = dimension > 1 ? dimension : 2;
    dest = dest ? dest : new Array(dimension);
    for (let i = 0; i < dimension; ++i) {
      dest[i] =
        o === undefined
          ? NaN
          : t === undefined
            ? flatCoordinates[o + i]
            : lerp$1(flatCoordinates[o + i], flatCoordinates[o + stride + i], t);
    }
    return dest;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {number} m M.
   * @param {boolean} extrapolate Extrapolate.
   * @return {import("../../coordinate.js").Coordinate|null} Coordinate.
   */
  function lineStringCoordinateAtM(
    flatCoordinates,
    offset,
    end,
    stride,
    m,
    extrapolate,
  ) {
    if (end == offset) {
      return null;
    }
    let coordinate;
    if (m < flatCoordinates[offset + stride - 1]) {
      if (extrapolate) {
        coordinate = flatCoordinates.slice(offset, offset + stride);
        coordinate[stride - 1] = m;
        return coordinate;
      }
      return null;
    }
    if (flatCoordinates[end - 1] < m) {
      if (extrapolate) {
        coordinate = flatCoordinates.slice(end - stride, end);
        coordinate[stride - 1] = m;
        return coordinate;
      }
      return null;
    }
    // FIXME use O(1) search
    if (m == flatCoordinates[offset + stride - 1]) {
      return flatCoordinates.slice(offset, offset + stride);
    }
    let lo = offset / stride;
    let hi = end / stride;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (m < flatCoordinates[(mid + 1) * stride - 1]) {
        hi = mid;
      } else {
        lo = mid + 1;
      }
    }
    const m0 = flatCoordinates[lo * stride - 1];
    if (m == m0) {
      return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride);
    }
    const m1 = flatCoordinates[(lo + 1) * stride - 1];
    const t = (m - m0) / (m1 - m0);
    coordinate = [];
    for (let i = 0; i < stride - 1; ++i) {
      coordinate.push(
        lerp$1(
          flatCoordinates[(lo - 1) * stride + i],
          flatCoordinates[lo * stride + i],
          t,
        ),
      );
    }
    coordinate.push(m);
    return coordinate;
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<number>} ends Ends.
   * @param {number} stride Stride.
   * @param {number} m M.
   * @param {boolean} extrapolate Extrapolate.
   * @param {boolean} interpolate Interpolate.
   * @return {import("../../coordinate.js").Coordinate|null} Coordinate.
   */
  function lineStringsCoordinateAtM(
    flatCoordinates,
    offset,
    ends,
    stride,
    m,
    extrapolate,
    interpolate,
  ) {
    if (interpolate) {
      return lineStringCoordinateAtM(
        flatCoordinates,
        offset,
        ends[ends.length - 1],
        stride,
        m,
        extrapolate,
      );
    }
    let coordinate;
    if (m < flatCoordinates[stride - 1]) {
      if (extrapolate) {
        coordinate = flatCoordinates.slice(0, stride);
        coordinate[stride - 1] = m;
        return coordinate;
      }
      return null;
    }
    if (flatCoordinates[flatCoordinates.length - 1] < m) {
      if (extrapolate) {
        coordinate = flatCoordinates.slice(flatCoordinates.length - stride);
        coordinate[stride - 1] = m;
        return coordinate;
      }
      return null;
    }
    for (let i = 0, ii = ends.length; i < ii; ++i) {
      const end = ends[i];
      if (offset == end) {
        continue;
      }
      if (m < flatCoordinates[offset + stride - 1]) {
        return null;
      }
      if (m <= flatCoordinates[end - 1]) {
        return lineStringCoordinateAtM(
          flatCoordinates,
          offset,
          end,
          stride,
          m,
          false,
        );
      }
      offset = end;
    }
    return null;
  }

  /**
   * @module ol/geom/flat/length
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @return {number} Length.
   */
  function lineStringLength(flatCoordinates, offset, end, stride) {
    let x1 = flatCoordinates[offset];
    let y1 = flatCoordinates[offset + 1];
    let length = 0;
    for (let i = offset + stride; i < end; i += stride) {
      const x2 = flatCoordinates[i];
      const y2 = flatCoordinates[i + 1];
      length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
      x1 = x2;
      y1 = y2;
    }
    return length;
  }

  /**
   * @module ol/geom/LineString
   */

  /**
   * @classdesc
   * Linestring geometry.
   *
   * @api
   */
  class LineString extends SimpleGeometry {
    /**
     * @param {Array<import("../coordinate.js").Coordinate>|Array<number>} coordinates Coordinates.
     *     For internal use, flat coordinates in combination with `layout` are also accepted.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    constructor(coordinates, layout) {
      super();

      /**
       * @private
       * @type {import("../coordinate.js").Coordinate|null}
       */
      this.flatMidpoint_ = null;

      /**
       * @private
       * @type {number}
       */
      this.flatMidpointRevision_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDeltaRevision_ = -1;

      if (layout !== undefined && !Array.isArray(coordinates[0])) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
      } else {
        this.setCoordinates(
          /** @type {Array<import("../coordinate.js").Coordinate>} */ (
            coordinates
          ),
          layout,
        );
      }
    }

    /**
     * Append the passed coordinate to the coordinates of the linestring.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @api
     */
    appendCoordinate(coordinate) {
      extend$2(this.flatCoordinates, coordinate);
      this.changed();
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!LineString} Clone.
     * @api
     * @override
     */
    clone() {
      const lineString = new LineString(
        this.flatCoordinates.slice(),
        this.layout,
      );
      lineString.applyProperties(this);
      return lineString;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      if (this.maxDeltaRevision_ != this.getRevision()) {
        this.maxDelta_ = Math.sqrt(
          maxSquaredDelta(
            this.flatCoordinates,
            0,
            this.flatCoordinates.length,
            this.stride,
            0,
          ),
        );
        this.maxDeltaRevision_ = this.getRevision();
      }
      return assignClosestPoint(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        this.maxDelta_,
        false,
        x,
        y,
        closestPoint,
        minSquaredDistance,
      );
    }

    /**
     * Iterate over each segment, calling the provided callback.
     * If the callback returns a truthy value the function returns that
     * value immediately. Otherwise the function returns `false`.
     *
     * @param {function(this: S, import("../coordinate.js").Coordinate, import("../coordinate.js").Coordinate): T} callback Function
     *     called for each segment. The function will receive two arguments, the start and end coordinates of the segment.
     * @return {T|boolean} Value.
     * @template T,S
     * @api
     */
    forEachSegment(callback) {
      return forEach(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        callback,
      );
    }

    /**
     * Returns the coordinate at `m` using linear interpolation, or `null` if no
     * such coordinate exists.
     *
     * `extrapolate` controls extrapolation beyond the range of Ms in the
     * MultiLineString. If `extrapolate` is `true` then Ms less than the first
     * M will return the first coordinate and Ms greater than the last M will
     * return the last coordinate.
     *
     * @param {number} m M.
     * @param {boolean} [extrapolate] Extrapolate. Default is `false`.
     * @return {import("../coordinate.js").Coordinate|null} Coordinate.
     * @api
     */
    getCoordinateAtM(m, extrapolate) {
      if (this.layout != 'XYM' && this.layout != 'XYZM') {
        return null;
      }
      extrapolate = extrapolate !== undefined ? extrapolate : false;
      return lineStringCoordinateAtM(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        m,
        extrapolate,
      );
    }

    /**
     * Return the coordinates of the linestring.
     * @return {Array<import("../coordinate.js").Coordinate>} Coordinates.
     * @api
     * @override
     */
    getCoordinates() {
      return inflateCoordinates(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
      );
    }

    /**
     * Return the coordinate at the provided fraction along the linestring.
     * The `fraction` is a number between 0 and 1, where 0 is the start of the
     * linestring and 1 is the end.
     * @param {number} fraction Fraction.
     * @param {import("../coordinate.js").Coordinate} [dest] Optional coordinate whose values will
     *     be modified. If not provided, a new coordinate will be returned.
     * @return {import("../coordinate.js").Coordinate} Coordinate of the interpolated point.
     * @api
     */
    getCoordinateAt(fraction, dest) {
      return interpolatePoint(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        fraction,
        dest,
        this.stride,
      );
    }

    /**
     * Return the length of the linestring on projected plane.
     * @return {number} Length (on projected plane).
     * @api
     */
    getLength() {
      return lineStringLength(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
      );
    }

    /**
     * @return {Array<number>} Flat midpoint.
     */
    getFlatMidpoint() {
      if (this.flatMidpointRevision_ != this.getRevision()) {
        this.flatMidpoint_ = this.getCoordinateAt(
          0.5,
          this.flatMidpoint_ ?? undefined,
        );
        this.flatMidpointRevision_ = this.getRevision();
      }
      return /** @type {Array<number>} */ (this.flatMidpoint_);
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {LineString} Simplified LineString.
     * @protected
     * @override
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      /** @type {Array<number>} */
      const simplifiedFlatCoordinates = [];
      simplifiedFlatCoordinates.length = douglasPeucker(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        squaredTolerance,
        simplifiedFlatCoordinates,
        0,
      );
      return new LineString(simplifiedFlatCoordinates, 'XY');
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'LineString';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return intersectsLineString(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
        extent,
        this.getExtent(),
      );
    }

    /**
     * Set the coordinates of the linestring.
     * @param {!Array<import("../coordinate.js").Coordinate>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 1);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      this.flatCoordinates.length = deflateCoordinates(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
      );
      this.changed();
    }
  }

  /**
   * @module ol/geom/flat/geodesic
   */

  /**
   * @param {function(number): import("../../coordinate.js").Coordinate} interpolate Interpolate function.
   * @param {import("../../proj.js").TransformFunction} transform Transform from longitude/latitude to
   *     projected coordinates.
   * @param {number} squaredTolerance Squared tolerance.
   * @return {Array<number>} Flat coordinates.
   */
  function line(interpolate, transform, squaredTolerance) {
    // FIXME reduce garbage generation
    // FIXME optimize stack operations

    /** @type {Array<number>} */
    const flatCoordinates = [];

    let geoA = interpolate(0);
    let geoB = interpolate(1);

    let a = transform(geoA);
    let b = transform(geoB);

    /** @type {Array<import("../../coordinate.js").Coordinate>} */
    const geoStack = [geoB, geoA];
    /** @type {Array<import("../../coordinate.js").Coordinate>} */
    const stack = [b, a];
    /** @type {Array<number>} */
    const fractionStack = [1, 0];

    /** @type {!Object<string, boolean>} */
    const fractions = {};

    let maxIterations = 1e5;
    let geoM, m, fracA, fracB, fracM, key;

    while (--maxIterations > 0 && fractionStack.length > 0) {
      // Pop the a coordinate off the stack
      fracA = fractionStack.pop();
      geoA = geoStack.pop();
      a = stack.pop();
      // Add the a coordinate if it has not been added yet
      key = fracA.toString();
      if (!(key in fractions)) {
        flatCoordinates.push(a[0], a[1]);
        fractions[key] = true;
      }
      // Pop the b coordinate off the stack
      fracB = fractionStack.pop();
      geoB = geoStack.pop();
      b = stack.pop();
      // Find the m point between the a and b coordinates
      fracM = (fracA + fracB) / 2;
      geoM = interpolate(fracM);
      m = transform(geoM);
      if (
        squaredSegmentDistance(m[0], m[1], a[0], a[1], b[0], b[1]) <
        squaredTolerance
      ) {
        // If the m point is sufficiently close to the straight line, then we
        // discard it.  Just use the b coordinate and move on to the next line
        // segment.
        flatCoordinates.push(b[0], b[1]);
        key = fracB.toString();
        fractions[key] = true;
      } else {
        // Otherwise, we need to subdivide the current line segment.  Split it
        // into two and push the two line segments onto the stack.
        fractionStack.push(fracB, fracM, fracM, fracA);
        stack.push(b, m, m, a);
        geoStack.push(geoB, geoM, geoM, geoA);
      }
    }

    return flatCoordinates;
  }

  /**
   * Generate a meridian (line at constant longitude).
   * @param {number} lon Longitude.
   * @param {number} lat1 Latitude 1.
   * @param {number} lat2 Latitude 2.
   * @param {import("../../proj/Projection.js").default} projection Projection.
   * @param {number} squaredTolerance Squared tolerance.
   * @return {Array<number>} Flat coordinates.
   */
  function meridian(lon, lat1, lat2, projection, squaredTolerance) {
    const epsg4326Projection = get$2('EPSG:4326');
    return line(
      /**
       * @param {number} frac Fraction.
       * @return {import("../../coordinate.js").Coordinate} Coordinate.
       */
      function (frac) {
        return [lon, lat1 + (lat2 - lat1) * frac];
      },
      getTransform(epsg4326Projection, projection),
      squaredTolerance,
    );
  }

  /**
   * Generate a parallel (line at constant latitude).
   * @param {number} lat Latitude.
   * @param {number} lon1 Longitude 1.
   * @param {number} lon2 Longitude 2.
   * @param {import("../../proj/Projection.js").default} projection Projection.
   * @param {number} squaredTolerance Squared tolerance.
   * @return {Array<number>} Flat coordinates.
   */
  function parallel(lat, lon1, lon2, projection, squaredTolerance) {
    const epsg4326Projection = get$2('EPSG:4326');
    return line(
      /**
       * @param {number} frac Fraction.
       * @return {import("../../coordinate.js").Coordinate} Coordinate.
       */
      function (frac) {
        return [lon1 + (lon2 - lon1) * frac, lat];
      },
      getTransform(epsg4326Projection, projection),
      squaredTolerance,
    );
  }

  /**
   * @module ol/render/EventType
   */

  /**
   * @enum {string}
   */
  var RenderEventType = {
    /**
     * Triggered before a layer is rendered.
     * @event module:ol/render/Event~RenderEvent#prerender
     * @api
     */
    PRERENDER: 'prerender',

    /**
     * Triggered after a layer is rendered.
     * @event module:ol/render/Event~RenderEvent#postrender
     * @api
     */
    POSTRENDER: 'postrender',

    /**
     * Triggered before layers are composed.  When dispatched by the map, the event object will not have
     * a `context` set.  When dispatched by a layer, the event object will have a `context` set.  Only
     * WebGL layers currently dispatch this event.
     * @event module:ol/render/Event~RenderEvent#precompose
     * @api
     */
    PRECOMPOSE: 'precompose',

    /**
     * Triggered after layers are composed.  When dispatched by the map, the event object will not have
     * a `context` set.  When dispatched by a layer, the event object will have a `context` set.  Only
     * WebGL layers currently dispatch this event.
     * @event module:ol/render/Event~RenderEvent#postcompose
     * @api
     */
    POSTCOMPOSE: 'postcompose',

    /**
     * Triggered when rendering is complete, i.e. all sources and tiles have
     * finished loading for the current viewport, and all tiles are faded in.
     * The event object will not have a `context` set.
     * @event module:ol/render/Event~RenderEvent#rendercomplete
     * @api
     */
    RENDERCOMPLETE: 'rendercomplete',
  };

  /**
   * @typedef {'postrender'|'precompose'|'postcompose'|'rendercomplete'} MapRenderEventTypes
   */

  /**
   * @typedef {'postrender'|'prerender'} LayerRenderEventTypes
   */

  /**
   * @module ol/has
   */

  const ua =
    typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined'
      ? navigator.userAgent.toLowerCase()
      : '';

  /**
   * User agent string says we are dealing with Safari as browser.
   * @type {boolean}
   */
  const SAFARI = ua.includes('safari') && !ua.includes('chrom');

  /**
   * https://bugs.webkit.org/show_bug.cgi?id=237906
   * @type {boolean}
   */
  const SAFARI_BUG_237906 =
    SAFARI &&
    (ua.includes('version/15.4') ||
      /cpu (os|iphone os) 15_4 like mac os x/.test(ua));

  /**
   * User agent string says we are dealing with a WebKit engine.
   * @type {boolean}
   */
  const WEBKIT = ua.includes('webkit') && !ua.includes('edge');

  /**
   * User agent string says we are dealing with a Mac as platform.
   * @type {boolean}
   */
  const MAC = ua.includes('macintosh');

  /**
   * The ratio between physical pixels and device-independent pixels
   * (dips) on the device (`window.devicePixelRatio`).
   * @const
   * @type {number}
   * @api
   */
  const DEVICE_PIXEL_RATIO =
    typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;

  /**
   * The execution context is a worker with OffscreenCanvas available.
   * @const
   * @type {boolean}
   */
  const WORKER_OFFSCREEN_CANVAS =
    typeof WorkerGlobalScope !== 'undefined' &&
    typeof OffscreenCanvas !== 'undefined' &&
    self instanceof WorkerGlobalScope; //eslint-disable-line

  /**
   * Image.prototype.decode() is supported.
   * @type {boolean}
   */
  const IMAGE_DECODE =
    typeof Image !== 'undefined' && Image.prototype.decode;

  /**
   * createImageBitmap() is supported.
   * @type {boolean}
   */
  const CREATE_IMAGE_BITMAP = typeof createImageBitmap === 'function';

  /**
   * @type {boolean}
   */
  const PASSIVE_EVENT_LISTENERS = (function () {
    let passive = false;
    try {
      const options = Object.defineProperty({}, 'passive', {
        get: function () {
          passive = true;
        },
      });

      // @ts-ignore Ignore invalid event type '_'
      window.addEventListener('_', null, options);
      // @ts-ignore Ignore invalid event type '_'
      window.removeEventListener('_', null, options);
    } catch {
      // passive not supported
    }
    return passive;
  })();

  /**
   * @module ol/ImageState
   */

  /**
   * @enum {number}
   */
  var ImageState = {
    IDLE: 0,
    LOADING: 1,
    LOADED: 2,
    ERROR: 3,
    EMPTY: 4,
  };

  /**
   * @module ol/dom
   */

  //FIXME Move this function to the canvas module
  /**
   * Create an html canvas element and returns its 2d context.
   * @param {number} [width] Canvas width.
   * @param {number} [height] Canvas height.
   * @param {Array<HTMLCanvasElement>} [canvasPool] Canvas pool to take existing canvas from.
   * @param {CanvasRenderingContext2DSettings} [settings] CanvasRenderingContext2DSettings
   * @return {CanvasRenderingContext2D} The context.
   */
  function createCanvasContext2D(width, height, canvasPool, settings) {
    /** @type {HTMLCanvasElement|OffscreenCanvas} */
    let canvas;
    if (canvasPool && canvasPool.length) {
      canvas = /** @type {HTMLCanvasElement} */ (canvasPool.shift());
    } else if (WORKER_OFFSCREEN_CANVAS) {
      canvas = new OffscreenCanvas(width || 300, height || 300);
    } else {
      canvas = document.createElement('canvas');
    }
    if (width) {
      canvas.width = width;
    }
    if (height) {
      canvas.height = height;
    }
    //FIXME Allow OffscreenCanvasRenderingContext2D as return type
    return /** @type {CanvasRenderingContext2D} */ (
      canvas.getContext('2d', settings)
    );
  }

  /** @type {CanvasRenderingContext2D} */
  let sharedCanvasContext;

  /**
   * @return {CanvasRenderingContext2D} Shared canvas context.
   */
  function getSharedCanvasContext2D() {
    if (!sharedCanvasContext) {
      sharedCanvasContext = createCanvasContext2D(1, 1);
    }
    return sharedCanvasContext;
  }

  /**
   * Releases canvas memory to avoid exceeding memory limits in Safari.
   * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/
   * @param {CanvasRenderingContext2D} context Context.
   */
  function releaseCanvas$1(context) {
    const canvas = context.canvas;
    canvas.width = 1;
    canvas.height = 1;
    context.clearRect(0, 0, 1, 1);
  }

  /**
   * Get the current computed width for the given element including margin,
   * padding and border.
   * Equivalent to jQuery's `$(el).outerWidth(true)`.
   * @param {!HTMLElement} element Element.
   * @return {number} The width.
   */
  function outerWidth(element) {
    let width = element.offsetWidth;
    const style = getComputedStyle(element);
    width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10);

    return width;
  }

  /**
   * Get the current computed height for the given element including margin,
   * padding and border.
   * Equivalent to jQuery's `$(el).outerHeight(true)`.
   * @param {!HTMLElement} element Element.
   * @return {number} The height.
   */
  function outerHeight(element) {
    let height = element.offsetHeight;
    const style = getComputedStyle(element);
    height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10);

    return height;
  }

  /**
   * @param {Node} newNode Node to replace old node
   * @param {Node} oldNode The node to be replaced
   */
  function replaceNode(newNode, oldNode) {
    const parent = oldNode.parentNode;
    if (parent) {
      parent.replaceChild(newNode, oldNode);
    }
  }

  /**
   * @param {Node} node The node to remove the children from.
   */
  function removeChildren(node) {
    while (node.lastChild) {
      node.lastChild.remove();
    }
  }

  /**
   * Transform the children of a parent node so they match the
   * provided list of children.  This function aims to efficiently
   * remove, add, and reorder child nodes while maintaining a simple
   * implementation (it is not guaranteed to minimize DOM operations).
   * @param {Node} node The parent node whose children need reworking.
   * @param {Array<Node>} children The desired children.
   */
  function replaceChildren(node, children) {
    const oldChildren = node.childNodes;

    for (let i = 0; true; ++i) {
      const oldChild = oldChildren[i];
      const newChild = children[i];

      // check if our work is done
      if (!oldChild && !newChild) {
        break;
      }

      // check if children match
      if (oldChild === newChild) {
        continue;
      }

      // check if a new child needs to be added
      if (!oldChild) {
        node.appendChild(newChild);
        continue;
      }

      // check if an old child needs to be removed
      if (!newChild) {
        node.removeChild(oldChild);
        --i;
        continue;
      }

      // reorder
      node.insertBefore(newChild, oldChild);
    }
  }

  /**
   * @module ol/color
   */

  /**
   * A color represented as a short array [red, green, blue, alpha].
   * red, green, and blue should be integers in the range 0..255 inclusive.
   * alpha should be a float in the range 0..1 inclusive. If no alpha value is
   * given then `1` will be used.
   * @typedef {Array<number>} Color
   * @api
   */

  /**
   * Color to indicate that no color should be rendered. This is meant to be used for per-reference
   * comparisons only.
   * @type {Color}
   */
  const NO_COLOR = [NaN, NaN, NaN, 0];

  let colorParseContext;
  /**
   * @return {CanvasRenderingContext2D} The color parse context
   */
  function getColorParseContext() {
    if (!colorParseContext) {
      colorParseContext = createCanvasContext2D(1, 1, undefined, {
        willReadFrequently: true,
        desynchronized: true,
      });
    }
    return colorParseContext;
  }

  const rgbModernRegEx =
    /^rgba?\(\s*(\d+%?)\s+(\d+%?)\s+(\d+%?)(?:\s*\/\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i;
  const rgbLegacyAbsoluteRegEx =
    /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i;
  const rgbLegacyPercentageRegEx =
    /^rgba?\(\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(\d+%)(?:\s*,\s*(\d+%|\d*\.\d+|[01]))?\s*\)$/i;
  const hexRegEx = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i;

  /**
   * @param {string} s Color component as number or percentage.
   * @param {number} divider Divider for percentage.
   * @return {number} Color component.
   */
  function toColorComponent(s, divider) {
    return s.endsWith('%')
      ? Number(s.substring(0, s.length - 1)) / divider
      : Number(s);
  }

  /**
   * @param {string} color Color string.
   */
  function throwInvalidColor(color) {
    throw new Error('failed to parse "' + color + '" as color');
  }

  /**
   * @param {string} color Color string.
   * @return {Color} RGBa color array.
   */
  function parseRgba(color) {
    // Fast lane for rgb(a) colors
    if (color.toLowerCase().startsWith('rgb')) {
      const rgb =
        color.match(rgbLegacyAbsoluteRegEx) ||
        color.match(rgbModernRegEx) ||
        color.match(rgbLegacyPercentageRegEx);
      if (rgb) {
        const alpha = rgb[4];
        const rgbDivider = 100 / 255;
        return [
          clamp$1((toColorComponent(rgb[1], rgbDivider) + 0.5) | 0, 0, 255),
          clamp$1((toColorComponent(rgb[2], rgbDivider) + 0.5) | 0, 0, 255),
          clamp$1((toColorComponent(rgb[3], rgbDivider) + 0.5) | 0, 0, 255),
          alpha !== undefined ? clamp$1(toColorComponent(alpha, 100), 0, 1) : 1,
        ];
      }
      throwInvalidColor(color);
    }
    // Fast lane for hex colors (also with alpha)
    if (color.startsWith('#')) {
      if (hexRegEx.test(color)) {
        const hex = color.substring(1);
        const step = hex.length <= 4 ? 1 : 2;
        const colorFromHex = [0, 0, 0, 255];
        for (let i = 0, ii = hex.length; i < ii; i += step) {
          let colorComponent = parseInt(hex.substring(i, i + step), 16);
          if (step === 1) {
            colorComponent += colorComponent << 4;
          }
          colorFromHex[i / step] = colorComponent;
        }
        colorFromHex[3] = colorFromHex[3] / 255;
        return colorFromHex;
      }
      throwInvalidColor(color);
    }
    // Use canvas color serialization to parse the color into hex or rgba
    // See https://www.w3.org/TR/2021/SPSD-2dcontext-20210128/#serialization-of-a-color
    const context = getColorParseContext();
    context.fillStyle = '#abcdef';
    let invalidCheckFillStyle = context.fillStyle;
    context.fillStyle = color;
    if (context.fillStyle === invalidCheckFillStyle) {
      context.fillStyle = '#fedcba';
      invalidCheckFillStyle = context.fillStyle;
      context.fillStyle = color;
      if (context.fillStyle === invalidCheckFillStyle) {
        throwInvalidColor(color);
      }
    }
    const colorString = context.fillStyle;
    if (colorString.startsWith('#') || colorString.startsWith('rgba')) {
      return parseRgba(colorString);
    }
    context.clearRect(0, 0, 1, 1);
    context.fillRect(0, 0, 1, 1);
    const colorFromImage = Array.from(context.getImageData(0, 0, 1, 1).data);
    colorFromImage[3] = toFixed(colorFromImage[3] / 255, 3);
    return colorFromImage;
  }

  /**
   * Return the color as an rgba string.
   * @param {Color|string} color Color.
   * @return {string} Rgba string.
   * @api
   */
  function asString(color) {
    if (typeof color === 'string') {
      return color;
    }
    return toString$1(color);
  }

  /**
   * @type {number}
   */
  const MAX_CACHE_SIZE = 1024;

  /**
   * We maintain a small cache of parsed strings.  Whenever the cache grows too large,
   * we delete an arbitrary set of the entries.
   *
   * @type {Object<string, Color>}
   */
  const cache = {};

  /**
   * @type {number}
   */
  let cacheSize = 0;

  /**
   * @param {Color} color A color that may or may not have an alpha channel.
   * @return {Color} The input color with an alpha channel.  If the input color has
   * an alpha channel, the input color will be returned unchanged.  Otherwise, a new
   * array will be returned with the input color and an alpha channel of 1.
   */
  function withAlpha(color) {
    if (color.length === 4) {
      return color;
    }
    const output = color.slice();
    output[3] = 1;
    return output;
  }

  // The functions b1, b2, a1, a2, rgbaToLcha and lchaToRgba below are adapted from
  // https://stackoverflow.com/a/67219995/2389327

  /**
   * @param {number} v Input value.
   * @return {number} Output value.
   */
  function b1(v) {
    return v > 0.0031308 ? Math.pow(v, 1 / 2.4) * 269.025 - 14.025 : v * 3294.6;
  }

  /**
   * @param {number} v Input value.
   * @return {number} Output value.
   */
  function b2(v) {
    return v > 0.2068965 ? Math.pow(v, 3) : (v - 4 / 29) * (108 / 841);
  }

  /**
   * @param {number} v Input value.
   * @return {number} Output value.
   */
  function a1(v) {
    return v > 10.314724 ? Math.pow((v + 14.025) / 269.025, 2.4) : v / 3294.6;
  }

  /**
   * @param {number} v Input value.
   * @return {number} Output value.
   */
  function a2(v) {
    return v > 0.0088564 ? Math.pow(v, 1 / 3) : v / (108 / 841) + 4 / 29;
  }

  /**
   * @param {Color} color RGBA color.
   * @return {Color} LCHuv color with alpha.
   */
  function rgbaToLcha(color) {
    const r = a1(color[0]);
    const g = a1(color[1]);
    const b = a1(color[2]);
    const y = a2(r * 0.222488403 + g * 0.716873169 + b * 0.06060791);
    const l = 500 * (a2(r * 0.452247074 + g * 0.399439023 + b * 0.148375274) - y);
    const q = 200 * (y - a2(r * 0.016863605 + g * 0.117638439 + b * 0.865350722));
    const h = Math.atan2(q, l) * (180 / Math.PI);
    return [
      116 * y - 16,
      Math.sqrt(l * l + q * q),
      h < 0 ? h + 360 : h,
      color[3],
    ];
  }

  /**
   * @param {Color} color LCHuv color with alpha.
   * @return {Color} RGBA color.
   */
  function lchaToRgba(color) {
    const l = (color[0] + 16) / 116;
    const c = color[1];
    const h = (color[2] * Math.PI) / 180;
    const y = b2(l);
    const x = b2(l + (c / 500) * Math.cos(h));
    const z = b2(l - (c / 200) * Math.sin(h));
    const r = b1(x * 3.021973625 - y * 1.617392459 - z * 0.404875592);
    const g = b1(x * -0.943766287 + y * 1.916279586 + z * 0.027607165);
    const b = b1(x * 0.069407491 - y * 0.22898585 + z * 1.159737864);
    return [
      clamp$1((r + 0.5) | 0, 0, 255),
      clamp$1((g + 0.5) | 0, 0, 255),
      clamp$1((b + 0.5) | 0, 0, 255),
      color[3],
    ];
  }

  /**
   * @param {string} s String.
   * @return {Color} Color.
   */
  function fromString(s) {
    if (s === 'none') {
      return NO_COLOR;
    }
    if (cache.hasOwnProperty(s)) {
      return cache[s];
    }
    if (cacheSize >= MAX_CACHE_SIZE) {
      let i = 0;
      for (const key in cache) {
        if ((i++ & 3) === 0) {
          delete cache[key];
          --cacheSize;
        }
      }
    }

    const color = parseRgba(s);
    if (color.length !== 4) {
      throwInvalidColor(s);
    }
    for (const c of color) {
      if (isNaN(c)) {
        throwInvalidColor(s);
      }
    }
    cache[s] = color;
    ++cacheSize;
    return color;
  }

  /**
   * Return the color as an array. This function maintains a cache of calculated
   * arrays which means the result should not be modified.
   * @param {Color|string} color Color.
   * @return {Color} Color.
   * @api
   */
  function asArray(color) {
    if (Array.isArray(color)) {
      return color;
    }
    return fromString(color);
  }

  /**
   * @param {Color} color Color.
   * @return {string} String.
   */
  function toString$1(color) {
    let r = color[0];
    if (r != (r | 0)) {
      r = (r + 0.5) | 0;
    }
    let g = color[1];
    if (g != (g | 0)) {
      g = (g + 0.5) | 0;
    }
    let b = color[2];
    if (b != (b | 0)) {
      b = (b + 0.5) | 0;
    }
    const a = color[3] === undefined ? 1 : Math.round(color[3] * 1000) / 1000;
    return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  }

  /**
   * @module ol/Image
   */

  /**
   * A function that takes an {@link module:ol/Image~ImageWrapper} for the image and a
   * `{string}` for the src as arguments. It is supposed to make it so the
   * underlying image {@link module:ol/Image~ImageWrapper#getImage} is assigned the
   * content specified by the src. If not specified, the default is
   *
   *     function(image, src) {
   *       image.getImage().src = src;
   *     }
   *
   * Providing a custom `imageLoadFunction` can be useful to load images with
   * post requests or - in general - through XHR requests, where the src of the
   * image element would be set to a data URI when the content is loaded.
   *
   * @typedef {function(import("./Image.js").default, string): void} LoadFunction
   * @api
   */

  /**
   * @typedef {Object} ImageObject
   * @property {import("./extent.js").Extent} [extent] Extent, if different from the requested one.
   * @property {import("./resolution.js").ResolutionLike} [resolution] Resolution, if different from the requested one.
   * When x and y resolution are different, use the array type (`[xResolution, yResolution]`).
   * @property {number} [pixelRatio] Pixel ratio, if different from the requested one.
   * @property {import('./DataTile.js').ImageLike} image Image.
   */

  /**
   * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.
   * For images that cover any extent and resolution (static images), the loader function should not accept
   * any arguments. The function returns an {@link import("./DataTile.js").ImageLike image}, an
   * {@link import("./Image.js").ImageObject image object}, or a promise for the same.
   * For loaders that generate images, the promise should not resolve until the image is loaded.
   * If the returned image does not match the extent, resolution or pixel ratio passed to the loader,
   * it has to return an {@link import("./Image.js").ImageObject image object} with the `image` and the
   * correct `extent`, `resolution` and `pixelRatio`.
   *
   * @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): import("./DataTile.js").ImageLike|ImageObject|Promise<import("./DataTile.js").ImageLike|ImageObject>} Loader
   * @api
   */

  /**
   * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments.
   * The function returns a promise for an  {@link import("./Image.js").ImageObject image object}.
   *
   * @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): Promise<import("./DataTile.js").ImageLike|ImageObject>} ImageObjectPromiseLoader
   */

  class ImageWrapper extends Target {
    /**
     * @param {import("./extent.js").Extent} extent Extent.
     * @param {number|Array<number>|undefined} resolution Resolution. If provided as array, x and y
     * resolution will be assumed.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("./ImageState.js").default|Loader} stateOrLoader State.
     */
    constructor(extent, resolution, pixelRatio, stateOrLoader) {
      super();

      /**
       * @protected
       * @type {import("./extent.js").Extent}
       */
      this.extent = extent;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = pixelRatio;

      /**
       * @protected
       * @type {number|Array<number>|undefined}
       */
      this.resolution = resolution;

      /**
       * @protected
       * @type {import("./ImageState.js").default}
       */
      this.state =
        typeof stateOrLoader === 'function' ? ImageState.IDLE : stateOrLoader;

      /**
       * @private
       * @type {import('./DataTile.js').ImageLike|null}
       */
      this.image_ = null;

      /**
       * @protected
       * @type {Loader|null}
       */
      this.loader = typeof stateOrLoader === 'function' ? stateOrLoader : null;
    }

    /**
     * @protected
     */
    changed() {
      this.dispatchEvent(EventType.CHANGE);
    }

    /**
     * @return {import("./extent.js").Extent} Extent.
     */
    getExtent() {
      return this.extent;
    }

    /**
     * @return {import('./DataTile.js').ImageLike} Image.
     */
    getImage() {
      return this.image_;
    }

    /**
     * @return {number} PixelRatio.
     */
    getPixelRatio() {
      return this.pixelRatio_;
    }

    /**
     * @return {number|Array<number>} Resolution.
     */
    getResolution() {
      return /** @type {number} */ (this.resolution);
    }

    /**
     * @return {import("./ImageState.js").default} State.
     */
    getState() {
      return this.state;
    }

    /**
     * Load not yet loaded URI.
     */
    load() {
      if (this.state == ImageState.IDLE) {
        if (this.loader) {
          this.state = ImageState.LOADING;
          this.changed();
          const resolution = this.getResolution();
          const requestResolution = Array.isArray(resolution)
            ? resolution[0]
            : resolution;
          toPromise(() =>
            this.loader(
              this.getExtent(),
              requestResolution,
              this.getPixelRatio(),
            ),
          )
            .then((image) => {
              if ('image' in image) {
                this.image_ = image.image;
              }
              if ('extent' in image) {
                this.extent = image.extent;
              }
              if ('resolution' in image) {
                this.resolution = image.resolution;
              }
              if ('pixelRatio' in image) {
                this.pixelRatio_ = image.pixelRatio;
              }
              if (
                image instanceof HTMLImageElement ||
                (CREATE_IMAGE_BITMAP && image instanceof ImageBitmap) ||
                image instanceof HTMLCanvasElement ||
                image instanceof HTMLVideoElement
              ) {
                this.image_ = image;
              }
              this.state = ImageState.LOADED;
            })
            .catch((error) => {
              this.state = ImageState.ERROR;
              console.error(error); // eslint-disable-line no-console
            })
            .finally(() => this.changed());
        }
      }
    }

    /**
     * @param {import('./DataTile.js').ImageLike} image The image.
     */
    setImage(image) {
      this.image_ = image;
    }

    /**
     * @param {number|Array<number>} resolution Resolution.
     */
    setResolution(resolution) {
      this.resolution = resolution;
    }
  }

  /**
   * @param {import('./DataTile.js').ImageLike} image Image element.
   * @param {function():any} loadHandler Load callback function.
   * @param {function():any} errorHandler Error callback function.
   * @return {function():void} Callback to stop listening.
   */
  function listenImage(image, loadHandler, errorHandler) {
    const img = /** @type {HTMLImageElement} */ (image);
    let listening = true;
    let decoding = false;
    let loaded = false;

    const listenerKeys = [
      listenOnce(img, EventType.LOAD, function () {
        loaded = true;
        if (!decoding) {
          loadHandler();
        }
      }),
    ];

    if (img.src && IMAGE_DECODE) {
      decoding = true;
      img
        .decode()
        .then(function () {
          if (listening) {
            loadHandler();
          }
        })
        .catch(function (error) {
          if (listening) {
            if (loaded) {
              loadHandler();
            } else {
              errorHandler();
            }
          }
        });
    } else {
      listenerKeys.push(listenOnce(img, EventType.ERROR, errorHandler));
    }

    return function unlisten() {
      listening = false;
      listenerKeys.forEach(unlistenByKey);
    };
  }

  /**
   * Loads an image.
   * @param {HTMLImageElement} image Image, not yet loaded.
   * @param {string} [src] `src` attribute of the image. Optional, not required if already present.
   * @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.
   * @api
   */
  function load(image, src) {
    return new Promise((resolve, reject) => {
      function handleLoad() {
        unlisten();
        resolve(image);
      }
      function handleError() {
        unlisten();
        reject(new Error('Image load error'));
      }
      function unlisten() {
        image.removeEventListener('load', handleLoad);
        image.removeEventListener('error', handleError);
      }
      image.addEventListener('load', handleLoad);
      image.addEventListener('error', handleError);
    });
  }

  /**
   * @param {HTMLImageElement} image Image, not yet loaded.
   * @param {string} [src] `src` attribute of the image. Optional, not required if already present.
   * @return {Promise<HTMLImageElement>} Promise resolving to an `HTMLImageElement`.
   */
  function decodeFallback(image, src) {
    if (src) {
      image.src = src;
    }
    return image.src && IMAGE_DECODE
      ? new Promise((resolve, reject) =>
          image
            .decode()
            .then(() => resolve(image))
            .catch((e) =>
              image.complete && image.width ? resolve(image) : reject(e),
            ),
        )
      : load(image);
  }

  /**
   * Loads an image and decodes it to an `ImageBitmap` if `createImageBitmap()` is supported. Returns
   * the loaded image otherwise.
   * @param {HTMLImageElement} image Image, not yet loaded.
   * @param {string} [src] `src` attribute of the image. Optional, not required if already present.
   * @return {Promise<ImageBitmap|HTMLImageElement>} Promise resolving to an `ImageBitmap` or an
   * `HTMLImageElement` if `createImageBitmap()` is not supported.
   * @api
   */
  function decode(image, src) {
    if (src) {
      image.src = src;
    }
    return image.src && IMAGE_DECODE && CREATE_IMAGE_BITMAP
      ? image
          .decode()
          .then(() => createImageBitmap(image))
          .catch((e) => {
            if (image.complete && image.width) {
              return image;
            }
            throw e;
          })
      : decodeFallback(image);
  }

  /**
   * @module ol/style/IconImageCache
   */

  /**
   * @classdesc
   * Singleton class. Available through {@link module:ol/style/IconImageCache.shared}.
   */
  class IconImageCache {
    constructor() {
      /**
       * @type {!Object<string, import("./IconImage.js").default>}
       * @private
       */
      this.cache_ = {};

      /**
       * @type {!Object<string, CanvasPattern>}
       * @private
       */
      this.patternCache_ = {};

      /**
       * @type {number}
       * @private
       */
      this.cacheSize_ = 0;

      /**
       * @type {number}
       * @private
       */
      this.maxCacheSize_ = 1024;
    }

    /**
     * FIXME empty description for jsdoc
     */
    clear() {
      this.cache_ = {};
      this.patternCache_ = {};
      this.cacheSize_ = 0;
    }

    /**
     * @return {boolean} Can expire cache.
     */
    canExpireCache() {
      return this.cacheSize_ > this.maxCacheSize_;
    }

    /**
     * FIXME empty description for jsdoc
     */
    expire() {
      if (this.canExpireCache()) {
        let i = 0;
        for (const key in this.cache_) {
          const iconImage = this.cache_[key];
          if ((i++ & 3) === 0 && !iconImage.hasListener()) {
            delete this.cache_[key];
            delete this.patternCache_[key];
            --this.cacheSize_;
          }
        }
      }
    }

    /**
     * @param {string} src Src.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("../color.js").Color|string|null} color Color.
     * @return {import("./IconImage.js").default} Icon image.
     */
    get(src, crossOrigin, color) {
      const key = getCacheKey$2(src, crossOrigin, color);
      return key in this.cache_ ? this.cache_[key] : null;
    }

    /**
     * @param {string} src Src.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("../color.js").Color|string|null} color Color.
     * @return {CanvasPattern} Icon image.
     */
    getPattern(src, crossOrigin, color) {
      const key = getCacheKey$2(src, crossOrigin, color);
      return key in this.patternCache_ ? this.patternCache_[key] : null;
    }

    /**
     * @param {string} src Src.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("../color.js").Color|string|null} color Color.
     * @param {import("./IconImage.js").default|null} iconImage Icon image.
     * @param {boolean} [pattern] Also cache a `'repeat'` pattern with this `iconImage`.
     */
    set(src, crossOrigin, color, iconImage, pattern) {
      const key = getCacheKey$2(src, crossOrigin, color);
      const update = key in this.cache_;
      this.cache_[key] = iconImage;
      if (pattern) {
        if (iconImage.getImageState() === ImageState.IDLE) {
          iconImage.load();
        }
        if (iconImage.getImageState() === ImageState.LOADING) {
          iconImage.ready().then(() => {
            this.patternCache_[key] = getSharedCanvasContext2D().createPattern(
              iconImage.getImage(1),
              'repeat',
            );
          });
        } else {
          this.patternCache_[key] = getSharedCanvasContext2D().createPattern(
            iconImage.getImage(1),
            'repeat',
          );
        }
      }
      if (!update) {
        ++this.cacheSize_;
      }
    }

    /**
     * Set the cache size of the icon cache. Default is `1024`. Change this value when
     * your map uses more than 1024 different icon images and you are not caching icon
     * styles on the application level.
     * @param {number} maxCacheSize Cache max size.
     * @api
     */
    setSize(maxCacheSize) {
      this.maxCacheSize_ = maxCacheSize;
      this.expire();
    }
  }

  /**
   * @param {string} src Src.
   * @param {?string} crossOrigin Cross origin.
   * @param {import("../color.js").Color|string|null} color Color.
   * @return {string} Cache key.
   */
  function getCacheKey$2(src, crossOrigin, color) {
    const colorString = color ? asArray(color) : 'null';
    return crossOrigin + ':' + src + ':' + colorString;
  }

  /**
   * The {@link module:ol/style/IconImageCache~IconImageCache} for
   * {@link module:ol/style/Icon~Icon} images.
   * @api
   */
  const shared = new IconImageCache();

  /**
   * @module ol/style/IconImage
   */


  /**
   * @type {CanvasRenderingContext2D}
   */
  let taintedTestContext = null;

  class IconImage extends Target {
    /**
     * @param {HTMLImageElement|HTMLCanvasElement|ImageBitmap|null} image Image.
     * @param {string|undefined} src Src.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("../ImageState.js").default|undefined} imageState Image state.
     * @param {import("../color.js").Color|string|null} color Color.
     */
    constructor(image, src, crossOrigin, imageState, color) {
      super();

      /**
       * @private
       * @type {HTMLImageElement|HTMLCanvasElement|ImageBitmap}
       */
      this.hitDetectionImage_ = null;

      /**
       * @private
       * @type {HTMLImageElement|HTMLCanvasElement|ImageBitmap|null}
       */
      this.image_ = image;

      /**
       * @private
       * @type {string|null}
       */
      this.crossOrigin_ = crossOrigin;

      /**
       * @private
       * @type {Object<number, HTMLCanvasElement>}
       */
      this.canvas_ = {};

      /**
       * @private
       * @type {import("../color.js").Color|string|null}
       */
      this.color_ = color;

      /**
       * @private
       * @type {import("../ImageState.js").default}
       */
      this.imageState_ = imageState === undefined ? ImageState.IDLE : imageState;

      /**
       * @private
       * @type {import("../size.js").Size|null}
       */
      this.size_ =
        image && image.width && image.height ? [image.width, image.height] : null;

      /**
       * @private
       * @type {string|undefined}
       */
      this.src_ = src;

      /**
       * @private
       */
      this.tainted_;

      /**
       * @private
       * @type {Promise<void>|null}
       */
      this.ready_ = null;
    }

    /**
     * @private
     */
    initializeImage_() {
      this.image_ = new Image();
      if (this.crossOrigin_ !== null) {
        this.image_.crossOrigin = this.crossOrigin_;
      }
    }

    /**
     * @private
     * @return {boolean} The image canvas is tainted.
     */
    isTainted_() {
      if (this.tainted_ === undefined && this.imageState_ === ImageState.LOADED) {
        if (!taintedTestContext) {
          taintedTestContext = createCanvasContext2D(1, 1, undefined, {
            willReadFrequently: true,
          });
        }
        taintedTestContext.drawImage(this.image_, 0, 0);
        try {
          taintedTestContext.getImageData(0, 0, 1, 1);
          this.tainted_ = false;
        } catch {
          taintedTestContext = null;
          this.tainted_ = true;
        }
      }
      return this.tainted_ === true;
    }

    /**
     * @private
     */
    dispatchChangeEvent_() {
      this.dispatchEvent(EventType.CHANGE);
    }

    /**
     * @private
     */
    handleImageError_() {
      this.imageState_ = ImageState.ERROR;
      this.dispatchChangeEvent_();
    }

    /**
     * @private
     */
    handleImageLoad_() {
      this.imageState_ = ImageState.LOADED;
      this.size_ = [this.image_.width, this.image_.height];
      this.dispatchChangeEvent_();
    }

    /**
     * @param {number} pixelRatio Pixel ratio.
     * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image or Canvas element or image bitmap.
     */
    getImage(pixelRatio) {
      if (!this.image_) {
        this.initializeImage_();
      }
      this.replaceColor_(pixelRatio);
      return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_;
    }

    /**
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Image or Canvas element.
     */
    getPixelRatio(pixelRatio) {
      this.replaceColor_(pixelRatio);
      return this.canvas_[pixelRatio] ? pixelRatio : 1;
    }

    /**
     * @return {import("../ImageState.js").default} Image state.
     */
    getImageState() {
      return this.imageState_;
    }

    /**
     * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image element.
     */
    getHitDetectionImage() {
      if (!this.image_) {
        this.initializeImage_();
      }
      if (!this.hitDetectionImage_) {
        if (this.isTainted_()) {
          const width = this.size_[0];
          const height = this.size_[1];
          const context = createCanvasContext2D(width, height);
          context.fillRect(0, 0, width, height);
          this.hitDetectionImage_ = context.canvas;
        } else {
          this.hitDetectionImage_ = this.image_;
        }
      }
      return this.hitDetectionImage_;
    }

    /**
     * Get the size of the icon (in pixels).
     * @return {import("../size.js").Size} Image size.
     */
    getSize() {
      return this.size_;
    }

    /**
     * @return {string|undefined} Image src.
     */
    getSrc() {
      return this.src_;
    }

    /**
     * Load not yet loaded URI.
     */
    load() {
      if (this.imageState_ !== ImageState.IDLE) {
        return;
      }
      if (!this.image_) {
        this.initializeImage_();
      }

      this.imageState_ = ImageState.LOADING;
      try {
        if (this.src_ !== undefined) {
          /** @type {HTMLImageElement} */ (this.image_).src = this.src_;
        }
      } catch {
        this.handleImageError_();
      }
      if (this.image_ instanceof HTMLImageElement) {
        decodeFallback(this.image_, this.src_)
          .then((image) => {
            this.image_ = image;
            this.handleImageLoad_();
          })
          .catch(this.handleImageError_.bind(this));
      }
    }

    /**
     * @param {number} pixelRatio Pixel ratio.
     * @private
     */
    replaceColor_(pixelRatio) {
      if (
        !this.color_ ||
        this.canvas_[pixelRatio] ||
        this.imageState_ !== ImageState.LOADED
      ) {
        return;
      }

      const image = this.image_;
      const ctx = createCanvasContext2D(
        Math.ceil(image.width * pixelRatio),
        Math.ceil(image.height * pixelRatio),
      );
      const canvas = ctx.canvas;

      ctx.scale(pixelRatio, pixelRatio);
      ctx.drawImage(image, 0, 0);

      ctx.globalCompositeOperation = 'multiply';
      ctx.fillStyle = asString(this.color_);
      ctx.fillRect(0, 0, canvas.width / pixelRatio, canvas.height / pixelRatio);

      ctx.globalCompositeOperation = 'destination-in';
      ctx.drawImage(image, 0, 0);

      this.canvas_[pixelRatio] = canvas;
    }

    /**
     * @return {Promise<void>} Promise that resolves when the image is loaded.
     */
    ready() {
      if (!this.ready_) {
        this.ready_ = new Promise((resolve) => {
          if (
            this.imageState_ === ImageState.LOADED ||
            this.imageState_ === ImageState.ERROR
          ) {
            resolve();
          } else {
            const onChange = () => {
              if (
                this.imageState_ === ImageState.LOADED ||
                this.imageState_ === ImageState.ERROR
              ) {
                this.removeEventListener(EventType.CHANGE, onChange);
                resolve();
              }
            };
            this.addEventListener(EventType.CHANGE, onChange);
          }
        });
      }
      return this.ready_;
    }
  }

  /**
   * @param {HTMLImageElement|HTMLCanvasElement|ImageBitmap|null} image Image.
   * @param {string|undefined} cacheKey Src.
   * @param {?string} crossOrigin Cross origin.
   * @param {import("../ImageState.js").default|undefined} imageState Image state.
   * @param {import("../color.js").Color|string|null} color Color.
   * @param {boolean} [pattern] Also cache a `repeat` pattern with the icon image.
   * @return {IconImage} Icon image.
   */
  function get$1(image, cacheKey, crossOrigin, imageState, color, pattern) {
    let iconImage =
      cacheKey === undefined
        ? undefined
        : shared.get(cacheKey, crossOrigin, color);
    if (!iconImage) {
      iconImage = new IconImage(
        image,
        image && 'src' in image ? image.src || undefined : cacheKey,
        crossOrigin,
        imageState,
        color,
      );
      shared.set(cacheKey, crossOrigin, color, iconImage, pattern);
    }
    if (
      pattern &&
      iconImage &&
      !shared.getPattern(cacheKey, crossOrigin, color)
    ) {
      shared.set(cacheKey, crossOrigin, color, iconImage, pattern);
    }
    return iconImage;
  }

  /**
   * @module ol/colorlike
   */

  /**
   * @typedef {Object} PatternDescriptor
   * @property {string} src Pattern image URL
   * @property {import("./color.js").Color|string} [color] Color to tint the pattern with.
   * @property {import("./size.js").Size} [size] Size of the desired slice from the pattern image.
   * Use this together with `offset` when the pattern image is a sprite sheet.
   * @property {import("./size.js").Size} [offset] Offset of the desired slice from the pattern image.
   * Use this together with `size` when the pattern image is a sprite sheet.
   */

  /**
   * A type accepted by CanvasRenderingContext2D.fillStyle
   * or CanvasRenderingContext2D.strokeStyle.
   * Represents a color, [CanvasPattern](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern),
   * or [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient). The origin for
   * patterns and gradients as fill style is an increment of 512 css pixels from map coordinate
   * `[0, 0]`. For seamless repeat patterns, width and height of the pattern image
   * must be a factor of two (2, 4, 8, ..., 512).
   *
   * @typedef {string|CanvasPattern|CanvasGradient} ColorLike
   * @api
   */

  /**
   * @param {import("./color.js").Color|ColorLike|PatternDescriptor|null} color Color.
   * @return {ColorLike|null} The color as an {@link ol/colorlike~ColorLike}.
   * @api
   */
  function asColorLike(color) {
    if (!color) {
      return null;
    }
    if (Array.isArray(color)) {
      return toString$1(color);
    }
    if (typeof color === 'object' && 'src' in color) {
      return asCanvasPattern(color);
    }
    return color;
  }

  /**
   * @param {PatternDescriptor} pattern Pattern descriptor.
   * @return {CanvasPattern|null} Canvas pattern or null if the pattern referenced in the
   * PatternDescriptor was not found in the icon image cache.
   */
  function asCanvasPattern(pattern) {
    if (!pattern.offset || !pattern.size) {
      return shared.getPattern(pattern.src, 'anonymous', pattern.color);
    }

    const cacheKey = pattern.src + ':' + pattern.offset;

    const canvasPattern = shared.getPattern(
      cacheKey,
      undefined,
      pattern.color,
    );
    if (canvasPattern) {
      return canvasPattern;
    }

    const iconImage = shared.get(pattern.src, 'anonymous', null);
    if (iconImage.getImageState() !== ImageState.LOADED) {
      return null;
    }
    const patternCanvasContext = createCanvasContext2D(
      pattern.size[0],
      pattern.size[1],
    );
    patternCanvasContext.drawImage(
      iconImage.getImage(1),
      pattern.offset[0],
      pattern.offset[1],
      pattern.size[0],
      pattern.size[1],
      0,
      0,
      pattern.size[0],
      pattern.size[1],
    );
    get$1(
      patternCanvasContext.canvas,
      cacheKey,
      undefined,
      ImageState.LOADED,
      pattern.color,
      true,
    );
    return shared.getPattern(cacheKey, undefined, pattern.color);
  }

  /**
   * @module ol/render/VectorContext
   */

  /**
   * @classdesc
   * Context for drawing geometries.  A vector context is available on render
   * events and does not need to be constructed directly.
   * @api
   */
  class VectorContext {
    /**
     * Render a geometry with a custom renderer.
     *
     * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {Function} renderer Renderer.
     * @param {Function} hitDetectionRenderer Renderer.
     * @param {number} [index] Render order index.
     */
    drawCustom(geometry, feature, renderer, hitDetectionRenderer, index) {}

    /**
     * Render a geometry.
     *
     * @param {import("../geom/Geometry.js").default} geometry The geometry to render.
     */
    drawGeometry(geometry) {}

    /**
     * Set the rendering style.
     *
     * @param {import("../style/Style.js").default} style The rendering style.
     */
    setStyle(style) {}

    /**
     * @param {import("../geom/Circle.js").default} circleGeometry Circle geometry.
     * @param {import("../Feature.js").default} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawCircle(circleGeometry, feature, index) {}

    /**
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("../style/Style.js").default} style Style.
     * @param {number} [index] Render order index.
     */
    drawFeature(feature, style, index) {}

    /**
     * @param {import("../geom/GeometryCollection.js").default} geometryCollectionGeometry Geometry collection.
     * @param {import("../Feature.js").default} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawGeometryCollection(geometryCollectionGeometry, feature, index) {}

    /**
     * @param {import("../geom/LineString.js").default|import("./Feature.js").default} lineStringGeometry Line string geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawLineString(lineStringGeometry, feature, index) {}

    /**
     * @param {import("../geom/MultiLineString.js").default|import("./Feature.js").default} multiLineStringGeometry MultiLineString geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawMultiLineString(multiLineStringGeometry, feature, index) {}

    /**
     * @param {import("../geom/MultiPoint.js").default|import("./Feature.js").default} multiPointGeometry MultiPoint geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawMultiPoint(multiPointGeometry, feature, index) {}

    /**
     * @param {import("../geom/MultiPolygon.js").default} multiPolygonGeometry MultiPolygon geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawMultiPolygon(multiPolygonGeometry, feature, index) {}

    /**
     * @param {import("../geom/Point.js").default|import("./Feature.js").default} pointGeometry Point geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawPoint(pointGeometry, feature, index) {}

    /**
     * @param {import("../geom/Polygon.js").default|import("./Feature.js").default} polygonGeometry Polygon geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawPolygon(polygonGeometry, feature, index) {}

    /**
     * @param {import("../geom/SimpleGeometry.js").default|import("./Feature.js").default} geometry Geometry.
     * @param {import("../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     */
    drawText(geometry, feature, index) {}

    /**
     * @param {import("../style/Fill.js").default} fillStyle Fill style.
     * @param {import("../style/Stroke.js").default} strokeStyle Stroke style.
     */
    setFillStrokeStyle(fillStyle, strokeStyle) {}

    /**
     * @param {import("../style/Image.js").default} imageStyle Image style.
     * @param {import("../render/canvas.js").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with a text style.
     */
    setImageStyle(imageStyle, declutterImageWithText) {}

    /**
     * @param {import("../style/Text.js").default} textStyle Text style.
     * @param {import("../render/canvas.js").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with an image style.
     */
    setTextStyle(textStyle, declutterImageWithText) {}
  }

  /**
   * @module ol/css
   */

  /**
   * @typedef {Object} FontParameters
   * @property {string} style Style.
   * @property {string} variant Variant.
   * @property {string} weight Weight.
   * @property {string} size Size.
   * @property {string} lineHeight LineHeight.
   * @property {string} family Family.
   * @property {Array<string>} families Families.
   */

  /**
   * The CSS class for hidden feature.
   *
   * @const
   * @type {string}
   */
  const CLASS_HIDDEN = 'ol-hidden';

  /**
   * The CSS class that we'll give the DOM elements to have them selectable.
   *
   * @const
   * @type {string}
   */
  const CLASS_SELECTABLE = 'ol-selectable';

  /**
   * The CSS class that we'll give the DOM elements to have them unselectable.
   *
   * @const
   * @type {string}
   */
  const CLASS_UNSELECTABLE = 'ol-unselectable';

  /**
   * The CSS class for unsupported feature.
   *
   * @const
   * @type {string}
   */
  const CLASS_UNSUPPORTED = 'ol-unsupported';

  /**
   * The CSS class for controls.
   *
   * @const
   * @type {string}
   */
  const CLASS_CONTROL = 'ol-control';

  /**
   * The CSS class that we'll give the DOM elements that are collapsed, i.e.
   * to those elements which usually can be expanded.
   *
   * @const
   * @type {string}
   */
  const CLASS_COLLAPSED = 'ol-collapsed';

  /**
   * From https://stackoverflow.com/questions/10135697/regex-to-parse-any-css-font
   * @type {RegExp}
   */
  const fontRegEx = new RegExp(
    [
      '^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)',
      '(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)',
      '(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)',
      '(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?',
      '(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))',
      '(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))',
      '?\\s*([-,\\"\\\'\\sa-z0-9]+?)\\s*$',
    ].join(''),
    'i',
  );
  /** @type {Array<'style'|'variant'|'weight'|'size'|'lineHeight'|'family'>} */
  const fontRegExMatchIndex = [
    'style',
    'variant',
    'weight',
    'size',
    'lineHeight',
    'family',
  ];

  /** @type {Object<string|number, number>} */
  const fontWeights$1 = {
    normal: 400,
    bold: 700,
  };

  /**
   * Get the list of font families from a font spec.  Note that this doesn't work
   * for font families that have commas in them.
   * @param {string} fontSpec The CSS font property.
   * @return {FontParameters|null} The font parameters (or null if the input spec is invalid).
   */
  const getFontParameters = function (fontSpec) {
    const match = fontSpec.match(fontRegEx);
    if (!match) {
      return null;
    }
    const style = /** @type {FontParameters} */ ({
      lineHeight: 'normal',
      size: '1.2em',
      style: 'normal',
      weight: '400',
      variant: 'normal',
    });
    for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) {
      const value = match[i + 1];
      if (value !== undefined) {
        style[fontRegExMatchIndex[i]] =
          typeof value === 'string' ? value.trim() : value;
      }
    }
    if (isNaN(Number(style.weight)) && style.weight in fontWeights$1) {
      style.weight = fontWeights$1[style.weight];
    }
    style.families = style.family
      .split(/,\s?/)
      .map((f) => f.trim().replace(/^['"]|['"]$/g, ''));
    return style;
  };

  /**
   * @module ol/render/canvas
   */

  /**
   * @typedef {'Circle' | 'Image' | 'LineString' | 'Polygon' | 'Text' | 'Default'} BuilderType
   */

  /**
   * @typedef {Object} FillState
   * @property {import("../colorlike.js").ColorLike} fillStyle FillStyle.
   */

  /**
   * @typedef Label
   * @property {number} width Width.
   * @property {number} height Height.
   * @property {Array<string|number>} contextInstructions ContextInstructions.
   */

  /**
   * @typedef {Object} FillStrokeState
   * @property {import("../colorlike.js").ColorLike} [currentFillStyle] Current FillStyle.
   * @property {import("../colorlike.js").ColorLike} [currentStrokeStyle] Current StrokeStyle.
   * @property {CanvasLineCap} [currentLineCap] Current LineCap.
   * @property {Array<number>} currentLineDash Current LineDash.
   * @property {number} [currentLineDashOffset] Current LineDashOffset.
   * @property {CanvasLineJoin} [currentLineJoin] Current LineJoin.
   * @property {number} [currentLineWidth] Current LineWidth.
   * @property {number} [currentMiterLimit] Current MiterLimit.
   * @property {number} [lastStroke] Last stroke.
   * @property {import("../colorlike.js").ColorLike} [fillStyle] FillStyle.
   * @property {import("../colorlike.js").ColorLike} [strokeStyle] StrokeStyle.
   * @property {CanvasLineCap} [lineCap] LineCap.
   * @property {Array<number>} lineDash LineDash.
   * @property {number} [lineDashOffset] LineDashOffset.
   * @property {CanvasLineJoin} [lineJoin] LineJoin.
   * @property {number} [lineWidth] LineWidth.
   * @property {number} [miterLimit] MiterLimit.
   * @property {number} [fillPatternScale] Fill pattern scale.
   */

  /**
   * @typedef {Object} StrokeState
   * @property {CanvasLineCap} lineCap LineCap.
   * @property {Array<number>} lineDash LineDash.
   * @property {number} lineDashOffset LineDashOffset.
   * @property {CanvasLineJoin} lineJoin LineJoin.
   * @property {number} lineWidth LineWidth.
   * @property {number} miterLimit MiterLimit.
   * @property {import("../colorlike.js").ColorLike} strokeStyle StrokeStyle.
   */

  /**
   * @typedef {Object} TextState
   * @property {string} font Font.
   * @property {CanvasTextAlign} [textAlign] TextAlign.
   * @property {number} [repeat] Repeat.
   * @property {import("../style/Text.js").TextJustify} [justify] Justify.
   * @property {CanvasTextBaseline} textBaseline TextBaseline.
   * @property {import("../style/Text.js").TextPlacement} [placement] Placement.
   * @property {number} [maxAngle] MaxAngle.
   * @property {boolean} [overflow] Overflow.
   * @property {import("../style/Fill.js").default} [backgroundFill] BackgroundFill.
   * @property {import("../style/Stroke.js").default} [backgroundStroke] BackgroundStroke.
   * @property {import("../size.js").Size} [scale] Scale.
   * @property {Array<number>} [padding] Padding.
   */

  /**
   * @typedef {Object} SerializableInstructions
   * @property {Array<*>} instructions The rendering instructions.
   * @property {Array<*>} hitDetectionInstructions The rendering hit detection instructions.
   * @property {Array<number>} coordinates The array of all coordinates.
   * @property {!Object<string, TextState>} [textStates] The text states (decluttering).
   * @property {!Object<string, FillState>} [fillStates] The fill states (decluttering).
   * @property {!Object<string, StrokeState>} [strokeStates] The stroke states (decluttering).
   */

  /**
   * @typedef {Object<number, import("./canvas/Executor.js").ReplayImageOrLabelArgs>} DeclutterImageWithText
   */

  /**
   * @const
   * @type {string}
   */
  const defaultFont = '10px sans-serif';

  /**
   * @const
   * @type {string}
   */
  const defaultFillStyle = '#000';

  /**
   * @const
   * @type {CanvasLineCap}
   */
  const defaultLineCap = 'round';

  /**
   * @const
   * @type {Array<number>}
   */
  const defaultLineDash = [];

  /**
   * @const
   * @type {number}
   */
  const defaultLineDashOffset = 0;

  /**
   * @const
   * @type {CanvasLineJoin}
   */
  const defaultLineJoin = 'round';

  /**
   * @const
   * @type {number}
   */
  const defaultMiterLimit = 10;

  /**
   * @const
   * @type {import("../colorlike.js").ColorLike}
   */
  const defaultStrokeStyle = '#000';

  /**
   * @const
   * @type {CanvasTextAlign}
   */
  const defaultTextAlign = 'center';

  /**
   * @const
   * @type {CanvasTextBaseline}
   */
  const defaultTextBaseline = 'middle';

  /**
   * @const
   * @type {Array<number>}
   */
  const defaultPadding = [0, 0, 0, 0];

  /**
   * @const
   * @type {number}
   */
  const defaultLineWidth = 1;

  /**
   * @type {BaseObject}
   */
  const checkedFonts = new BaseObject();

  /**
   * @type {CanvasRenderingContext2D}
   */
  let measureContext$1 = null;

  /**
   * @type {string}
   */
  let measureFont;

  /**
   * @type {!Object<string, number>}
   */
  const textHeights = {};

  const genericFontFamilies = new Set([
    'serif',
    'sans-serif',
    'monospace',
    'cursive',
    'fantasy',
    'system-ui',
    'ui-serif',
    'ui-sans-serif',
    'ui-monospace',
    'ui-rounded',
    'emoji',
    'math',
    'fangsong',
  ]);

  /**
   * @param {string} style Css font-style
   * @param {string} weight Css font-weight
   * @param {string} family Css font-family
   * @return {string} Font key.
   */
  function getFontKey(style, weight, family) {
    return `${style} ${weight} 16px "${family}"`;
  }

  /**
   * Clears the label cache when a font becomes available.
   * @param {string} fontSpec CSS font spec.
   */
  const registerFont = (function () {
    const retries = 100;
    let timeout, fontFaceSet;

    /**
     * @param {string} fontSpec Css font spec
     * @return {Promise<boolean>} Font with style and weight is available
     */
    async function isAvailable(fontSpec) {
      await fontFaceSet.ready;
      const fontFaces = await fontFaceSet.load(fontSpec);
      if (fontFaces.length === 0) {
        return false;
      }
      const font = getFontParameters(fontSpec);
      const checkFamily = font.families[0].toLowerCase();
      const checkWeight = font.weight;
      return fontFaces.some(
        /**
         * @param {import('../css.js').FontParameters} f Font.
         * @return {boolean} Font matches.
         */
        (f) => {
          const family = f.family.replace(/^['"]|['"]$/g, '').toLowerCase();
          const weight = fontWeights$1[f.weight] || f.weight;
          return (
            family === checkFamily &&
            f.style === font.style &&
            weight == checkWeight
          );
        },
      );
    }

    async function check() {
      await fontFaceSet.ready;
      let done = true;
      const checkedFontsProperties = checkedFonts.getProperties();
      const fonts = Object.keys(checkedFontsProperties).filter(
        (key) => checkedFontsProperties[key] < retries,
      );
      for (let i = fonts.length - 1; i >= 0; --i) {
        const font = fonts[i];
        let currentRetries = checkedFontsProperties[font];
        if (currentRetries < retries) {
          if (await isAvailable(font)) {
            clear$2(textHeights);
            checkedFonts.set(font, retries);
          } else {
            currentRetries += 10;
            checkedFonts.set(font, currentRetries, true);
            if (currentRetries < retries) {
              done = false;
            }
          }
        }
      }
      timeout = undefined;
      if (!done) {
        timeout = setTimeout(check, 100);
      }
    }

    return async function (fontSpec) {
      if (!fontFaceSet) {
        fontFaceSet = WORKER_OFFSCREEN_CANVAS ? self.fonts : document.fonts;
      }
      const font = getFontParameters(fontSpec);
      if (!font) {
        return;
      }
      const families = font.families;
      let needCheck = false;
      for (const family of families) {
        if (genericFontFamilies.has(family)) {
          continue;
        }
        const key = getFontKey(font.style, font.weight, family);
        if (checkedFonts.get(key) !== undefined) {
          continue;
        }
        checkedFonts.set(key, 0, true);
        needCheck = true;
      }
      if (needCheck) {
        clearTimeout(timeout);
        timeout = setTimeout(check, 100);
      }
    };
  })();

  /**
   * @param {string} font Font to use for measuring.
   * @return {import("../size.js").Size} Measurement.
   */
  const measureTextHeight = (function () {
    /**
     * @type {HTMLDivElement}
     */
    let measureElement;
    return function (fontSpec) {
      let height = textHeights[fontSpec];
      if (height == undefined) {
        if (WORKER_OFFSCREEN_CANVAS) {
          const font = getFontParameters(fontSpec);
          const metrics = measureText$1(fontSpec, 'Žg');
          const lineHeight = isNaN(Number(font.lineHeight))
            ? 1.2
            : Number(font.lineHeight);
          height =
            lineHeight *
            (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent);
        } else {
          if (!measureElement) {
            measureElement = document.createElement('div');
            measureElement.innerHTML = 'M';
            measureElement.style.minHeight = '0';
            measureElement.style.maxHeight = 'none';
            measureElement.style.height = 'auto';
            measureElement.style.padding = '0';
            measureElement.style.border = 'none';
            measureElement.style.position = 'absolute';
            measureElement.style.display = 'block';
            measureElement.style.left = '-99999px';
          }
          measureElement.style.font = fontSpec;
          document.body.appendChild(measureElement);
          height = measureElement.offsetHeight;
          document.body.removeChild(measureElement);
        }
        textHeights[fontSpec] = height;
      }
      return height;
    };
  })();

  /**
   * @param {string} font Font.
   * @param {string} text Text.
   * @return {TextMetrics} Text metrics.
   */
  function measureText$1(font, text) {
    if (!measureContext$1) {
      measureContext$1 = createCanvasContext2D(1, 1);
    }
    if (font != measureFont) {
      measureContext$1.font = font;
      measureFont = measureContext$1.font;
    }
    return measureContext$1.measureText(text);
  }

  /**
   * @param {string} font Font.
   * @param {string} text Text.
   * @return {number} Width.
   */
  function measureTextWidth(font, text) {
    return measureText$1(font, text).width;
  }

  /**
   * Measure text width using a cache.
   * @param {string} font The font.
   * @param {string} text The text to measure.
   * @param {Object<string, number>} cache A lookup of cached widths by text.
   * @return {number} The text width.
   */
  function measureAndCacheTextWidth(font, text, cache) {
    if (text in cache) {
      return cache[text];
    }
    const width = text
      .split('\n')
      .reduce((prev, curr) => Math.max(prev, measureTextWidth(font, curr)), 0);
    cache[text] = width;
    return width;
  }

  /**
   * @param {TextState} baseStyle Base style.
   * @param {Array<string>} chunks Text chunks to measure.
   * @return {{width: number, height: number, widths: Array<number>, heights: Array<number>, lineWidths: Array<number>}}} Text metrics.
   */
  function getTextDimensions(baseStyle, chunks) {
    const widths = [];
    const heights = [];
    const lineWidths = [];
    let width = 0;
    let lineWidth = 0;
    let height = 0;
    let lineHeight = 0;
    for (let i = 0, ii = chunks.length; i <= ii; i += 2) {
      const text = chunks[i];
      if (text === '\n' || i === ii) {
        width = Math.max(width, lineWidth);
        lineWidths.push(lineWidth);
        lineWidth = 0;
        height += lineHeight;
        lineHeight = 0;
        continue;
      }
      const font = chunks[i + 1] || baseStyle.font;
      const currentWidth = measureTextWidth(font, text);
      widths.push(currentWidth);
      lineWidth += currentWidth;
      const currentHeight = measureTextHeight(font);
      heights.push(currentHeight);
      lineHeight = Math.max(lineHeight, currentHeight);
    }
    return {width, height, widths, heights, lineWidths};
  }

  /**
   * @param {CanvasRenderingContext2D|import("../render/canvas/ZIndexContext.js").ZIndexContextProxy} context Context.
   * @param {import("../transform.js").Transform|null} transform Transform.
   * @param {number} opacity Opacity.
   * @param {Label|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} labelOrImage Label.
   * @param {number} originX Origin X.
   * @param {number} originY Origin Y.
   * @param {number} w Width.
   * @param {number} h Height.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {import("../size.js").Size} scale Scale.
   */
  function drawImageOrLabel(
    context,
    transform,
    opacity,
    labelOrImage,
    originX,
    originY,
    w,
    h,
    x,
    y,
    scale,
  ) {
    context.save();

    if (opacity !== 1) {
      if (context.globalAlpha === undefined) {
        context.globalAlpha = (context) => (context.globalAlpha *= opacity);
      } else {
        context.globalAlpha *= opacity;
      }
    }
    if (transform) {
      context.transform.apply(context, transform);
    }

    if (/** @type {*} */ (labelOrImage).contextInstructions) {
      // label
      context.translate(x, y);
      context.scale(scale[0], scale[1]);
      executeLabelInstructions(/** @type {Label} */ (labelOrImage), context);
    } else if (scale[0] < 0 || scale[1] < 0) {
      // flipped image
      context.translate(x, y);
      context.scale(scale[0], scale[1]);
      context.drawImage(
        /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (
          labelOrImage
        ),
        originX,
        originY,
        w,
        h,
        0,
        0,
        w,
        h,
      );
    } else {
      // if image not flipped translate and scale can be avoided
      context.drawImage(
        /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (
          labelOrImage
        ),
        originX,
        originY,
        w,
        h,
        x,
        y,
        w * scale[0],
        h * scale[1],
      );
    }

    context.restore();
  }

  /**
   * @param {Label} label Label.
   * @param {CanvasRenderingContext2D} context Context.
   */
  function executeLabelInstructions(label, context) {
    const contextInstructions = label.contextInstructions;
    for (let i = 0, ii = contextInstructions.length; i < ii; i += 2) {
      if (Array.isArray(contextInstructions[i + 1])) {
        context[contextInstructions[i]].apply(
          context,
          contextInstructions[i + 1],
        );
      } else {
        context[contextInstructions[i]] = contextInstructions[i + 1];
      }
    }
  }

  /**
   * @module ol/render/canvas/Immediate
   */
  // FIXME test, especially polygons with holes and multipolygons
  // FIXME need to handle large thick features (where pixel size matters)
  // FIXME add offset and end to ol/geom/flat/transform~transform2D?


  /**
   * @classdesc
   * A concrete subclass of {@link module:ol/render/VectorContext~VectorContext} that implements
   * direct rendering of features and geometries to an HTML5 Canvas context.
   * Instances of this class are created internally by the library and
   * provided to application code as vectorContext member of the
   * {@link module:ol/render/Event~RenderEvent} object associated with postcompose, precompose and
   * render events emitted by layers and maps.
   */
  class CanvasImmediateRenderer extends VectorContext {
    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../extent.js").Extent} extent Extent.
     * @param {import("../../transform.js").Transform} transform Transform.
     * @param {number} viewRotation View rotation.
     * @param {number} [squaredTolerance] Optional squared tolerance for simplification.
     * @param {import("../../proj.js").TransformFunction} [userTransform] Transform from user to view projection.
     */
    constructor(
      context,
      pixelRatio,
      extent,
      transform,
      viewRotation,
      squaredTolerance,
      userTransform,
    ) {
      super();

      /**
       * @private
       * @type {CanvasRenderingContext2D}
       */
      this.context_ = context;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = pixelRatio;

      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.extent_ = extent;

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.transform_ = transform;

      /**
       * @private
       * @type {number}
       */
      this.transformRotation_ = transform
        ? toFixed(Math.atan2(transform[1], transform[0]), 10)
        : 0;

      /**
       * @private
       * @type {number}
       */
      this.viewRotation_ = viewRotation;

      /**
       * @private
       * @type {number}
       */
      this.squaredTolerance_ = squaredTolerance;

      /**
       * @private
       * @type {import("../../proj.js").TransformFunction}
       */
      this.userTransform_ = userTransform;

      /**
       * @private
       * @type {?import("../canvas.js").FillState}
       */
      this.contextFillState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").StrokeState}
       */
      this.contextStrokeState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").TextState}
       */
      this.contextTextState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").FillState}
       */
      this.fillState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").StrokeState}
       */
      this.strokeState_ = null;

      /**
       * @private
       * @type {import('../../DataTile.js').ImageLike}
       */
      this.image_ = null;

      /**
       * @private
       * @type {number}
       */
      this.imageAnchorX_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.imageAnchorY_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.imageHeight_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.imageOpacity_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.imageOriginX_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.imageOriginY_ = 0;

      /**
       * @private
       * @type {boolean}
       */
      this.imageRotateWithView_ = false;

      /**
       * @private
       * @type {number}
       */
      this.imageRotation_ = 0;

      /**
       * @private
       * @type {import("../../size.js").Size}
       */
      this.imageScale_ = [0, 0];

      /**
       * @private
       * @type {number}
       */
      this.imageWidth_ = 0;

      /**
       * @private
       * @type {string}
       */
      this.text_ = '';

      /**
       * @private
       * @type {number}
       */
      this.textOffsetX_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.textOffsetY_ = 0;

      /**
       * @private
       * @type {boolean}
       */
      this.textRotateWithView_ = false;

      /**
       * @private
       * @type {number}
       */
      this.textRotation_ = 0;

      /**
       * @private
       * @type {import("../../size.js").Size}
       */
      this.textScale_ = [0, 0];

      /**
       * @private
       * @type {?import("../canvas.js").FillState}
       */
      this.textFillState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").StrokeState}
       */
      this.textStrokeState_ = null;

      /**
       * @private
       * @type {?import("../canvas.js").TextState}
       */
      this.textState_ = null;

      /**
       * @private
       * @type {Array<number>}
       */
      this.pixelCoordinates_ = [];

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.tmpLocalTransform_ = create$3();
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {number} end End.
     * @param {number} stride Stride.
     * @private
     */
    drawImages_(flatCoordinates, offset, end, stride) {
      if (!this.image_) {
        return;
      }
      const pixelCoordinates = transform2D(
        flatCoordinates,
        offset,
        end,
        stride,
        this.transform_,
        this.pixelCoordinates_,
      );
      const context = this.context_;
      const localTransform = this.tmpLocalTransform_;
      const alpha = context.globalAlpha;
      if (this.imageOpacity_ != 1) {
        context.globalAlpha = alpha * this.imageOpacity_;
      }
      let rotation = this.imageRotation_;
      if (this.transformRotation_ === 0) {
        rotation -= this.viewRotation_;
      }
      if (this.imageRotateWithView_) {
        rotation += this.viewRotation_;
      }
      for (let i = 0, ii = pixelCoordinates.length; i < ii; i += 2) {
        const x = pixelCoordinates[i] - this.imageAnchorX_;
        const y = pixelCoordinates[i + 1] - this.imageAnchorY_;
        if (
          rotation !== 0 ||
          this.imageScale_[0] != 1 ||
          this.imageScale_[1] != 1
        ) {
          const centerX = x + this.imageAnchorX_;
          const centerY = y + this.imageAnchorY_;
          compose(
            localTransform,
            centerX,
            centerY,
            1,
            1,
            rotation,
            -centerX,
            -centerY,
          );
          context.save();
          context.transform.apply(context, localTransform);
          context.translate(centerX, centerY);
          context.scale(this.imageScale_[0], this.imageScale_[1]);
          context.drawImage(
            this.image_,
            this.imageOriginX_,
            this.imageOriginY_,
            this.imageWidth_,
            this.imageHeight_,
            -this.imageAnchorX_,
            -this.imageAnchorY_,
            this.imageWidth_,
            this.imageHeight_,
          );
          context.restore();
        } else {
          context.drawImage(
            this.image_,
            this.imageOriginX_,
            this.imageOriginY_,
            this.imageWidth_,
            this.imageHeight_,
            x,
            y,
            this.imageWidth_,
            this.imageHeight_,
          );
        }
      }
      if (this.imageOpacity_ != 1) {
        context.globalAlpha = alpha;
      }
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {number} end End.
     * @param {number} stride Stride.
     * @private
     */
    drawText_(flatCoordinates, offset, end, stride) {
      if (!this.textState_ || this.text_ === '') {
        return;
      }
      if (this.textFillState_) {
        this.setContextFillState_(this.textFillState_);
      }
      if (this.textStrokeState_) {
        this.setContextStrokeState_(this.textStrokeState_);
      }
      this.setContextTextState_(this.textState_);
      const pixelCoordinates = transform2D(
        flatCoordinates,
        offset,
        end,
        stride,
        this.transform_,
        this.pixelCoordinates_,
      );
      const context = this.context_;
      let rotation = this.textRotation_;
      if (this.transformRotation_ === 0) {
        rotation -= this.viewRotation_;
      }
      if (this.textRotateWithView_) {
        rotation += this.viewRotation_;
      }
      for (; offset < end; offset += stride) {
        const x = pixelCoordinates[offset] + this.textOffsetX_;
        const y = pixelCoordinates[offset + 1] + this.textOffsetY_;
        if (
          rotation !== 0 ||
          this.textScale_[0] != 1 ||
          this.textScale_[1] != 1
        ) {
          context.save();
          context.translate(x - this.textOffsetX_, y - this.textOffsetY_);
          context.rotate(rotation);
          context.translate(this.textOffsetX_, this.textOffsetY_);
          context.scale(this.textScale_[0], this.textScale_[1]);
          if (this.textStrokeState_) {
            context.strokeText(this.text_, 0, 0);
          }
          if (this.textFillState_) {
            context.fillText(this.text_, 0, 0);
          }
          context.restore();
        } else {
          if (this.textStrokeState_) {
            context.strokeText(this.text_, x, y);
          }
          if (this.textFillState_) {
            context.fillText(this.text_, x, y);
          }
        }
      }
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {number} end End.
     * @param {number} stride Stride.
     * @param {boolean} close Close.
     * @private
     * @return {number} end End.
     */
    moveToLineTo_(flatCoordinates, offset, end, stride, close) {
      const context = this.context_;
      const pixelCoordinates = transform2D(
        flatCoordinates,
        offset,
        end,
        stride,
        this.transform_,
        this.pixelCoordinates_,
      );
      context.moveTo(pixelCoordinates[0], pixelCoordinates[1]);
      let length = pixelCoordinates.length;
      if (close) {
        length -= 2;
      }
      for (let i = 2; i < length; i += 2) {
        context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]);
      }
      if (close) {
        context.closePath();
      }
      return end;
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {Array<number>} ends Ends.
     * @param {number} stride Stride.
     * @private
     * @return {number} End.
     */
    drawRings_(flatCoordinates, offset, ends, stride) {
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        offset = this.moveToLineTo_(
          flatCoordinates,
          offset,
          ends[i],
          stride,
          true,
        );
      }
      return offset;
    }

    /**
     * Render a circle geometry into the canvas.  Rendering is immediate and uses
     * the current fill and stroke styles.
     *
     * @param {import("../../geom/Circle.js").default} geometry Circle geometry.
     * @api
     * @override
     */
    drawCircle(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/Circle.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      if (!intersects$2(this.extent_, geometry.getExtent())) {
        return;
      }
      if (this.fillState_ || this.strokeState_) {
        if (this.fillState_) {
          this.setContextFillState_(this.fillState_);
        }
        if (this.strokeState_) {
          this.setContextStrokeState_(this.strokeState_);
        }
        const pixelCoordinates = transformGeom2D(
          geometry,
          this.transform_,
          this.pixelCoordinates_,
        );
        const dx = pixelCoordinates[2] - pixelCoordinates[0];
        const dy = pixelCoordinates[3] - pixelCoordinates[1];
        const radius = Math.sqrt(dx * dx + dy * dy);
        const context = this.context_;
        context.beginPath();
        context.arc(
          pixelCoordinates[0],
          pixelCoordinates[1],
          radius,
          0,
          2 * Math.PI,
        );
        if (this.fillState_) {
          context.fill();
        }
        if (this.strokeState_) {
          context.stroke();
        }
      }
      if (this.text_ !== '') {
        this.drawText_(geometry.getCenter(), 0, 2, 2);
      }
    }

    /**
     * Set the rendering style.  Note that since this is an immediate rendering API,
     * any `zIndex` on the provided style will be ignored.
     *
     * @param {import("../../style/Style.js").default} style The rendering style.
     * @api
     * @override
     */
    setStyle(style) {
      this.setFillStrokeStyle(style.getFill(), style.getStroke());
      this.setImageStyle(style.getImage());
      this.setTextStyle(style.getText());
    }

    /**
     * @param {import("../../transform.js").Transform} transform Transform.
     */
    setTransform(transform) {
      this.transform_ = transform;
    }

    /**
     * Render a geometry into the canvas.  Call
     * {@link module:ol/render/canvas/Immediate~CanvasImmediateRenderer#setStyle renderer.setStyle()} first to set the rendering style.
     *
     * @param {import("../../geom/Geometry.js").default|import("../Feature.js").default} geometry The geometry to render.
     * @api
     * @override
     */
    drawGeometry(geometry) {
      const type = geometry.getType();
      switch (type) {
        case 'Point':
          this.drawPoint(
            /** @type {import("../../geom/Point.js").default} */ (geometry),
          );
          break;
        case 'LineString':
          this.drawLineString(
            /** @type {import("../../geom/LineString.js").default} */ (geometry),
          );
          break;
        case 'Polygon':
          this.drawPolygon(
            /** @type {import("../../geom/Polygon.js").default} */ (geometry),
          );
          break;
        case 'MultiPoint':
          this.drawMultiPoint(
            /** @type {import("../../geom/MultiPoint.js").default} */ (geometry),
          );
          break;
        case 'MultiLineString':
          this.drawMultiLineString(
            /** @type {import("../../geom/MultiLineString.js").default} */ (
              geometry
            ),
          );
          break;
        case 'MultiPolygon':
          this.drawMultiPolygon(
            /** @type {import("../../geom/MultiPolygon.js").default} */ (
              geometry
            ),
          );
          break;
        case 'GeometryCollection':
          this.drawGeometryCollection(
            /** @type {import("../../geom/GeometryCollection.js").default} */ (
              geometry
            ),
          );
          break;
        case 'Circle':
          this.drawCircle(
            /** @type {import("../../geom/Circle.js").default} */ (geometry),
          );
          break;
      }
    }

    /**
     * Render a feature into the canvas.  Note that any `zIndex` on the provided
     * style will be ignored - features are rendered immediately in the order that
     * this method is called.  If you need `zIndex` support, you should be using an
     * {@link module:ol/layer/Vector~VectorLayer} instead.
     *
     * @param {import("../../Feature.js").default} feature Feature.
     * @param {import("../../style/Style.js").default} style Style.
     * @api
     * @override
     */
    drawFeature(feature, style) {
      const geometry = style.getGeometryFunction()(feature);
      if (!geometry) {
        return;
      }
      this.setStyle(style);
      this.drawGeometry(geometry);
    }

    /**
     * Render a GeometryCollection to the canvas.  Rendering is immediate and
     * uses the current styles appropriate for each geometry in the collection.
     *
     * @param {import("../../geom/GeometryCollection.js").default} geometry Geometry collection.
     * @override
     */
    drawGeometryCollection(geometry) {
      const geometries = geometry.getGeometriesArray();
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        this.drawGeometry(geometries[i]);
      }
    }

    /**
     * Render a Point geometry into the canvas.  Rendering is immediate and uses
     * the current style.
     *
     * @param {import("../../geom/Point.js").default|import("../Feature.js").default} geometry Point geometry.
     * @override
     */
    drawPoint(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/Point.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      const flatCoordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      if (this.image_) {
        this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);
      }
      if (this.text_ !== '') {
        this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);
      }
    }

    /**
     * Render a MultiPoint geometry  into the canvas.  Rendering is immediate and
     * uses the current style.
     *
     * @param {import("../../geom/MultiPoint.js").default|import("../Feature.js").default} geometry MultiPoint geometry.
     * @override
     */
    drawMultiPoint(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/MultiPoint.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      const flatCoordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      if (this.image_) {
        this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);
      }
      if (this.text_ !== '') {
        this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);
      }
    }

    /**
     * Render a LineString into the canvas.  Rendering is immediate and uses
     * the current style.
     *
     * @param {import("../../geom/LineString.js").default|import("../Feature.js").default} geometry LineString geometry.
     * @override
     */
    drawLineString(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/LineString.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      if (!intersects$2(this.extent_, geometry.getExtent())) {
        return;
      }
      if (this.strokeState_) {
        this.setContextStrokeState_(this.strokeState_);
        const context = this.context_;
        const flatCoordinates = geometry.getFlatCoordinates();
        context.beginPath();
        this.moveToLineTo_(
          flatCoordinates,
          0,
          flatCoordinates.length,
          geometry.getStride(),
          false,
        );
        context.stroke();
      }
      if (this.text_ !== '') {
        const flatMidpoint = geometry.getFlatMidpoint();
        this.drawText_(flatMidpoint, 0, 2, 2);
      }
    }

    /**
     * Render a MultiLineString geometry into the canvas.  Rendering is immediate
     * and uses the current style.
     *
     * @param {import("../../geom/MultiLineString.js").default|import("../Feature.js").default} geometry MultiLineString geometry.
     * @override
     */
    drawMultiLineString(geometry) {
      if (this.squaredTolerance_) {
        geometry =
          /** @type {import("../../geom/MultiLineString.js").default} */ (
            geometry.simplifyTransformed(
              this.squaredTolerance_,
              this.userTransform_,
            )
          );
      }
      const geometryExtent = geometry.getExtent();
      if (!intersects$2(this.extent_, geometryExtent)) {
        return;
      }
      if (this.strokeState_) {
        this.setContextStrokeState_(this.strokeState_);
        const context = this.context_;
        const flatCoordinates = geometry.getFlatCoordinates();
        let offset = 0;
        const ends = /** @type {Array<number>} */ (geometry.getEnds());
        const stride = geometry.getStride();
        context.beginPath();
        for (let i = 0, ii = ends.length; i < ii; ++i) {
          offset = this.moveToLineTo_(
            flatCoordinates,
            offset,
            ends[i],
            stride,
            false,
          );
        }
        context.stroke();
      }
      if (this.text_ !== '') {
        const flatMidpoints = geometry.getFlatMidpoints();
        this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2);
      }
    }

    /**
     * Render a Polygon geometry into the canvas.  Rendering is immediate and uses
     * the current style.
     *
     * @param {import("../../geom/Polygon.js").default|import("../Feature.js").default} geometry Polygon geometry.
     * @override
     */
    drawPolygon(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/Polygon.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      if (!intersects$2(this.extent_, geometry.getExtent())) {
        return;
      }
      if (this.strokeState_ || this.fillState_) {
        if (this.fillState_) {
          this.setContextFillState_(this.fillState_);
        }
        if (this.strokeState_) {
          this.setContextStrokeState_(this.strokeState_);
        }
        const context = this.context_;
        context.beginPath();
        this.drawRings_(
          geometry.getOrientedFlatCoordinates(),
          0,
          /** @type {Array<number>} */ (geometry.getEnds()),
          geometry.getStride(),
        );
        if (this.fillState_) {
          context.fill();
        }
        if (this.strokeState_) {
          context.stroke();
        }
      }
      if (this.text_ !== '') {
        const flatInteriorPoint = geometry.getFlatInteriorPoint();
        this.drawText_(flatInteriorPoint, 0, 2, 2);
      }
    }

    /**
     * Render MultiPolygon geometry into the canvas.  Rendering is immediate and
     * uses the current style.
     * @param {import("../../geom/MultiPolygon.js").default} geometry MultiPolygon geometry.
     * @override
     */
    drawMultiPolygon(geometry) {
      if (this.squaredTolerance_) {
        geometry = /** @type {import("../../geom/MultiPolygon.js").default} */ (
          geometry.simplifyTransformed(
            this.squaredTolerance_,
            this.userTransform_,
          )
        );
      }
      if (!intersects$2(this.extent_, geometry.getExtent())) {
        return;
      }
      if (this.strokeState_ || this.fillState_) {
        if (this.fillState_) {
          this.setContextFillState_(this.fillState_);
        }
        if (this.strokeState_) {
          this.setContextStrokeState_(this.strokeState_);
        }
        const context = this.context_;
        const flatCoordinates = geometry.getOrientedFlatCoordinates();
        let offset = 0;
        const endss = geometry.getEndss();
        const stride = geometry.getStride();
        context.beginPath();
        for (let i = 0, ii = endss.length; i < ii; ++i) {
          const ends = endss[i];
          offset = this.drawRings_(flatCoordinates, offset, ends, stride);
        }
        if (this.fillState_) {
          context.fill();
        }
        if (this.strokeState_) {
          context.stroke();
        }
      }
      if (this.text_ !== '') {
        const flatInteriorPoints = geometry.getFlatInteriorPoints();
        this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2);
      }
    }

    /**
     * @param {import("../canvas.js").FillState} fillState Fill state.
     * @private
     */
    setContextFillState_(fillState) {
      const context = this.context_;
      const contextFillState = this.contextFillState_;
      if (!contextFillState) {
        context.fillStyle = fillState.fillStyle;
        this.contextFillState_ = {
          fillStyle: fillState.fillStyle,
        };
      } else {
        if (contextFillState.fillStyle != fillState.fillStyle) {
          contextFillState.fillStyle = fillState.fillStyle;
          context.fillStyle = fillState.fillStyle;
        }
      }
    }

    /**
     * @param {import("../canvas.js").StrokeState} strokeState Stroke state.
     * @private
     */
    setContextStrokeState_(strokeState) {
      const context = this.context_;
      const contextStrokeState = this.contextStrokeState_;
      if (!contextStrokeState) {
        context.lineCap = strokeState.lineCap;
        context.setLineDash(strokeState.lineDash);
        context.lineDashOffset = strokeState.lineDashOffset;
        context.lineJoin = strokeState.lineJoin;
        context.lineWidth = strokeState.lineWidth;
        context.miterLimit = strokeState.miterLimit;
        context.strokeStyle = strokeState.strokeStyle;
        this.contextStrokeState_ = {
          lineCap: strokeState.lineCap,
          lineDash: strokeState.lineDash,
          lineDashOffset: strokeState.lineDashOffset,
          lineJoin: strokeState.lineJoin,
          lineWidth: strokeState.lineWidth,
          miterLimit: strokeState.miterLimit,
          strokeStyle: strokeState.strokeStyle,
        };
      } else {
        if (contextStrokeState.lineCap != strokeState.lineCap) {
          contextStrokeState.lineCap = strokeState.lineCap;
          context.lineCap = strokeState.lineCap;
        }
        if (!equals$2(contextStrokeState.lineDash, strokeState.lineDash)) {
          context.setLineDash(
            (contextStrokeState.lineDash = strokeState.lineDash),
          );
        }
        if (contextStrokeState.lineDashOffset != strokeState.lineDashOffset) {
          contextStrokeState.lineDashOffset = strokeState.lineDashOffset;
          context.lineDashOffset = strokeState.lineDashOffset;
        }
        if (contextStrokeState.lineJoin != strokeState.lineJoin) {
          contextStrokeState.lineJoin = strokeState.lineJoin;
          context.lineJoin = strokeState.lineJoin;
        }
        if (contextStrokeState.lineWidth != strokeState.lineWidth) {
          contextStrokeState.lineWidth = strokeState.lineWidth;
          context.lineWidth = strokeState.lineWidth;
        }
        if (contextStrokeState.miterLimit != strokeState.miterLimit) {
          contextStrokeState.miterLimit = strokeState.miterLimit;
          context.miterLimit = strokeState.miterLimit;
        }
        if (contextStrokeState.strokeStyle != strokeState.strokeStyle) {
          contextStrokeState.strokeStyle = strokeState.strokeStyle;
          context.strokeStyle = strokeState.strokeStyle;
        }
      }
    }

    /**
     * @param {import("../canvas.js").TextState} textState Text state.
     * @private
     */
    setContextTextState_(textState) {
      const context = this.context_;
      const contextTextState = this.contextTextState_;
      const textAlign = textState.textAlign
        ? textState.textAlign
        : defaultTextAlign;
      if (!contextTextState) {
        context.font = textState.font;
        context.textAlign = textAlign;
        context.textBaseline = textState.textBaseline;
        this.contextTextState_ = {
          font: textState.font,
          textAlign: textAlign,
          textBaseline: textState.textBaseline,
        };
      } else {
        if (contextTextState.font != textState.font) {
          contextTextState.font = textState.font;
          context.font = textState.font;
        }
        if (contextTextState.textAlign != textAlign) {
          contextTextState.textAlign = textAlign;
          context.textAlign = textAlign;
        }
        if (contextTextState.textBaseline != textState.textBaseline) {
          contextTextState.textBaseline = textState.textBaseline;
          context.textBaseline = textState.textBaseline;
        }
      }
    }

    /**
     * Set the fill and stroke style for subsequent draw operations.  To clear
     * either fill or stroke styles, pass null for the appropriate parameter.
     *
     * @param {import("../../style/Fill.js").default} fillStyle Fill style.
     * @param {import("../../style/Stroke.js").default} strokeStyle Stroke style.
     * @override
     */
    setFillStrokeStyle(fillStyle, strokeStyle) {
      if (!fillStyle) {
        this.fillState_ = null;
      } else {
        const fillStyleColor = fillStyle.getColor();
        this.fillState_ = {
          fillStyle: asColorLike(
            fillStyleColor ? fillStyleColor : defaultFillStyle,
          ),
        };
      }
      if (!strokeStyle) {
        this.strokeState_ = null;
      } else {
        const strokeStyleColor = strokeStyle.getColor();
        const strokeStyleLineCap = strokeStyle.getLineCap();
        const strokeStyleLineDash = strokeStyle.getLineDash();
        const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset();
        const strokeStyleLineJoin = strokeStyle.getLineJoin();
        const strokeStyleWidth = strokeStyle.getWidth();
        const strokeStyleMiterLimit = strokeStyle.getMiterLimit();
        const lineDash = strokeStyleLineDash
          ? strokeStyleLineDash
          : defaultLineDash;
        this.strokeState_ = {
          lineCap:
            strokeStyleLineCap !== undefined
              ? strokeStyleLineCap
              : defaultLineCap,
          lineDash:
            this.pixelRatio_ === 1
              ? lineDash
              : lineDash.map((n) => n * this.pixelRatio_),
          lineDashOffset:
            (strokeStyleLineDashOffset
              ? strokeStyleLineDashOffset
              : defaultLineDashOffset) * this.pixelRatio_,
          lineJoin:
            strokeStyleLineJoin !== undefined
              ? strokeStyleLineJoin
              : defaultLineJoin,
          lineWidth:
            (strokeStyleWidth !== undefined
              ? strokeStyleWidth
              : defaultLineWidth) * this.pixelRatio_,
          miterLimit:
            strokeStyleMiterLimit !== undefined
              ? strokeStyleMiterLimit
              : defaultMiterLimit,
          strokeStyle: asColorLike(
            strokeStyleColor ? strokeStyleColor : defaultStrokeStyle,
          ),
        };
      }
    }

    /**
     * Set the image style for subsequent draw operations.  Pass null to remove
     * the image style.
     *
     * @param {import("../../style/Image.js").default} imageStyle Image style.
     * @override
     */
    setImageStyle(imageStyle) {
      let imageSize;
      if (!imageStyle || !(imageSize = imageStyle.getSize())) {
        this.image_ = null;
        return;
      }
      const imagePixelRatio = imageStyle.getPixelRatio(this.pixelRatio_);
      const imageAnchor = imageStyle.getAnchor();
      const imageOrigin = imageStyle.getOrigin();
      this.image_ = imageStyle.getImage(this.pixelRatio_);
      this.imageAnchorX_ = imageAnchor[0] * imagePixelRatio;
      this.imageAnchorY_ = imageAnchor[1] * imagePixelRatio;
      this.imageHeight_ = imageSize[1] * imagePixelRatio;
      this.imageOpacity_ = imageStyle.getOpacity();
      this.imageOriginX_ = imageOrigin[0];
      this.imageOriginY_ = imageOrigin[1];
      this.imageRotateWithView_ = imageStyle.getRotateWithView();
      this.imageRotation_ = imageStyle.getRotation();
      const imageScale = imageStyle.getScaleArray();
      this.imageScale_ = [
        (imageScale[0] * this.pixelRatio_) / imagePixelRatio,
        (imageScale[1] * this.pixelRatio_) / imagePixelRatio,
      ];
      this.imageWidth_ = imageSize[0] * imagePixelRatio;
    }

    /**
     * Set the text style for subsequent draw operations.  Pass null to
     * remove the text style.
     *
     * @param {import("../../style/Text.js").default} textStyle Text style.
     * @override
     */
    setTextStyle(textStyle) {
      if (!textStyle) {
        this.text_ = '';
      } else {
        const textFillStyle = textStyle.getFill();
        if (!textFillStyle) {
          this.textFillState_ = null;
        } else {
          const textFillStyleColor = textFillStyle.getColor();
          this.textFillState_ = {
            fillStyle: asColorLike(
              textFillStyleColor ? textFillStyleColor : defaultFillStyle,
            ),
          };
        }
        const textStrokeStyle = textStyle.getStroke();
        if (!textStrokeStyle) {
          this.textStrokeState_ = null;
        } else {
          const textStrokeStyleColor = textStrokeStyle.getColor();
          const textStrokeStyleLineCap = textStrokeStyle.getLineCap();
          const textStrokeStyleLineDash = textStrokeStyle.getLineDash();
          const textStrokeStyleLineDashOffset =
            textStrokeStyle.getLineDashOffset();
          const textStrokeStyleLineJoin = textStrokeStyle.getLineJoin();
          const textStrokeStyleWidth = textStrokeStyle.getWidth();
          const textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit();
          this.textStrokeState_ = {
            lineCap:
              textStrokeStyleLineCap !== undefined
                ? textStrokeStyleLineCap
                : defaultLineCap,
            lineDash: textStrokeStyleLineDash
              ? textStrokeStyleLineDash
              : defaultLineDash,
            lineDashOffset: textStrokeStyleLineDashOffset
              ? textStrokeStyleLineDashOffset
              : defaultLineDashOffset,
            lineJoin:
              textStrokeStyleLineJoin !== undefined
                ? textStrokeStyleLineJoin
                : defaultLineJoin,
            lineWidth:
              textStrokeStyleWidth !== undefined
                ? textStrokeStyleWidth
                : defaultLineWidth,
            miterLimit:
              textStrokeStyleMiterLimit !== undefined
                ? textStrokeStyleMiterLimit
                : defaultMiterLimit,
            strokeStyle: asColorLike(
              textStrokeStyleColor ? textStrokeStyleColor : defaultStrokeStyle,
            ),
          };
        }
        const textFont = textStyle.getFont();
        const textOffsetX = textStyle.getOffsetX();
        const textOffsetY = textStyle.getOffsetY();
        const textRotateWithView = textStyle.getRotateWithView();
        const textRotation = textStyle.getRotation();
        const textScale = textStyle.getScaleArray();
        const textText = textStyle.getText();
        const textTextAlign = textStyle.getTextAlign();
        const textTextBaseline = textStyle.getTextBaseline();
        this.textState_ = {
          font: textFont !== undefined ? textFont : defaultFont,
          textAlign:
            textTextAlign !== undefined ? textTextAlign : defaultTextAlign,
          textBaseline:
            textTextBaseline !== undefined
              ? textTextBaseline
              : defaultTextBaseline,
        };
        this.text_ =
          textText !== undefined
            ? Array.isArray(textText)
              ? textText.reduce((acc, t, i) => (acc += i % 2 ? ' ' : t), '')
              : textText
            : '';
        this.textOffsetX_ =
          textOffsetX !== undefined ? this.pixelRatio_ * textOffsetX : 0;
        this.textOffsetY_ =
          textOffsetY !== undefined ? this.pixelRatio_ * textOffsetY : 0;
        this.textRotateWithView_ =
          textRotateWithView !== undefined ? textRotateWithView : false;
        this.textRotation_ = textRotation !== undefined ? textRotation : 0;
        this.textScale_ = [
          this.pixelRatio_ * textScale[0],
          this.pixelRatio_ * textScale[1],
        ];
      }
    }
  }

  /**
   * @module ol/renderer/vector
   */

  /**
   * Feature callback. The callback will be called with three arguments. The first
   * argument is one {@link module:ol/Feature~Feature feature} or {@link module:ol/render/Feature~RenderFeature render feature}
   * at the pixel, the second is the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for
   * unmanaged layers. The third is the {@link module:ol/geom/SimpleGeometry~SimpleGeometry} of the feature. For features
   * with a GeometryCollection geometry, it will be the first detected geometry from the collection.
   * @template T
   * @typedef {function(import("../Feature.js").FeatureLike, import("../layer/Layer.js").default<import("../source/Source").default>, import("../geom/SimpleGeometry.js").default): T} FeatureCallback
   */

  /**
   * Tolerance for geometry simplification in device pixels.
   * @type {number}
   */
  const SIMPLIFY_TOLERANCE = 0.5;

  /**
   * @const
   * @type {Object<import("../geom/Geometry.js").Type,
   *                function(import("../render/canvas/BuilderGroup.js").default, import("../geom/Geometry.js").default,
   *                         import("../style/Style.js").default, Object): void>}
   */
  const GEOMETRY_RENDERERS = {
    'Point': renderPointGeometry,
    'LineString': renderLineStringGeometry,
    'Polygon': renderPolygonGeometry,
    'MultiPoint': renderMultiPointGeometry,
    'MultiLineString': renderMultiLineStringGeometry,
    'MultiPolygon': renderMultiPolygonGeometry,
    'GeometryCollection': renderGeometryCollectionGeometry,
    'Circle': renderCircleGeometry,
  };

  /**
   * @param {import("../Feature.js").FeatureLike} feature1 Feature 1.
   * @param {import("../Feature.js").FeatureLike} feature2 Feature 2.
   * @return {number} Order.
   */
  function defaultOrder(feature1, feature2) {
    return parseInt(getUid(feature1), 10) - parseInt(getUid(feature2), 10);
  }

  /**
   * @param {number} resolution Resolution.
   * @param {number} pixelRatio Pixel ratio.
   * @return {number} Squared pixel tolerance.
   */
  function getSquaredTolerance(resolution, pixelRatio) {
    const tolerance = getTolerance(resolution, pixelRatio);
    return tolerance * tolerance;
  }

  /**
   * @param {number} resolution Resolution.
   * @param {number} pixelRatio Pixel ratio.
   * @return {number} Pixel tolerance.
   */
  function getTolerance(resolution, pixelRatio) {
    return (SIMPLIFY_TOLERANCE * resolution) / pixelRatio;
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Builder group.
   * @param {import("../geom/Circle.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderCircleGeometry(builderGroup, geometry, style, feature, index) {
    const fillStyle = style.getFill();
    const strokeStyle = style.getStroke();
    if (fillStyle || strokeStyle) {
      const circleReplay = builderGroup.getBuilder(style.getZIndex(), 'Circle');
      circleReplay.setFillStrokeStyle(fillStyle, strokeStyle);
      circleReplay.drawCircle(geometry, feature, index);
    }
    const textStyle = style.getText();
    if (textStyle && textStyle.getText()) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle);
      textReplay.drawText(geometry, feature);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} replayGroup Replay group.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {import("../style/Style.js").default} style Style.
   * @param {number} squaredTolerance Squared tolerance.
   * @param {function(import("../events/Event.js").default): void} listener Listener function.
   * @param {import("../proj.js").TransformFunction} [transform] Transform from user to view projection.
   * @param {boolean} [declutter] Enable decluttering.
   * @param {number} [index] Render order index..
   * @return {boolean} `true` if style is loading.
   */
  function renderFeature$1(
    replayGroup,
    feature,
    style,
    squaredTolerance,
    listener,
    transform,
    declutter,
    index,
  ) {
    const loadingPromises = [];
    const imageStyle = style.getImage();
    if (imageStyle) {
      let loading = true;
      const imageState = imageStyle.getImageState();
      if (imageState == ImageState.LOADED || imageState == ImageState.ERROR) {
        loading = false;
      } else {
        if (imageState == ImageState.IDLE) {
          imageStyle.load();
        }
      }
      if (loading) {
        loadingPromises.push(imageStyle.ready());
      }
    }
    const fillStyle = style.getFill();
    if (fillStyle && fillStyle.loading()) {
      loadingPromises.push(fillStyle.ready());
    }
    const loading = loadingPromises.length > 0;
    if (loading) {
      Promise.all(loadingPromises).then(() => listener(null));
    }
    renderFeatureInternal(
      replayGroup,
      feature,
      style,
      squaredTolerance,
      transform,
      declutter,
      index,
    );

    return loading;
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} replayGroup Replay group.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {import("../style/Style.js").default} style Style.
   * @param {number} squaredTolerance Squared tolerance.
   * @param {import("../proj.js").TransformFunction} [transform] Optional transform function.
   * @param {boolean} [declutter] Enable decluttering.
   * @param {number} [index] Render order index..
   */
  function renderFeatureInternal(
    replayGroup,
    feature,
    style,
    squaredTolerance,
    transform,
    declutter,
    index,
  ) {
    const geometry = style.getGeometryFunction()(feature);
    if (!geometry) {
      return;
    }
    const simplifiedGeometry = geometry.simplifyTransformed(
      squaredTolerance,
      transform,
    );
    const renderer = style.getRenderer();
    if (renderer) {
      renderGeometry(replayGroup, simplifiedGeometry, style, feature, index);
    } else {
      const geometryRenderer = GEOMETRY_RENDERERS[simplifiedGeometry.getType()];
      geometryRenderer(
        replayGroup,
        simplifiedGeometry,
        style,
        feature,
        index,
        declutter,
      );
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} replayGroup Replay group.
   * @param {import("../geom/Geometry.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderGeometry(replayGroup, geometry, style, feature, index) {
    if (geometry.getType() == 'GeometryCollection') {
      const geometries =
        /** @type {import("../geom/GeometryCollection.js").default} */ (
          geometry
        ).getGeometries();
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        renderGeometry(replayGroup, geometries[i], style, feature, index);
      }
      return;
    }
    const replay = replayGroup.getBuilder(style.getZIndex(), 'Default');
    replay.drawCustom(
      /** @type {import("../geom/SimpleGeometry.js").default} */ (geometry),
      feature,
      style.getRenderer(),
      style.getHitDetectionRenderer(),
      index,
    );
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} replayGroup Replay group.
   * @param {import("../geom/GeometryCollection.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {import("../render/canvas/BuilderGroup.js").default} [declutterBuilderGroup] Builder for decluttering.
   * @param {number} [index] Render order index.
   */
  function renderGeometryCollectionGeometry(
    replayGroup,
    geometry,
    style,
    feature,
    declutterBuilderGroup,
    index,
  ) {
    const geometries = geometry.getGeometriesArray();
    let i, ii;
    for (i = 0, ii = geometries.length; i < ii; ++i) {
      const geometryRenderer = GEOMETRY_RENDERERS[geometries[i].getType()];
      geometryRenderer(
        replayGroup,
        geometries[i],
        style,
        feature,
        declutterBuilderGroup,
        index,
      );
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/LineString.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderLineStringGeometry(
    builderGroup,
    geometry,
    style,
    feature,
    index,
  ) {
    const strokeStyle = style.getStroke();
    if (strokeStyle) {
      const lineStringReplay = builderGroup.getBuilder(
        style.getZIndex(),
        'LineString',
      );
      lineStringReplay.setFillStrokeStyle(null, strokeStyle);
      lineStringReplay.drawLineString(geometry, feature, index);
    }
    const textStyle = style.getText();
    if (textStyle && textStyle.getText()) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/MultiLineString.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderMultiLineStringGeometry(
    builderGroup,
    geometry,
    style,
    feature,
    index,
  ) {
    const strokeStyle = style.getStroke();
    if (strokeStyle) {
      const lineStringReplay = builderGroup.getBuilder(
        style.getZIndex(),
        'LineString',
      );
      lineStringReplay.setFillStrokeStyle(null, strokeStyle);
      lineStringReplay.drawMultiLineString(geometry, feature, index);
    }
    const textStyle = style.getText();
    if (textStyle && textStyle.getText()) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/MultiPolygon.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderMultiPolygonGeometry(
    builderGroup,
    geometry,
    style,
    feature,
    index,
  ) {
    const fillStyle = style.getFill();
    const strokeStyle = style.getStroke();
    if (strokeStyle || fillStyle) {
      const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');
      polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);
      polygonReplay.drawMultiPolygon(geometry, feature, index);
    }
    const textStyle = style.getText();
    if (textStyle && textStyle.getText()) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/Point.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   * @param {boolean} [declutter] Enable decluttering.
   */
  function renderPointGeometry(
    builderGroup,
    geometry,
    style,
    feature,
    index,
    declutter,
  ) {
    const imageStyle = style.getImage();
    const textStyle = style.getText();
    const hasText = textStyle && textStyle.getText();
    /** @type {import("../render/canvas.js").DeclutterImageWithText} */
    const declutterImageWithText =
      declutter && imageStyle && hasText ? {} : undefined;
    if (imageStyle) {
      if (imageStyle.getImageState() != ImageState.LOADED) {
        return;
      }
      const imageReplay = builderGroup.getBuilder(style.getZIndex(), 'Image');
      imageReplay.setImageStyle(imageStyle, declutterImageWithText);
      imageReplay.drawPoint(geometry, feature, index);
    }
    if (hasText) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle, declutterImageWithText);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/MultiPoint.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   * @param {boolean} [declutter] Enable decluttering.
   */
  function renderMultiPointGeometry(
    builderGroup,
    geometry,
    style,
    feature,
    index,
    declutter,
  ) {
    const imageStyle = style.getImage();
    const hasImage = imageStyle && imageStyle.getOpacity() !== 0;
    const textStyle = style.getText();
    const hasText = textStyle && textStyle.getText();
    /** @type {import("../render/canvas.js").DeclutterImageWithText} */
    const declutterImageWithText =
      declutter && hasImage && hasText ? {} : undefined;
    if (hasImage) {
      if (imageStyle.getImageState() != ImageState.LOADED) {
        return;
      }
      const imageReplay = builderGroup.getBuilder(style.getZIndex(), 'Image');
      imageReplay.setImageStyle(imageStyle, declutterImageWithText);
      imageReplay.drawMultiPoint(geometry, feature, index);
    }
    if (hasText) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle, declutterImageWithText);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @param {import("../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
   * @param {import("../geom/Polygon.js").default|import("../render/Feature.js").default} geometry Geometry.
   * @param {import("../style/Style.js").default} style Style.
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} [index] Render order index.
   */
  function renderPolygonGeometry(builderGroup, geometry, style, feature, index) {
    const fillStyle = style.getFill();
    const strokeStyle = style.getStroke();
    if (fillStyle || strokeStyle) {
      const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');
      polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);
      polygonReplay.drawPolygon(geometry, feature, index);
    }
    const textStyle = style.getText();
    if (textStyle && textStyle.getText()) {
      const textReplay = builderGroup.getBuilder(style.getZIndex(), 'Text');
      textReplay.setTextStyle(textStyle);
      textReplay.drawText(geometry, feature, index);
    }
  }

  /**
   * @module ol/render
   */

  /**
   * @typedef {Object} State
   * @property {CanvasRenderingContext2D} context Canvas context that the layer is being rendered to.
   * @property {import("./Feature.js").FeatureLike} feature Feature.
   * @property {import("./geom/SimpleGeometry.js").default} geometry Geometry.
   * @property {number} pixelRatio Pixel ratio used by the layer renderer.
   * @property {number} resolution Resolution that the render batch was created and optimized for.
   * This is not the view's resolution that is being rendered.
   * @property {number} rotation Rotation of the rendered layer in radians.
   */

  /**
   * A function to be used when sorting features before rendering.
   * It takes two instances of {@link module:ol/Feature~Feature} or
   * {@link module:ol/render/Feature~RenderFeature} and returns a `{number}`.
   *
   * @typedef {function(import("./Feature.js").FeatureLike, import("./Feature.js").FeatureLike):number} OrderFunction
   */

  /**
   * @typedef {Object} ToContextOptions
   * @property {import("./size.js").Size} [size] Desired size of the canvas in css
   * pixels. When provided, both canvas and css size will be set according to the
   * `pixelRatio`. If not provided, the current canvas and css sizes will not be
   * altered.
   * @property {number} [pixelRatio=window.devicePixelRatio] Pixel ratio (canvas
   * pixel to css pixel ratio) for the canvas.
   */

  /**
   * Binds a Canvas Immediate API to a canvas context, to allow drawing geometries
   * to the context's canvas.
   *
   * The units for geometry coordinates are css pixels relative to the top left
   * corner of the canvas element.
   * ```js
   * import {toContext} from 'ol/render.js';
   * import Fill from 'ol/style/Fill.js';
   * import Polygon from 'ol/geom/Polygon.js';
   *
   * const canvas = document.createElement('canvas');
   * const render = toContext(
   *     canvas.getContext('2d'),
   *     {size: [100, 100]}
   * );
   * render.setFillStrokeStyle(new Fill({ color: blue }));
   * render.drawPolygon(
   *     new Polygon([[[0, 0], [100, 100], [100, 0], [0, 0]]])
   * );
   * ```
   *
   * @param {CanvasRenderingContext2D} context Canvas context.
   * @param {ToContextOptions} [options] Options.
   * @return {CanvasImmediateRenderer} Canvas Immediate.
   * @api
   */
  function toContext(context, options) {
    const canvas = context.canvas;
    options = options ? options : {};
    const pixelRatio = options.pixelRatio || DEVICE_PIXEL_RATIO;
    const size = options.size;
    if (size) {
      canvas.width = size[0] * pixelRatio;
      canvas.height = size[1] * pixelRatio;
      canvas.style.width = size[0] + 'px';
      canvas.style.height = size[1] + 'px';
    }
    const extent = [0, 0, canvas.width, canvas.height];
    const transform = scale$3(create$3(), pixelRatio, pixelRatio);
    return new CanvasImmediateRenderer(context, pixelRatio, extent, transform, 0);
  }

  /**
   * Gets a vector context for drawing to the event's canvas.
   * @param {import("./render/Event.js").default} event Render event.
   * @return {CanvasImmediateRenderer} Vector context.
   * @api
   */
  function getVectorContext(event) {
    if (!(event.context instanceof CanvasRenderingContext2D)) {
      throw new Error('Only works for render events from Canvas 2D layers');
    }

    // canvas may be at a different pixel ratio than frameState.pixelRatio
    const a = event.inversePixelTransform[0];
    const b = event.inversePixelTransform[1];
    const canvasPixelRatio = Math.sqrt(a * a + b * b);
    const frameState = event.frameState;
    const transform = multiply(
      event.inversePixelTransform.slice(),
      frameState.coordinateToPixelTransform,
    );
    const squaredTolerance = getSquaredTolerance(
      frameState.viewState.resolution,
      canvasPixelRatio,
    );
    let userTransform;
    const userProjection = getUserProjection();
    if (userProjection) {
      userTransform = getTransformFromProjections(
        userProjection,
        frameState.viewState.projection,
      );
    }

    return new CanvasImmediateRenderer(
      event.context,
      canvasPixelRatio,
      frameState.extent,
      transform,
      frameState.viewState.rotation,
      squaredTolerance,
      userTransform,
    );
  }

  /**
   * @module ol/featureloader
   */

  /**
   *
   * @type {boolean}
   * @private
   */
  let withCredentials = false;

  /**
   * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to
   * load features.
   *
   * This function takes up to 5 arguments. These are an {@link module:ol/extent~Extent} representing
   * the area to be loaded, a `{number}` representing the resolution (map units per pixel), a
   * {@link module:ol/proj/Projection~Projection} for the projection, an optional success callback that should get
   * the loaded features passed as an argument and an optional failure callback with no arguments. If
   * the callbacks are not used, the corresponding vector source will not fire `'featuresloadend'` and
   * `'featuresloaderror'` events. `this` within the function is bound to the
   * {@link module:ol/source/Vector~VectorSource} it's called from.
   *
   * The function is responsible for loading the features and adding them to the
   * source.
   *
   * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").FeatureLike]
   * @typedef {(
   *           extent: import("./extent.js").Extent,
   *           resolution: number,
   *           projection: import("./proj/Projection.js").default,
   *           success?: (features: Array<FeatureType>) => void,
   *           failure?: () => void) => void} FeatureLoader
   * @api
   */

  /**
   * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to
   * get the url to load features from.
   *
   * This function takes an {@link module:ol/extent~Extent} representing the area
   * to be loaded, a `{number}` representing the resolution (map units per pixel)
   * and an {@link module:ol/proj/Projection~Projection} for the projection  as
   * arguments and returns a `{string}` representing the URL.
   * @typedef {function(import("./extent.js").Extent, number, import("./proj/Projection.js").default): string} FeatureUrlFunction
   * @api
   */

  /**
   * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").default]
   * @param {string|FeatureUrlFunction} url Feature URL service.
   * @param {import("./format/Feature.js").default<FeatureType>} format Feature format.
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {number} resolution Resolution.
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @param {function(Array<FeatureType>, import("./proj/Projection.js").default): void} success Success
   *      Function called with the loaded features and optionally with the data projection.
   * @param {function(): void} failure Failure
   *      Function called when loading failed.
   */
  function loadFeaturesXhr(
    url,
    format,
    extent,
    resolution,
    projection,
    success,
    failure,
  ) {
    const xhr = new XMLHttpRequest();
    xhr.open(
      'GET',
      typeof url === 'function' ? url(extent, resolution, projection) : url,
      true,
    );
    if (format.getType() == 'arraybuffer') {
      xhr.responseType = 'arraybuffer';
    }
    xhr.withCredentials = withCredentials;
    /**
     * @param {Event} event Event.
     * @private
     */
    xhr.onload = function (event) {
      // status will be 0 for file:// urls
      if (!xhr.status || (xhr.status >= 200 && xhr.status < 300)) {
        const type = format.getType();
        try {
          /** @type {Document|Node|Object|string|undefined} */
          let source;
          if (type == 'text' || type == 'json') {
            source = xhr.responseText;
          } else if (type == 'xml') {
            source = xhr.responseXML || xhr.responseText;
          } else if (type == 'arraybuffer') {
            source = /** @type {ArrayBuffer} */ (xhr.response);
          }
          if (source) {
            success(
              /** @type {Array<FeatureType>} */
              (
                format.readFeatures(source, {
                  extent: extent,
                  featureProjection: projection,
                })
              ),
              format.readProjection(source),
            );
          } else {
            failure();
          }
        } catch {
          failure();
        }
      } else {
        failure();
      }
    };
    /**
     * @private
     */
    xhr.onerror = failure;
    xhr.send();
  }

  /**
   * Create an XHR feature loader for a `url` and `format`. The feature loader
   * loads features (with XHR), parses the features, and adds them to the
   * vector source.
   *
   * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").default]
   * @param {string|FeatureUrlFunction} url Feature URL service.
   * @param {import("./format/Feature.js").default<FeatureType>} format Feature format.
   * @return {FeatureLoader<FeatureType>} The feature loader.
   * @api
   */
  function xhr(url, format) {
    /**
     * @param {import("./extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {import("./proj/Projection.js").default} projection Projection.
     * @param {function(Array<FeatureType>): void} [success] Success
     *      Function called when loading succeeded.
     * @param {function(): void} [failure] Failure
     *      Function called when loading failed.
     * @this {import("./source/Vector.js").default<FeatureType>}
     */
    return function (extent, resolution, projection, success, failure) {
      loadFeaturesXhr(
        url,
        format,
        extent,
        resolution,
        projection,
        /**
         * @param {Array<FeatureType>} features The loaded features.
         * @param {import("./proj/Projection.js").default} dataProjection Data
         * projection.
         */
        (features, dataProjection) => {
          this.addFeatures(features);
          if (success !== undefined) {
            success(features);
          }
        },
        () => {
          this.changed();
          if (failure !== undefined) {
            failure();
          }
        },
      );
    };
  }

  /**
   * @module ol/loadingstrategy
   */


  /**
   * Strategy function for loading all features with a single request.
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {number} resolution Resolution.
   * @return {Array<import("./extent.js").Extent>} Extents.
   * @api
   */
  function all$1(extent, resolution) {
    return [[-Infinity, -Infinity, Infinity, Infinity]];
  }

  /**
   * Strategy function for loading features based on the view's extent and
   * resolution.
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {number} resolution Resolution.
   * @return {Array<import("./extent.js").Extent>} Extents.
   * @api
   */
  function bbox$1(extent, resolution) {
    return [extent];
  }

  /**
   * Creates a strategy function for loading features based on a tile grid.
   * @param {import("./tilegrid/TileGrid.js").default} tileGrid Tile grid.
   * @return {function(import("./extent.js").Extent, number, import("./proj.js").Projection): Array<import("./extent.js").Extent>} Loading strategy.
   * @api
   */
  function tile(tileGrid) {
    return (
      /**
       * @param {import("./extent.js").Extent} extent Extent.
       * @param {number} resolution Resolution.
       * @param {import("./proj.js").Projection} projection Projection.
       * @return {Array<import("./extent.js").Extent>} Extents.
       */
      function (extent, resolution, projection) {
        const z = tileGrid.getZForResolution(
          fromUserResolution(resolution, projection),
        );
        const tileRange = tileGrid.getTileRangeForExtentAndZ(
          fromUserExtent(extent, projection),
          z,
        );
        /** @type {Array<import("./extent.js").Extent>} */
        const extents = [];
        /** @type {import("./tilecoord.js").TileCoord} */
        const tileCoord = [z, 0, 0];
        for (
          tileCoord[1] = tileRange.minX;
          tileCoord[1] <= tileRange.maxX;
          ++tileCoord[1]
        ) {
          for (
            tileCoord[2] = tileRange.minY;
            tileCoord[2] <= tileRange.maxY;
            ++tileCoord[2]
          ) {
            extents.push(
              toUserExtent(tileGrid.getTileCoordExtent(tileCoord), projection),
            );
          }
        }
        return extents;
      }
    );
  }

  var nsLoadingStrategy = {
    __proto__: null,
    all: all$1,
    bbox: bbox$1,
    tile: tile
  };

  /**
   * @module ol/geom/flat/center
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {Array<Array<number>>} endss Endss.
   * @param {number} stride Stride.
   * @return {Array<number>} Flat centers.
   */
  function linearRingss(flatCoordinates, offset, endss, stride) {
    const flatCenters = [];
    let extent = createEmpty();
    for (let i = 0, ii = endss.length; i < ii; ++i) {
      const ends = endss[i];
      extent = createOrUpdateFromFlatCoordinates(
        flatCoordinates,
        offset,
        ends[0],
        stride,
      );
      flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2);
      offset = ends[ends.length - 1];
    }
    return flatCenters;
  }

  /**
   * @module ol/geom/Circle
   */

  /**
   * @classdesc
   * Circle geometry.
   *
   * @api
   */
  class Circle extends SimpleGeometry {
    /**
     * @param {!import("../coordinate.js").Coordinate} center Center.
     *     For internal use, flat coordinates in combination with `layout` and no
     *     `radius` are also accepted.
     * @param {number} [radius] Radius in units of the projection.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    constructor(center, radius, layout) {
      super();
      if (layout !== undefined && radius === undefined) {
        this.setFlatCoordinates(layout, center);
      } else {
        radius = radius ? radius : 0;
        this.setCenterAndRadius(center, radius, layout);
      }
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!Circle} Clone.
     * @api
     * @override
     */
    clone() {
      const circle = new Circle(
        this.flatCoordinates.slice(),
        undefined,
        this.layout,
      );
      circle.applyProperties(this);
      return circle;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      const flatCoordinates = this.flatCoordinates;
      const dx = x - flatCoordinates[0];
      const dy = y - flatCoordinates[1];
      const squaredDistance = dx * dx + dy * dy;
      if (squaredDistance < minSquaredDistance) {
        if (squaredDistance === 0) {
          for (let i = 0; i < this.stride; ++i) {
            closestPoint[i] = flatCoordinates[i];
          }
        } else {
          const delta = this.getRadius() / Math.sqrt(squaredDistance);
          closestPoint[0] = flatCoordinates[0] + delta * dx;
          closestPoint[1] = flatCoordinates[1] + delta * dy;
          for (let i = 2; i < this.stride; ++i) {
            closestPoint[i] = flatCoordinates[i];
          }
        }
        closestPoint.length = this.stride;
        return squaredDistance;
      }
      return minSquaredDistance;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @return {boolean} Contains (x, y).
     * @override
     */
    containsXY(x, y) {
      const flatCoordinates = this.flatCoordinates;
      const dx = x - flatCoordinates[0];
      const dy = y - flatCoordinates[1];
      return dx * dx + dy * dy <= this.getRadiusSquared_();
    }

    /**
     * Return the center of the circle as {@link module:ol/coordinate~Coordinate coordinate}.
     * @return {import("../coordinate.js").Coordinate} Center.
     * @api
     */
    getCenter() {
      return this.flatCoordinates.slice(0, this.stride);
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @protected
     * @return {import("../extent.js").Extent} extent Extent.
     * @override
     */
    computeExtent(extent) {
      const flatCoordinates = this.flatCoordinates;
      const radius = flatCoordinates[this.stride] - flatCoordinates[0];
      return createOrUpdate$2(
        flatCoordinates[0] - radius,
        flatCoordinates[1] - radius,
        flatCoordinates[0] + radius,
        flatCoordinates[1] + radius,
        extent,
      );
    }

    /**
     * Return the radius of the circle.
     * @return {number} Radius.
     * @api
     */
    getRadius() {
      return Math.sqrt(this.getRadiusSquared_());
    }

    /**
     * @private
     * @return {number} Radius squared.
     */
    getRadiusSquared_() {
      const dx = this.flatCoordinates[this.stride] - this.flatCoordinates[0];
      const dy = this.flatCoordinates[this.stride + 1] - this.flatCoordinates[1];
      return dx * dx + dy * dy;
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'Circle';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      const circleExtent = this.getExtent();
      if (intersects$2(extent, circleExtent)) {
        const center = this.getCenter();

        if (extent[0] <= center[0] && extent[2] >= center[0]) {
          return true;
        }
        if (extent[1] <= center[1] && extent[3] >= center[1]) {
          return true;
        }

        return forEachCorner(extent, this.intersectsCoordinate.bind(this));
      }
      return false;
    }

    /**
     * Set the center of the circle as {@link module:ol/coordinate~Coordinate coordinate}.
     * @param {import("../coordinate.js").Coordinate} center Center.
     * @api
     */
    setCenter(center) {
      const stride = this.stride;
      const radius = this.flatCoordinates[stride] - this.flatCoordinates[0];
      const flatCoordinates = center.slice();
      flatCoordinates[stride] = flatCoordinates[0] + radius;
      for (let i = 1; i < stride; ++i) {
        flatCoordinates[stride + i] = center[i];
      }
      this.setFlatCoordinates(this.layout, flatCoordinates);
      this.changed();
    }

    /**
     * Set the center (as {@link module:ol/coordinate~Coordinate coordinate}) and the radius (as
     * number) of the circle.
     * @param {!import("../coordinate.js").Coordinate} center Center.
     * @param {number} radius Radius.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     */
    setCenterAndRadius(center, radius, layout) {
      this.setLayout(layout, center, 0);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      /** @type {Array<number>} */
      const flatCoordinates = this.flatCoordinates;
      let offset = deflateCoordinate(flatCoordinates, 0, center, this.stride);
      flatCoordinates[offset++] = flatCoordinates[0] + radius;
      for (let i = 1, ii = this.stride; i < ii; ++i) {
        flatCoordinates[offset++] = flatCoordinates[i];
      }
      flatCoordinates.length = offset;
      this.changed();
    }

    /**
     * @override
     */
    getCoordinates() {
      return null;
    }

    /**
     * @override
     */
    setCoordinates(coordinates, layout) {}

    /**
     * Set the radius of the circle. The radius is in the units of the projection.
     * @param {number} radius Radius.
     * @api
     */
    setRadius(radius) {
      this.flatCoordinates[this.stride] = this.flatCoordinates[0] + radius;
      this.changed();
    }

    /**
     * Rotate the geometry around a given coordinate. This modifies the geometry
     * coordinates in place.
     * @param {number} angle Rotation angle in counter-clockwise radians.
     * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
     * @api
     * @override
     */
    rotate(angle, anchor) {
      const center = this.getCenter();
      const stride = this.getStride();
      this.setCenter(
        rotate(center, 0, center.length, stride, angle, anchor, center),
      );
      this.changed();
    }
  }

  /**
   * Transform each coordinate of the circle from one coordinate reference system
   * to another. The geometry is modified in place.
   * If you do not want the geometry modified in place, first clone() it and
   * then use this function on the clone.
   *
   * Internally a circle is currently represented by two points: the center of
   * the circle `[cx, cy]`, and the point to the right of the circle
   * `[cx + r, cy]`. This `transform` function just transforms these two points.
   * So the resulting geometry is also a circle, and that circle does not
   * correspond to the shape that would be obtained by transforming every point
   * of the original circle.
   *
   * @param {import("../proj.js").ProjectionLike} source The current projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @param {import("../proj.js").ProjectionLike} destination The desired projection.  Can be a
   *     string identifier or a {@link module:ol/proj/Projection~Projection} object.
   * @return {Circle} This geometry.  Note that original geometry is
   *     modified in place.
   * @function
   * @api
   */
  Circle.prototype.transform;

  /**
   * @module ol/geom/GeometryCollection
   */

  /**
   * @classdesc
   * An array of {@link module:ol/geom/Geometry~Geometry} objects.
   *
   * @api
   */
  class GeometryCollection extends Geometry {
    /**
     * @param {Array<Geometry>} geometries Geometries.
     */
    constructor(geometries) {
      super();

      /**
       * @private
       * @type {Array<Geometry>}
       */
      this.geometries_ = geometries;

      /**
       * @private
       * @type {Array<import("../events.js").EventsKey>}
       */
      this.changeEventsKeys_ = [];

      this.listenGeometriesChange_();
    }

    /**
     * @private
     */
    unlistenGeometriesChange_() {
      this.changeEventsKeys_.forEach(unlistenByKey);
      this.changeEventsKeys_.length = 0;
    }

    /**
     * @private
     */
    listenGeometriesChange_() {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        this.changeEventsKeys_.push(
          listen(geometries[i], EventType.CHANGE, this.changed, this),
        );
      }
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!GeometryCollection} Clone.
     * @api
     * @override
     */
    clone() {
      const geometryCollection = new GeometryCollection(
        cloneGeometries(this.geometries_),
      );
      geometryCollection.applyProperties(this);
      return geometryCollection;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        minSquaredDistance = geometries[i].closestPointXY(
          x,
          y,
          closestPoint,
          minSquaredDistance,
        );
      }
      return minSquaredDistance;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @return {boolean} Contains (x, y).
     * @override
     */
    containsXY(x, y) {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        if (geometries[i].containsXY(x, y)) {
          return true;
        }
      }
      return false;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @protected
     * @return {import("../extent.js").Extent} extent Extent.
     * @override
     */
    computeExtent(extent) {
      createOrUpdateEmpty(extent);
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        extend$1(extent, geometries[i].getExtent());
      }
      return extent;
    }

    /**
     * Return the geometries that make up this geometry collection.
     * @return {Array<Geometry>} Geometries.
     * @api
     */
    getGeometries() {
      return cloneGeometries(this.geometries_);
    }

    /**
     * @return {Array<Geometry>} Geometries.
     */
    getGeometriesArray() {
      return this.geometries_;
    }

    /**
     * @return {Array<Geometry>} Geometries.
     */
    getGeometriesArrayRecursive() {
      /** @type {Array<Geometry>} */
      let geometriesArray = [];
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        if (geometries[i].getType() === this.getType()) {
          geometriesArray = geometriesArray.concat(
            /** @type {GeometryCollection} */ (
              geometries[i]
            ).getGeometriesArrayRecursive(),
          );
        } else {
          geometriesArray.push(geometries[i]);
        }
      }
      return geometriesArray;
    }

    /**
     * Create a simplified version of this geometry using the Douglas Peucker algorithm.
     * @param {number} squaredTolerance Squared tolerance.
     * @return {GeometryCollection} Simplified GeometryCollection.
     * @override
     */
    getSimplifiedGeometry(squaredTolerance) {
      if (this.simplifiedGeometryRevision !== this.getRevision()) {
        this.simplifiedGeometryMaxMinSquaredTolerance = 0;
        this.simplifiedGeometryRevision = this.getRevision();
      }
      if (
        squaredTolerance < 0 ||
        (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&
          squaredTolerance < this.simplifiedGeometryMaxMinSquaredTolerance)
      ) {
        return this;
      }

      const simplifiedGeometries = [];
      const geometries = this.geometries_;
      let simplified = false;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        const geometry = geometries[i];
        const simplifiedGeometry =
          geometry.getSimplifiedGeometry(squaredTolerance);
        simplifiedGeometries.push(simplifiedGeometry);
        if (simplifiedGeometry !== geometry) {
          simplified = true;
        }
      }
      if (simplified) {
        const simplifiedGeometryCollection = new GeometryCollection(
          simplifiedGeometries,
        );
        return simplifiedGeometryCollection;
      }
      this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;
      return this;
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'GeometryCollection';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        if (geometries[i].intersectsExtent(extent)) {
          return true;
        }
      }
      return false;
    }

    /**
     * @return {boolean} Is empty.
     */
    isEmpty() {
      return this.geometries_.length === 0;
    }

    /**
     * Rotate the geometry around a given coordinate. This modifies the geometry
     * coordinates in place.
     * @param {number} angle Rotation angle in radians.
     * @param {import("../coordinate.js").Coordinate} anchor The rotation center.
     * @api
     * @override
     */
    rotate(angle, anchor) {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        geometries[i].rotate(angle, anchor);
      }
      this.changed();
    }

    /**
     * Scale the geometry (with an optional origin).  This modifies the geometry
     * coordinates in place.
     * @abstract
     * @param {number} sx The scaling factor in the x-direction.
     * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).
     * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center
     *     of the geometry extent).
     * @api
     * @override
     */
    scale(sx, sy, anchor) {
      if (!anchor) {
        anchor = getCenter(this.getExtent());
      }
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        geometries[i].scale(sx, sy, anchor);
      }
      this.changed();
    }

    /**
     * Set the geometries that make up this geometry collection.
     * @param {Array<Geometry>} geometries Geometries.
     * @api
     */
    setGeometries(geometries) {
      this.setGeometriesArray(cloneGeometries(geometries));
    }

    /**
     * @param {Array<Geometry>} geometries Geometries.
     */
    setGeometriesArray(geometries) {
      this.unlistenGeometriesChange_();
      this.geometries_ = geometries;
      this.listenGeometriesChange_();
      this.changed();
    }

    /**
     * Apply a transform function to the coordinates of the geometry.
     * The geometry is modified in place.
     * If you do not want the geometry modified in place, first `clone()` it and
     * then use this function on the clone.
     * @param {import("../proj.js").TransformFunction} transformFn Transform function.
     * Called with a flat array of geometry coordinates.
     * @api
     * @override
     */
    applyTransform(transformFn) {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        geometries[i].applyTransform(transformFn);
      }
      this.changed();
    }

    /**
     * Translate the geometry.  This modifies the geometry coordinates in place.  If
     * instead you want a new geometry, first `clone()` this geometry.
     * @param {number} deltaX Delta X.
     * @param {number} deltaY Delta Y.
     * @api
     * @override
     */
    translate(deltaX, deltaY) {
      const geometries = this.geometries_;
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        geometries[i].translate(deltaX, deltaY);
      }
      this.changed();
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.unlistenGeometriesChange_();
      super.disposeInternal();
    }
  }

  /**
   * @param {Array<Geometry>} geometries Geometries.
   * @return {Array<Geometry>} Cloned geometries.
   */
  function cloneGeometries(geometries) {
    return geometries.map((geometry) => geometry.clone());
  }

  /**
   * @module ol/geom/MultiLineString
   */

  /**
   * @classdesc
   * Multi-linestring geometry.
   *
   * @api
   */
  class MultiLineString extends SimpleGeometry {
    /**
     * @param {Array<Array<import("../coordinate.js").Coordinate>|LineString>|Array<number>} coordinates
     *     Coordinates or LineString geometries. (For internal use, flat coordinates in
     *     combination with `layout` and `ends` are also accepted.)
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @param {Array<number>} [ends] Flat coordinate ends for internal use.
     */
    constructor(coordinates, layout, ends) {
      super();

      /**
       * @type {Array<number>}
       * @private
       */
      this.ends_ = [];

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDeltaRevision_ = -1;

      if (Array.isArray(coordinates[0])) {
        this.setCoordinates(
          /** @type {Array<Array<import("../coordinate.js").Coordinate>>} */ (
            coordinates
          ),
          layout,
        );
      } else if (layout !== undefined && ends) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
        this.ends_ = ends;
      } else {
        const lineStrings = /** @type {Array<LineString>} */ (coordinates);
        /** @type {Array<number>} */
        const flatCoordinates = [];
        const ends = [];
        for (let i = 0, ii = lineStrings.length; i < ii; ++i) {
          const lineString = lineStrings[i];
          extend$2(flatCoordinates, lineString.getFlatCoordinates());
          ends.push(flatCoordinates.length);
        }
        const layout =
          lineStrings.length === 0
            ? this.getLayout()
            : lineStrings[0].getLayout();
        this.setFlatCoordinates(layout, flatCoordinates);
        this.ends_ = ends;
      }
    }

    /**
     * Append the passed linestring to the multilinestring.
     * @param {LineString} lineString LineString.
     * @api
     */
    appendLineString(lineString) {
      extend$2(this.flatCoordinates, lineString.getFlatCoordinates().slice());
      this.ends_.push(this.flatCoordinates.length);
      this.changed();
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!MultiLineString} Clone.
     * @api
     * @override
     */
    clone() {
      const multiLineString = new MultiLineString(
        this.flatCoordinates.slice(),
        this.layout,
        this.ends_.slice(),
      );
      multiLineString.applyProperties(this);
      return multiLineString;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      if (this.maxDeltaRevision_ != this.getRevision()) {
        this.maxDelta_ = Math.sqrt(
          arrayMaxSquaredDelta(
            this.flatCoordinates,
            0,
            this.ends_,
            this.stride,
            0,
          ),
        );
        this.maxDeltaRevision_ = this.getRevision();
      }
      return assignClosestArrayPoint(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        this.maxDelta_,
        false,
        x,
        y,
        closestPoint,
        minSquaredDistance,
      );
    }

    /**
     * Returns the coordinate at `m` using linear interpolation, or `null` if no
     * such coordinate exists.
     *
     * `extrapolate` controls extrapolation beyond the range of Ms in the
     * MultiLineString. If `extrapolate` is `true` then Ms less than the first
     * M will return the first coordinate and Ms greater than the last M will
     * return the last coordinate.
     *
     * `interpolate` controls interpolation between consecutive LineStrings
     * within the MultiLineString. If `interpolate` is `true` the coordinates
     * will be linearly interpolated between the last coordinate of one LineString
     * and the first coordinate of the next LineString.  If `interpolate` is
     * `false` then the function will return `null` for Ms falling between
     * LineStrings.
     *
     * @param {number} m M.
     * @param {boolean} [extrapolate] Extrapolate. Default is `false`.
     * @param {boolean} [interpolate] Interpolate. Default is `false`.
     * @return {import("../coordinate.js").Coordinate|null} Coordinate.
     * @api
     */
    getCoordinateAtM(m, extrapolate, interpolate) {
      if (
        (this.layout != 'XYM' && this.layout != 'XYZM') ||
        this.flatCoordinates.length === 0
      ) {
        return null;
      }
      extrapolate = extrapolate !== undefined ? extrapolate : false;
      interpolate = interpolate !== undefined ? interpolate : false;
      return lineStringsCoordinateAtM(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        m,
        extrapolate,
        interpolate,
      );
    }

    /**
     * Return the coordinates of the multilinestring.
     * @return {Array<Array<import("../coordinate.js").Coordinate>>} Coordinates.
     * @api
     * @override
     */
    getCoordinates() {
      return inflateCoordinatesArray(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
      );
    }

    /**
     * @return {Array<number>} Ends.
     */
    getEnds() {
      return this.ends_;
    }

    /**
     * Return the linestring at the specified index.
     * @param {number} index Index.
     * @return {LineString} LineString.
     * @api
     */
    getLineString(index) {
      if (index < 0 || this.ends_.length <= index) {
        return null;
      }
      return new LineString(
        this.flatCoordinates.slice(
          index === 0 ? 0 : this.ends_[index - 1],
          this.ends_[index],
        ),
        this.layout,
      );
    }

    /**
     * Return the linestrings of this multilinestring.
     * @return {Array<LineString>} LineStrings.
     * @api
     */
    getLineStrings() {
      const flatCoordinates = this.flatCoordinates;
      const ends = this.ends_;
      const layout = this.layout;
      /** @type {Array<LineString>} */
      const lineStrings = [];
      let offset = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        const lineString = new LineString(
          flatCoordinates.slice(offset, end),
          layout,
        );
        lineStrings.push(lineString);
        offset = end;
      }
      return lineStrings;
    }

    /**
     * Return the sum of all line string lengths
     * @return {number} Length (on projected plane).
     * @api
     */
    getLength() {
      const ends = this.ends_;
      let start = 0;
      let length = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        length += lineStringLength(
          this.flatCoordinates,
          start,
          ends[i],
          this.stride,
        );
        start = ends[i];
      }
      return length;
    }

    /**
     * @return {Array<number>} Flat midpoints.
     */
    getFlatMidpoints() {
      /** @type {Array<number>} */
      const midpoints = [];
      const flatCoordinates = this.flatCoordinates;
      let offset = 0;
      const ends = this.ends_;
      const stride = this.stride;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        const midpoint = interpolatePoint(
          flatCoordinates,
          offset,
          end,
          stride,
          0.5,
        );
        extend$2(midpoints, midpoint);
        offset = end;
      }
      return midpoints;
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {MultiLineString} Simplified MultiLineString.
     * @protected
     * @override
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      /** @type {Array<number>} */
      const simplifiedFlatCoordinates = [];
      /** @type {Array<number>} */
      const simplifiedEnds = [];
      simplifiedFlatCoordinates.length = douglasPeuckerArray(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        squaredTolerance,
        simplifiedFlatCoordinates,
        0,
        simplifiedEnds,
      );
      return new MultiLineString(simplifiedFlatCoordinates, 'XY', simplifiedEnds);
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'MultiLineString';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return intersectsLineStringArray(
        this.flatCoordinates,
        0,
        this.ends_,
        this.stride,
        extent,
      );
    }

    /**
     * Set the coordinates of the multilinestring.
     * @param {!Array<Array<import("../coordinate.js").Coordinate>>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 2);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      const ends = deflateCoordinatesArray(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
        this.ends_,
      );
      this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];
      this.changed();
    }
  }

  /**
   * @module ol/geom/MultiPoint
   */

  /**
   * @classdesc
   * Multi-point geometry.
   *
   * @api
   */
  class MultiPoint extends SimpleGeometry {
    /**
     * @param {Array<import("../coordinate.js").Coordinate>|Array<number>} coordinates Coordinates.
     *     For internal use, flat coordinates in combination with `layout` are also accepted.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     */
    constructor(coordinates, layout) {
      super();
      if (layout && !Array.isArray(coordinates[0])) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
      } else {
        this.setCoordinates(
          /** @type {Array<import("../coordinate.js").Coordinate>} */ (
            coordinates
          ),
          layout,
        );
      }
    }

    /**
     * Append the passed point to this multipoint.
     * @param {Point} point Point.
     * @api
     */
    appendPoint(point) {
      extend$2(this.flatCoordinates, point.getFlatCoordinates());
      this.changed();
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!MultiPoint} Clone.
     * @api
     * @override
     */
    clone() {
      const multiPoint = new MultiPoint(
        this.flatCoordinates.slice(),
        this.layout,
      );
      multiPoint.applyProperties(this);
      return multiPoint;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      const flatCoordinates = this.flatCoordinates;
      const stride = this.stride;
      for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
        const squaredDistance = squaredDistance$1(
          x,
          y,
          flatCoordinates[i],
          flatCoordinates[i + 1],
        );
        if (squaredDistance < minSquaredDistance) {
          minSquaredDistance = squaredDistance;
          for (let j = 0; j < stride; ++j) {
            closestPoint[j] = flatCoordinates[i + j];
          }
          closestPoint.length = stride;
        }
      }
      return minSquaredDistance;
    }

    /**
     * Return the coordinates of the multipoint.
     * @return {Array<import("../coordinate.js").Coordinate>} Coordinates.
     * @api
     * @override
     */
    getCoordinates() {
      return inflateCoordinates(
        this.flatCoordinates,
        0,
        this.flatCoordinates.length,
        this.stride,
      );
    }

    /**
     * Return the point at the specified index.
     * @param {number} index Index.
     * @return {Point} Point.
     * @api
     */
    getPoint(index) {
      const n = this.flatCoordinates.length / this.stride;
      if (index < 0 || n <= index) {
        return null;
      }
      return new Point(
        this.flatCoordinates.slice(
          index * this.stride,
          (index + 1) * this.stride,
        ),
        this.layout,
      );
    }

    /**
     * Return the points of this multipoint.
     * @return {Array<Point>} Points.
     * @api
     */
    getPoints() {
      const flatCoordinates = this.flatCoordinates;
      const layout = this.layout;
      const stride = this.stride;
      /** @type {Array<Point>} */
      const points = [];
      for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
        const point = new Point(flatCoordinates.slice(i, i + stride), layout);
        points.push(point);
      }
      return points;
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'MultiPoint';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      const flatCoordinates = this.flatCoordinates;
      const stride = this.stride;
      for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
        const x = flatCoordinates[i];
        const y = flatCoordinates[i + 1];
        if (containsXY(extent, x, y)) {
          return true;
        }
      }
      return false;
    }

    /**
     * Set the coordinates of the multipoint.
     * @param {!Array<import("../coordinate.js").Coordinate>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 1);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      this.flatCoordinates.length = deflateCoordinates(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
      );
      this.changed();
    }
  }

  /**
   * @module ol/geom/MultiPolygon
   */

  /**
   * @classdesc
   * Multi-polygon geometry.
   *
   * @api
   */
  class MultiPolygon extends SimpleGeometry {
    /**
     * @param {Array<Array<Array<import("../coordinate.js").Coordinate>>|Polygon>|Array<number>} coordinates Coordinates.
     *     For internal use, flat coordinates in combination with `layout` and `endss` are also accepted.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @param {Array<Array<number>>} [endss] Array of ends for internal use with flat coordinates.
     */
    constructor(coordinates, layout, endss) {
      super();

      /**
       * @type {Array<Array<number>>}
       * @private
       */
      this.endss_ = [];

      /**
       * @private
       * @type {number}
       */
      this.flatInteriorPointsRevision_ = -1;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.flatInteriorPoints_ = null;

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.maxDeltaRevision_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.orientedRevision_ = -1;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.orientedFlatCoordinates_ = null;

      if (!endss && !Array.isArray(coordinates[0])) {
        const polygons = /** @type {Array<Polygon>} */ (coordinates);
        /** @type {Array<number>} */
        const flatCoordinates = [];
        const thisEndss = [];
        for (let i = 0, ii = polygons.length; i < ii; ++i) {
          const polygon = polygons[i];
          const offset = flatCoordinates.length;
          const ends = polygon.getEnds();
          for (let j = 0, jj = ends.length; j < jj; ++j) {
            ends[j] += offset;
          }
          extend$2(flatCoordinates, polygon.getFlatCoordinates());
          thisEndss.push(ends);
        }
        layout =
          polygons.length === 0 ? this.getLayout() : polygons[0].getLayout();
        coordinates = flatCoordinates;
        endss = thisEndss;
      }
      if (layout !== undefined && endss) {
        this.setFlatCoordinates(
          layout,
          /** @type {Array<number>} */ (coordinates),
        );
        this.endss_ = endss;
      } else {
        this.setCoordinates(
          /** @type {Array<Array<Array<import("../coordinate.js").Coordinate>>>} */ (
            coordinates
          ),
          layout,
        );
      }
    }

    /**
     * Append the passed polygon to this multipolygon.
     * @param {Polygon} polygon Polygon.
     * @api
     */
    appendPolygon(polygon) {
      /** @type {Array<number>} */
      let ends;
      if (!this.flatCoordinates) {
        this.flatCoordinates = polygon.getFlatCoordinates().slice();
        ends = polygon.getEnds().slice();
        this.endss_.push();
      } else {
        const offset = this.flatCoordinates.length;
        extend$2(this.flatCoordinates, polygon.getFlatCoordinates());
        ends = polygon.getEnds().slice();
        for (let i = 0, ii = ends.length; i < ii; ++i) {
          ends[i] += offset;
        }
      }
      this.endss_.push(ends);
      this.changed();
    }

    /**
     * Make a complete copy of the geometry.
     * @return {!MultiPolygon} Clone.
     * @api
     * @override
     */
    clone() {
      const len = this.endss_.length;
      const newEndss = new Array(len);
      for (let i = 0; i < len; ++i) {
        newEndss[i] = this.endss_[i].slice();
      }

      const multiPolygon = new MultiPolygon(
        this.flatCoordinates.slice(),
        this.layout,
        newEndss,
      );
      multiPolygon.applyProperties(this);

      return multiPolygon;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @param {import("../coordinate.js").Coordinate} closestPoint Closest point.
     * @param {number} minSquaredDistance Minimum squared distance.
     * @return {number} Minimum squared distance.
     * @override
     */
    closestPointXY(x, y, closestPoint, minSquaredDistance) {
      if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {
        return minSquaredDistance;
      }
      if (this.maxDeltaRevision_ != this.getRevision()) {
        this.maxDelta_ = Math.sqrt(
          multiArrayMaxSquaredDelta(
            this.flatCoordinates,
            0,
            this.endss_,
            this.stride,
            0,
          ),
        );
        this.maxDeltaRevision_ = this.getRevision();
      }
      return assignClosestMultiArrayPoint(
        this.getOrientedFlatCoordinates(),
        0,
        this.endss_,
        this.stride,
        this.maxDelta_,
        true,
        x,
        y,
        closestPoint,
        minSquaredDistance,
      );
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     * @return {boolean} Contains (x, y).
     * @override
     */
    containsXY(x, y) {
      return linearRingssContainsXY(
        this.getOrientedFlatCoordinates(),
        0,
        this.endss_,
        this.stride,
        x,
        y,
      );
    }

    /**
     * Return the area of the multipolygon on projected plane.
     * @return {number} Area (on projected plane).
     * @api
     */
    getArea() {
      return linearRingss$1(
        this.getOrientedFlatCoordinates(),
        0,
        this.endss_,
        this.stride,
      );
    }

    /**
     * Get the coordinate array for this geometry.  This array has the structure
     * of a GeoJSON coordinate array for multi-polygons.
     *
     * @param {boolean} [right] Orient coordinates according to the right-hand
     *     rule (counter-clockwise for exterior and clockwise for interior rings).
     *     If `false`, coordinates will be oriented according to the left-hand rule
     *     (clockwise for exterior and counter-clockwise for interior rings).
     *     By default, coordinate orientation will depend on how the geometry was
     *     constructed.
     * @return {Array<Array<Array<import("../coordinate.js").Coordinate>>>} Coordinates.
     * @api
     * @override
     */
    getCoordinates(right) {
      let flatCoordinates;
      if (right !== undefined) {
        flatCoordinates = this.getOrientedFlatCoordinates().slice();
        orientLinearRingsArray(
          flatCoordinates,
          0,
          this.endss_,
          this.stride,
          right,
        );
      } else {
        flatCoordinates = this.flatCoordinates;
      }

      return inflateMultiCoordinatesArray(
        flatCoordinates,
        0,
        this.endss_,
        this.stride,
      );
    }

    /**
     * @return {Array<Array<number>>} Endss.
     */
    getEndss() {
      return this.endss_;
    }

    /**
     * @return {Array<number>} Flat interior points.
     */
    getFlatInteriorPoints() {
      if (this.flatInteriorPointsRevision_ != this.getRevision()) {
        const flatCenters = linearRingss(
          this.flatCoordinates,
          0,
          this.endss_,
          this.stride,
        );
        this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(
          this.getOrientedFlatCoordinates(),
          0,
          this.endss_,
          this.stride,
          flatCenters,
        );
        this.flatInteriorPointsRevision_ = this.getRevision();
      }
      return /** @type {Array<number>} */ (this.flatInteriorPoints_);
    }

    /**
     * Return the interior points as {@link module:ol/geom/MultiPoint~MultiPoint multipoint}.
     * @return {MultiPoint} Interior points as XYM coordinates, where M is
     * the length of the horizontal intersection that the point belongs to.
     * @api
     */
    getInteriorPoints() {
      return new MultiPoint(this.getFlatInteriorPoints().slice(), 'XYM');
    }

    /**
     * @return {Array<number>} Oriented flat coordinates.
     */
    getOrientedFlatCoordinates() {
      if (this.orientedRevision_ != this.getRevision()) {
        const flatCoordinates = this.flatCoordinates;
        if (
          linearRingssAreOriented(flatCoordinates, 0, this.endss_, this.stride)
        ) {
          this.orientedFlatCoordinates_ = flatCoordinates;
        } else {
          this.orientedFlatCoordinates_ = flatCoordinates.slice();
          this.orientedFlatCoordinates_.length = orientLinearRingsArray(
            this.orientedFlatCoordinates_,
            0,
            this.endss_,
            this.stride,
          );
        }
        this.orientedRevision_ = this.getRevision();
      }
      return /** @type {Array<number>} */ (this.orientedFlatCoordinates_);
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {MultiPolygon} Simplified MultiPolygon.
     * @protected
     * @override
     */
    getSimplifiedGeometryInternal(squaredTolerance) {
      /** @type {Array<number>} */
      const simplifiedFlatCoordinates = [];
      /** @type {Array<Array<number>>} */
      const simplifiedEndss = [];
      simplifiedFlatCoordinates.length = quantizeMultiArray(
        this.flatCoordinates,
        0,
        this.endss_,
        this.stride,
        Math.sqrt(squaredTolerance),
        simplifiedFlatCoordinates,
        0,
        simplifiedEndss,
      );
      return new MultiPolygon(simplifiedFlatCoordinates, 'XY', simplifiedEndss);
    }

    /**
     * Return the polygon at the specified index.
     * @param {number} index Index.
     * @return {Polygon} Polygon.
     * @api
     */
    getPolygon(index) {
      if (index < 0 || this.endss_.length <= index) {
        return null;
      }
      let offset;
      if (index === 0) {
        offset = 0;
      } else {
        const prevEnds = this.endss_[index - 1];
        offset = prevEnds[prevEnds.length - 1];
      }
      const ends = this.endss_[index].slice();
      const end = ends[ends.length - 1];
      if (offset !== 0) {
        for (let i = 0, ii = ends.length; i < ii; ++i) {
          ends[i] -= offset;
        }
      }
      return new Polygon(
        this.flatCoordinates.slice(offset, end),
        this.layout,
        ends,
      );
    }

    /**
     * Return the polygons of this multipolygon.
     * @return {Array<Polygon>} Polygons.
     * @api
     */
    getPolygons() {
      const layout = this.layout;
      const flatCoordinates = this.flatCoordinates;
      const endss = this.endss_;
      const polygons = [];
      let offset = 0;
      for (let i = 0, ii = endss.length; i < ii; ++i) {
        const ends = endss[i].slice();
        const end = ends[ends.length - 1];
        if (offset !== 0) {
          for (let j = 0, jj = ends.length; j < jj; ++j) {
            ends[j] -= offset;
          }
        }
        const polygon = new Polygon(
          flatCoordinates.slice(offset, end),
          layout,
          ends,
        );
        polygons.push(polygon);
        offset = end;
      }
      return polygons;
    }

    /**
     * Get the type of this geometry.
     * @return {import("./Geometry.js").Type} Geometry type.
     * @api
     * @override
     */
    getType() {
      return 'MultiPolygon';
    }

    /**
     * Test if the geometry and the passed extent intersect.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {boolean} `true` if the geometry and the extent intersect.
     * @api
     * @override
     */
    intersectsExtent(extent) {
      return intersectsLinearRingMultiArray(
        this.getOrientedFlatCoordinates(),
        0,
        this.endss_,
        this.stride,
        extent,
      );
    }

    /**
     * Set the coordinates of the multipolygon.
     * @param {!Array<Array<Array<import("../coordinate.js").Coordinate>>>} coordinates Coordinates.
     * @param {import("./Geometry.js").GeometryLayout} [layout] Layout.
     * @api
     * @override
     */
    setCoordinates(coordinates, layout) {
      this.setLayout(layout, coordinates, 3);
      if (!this.flatCoordinates) {
        this.flatCoordinates = [];
      }
      const endss = deflateMultiCoordinatesArray(
        this.flatCoordinates,
        0,
        coordinates,
        this.stride,
        this.endss_,
      );
      if (endss.length === 0) {
        this.flatCoordinates.length = 0;
      } else {
        const lastEnds = endss[endss.length - 1];
        this.flatCoordinates.length =
          lastEnds.length === 0 ? 0 : lastEnds[lastEnds.length - 1];
      }
      this.changed();
    }
  }

  /**
   * @module ol/geom
   */

  var nsGeom = {
    __proto__: null,
    Circle: Circle,
    Geometry: Geometry,
    GeometryCollection: GeometryCollection,
    LineString: LineString,
    LinearRing: LinearRing,
    MultiLineString: MultiLineString,
    MultiPoint: MultiPoint,
    MultiPolygon: MultiPolygon,
    Point: Point,
    Polygon: Polygon,
    SimpleGeometry: SimpleGeometry
  };

  /**
   * @module ol/render/Feature
   */

  /**
   * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString'} Type
   * The geometry type.  One of `'Point'`, `'LineString'`, `'LinearRing'`,
   * `'Polygon'`, `'MultiPoint'` or 'MultiLineString'`.
   */

  /**
   * @type {import("../transform.js").Transform}
   */
  const tmpTransform = create$3();

  /**
   * Lightweight, read-only, {@link module:ol/Feature~Feature} and {@link module:ol/geom/Geometry~Geometry} like
   * structure, optimized for vector tile rendering and styling. Geometry access
   * through the API is limited to getting the type and extent of the geometry.
   */
  class RenderFeature {
    /**
     * @param {Type} type Geometry type.
     * @param {Array<number>} flatCoordinates Flat coordinates. These always need
     *     to be right-handed for polygons.
     * @param {Array<number>} ends Ends.
     * @param {number} stride Stride.
     * @param {Object<string, *>} properties Properties.
     * @param {number|string|undefined} id Feature id.
     */
    constructor(type, flatCoordinates, ends, stride, properties, id) {
      /**
       * @type {import("../style/Style.js").StyleFunction|undefined}
       */
      this.styleFunction;

      /**
       * @private
       * @type {import("../extent.js").Extent|undefined}
       */
      this.extent_;

      /**
       * @private
       * @type {number|string|undefined}
       */
      this.id_ = id;

      /**
       * @private
       * @type {Type}
       */
      this.type_ = type;

      /**
       * @private
       * @type {Array<number>}
       */
      this.flatCoordinates_ = flatCoordinates;

      /**
       * @private
       * @type {Array<number>}
       */
      this.flatInteriorPoints_ = null;

      /**
       * @private
       * @type {Array<number>}
       */
      this.flatMidpoints_ = null;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.ends_ = ends || null;

      /**
       * @private
       * @type {Object<string, *>}
       */
      this.properties_ = properties;

      /**
       * @private
       * @type {number}
       */
      this.squaredTolerance_;

      /**
       * @private
       * @type {number}
       */
      this.stride_ = stride;

      /**
       * @private
       * @type {RenderFeature}
       */
      this.simplifiedGeometry_;
    }

    /**
     * Get a feature property by its key.
     * @param {string} key Key
     * @return {*} Value for the requested key.
     * @api
     */
    get(key) {
      return this.properties_[key];
    }

    /**
     * Get the extent of this feature's geometry.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getExtent() {
      if (!this.extent_) {
        this.extent_ =
          this.type_ === 'Point'
            ? createOrUpdateFromCoordinate(this.flatCoordinates_)
            : createOrUpdateFromFlatCoordinates(
                this.flatCoordinates_,
                0,
                this.flatCoordinates_.length,
                2,
              );
      }
      return this.extent_;
    }

    /**
     * @return {Array<number>} Flat interior points.
     */
    getFlatInteriorPoint() {
      if (!this.flatInteriorPoints_) {
        const flatCenter = getCenter(this.getExtent());
        this.flatInteriorPoints_ = getInteriorPointOfArray(
          this.flatCoordinates_,
          0,
          this.ends_,
          2,
          flatCenter,
          0,
        );
      }
      return this.flatInteriorPoints_;
    }

    /**
     * @return {Array<number>} Flat interior points.
     */
    getFlatInteriorPoints() {
      if (!this.flatInteriorPoints_) {
        const ends = inflateEnds(this.flatCoordinates_, this.ends_);
        const flatCenters = linearRingss(this.flatCoordinates_, 0, ends, 2);
        this.flatInteriorPoints_ = getInteriorPointsOfMultiArray(
          this.flatCoordinates_,
          0,
          ends,
          2,
          flatCenters,
        );
      }
      return this.flatInteriorPoints_;
    }

    /**
     * @return {Array<number>} Flat midpoint.
     */
    getFlatMidpoint() {
      if (!this.flatMidpoints_) {
        this.flatMidpoints_ = interpolatePoint(
          this.flatCoordinates_,
          0,
          this.flatCoordinates_.length,
          2,
          0.5,
        );
      }
      return this.flatMidpoints_;
    }

    /**
     * @return {Array<number>} Flat midpoints.
     */
    getFlatMidpoints() {
      if (!this.flatMidpoints_) {
        this.flatMidpoints_ = [];
        const flatCoordinates = this.flatCoordinates_;
        let offset = 0;
        const ends = /** @type {Array<number>} */ (this.ends_);
        for (let i = 0, ii = ends.length; i < ii; ++i) {
          const end = ends[i];
          const midpoint = interpolatePoint(flatCoordinates, offset, end, 2, 0.5);
          extend$2(this.flatMidpoints_, midpoint);
          offset = end;
        }
      }
      return this.flatMidpoints_;
    }

    /**
     * Get the feature identifier.  This is a stable identifier for the feature and
     * is set when reading data from a remote source.
     * @return {number|string|undefined} Id.
     * @api
     */
    getId() {
      return this.id_;
    }

    /**
     * @return {Array<number>} Flat coordinates.
     */
    getOrientedFlatCoordinates() {
      return this.flatCoordinates_;
    }

    /**
     * For API compatibility with {@link module:ol/Feature~Feature}, this method is useful when
     * determining the geometry type in style function (see {@link #getType}).
     * @return {RenderFeature} Feature.
     * @api
     */
    getGeometry() {
      return this;
    }

    /**
     * @param {number} squaredTolerance Squared tolerance.
     * @return {RenderFeature} Simplified geometry.
     */
    getSimplifiedGeometry(squaredTolerance) {
      return this;
    }

    /**
     * Get a transformed and simplified version of the geometry.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../proj.js").TransformFunction} [transform] Optional transform function.
     * @return {RenderFeature} Simplified geometry.
     */
    simplifyTransformed(squaredTolerance, transform) {
      return this;
    }

    /**
     * Get the feature properties.
     * @return {Object<string, *>} Feature properties.
     * @api
     */
    getProperties() {
      return this.properties_;
    }

    /**
     * Get an object of all property names and values.  This has the same behavior as getProperties,
     * but is here to conform with the {@link module:ol/Feature~Feature} interface.
     * @return {Object<string, *>?} Object.
     */
    getPropertiesInternal() {
      return this.properties_;
    }

    /**
     * @return {number} Stride.
     */
    getStride() {
      return this.stride_;
    }

    /**
     * @return {import('../style/Style.js').StyleFunction|undefined} Style
     */
    getStyleFunction() {
      return this.styleFunction;
    }

    /**
     * Get the type of this feature's geometry.
     * @return {Type} Geometry type.
     * @api
     */
    getType() {
      return this.type_;
    }

    /**
     * Transform geometry coordinates from tile pixel space to projected.
     *
     * @param {import("../proj.js").ProjectionLike} projection The data projection
     */
    transform(projection) {
      projection = get$2(projection);
      const pixelExtent = projection.getExtent();
      const projectedExtent = projection.getWorldExtent();
      if (pixelExtent && projectedExtent) {
        const scale = getHeight(projectedExtent) / getHeight(pixelExtent);
        compose(
          tmpTransform,
          projectedExtent[0],
          projectedExtent[3],
          scale,
          -scale,
          0,
          0,
          0,
        );
        transform2D(
          this.flatCoordinates_,
          0,
          this.flatCoordinates_.length,
          2,
          tmpTransform,
          this.flatCoordinates_,
        );
      }
    }

    /**
     * Apply a transform function to the coordinates of the geometry.
     * The geometry is modified in place.
     * If you do not want the geometry modified in place, first `clone()` it and
     * then use this function on the clone.
     * @param {import("../proj.js").TransformFunction} transformFn Transform function.
     */
    applyTransform(transformFn) {
      transformFn(this.flatCoordinates_, this.flatCoordinates_, this.stride_);
    }

    /**
     * @return {RenderFeature} A cloned render feature.
     */
    clone() {
      return new RenderFeature(
        this.type_,
        this.flatCoordinates_.slice(),
        this.ends_?.slice(),
        this.stride_,
        Object.assign({}, this.properties_),
        this.id_,
      );
    }

    /**
     * @return {Array<number>|null} Ends.
     */
    getEnds() {
      return this.ends_;
    }

    /**
     * Add transform and resolution based geometry simplification to this instance.
     * @return {RenderFeature} This render feature.
     */
    enableSimplifyTransformed() {
      this.simplifyTransformed = memoizeOne((squaredTolerance, transform) => {
        if (squaredTolerance === this.squaredTolerance_) {
          return this.simplifiedGeometry_;
        }
        this.simplifiedGeometry_ = this.clone();
        if (transform) {
          this.simplifiedGeometry_.applyTransform(transform);
        }
        const simplifiedFlatCoordinates =
          this.simplifiedGeometry_.getFlatCoordinates();
        let simplifiedEnds;
        switch (this.type_) {
          case 'LineString':
            simplifiedFlatCoordinates.length = douglasPeucker(
              simplifiedFlatCoordinates,
              0,
              this.simplifiedGeometry_.flatCoordinates_.length,
              this.simplifiedGeometry_.stride_,
              squaredTolerance,
              simplifiedFlatCoordinates,
              0,
            );
            simplifiedEnds = [simplifiedFlatCoordinates.length];
            break;
          case 'MultiLineString':
            simplifiedEnds = [];
            simplifiedFlatCoordinates.length = douglasPeuckerArray(
              simplifiedFlatCoordinates,
              0,
              this.simplifiedGeometry_.ends_,
              this.simplifiedGeometry_.stride_,
              squaredTolerance,
              simplifiedFlatCoordinates,
              0,
              simplifiedEnds,
            );
            break;
          case 'Polygon':
            simplifiedEnds = [];
            simplifiedFlatCoordinates.length = quantizeArray(
              simplifiedFlatCoordinates,
              0,
              this.simplifiedGeometry_.ends_,
              this.simplifiedGeometry_.stride_,
              Math.sqrt(squaredTolerance),
              simplifiedFlatCoordinates,
              0,
              simplifiedEnds,
            );
            break;
        }
        if (simplifiedEnds) {
          this.simplifiedGeometry_ = new RenderFeature(
            this.type_,
            simplifiedFlatCoordinates,
            simplifiedEnds,
            2,
            this.properties_,
            this.id_,
          );
        }
        this.squaredTolerance_ = squaredTolerance;
        return this.simplifiedGeometry_;
      });
      return this;
    }
  }

  /**
   * @return {Array<number>} Flat coordinates.
   */
  RenderFeature.prototype.getFlatCoordinates =
    RenderFeature.prototype.getOrientedFlatCoordinates;

  /**
   * Create a geometry from an `ol/render/Feature`
   * @param {RenderFeature} renderFeature
   * Render Feature
   * @return {Point|MultiPoint|LineString|MultiLineString|Polygon|MultiPolygon}
   * New geometry instance.
   * @api
   */
  function toGeometry(renderFeature) {
    const geometryType = renderFeature.getType();
    switch (geometryType) {
      case 'Point':
        return new Point(renderFeature.getFlatCoordinates());
      case 'MultiPoint':
        return new MultiPoint(renderFeature.getFlatCoordinates(), 'XY');
      case 'LineString':
        return new LineString(renderFeature.getFlatCoordinates(), 'XY');
      case 'MultiLineString':
        return new MultiLineString(
          renderFeature.getFlatCoordinates(),
          'XY',
          /** @type {Array<number>} */ (renderFeature.getEnds()),
        );
      case 'Polygon':
        const flatCoordinates = renderFeature.getFlatCoordinates();
        const ends = renderFeature.getEnds();
        const endss = inflateEnds(flatCoordinates, ends);
        return endss.length > 1
          ? new MultiPolygon(flatCoordinates, 'XY', endss)
          : new Polygon(flatCoordinates, 'XY', ends);
      default:
        throw new Error('Invalid geometry type:' + geometryType);
    }
  }

  /**
   * Create an `ol/Feature` from an `ol/render/Feature`
   * @param {RenderFeature} renderFeature RenderFeature
   * @param {string} [geometryName] Geometry name to use
   * when creating the Feature.
   * @return {Feature} Newly constructed `ol/Feature` with properties,
   * geometry, and id copied over.
   * @api
   */
  function toFeature(renderFeature, geometryName) {
    const id = renderFeature.getId();
    const geometry = toGeometry(renderFeature);
    const properties = renderFeature.getProperties();
    const feature = new Feature();
    if (geometryName !== undefined) {
      feature.setGeometryName(geometryName);
    }
    feature.setGeometry(geometry);
    if (id !== undefined) {
      feature.setId(id);
    }
    feature.setProperties(properties, true);
    return feature;
  }

  /**
   * Rearranges items so that all items in the [left, k] are the smallest.
   * The k-th element will have the (k - left + 1)-th smallest value in [left, right].
   *
   * @template T
   * @param {T[]} arr the array to partially sort (in place)
   * @param {number} k middle index for partial sorting (as defined above)
   * @param {number} [left=0] left index of the range to sort
   * @param {number} [right=arr.length-1] right index
   * @param {(a: T, b: T) => number} [compare = (a, b) => a - b] compare function
   */
  function quickselect(arr, k, left = 0, right = arr.length - 1, compare = defaultCompare) {

      while (right > left) {
          if (right - left > 600) {
              const n = right - left + 1;
              const m = k - left + 1;
              const z = Math.log(n);
              const s = 0.5 * Math.exp(2 * z / 3);
              const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
              const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
              const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
              quickselect(arr, k, newLeft, newRight, compare);
          }

          const t = arr[k];
          let i = left;
          /** @type {number} */
          let j = right;

          swap(arr, left, k);
          if (compare(arr[right], t) > 0) swap(arr, left, right);

          while (i < j) {
              swap(arr, i, j);
              i++;
              j--;
              while (compare(arr[i], t) < 0) i++;
              while (compare(arr[j], t) > 0) j--;
          }

          if (compare(arr[left], t) === 0) swap(arr, left, j);
          else {
              j++;
              swap(arr, j, right);
          }

          if (j <= k) left = j + 1;
          if (k <= j) right = j - 1;
      }
  }

  /**
   * @template T
   * @param {T[]} arr
   * @param {number} i
   * @param {number} j
   */
  function swap(arr, i, j) {
      const tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
  }

  /**
   * @template T
   * @param {T} a
   * @param {T} b
   * @returns {number}
   */
  function defaultCompare(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
  }

  let RBush$1 = class RBush {
      constructor(maxEntries = 9) {
          // max entries in a node is 9 by default; min node fill is 40% for best performance
          this._maxEntries = Math.max(4, maxEntries);
          this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
          this.clear();
      }

      all() {
          return this._all(this.data, []);
      }

      search(bbox) {
          let node = this.data;
          const result = [];

          if (!intersects$1(bbox, node)) return result;

          const toBBox = this.toBBox;
          const nodesToSearch = [];

          while (node) {
              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const childBBox = node.leaf ? toBBox(child) : child;

                  if (intersects$1(bbox, childBBox)) {
                      if (node.leaf) result.push(child);
                      else if (contains$1(bbox, childBBox)) this._all(child, result);
                      else nodesToSearch.push(child);
                  }
              }
              node = nodesToSearch.pop();
          }

          return result;
      }

      collides(bbox) {
          let node = this.data;

          if (!intersects$1(bbox, node)) return false;

          const nodesToSearch = [];
          while (node) {
              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const childBBox = node.leaf ? this.toBBox(child) : child;

                  if (intersects$1(bbox, childBBox)) {
                      if (node.leaf || contains$1(bbox, childBBox)) return true;
                      nodesToSearch.push(child);
                  }
              }
              node = nodesToSearch.pop();
          }

          return false;
      }

      load(data) {
          if (!(data && data.length)) return this;

          if (data.length < this._minEntries) {
              for (let i = 0; i < data.length; i++) {
                  this.insert(data[i]);
              }
              return this;
          }

          // recursively build the tree with the given data from scratch using OMT algorithm
          let node = this._build(data.slice(), 0, data.length - 1, 0);

          if (!this.data.children.length) {
              // save as is if tree is empty
              this.data = node;

          } else if (this.data.height === node.height) {
              // split root if trees have the same height
              this._splitRoot(this.data, node);

          } else {
              if (this.data.height < node.height) {
                  // swap trees if inserted one is bigger
                  const tmpNode = this.data;
                  this.data = node;
                  node = tmpNode;
              }

              // insert the small tree into the large tree at appropriate level
              this._insert(node, this.data.height - node.height - 1, true);
          }

          return this;
      }

      insert(item) {
          if (item) this._insert(item, this.data.height - 1);
          return this;
      }

      clear() {
          this.data = createNode([]);
          return this;
      }

      remove(item, equalsFn) {
          if (!item) return this;

          let node = this.data;
          const bbox = this.toBBox(item);
          const path = [];
          const indexes = [];
          let i, parent, goingUp;

          // depth-first iterative tree traversal
          while (node || path.length) {

              if (!node) { // go up
                  node = path.pop();
                  parent = path[path.length - 1];
                  i = indexes.pop();
                  goingUp = true;
              }

              if (node.leaf) { // check current node
                  const index = findItem(item, node.children, equalsFn);

                  if (index !== -1) {
                      // item found, remove the item and condense tree upwards
                      node.children.splice(index, 1);
                      path.push(node);
                      this._condense(path);
                      return this;
                  }
              }

              if (!goingUp && !node.leaf && contains$1(node, bbox)) { // go down
                  path.push(node);
                  indexes.push(i);
                  i = 0;
                  parent = node;
                  node = node.children[0];

              } else if (parent) { // go right
                  i++;
                  node = parent.children[i];
                  goingUp = false;

              } else node = null; // nothing found
          }

          return this;
      }

      toBBox(item) { return item; }

      compareMinX(a, b) { return a.minX - b.minX; }
      compareMinY(a, b) { return a.minY - b.minY; }

      toJSON() { return this.data; }

      fromJSON(data) {
          this.data = data;
          return this;
      }

      _all(node, result) {
          const nodesToSearch = [];
          while (node) {
              if (node.leaf) result.push(...node.children);
              else nodesToSearch.push(...node.children);

              node = nodesToSearch.pop();
          }
          return result;
      }

      _build(items, left, right, height) {

          const N = right - left + 1;
          let M = this._maxEntries;
          let node;

          if (N <= M) {
              // reached leaf level; return leaf
              node = createNode(items.slice(left, right + 1));
              calcBBox(node, this.toBBox);
              return node;
          }

          if (!height) {
              // target height of the bulk-loaded tree
              height = Math.ceil(Math.log(N) / Math.log(M));

              // target number of root entries to maximize storage utilization
              M = Math.ceil(N / Math.pow(M, height - 1));
          }

          node = createNode([]);
          node.leaf = false;
          node.height = height;

          // split the items into M mostly square tiles

          const N2 = Math.ceil(N / M);
          const N1 = N2 * Math.ceil(Math.sqrt(M));

          multiSelect(items, left, right, N1, this.compareMinX);

          for (let i = left; i <= right; i += N1) {

              const right2 = Math.min(i + N1 - 1, right);

              multiSelect(items, i, right2, N2, this.compareMinY);

              for (let j = i; j <= right2; j += N2) {

                  const right3 = Math.min(j + N2 - 1, right2);

                  // pack each entry recursively
                  node.children.push(this._build(items, j, right3, height - 1));
              }
          }

          calcBBox(node, this.toBBox);

          return node;
      }

      _chooseSubtree(bbox, node, level, path) {
          while (true) {
              path.push(node);

              if (node.leaf || path.length - 1 === level) break;

              let minArea = Infinity;
              let minEnlargement = Infinity;
              let targetNode;

              for (let i = 0; i < node.children.length; i++) {
                  const child = node.children[i];
                  const area = bboxArea(child);
                  const enlargement = enlargedArea(bbox, child) - area;

                  // choose entry with the least area enlargement
                  if (enlargement < minEnlargement) {
                      minEnlargement = enlargement;
                      minArea = area < minArea ? area : minArea;
                      targetNode = child;

                  } else if (enlargement === minEnlargement) {
                      // otherwise choose one with the smallest area
                      if (area < minArea) {
                          minArea = area;
                          targetNode = child;
                      }
                  }
              }

              node = targetNode || node.children[0];
          }

          return node;
      }

      _insert(item, level, isNode) {
          const bbox = isNode ? item : this.toBBox(item);
          const insertPath = [];

          // find the best node for accommodating the item, saving all nodes along the path too
          const node = this._chooseSubtree(bbox, this.data, level, insertPath);

          // put the item into the node
          node.children.push(item);
          extend(node, bbox);

          // split on node overflow; propagate upwards if necessary
          while (level >= 0) {
              if (insertPath[level].children.length > this._maxEntries) {
                  this._split(insertPath, level);
                  level--;
              } else break;
          }

          // adjust bboxes along the insertion path
          this._adjustParentBBoxes(bbox, insertPath, level);
      }

      // split overflowed node into two
      _split(insertPath, level) {
          const node = insertPath[level];
          const M = node.children.length;
          const m = this._minEntries;

          this._chooseSplitAxis(node, m, M);

          const splitIndex = this._chooseSplitIndex(node, m, M);

          const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
          newNode.height = node.height;
          newNode.leaf = node.leaf;

          calcBBox(node, this.toBBox);
          calcBBox(newNode, this.toBBox);

          if (level) insertPath[level - 1].children.push(newNode);
          else this._splitRoot(node, newNode);
      }

      _splitRoot(node, newNode) {
          // split root node
          this.data = createNode([node, newNode]);
          this.data.height = node.height + 1;
          this.data.leaf = false;
          calcBBox(this.data, this.toBBox);
      }

      _chooseSplitIndex(node, m, M) {
          let index;
          let minOverlap = Infinity;
          let minArea = Infinity;

          for (let i = m; i <= M - m; i++) {
              const bbox1 = distBBox(node, 0, i, this.toBBox);
              const bbox2 = distBBox(node, i, M, this.toBBox);

              const overlap = intersectionArea(bbox1, bbox2);
              const area = bboxArea(bbox1) + bboxArea(bbox2);

              // choose distribution with minimum overlap
              if (overlap < minOverlap) {
                  minOverlap = overlap;
                  index = i;

                  minArea = area < minArea ? area : minArea;

              } else if (overlap === minOverlap) {
                  // otherwise choose distribution with minimum area
                  if (area < minArea) {
                      minArea = area;
                      index = i;
                  }
              }
          }

          return index || M - m;
      }

      // sorts node children by the best axis for split
      _chooseSplitAxis(node, m, M) {
          const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
          const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
          const xMargin = this._allDistMargin(node, m, M, compareMinX);
          const yMargin = this._allDistMargin(node, m, M, compareMinY);

          // if total distributions margin value is minimal for x, sort by minX,
          // otherwise it's already sorted by minY
          if (xMargin < yMargin) node.children.sort(compareMinX);
      }

      // total margin of all possible split distributions where each node is at least m full
      _allDistMargin(node, m, M, compare) {
          node.children.sort(compare);

          const toBBox = this.toBBox;
          const leftBBox = distBBox(node, 0, m, toBBox);
          const rightBBox = distBBox(node, M - m, M, toBBox);
          let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);

          for (let i = m; i < M - m; i++) {
              const child = node.children[i];
              extend(leftBBox, node.leaf ? toBBox(child) : child);
              margin += bboxMargin(leftBBox);
          }

          for (let i = M - m - 1; i >= m; i--) {
              const child = node.children[i];
              extend(rightBBox, node.leaf ? toBBox(child) : child);
              margin += bboxMargin(rightBBox);
          }

          return margin;
      }

      _adjustParentBBoxes(bbox, path, level) {
          // adjust bboxes along the given tree path
          for (let i = level; i >= 0; i--) {
              extend(path[i], bbox);
          }
      }

      _condense(path) {
          // go through the path, removing empty nodes and updating bboxes
          for (let i = path.length - 1, siblings; i >= 0; i--) {
              if (path[i].children.length === 0) {
                  if (i > 0) {
                      siblings = path[i - 1].children;
                      siblings.splice(siblings.indexOf(path[i]), 1);

                  } else this.clear();

              } else calcBBox(path[i], this.toBBox);
          }
      }
  };

  function findItem(item, items, equalsFn) {
      if (!equalsFn) return items.indexOf(item);

      for (let i = 0; i < items.length; i++) {
          if (equalsFn(item, items[i])) return i;
      }
      return -1;
  }

  // calculate node's bbox from bboxes of its children
  function calcBBox(node, toBBox) {
      distBBox(node, 0, node.children.length, toBBox, node);
  }

  // min bounding rectangle of node children from k to p-1
  function distBBox(node, k, p, toBBox, destNode) {
      if (!destNode) destNode = createNode(null);
      destNode.minX = Infinity;
      destNode.minY = Infinity;
      destNode.maxX = -Infinity;
      destNode.maxY = -Infinity;

      for (let i = k; i < p; i++) {
          const child = node.children[i];
          extend(destNode, node.leaf ? toBBox(child) : child);
      }

      return destNode;
  }

  function extend(a, b) {
      a.minX = Math.min(a.minX, b.minX);
      a.minY = Math.min(a.minY, b.minY);
      a.maxX = Math.max(a.maxX, b.maxX);
      a.maxY = Math.max(a.maxY, b.maxY);
      return a;
  }

  function compareNodeMinX(a, b) { return a.minX - b.minX; }
  function compareNodeMinY(a, b) { return a.minY - b.minY; }

  function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }

  function enlargedArea(a, b) {
      return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
             (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  }

  function intersectionArea(a, b) {
      const minX = Math.max(a.minX, b.minX);
      const minY = Math.max(a.minY, b.minY);
      const maxX = Math.min(a.maxX, b.maxX);
      const maxY = Math.min(a.maxY, b.maxY);

      return Math.max(0, maxX - minX) *
             Math.max(0, maxY - minY);
  }

  function contains$1(a, b) {
      return a.minX <= b.minX &&
             a.minY <= b.minY &&
             b.maxX <= a.maxX &&
             b.maxY <= a.maxY;
  }

  function intersects$1(a, b) {
      return b.minX <= a.maxX &&
             b.minY <= a.maxY &&
             b.maxX >= a.minX &&
             b.maxY >= a.minY;
  }

  function createNode(children) {
      return {
          children,
          height: 1,
          leaf: true,
          minX: Infinity,
          minY: Infinity,
          maxX: -Infinity,
          maxY: -Infinity
      };
  }

  // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  // combines selection algorithm with binary divide & conquer approach

  function multiSelect(arr, left, right, n, compare) {
      const stack = [left, right];

      while (stack.length) {
          right = stack.pop();
          left = stack.pop();

          if (right - left <= n) continue;

          const mid = left + Math.ceil((right - left) / n / 2) * n;
          quickselect(arr, mid, left, right, compare);

          stack.push(left, mid, mid, right);
      }
  }

  /**
   * @module ol/structs/RBush
   */

  /**
   * @typedef {import("rbush").BBox & {value: T}} Entry
   * @template T
   */

  /**
   * @classdesc
   * Wrapper around the RBush by Vladimir Agafonkin.
   * See https://github.com/mourner/rbush.
   *
   * @template {Object} T
   */
  class RBush {
    /**
     * @param {number} [maxEntries] Max entries.
     */
    constructor(maxEntries) {
      /**
       * @private
       * @type {RBush_<Entry<T>>}
       */
      this.rbush_ = new RBush$1(maxEntries);

      /**
       * A mapping between the objects added to this rbush wrapper
       * and the objects that are actually added to the internal rbush.
       * @private
       * @type {Object<string, Entry<T>>}
       */
      this.items_ = {};
    }

    /**
     * Insert a value into the RBush.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {T} value Value.
     */
    insert(extent, value) {
      /** @type {Entry<T>} */
      const item = {
        minX: extent[0],
        minY: extent[1],
        maxX: extent[2],
        maxY: extent[3],
        value: value,
      };

      this.rbush_.insert(item);
      this.items_[getUid(value)] = item;
    }

    /**
     * Bulk-insert values into the RBush.
     * @param {Array<import("../extent.js").Extent>} extents Extents.
     * @param {Array<T>} values Values.
     */
    load(extents, values) {
      const items = new Array(values.length);
      for (let i = 0, l = values.length; i < l; i++) {
        const extent = extents[i];
        const value = values[i];

        /** @type {Entry<T>} */
        const item = {
          minX: extent[0],
          minY: extent[1],
          maxX: extent[2],
          maxY: extent[3],
          value: value,
        };
        items[i] = item;
        this.items_[getUid(value)] = item;
      }
      this.rbush_.load(items);
    }

    /**
     * Remove a value from the RBush.
     * @param {T} value Value.
     * @return {boolean} Removed.
     */
    remove(value) {
      const uid = getUid(value);

      // get the object in which the value was wrapped when adding to the
      // internal rbush. then use that object to do the removal.
      const item = this.items_[uid];
      delete this.items_[uid];
      return this.rbush_.remove(item) !== null;
    }

    /**
     * Update the extent of a value in the RBush.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {T} value Value.
     */
    update(extent, value) {
      const item = this.items_[getUid(value)];
      const bbox = [item.minX, item.minY, item.maxX, item.maxY];
      if (!equals$1(bbox, extent)) {
        this.remove(value);
        this.insert(extent, value);
      }
    }

    /**
     * Return all values in the RBush.
     * @return {Array<T>} All.
     */
    getAll() {
      const items = this.rbush_.all();
      return items.map(function (item) {
        return item.value;
      });
    }

    /**
     * Return all values in the given extent.
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {Array<T>} All in extent.
     */
    getInExtent(extent) {
      /** @type {import("rbush").BBox} */
      const bbox = {
        minX: extent[0],
        minY: extent[1],
        maxX: extent[2],
        maxY: extent[3],
      };
      const items = this.rbush_.search(bbox);
      return items.map(function (item) {
        return item.value;
      });
    }

    /**
     * Calls a callback function with each value in the tree.
     * If the callback returns a truthy value, this value is returned without
     * checking the rest of the tree.
     * @param {function(T): R} callback Callback.
     * @return {R|undefined} Callback return value.
     * @template R
     */
    forEach(callback) {
      return this.forEach_(this.getAll(), callback);
    }

    /**
     * Calls a callback function with each value in the provided extent.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {function(T): R} callback Callback.
     * @return {R|undefined} Callback return value.
     * @template R
     */
    forEachInExtent(extent, callback) {
      return this.forEach_(this.getInExtent(extent), callback);
    }

    /**
     * @param {Array<T>} values Values.
     * @param {function(T): R} callback Callback.
     * @return {R|undefined} Callback return value.
     * @template R
     * @private
     */
    forEach_(values, callback) {
      let result;
      for (let i = 0, l = values.length; i < l; i++) {
        result = callback(values[i]);
        if (result) {
          return result;
        }
      }
      return result;
    }

    /**
     * @return {boolean} Is empty.
     */
    isEmpty() {
      return isEmpty$1(this.items_);
    }

    /**
     * Remove all values from the RBush.
     */
    clear() {
      this.rbush_.clear();
      this.items_ = {};
    }

    /**
     * @param {import("../extent.js").Extent} [extent] Extent.
     * @return {import("../extent.js").Extent} Extent.
     */
    getExtent(extent) {
      const data = this.rbush_.toJSON();
      return createOrUpdate$2(data.minX, data.minY, data.maxX, data.maxY, extent);
    }

    /**
     * @param {RBush<T>} rbush R-Tree.
     */
    concat(rbush) {
      this.rbush_.load(rbush.rbush_.all());
      for (const i in rbush.items_) {
        this.items_[i] = rbush.items_[i];
      }
    }
  }

  /**
   * @module ol/source/Source
   */

  /**
   * @typedef {'undefined' | 'loading' | 'ready' | 'error'} State
   * State of the source, one of 'undefined', 'loading', 'ready' or 'error'.
   */

  /**
   * A function that takes a {@link import("../View.js").ViewStateLayerStateExtent} and returns a string or
   * an array of strings representing source attributions.
   *
   * @typedef {function(import("../View.js").ViewStateLayerStateExtent): (string|Array<string>)} Attribution
   */

  /**
   * A type that can be used to provide attribution information for data sources.
   *
   * It represents either
   * a simple string (e.g. `'© Acme Inc.'`)
   * an array of simple strings (e.g. `['© Acme Inc.', '© Bacme Inc.']`)
   * a function that returns a string or array of strings ({@link module:ol/source/Source~Attribution})
   *
   * @typedef {string|Array<string>|Attribution} AttributionLike
   */

  /**
   * @typedef {Object} Options
   * @property {AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {import("./Source.js").State} [state='ready'] State.
   * @property {boolean} [wrapX=false] WrapX.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for {@link module:ol/layer/Layer~Layer} sources.
   *
   * A generic `change` event is triggered when the state of the source changes.
   * @abstract
   * @api
   */
  class Source extends BaseObject {
    /**
     * @param {Options} options Source options.
     */
    constructor(options) {
      super();

      /**
       * @protected
       * @type {import("../proj/Projection.js").default|null}
       */
      this.projection = get$2(options.projection);

      /**
       * @private
       * @type {?Attribution}
       */
      this.attributions_ = adaptAttributions(options.attributions);

      /**
       * @private
       * @type {boolean}
       */
      this.attributionsCollapsible_ = options.attributionsCollapsible ?? true;

      /**
       * This source is currently loading data. Sources that defer loading to the
       * map's tile queue never set this to `true`.
       * @type {boolean}
       */
      this.loading = false;

      /**
       * @private
       * @type {import("./Source.js").State}
       */
      this.state_ = options.state !== undefined ? options.state : 'ready';

      /**
       * @private
       * @type {boolean}
       */
      this.wrapX_ = options.wrapX !== undefined ? options.wrapX : false;

      /**
       * @private
       * @type {boolean}
       */
      this.interpolate_ = !!options.interpolate;

      /**
       * @protected
       * @type {function(import("../View.js").ViewOptions):void}
       */
      this.viewResolver = null;

      /**
       * @protected
       * @type {function(Error):void}
       */
      this.viewRejector = null;

      const self = this;
      /**
       * @private
       * @type {Promise<import("../View.js").ViewOptions>}
       */
      this.viewPromise_ = new Promise(function (resolve, reject) {
        self.viewResolver = resolve;
        self.viewRejector = reject;
      });
    }

    /**
     * Get the attribution function for the source.
     * @return {?Attribution} Attribution function.
     * @api
     */
    getAttributions() {
      return this.attributions_;
    }

    /**
     * @return {boolean} Attributions are collapsible.
     * @api
     */
    getAttributionsCollapsible() {
      return this.attributionsCollapsible_;
    }

    /**
     * Get the projection of the source.
     * @return {import("../proj/Projection.js").default|null} Projection.
     * @api
     */
    getProjection() {
      return this.projection;
    }

    /**
     * @param {import("../proj/Projection").default} [projection] Projection.
     * @return {Array<number>|null} Resolutions.
     */
    getResolutions(projection) {
      return null;
    }

    /**
     * @return {Promise<import("../View.js").ViewOptions>} A promise for view-related properties.
     */
    getView() {
      return this.viewPromise_;
    }

    /**
     * Get the state of the source, see {@link import("./Source.js").State} for possible states.
     * @return {import("./Source.js").State} State.
     * @api
     */
    getState() {
      return this.state_;
    }

    /**
     * @return {boolean|undefined} Wrap X.
     */
    getWrapX() {
      return this.wrapX_;
    }

    /**
     * @return {boolean} Use linear interpolation when resampling.
     */
    getInterpolate() {
      return this.interpolate_;
    }

    /**
     * Refreshes the source. The source will be cleared, and data from the server will be reloaded.
     * @api
     */
    refresh() {
      this.changed();
    }

    /**
     * Set the attributions of the source.
     * @param {AttributionLike|undefined} attributions Attributions.
     *     Can be passed as `string`, `Array<string>`, {@link module:ol/source/Source~Attribution},
     *     or `undefined`.
     * @api
     */
    setAttributions(attributions) {
      this.attributions_ = adaptAttributions(attributions);
      this.changed();
    }

    /**
     * Set the state of the source.
     * @param {import("./Source.js").State} state State.
     */
    setState(state) {
      this.state_ = state;
      this.changed();
    }
  }

  /**
   * Turns the attributions option into an attributions function.
   * @param {AttributionLike|undefined} attributionLike The attribution option.
   * @return {Attribution|null} An attribution function (or null).
   */
  function adaptAttributions(attributionLike) {
    if (!attributionLike) {
      return null;
    }
    if (typeof attributionLike === 'function') {
      return attributionLike;
    }
    if (!Array.isArray(attributionLike)) {
      attributionLike = [attributionLike];
    }
    return (frameState) => attributionLike;
  }

  /**
   * @module ol/source/VectorEventType
   */

  /**
   * @enum {string}
   */
  var VectorEventType = {
    /**
     * Triggered when a feature is added to the source.
     * @event module:ol/source/Vector.VectorSourceEvent#addfeature
     * @api
     */
    ADDFEATURE: 'addfeature',

    /**
     * Triggered when a feature is updated.
     * @event module:ol/source/Vector.VectorSourceEvent#changefeature
     * @api
     */
    CHANGEFEATURE: 'changefeature',

    /**
     * Triggered when the clear method is called on the source.
     * @event module:ol/source/Vector.VectorSourceEvent#clear
     * @api
     */
    CLEAR: 'clear',

    /**
     * Triggered when a feature is removed from the source.
     * See {@link module:ol/source/Vector~VectorSource#clear source.clear()} for exceptions.
     * @event module:ol/source/Vector.VectorSourceEvent#removefeature
     * @api
     */
    REMOVEFEATURE: 'removefeature',

    /**
     * Triggered when features starts loading.
     * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart
     * @api
     */
    FEATURESLOADSTART: 'featuresloadstart',

    /**
     * Triggered when features finishes loading.
     * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend
     * @api
     */
    FEATURESLOADEND: 'featuresloadend',

    /**
     * Triggered if feature loading results in an error.
     * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror
     * @api
     */
    FEATURESLOADERROR: 'featuresloaderror',
  };

  /**
   * @typedef {'addfeature'|'changefeature'|'clear'|'removefeature'|'featuresloadstart'|'featuresloadend'|'featuresloaderror'} VectorSourceEventTypes
   */

  /**
   * @module ol/source/Vector
   */


  /**
   * A function that takes an {@link module:ol/extent~Extent} and a resolution as arguments, and
   * returns an array of {@link module:ol/extent~Extent} with the extents to load. Usually this
   * is one of the standard {@link module:ol/loadingstrategy} strategies.
   *
   * @typedef {function(import("../extent.js").Extent, number, import("../proj/Projection.js").default): Array<import("../extent.js").Extent>} LoadingStrategy
   * @api
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/source/Vector~VectorSource} instances are instances of this
   * type.
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   */
  class VectorSourceEvent extends BaseEvent {
    /**
     * @param {string} type Type.
     * @param {FeatureType} [feature] Feature.
     * @param {Array<FeatureType>} [features] Features.
     */
    constructor(type, feature, features) {
      super(type);

      /**
       * The added or removed feature for the `ADDFEATURE` and `REMOVEFEATURE` events, `undefined` otherwise.
       * @type {FeatureType|undefined}
       * @api
       */
      this.feature = feature;

      /**
       * The loaded features for the `FEATURESLOADED` event, `undefined` otherwise.
       * @type {Array<FeatureType>|undefined}
       * @api
       */
      this.features = features;
    }
  }

  /***
   * @template {import("../Feature.js").FeatureLike} [T=import("../Feature.js").default]
   * @typedef {T extends RenderFeature ? T|Array<T> : T} FeatureClassOrArrayOfRenderFeatures
   */

  /***
   * @template Return
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("./VectorEventType").VectorSourceEventTypes, VectorSourceEvent<FeatureType>, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     import("./VectorEventType").VectorSourceEventTypes, Return>} VectorSourceOnSignature
   */

  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {Array<FeatureType>|Collection<FeatureType>} [features]
   * Features. If provided as {@link module:ol/Collection~Collection}, the features in the source
   * and the collection will stay in sync.
   * @property {import("../format/Feature.js").default<FeatureType>} [format] The feature format used by the XHR
   * feature loader when `url` is set. Required if `url` is set, otherwise ignored.
   * @property {import("../featureloader.js").FeatureLoader<FeatureType>} [loader]
   * The loader function used to load features, from a remote source for example.
   * If this is not set and `url` is set, the source will create and use an XHR
   * feature loader. The `'featuresloadend'` and `'featuresloaderror'` events
   * will only fire if the `success` and `failure` callbacks are used.
   *
   * Example:
   *
   * ```js
   * import Vector from 'ol/source/Vector.js';
   * import GeoJSON from 'ol/format/GeoJSON.js';
   * import {bbox} from 'ol/loadingstrategy.js';
   *
   * const vectorSource = new Vector({
   *   format: new GeoJSON(),
   *   loader: function(extent, resolution, projection, success, failure) {
   *      const proj = projection.getCode();
   *      const url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
   *          'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
   *          'outputFormat=application/json&srsname=' + proj + '&' +
   *          'bbox=' + extent.join(',') + ',' + proj;
   *      const xhr = new XMLHttpRequest();
   *      xhr.open('GET', url);
   *      const onError = function() {
   *        vectorSource.removeLoadedExtent(extent);
   *        failure();
   *      }
   *      xhr.onerror = onError;
   *      xhr.onload = function() {
   *        if (xhr.status == 200) {
   *          const features = vectorSource.getFormat().readFeatures(xhr.responseText);
   *          vectorSource.addFeatures(features);
   *          success(features);
   *        } else {
   *          onError();
   *        }
   *      }
   *      xhr.send();
   *    },
   *    strategy: bbox,
   *  });
   * ```
   * @property {boolean} [overlaps=true] This source may have overlapping geometries.
   * Setting this to `false` (e.g. for sources with polygons that represent administrative
   * boundaries or TopoJSON sources) allows the renderer to optimise fill and
   * stroke operations.
   * @property {LoadingStrategy} [strategy] The loading strategy to use.
   * By default an {@link module:ol/loadingstrategy.all}
   * strategy is used, a one-off strategy which loads all features at once.
   * @property {string|import("../featureloader.js").FeatureUrlFunction} [url]
   * Setting this option instructs the source to load features using an XHR loader
   * (see {@link module:ol/featureloader.xhr}). Use a `string` and an
   * {@link module:ol/loadingstrategy.all} for a one-off download of all features from
   * the given URL. Use a {@link module:ol/featureloader~FeatureUrlFunction} to generate the url with
   * other loading strategies.
   * Requires `format` to be set as well.
   * When default XHR feature loader is provided, the features will
   * be transformed from the data projection to the view projection
   * during parsing. If your remote data source does not advertise its projection
   * properly, this transformation will be incorrect. For some formats, the
   * default projection (usually EPSG:4326) can be overridden by setting the
   * dataProjection constructor option on the format.
   * Note that if a source contains non-feature data, such as a GeoJSON geometry
   * or a KML NetworkLink, these will be ignored. Use a custom loader to load these.
   * @property {boolean} [useSpatialIndex=true]
   * By default, an RTree is used as spatial index. When features are removed and
   * added frequently, and the total number of features is low, setting this to
   * `false` may improve performance.
   *
   * Note that
   * {@link module:ol/source/Vector~VectorSource#getFeaturesInExtent},
   * {@link module:ol/source/Vector~VectorSource#getClosestFeatureToCoordinate} and
   * {@link module:ol/source/Vector~VectorSource#getExtent} cannot be used when `useSpatialIndex` is
   * set to `false`, and {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent} will loop
   * through all features.
   *
   * When set to `false`, the features will be maintained in an
   * {@link module:ol/Collection~Collection}, which can be retrieved through
   * {@link module:ol/source/Vector~VectorSource#getFeaturesCollection}.
   * @property {boolean} [wrapX=true] Wrap the world horizontally. For vector editing across the
   * -180° and 180° meridians to work properly, this should be set to `false`. The
   * resulting geometry coordinates will then exceed the world bounds.
   */

  /**
   * @classdesc
   * Provides a source of features for vector layers. Vector features provided
   * by this source are suitable for editing. See {@link module:ol/source/VectorTile~VectorTile} for
   * vector data that is optimized for rendering.
   *
   * @fires VectorSourceEvent
   * @api
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   */
  class VectorSource extends Source {
    /**
     * @param {Options<FeatureType>} [options] Vector source options.
     */
    constructor(options) {
      options = options || {};

      super({
        attributions: options.attributions,
        interpolate: true,
        projection: undefined,
        state: 'ready',
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
      });

      /***
       * @type {VectorSourceOnSignature<import("../events").EventsKey, FeatureType>}
       */
      this.on;

      /***
       * @type {VectorSourceOnSignature<import("../events").EventsKey, FeatureType>}
       */
      this.once;

      /***
       * @type {VectorSourceOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {import("../featureloader.js").FeatureLoader<import("../Feature.js").FeatureLike>}
       */
      this.loader_ = VOID;

      /**
       * @private
       * @type {import("../format/Feature.js").default<FeatureType>|null}
       */
      this.format_ = options.format || null;

      /**
       * @private
       * @type {boolean}
       */
      this.overlaps_ = options.overlaps === undefined ? true : options.overlaps;

      /**
       * @private
       * @type {string|import("../featureloader.js").FeatureUrlFunction|undefined}
       */
      this.url_ = options.url;

      if (options.loader !== undefined) {
        this.loader_ = options.loader;
      } else if (this.url_ !== undefined) {
        assert(this.format_, '`format` must be set when `url` is set');
        // create a XHR feature loader for "url" and "format"
        this.loader_ = xhr(this.url_, this.format_);
      }

      /**
       * @private
       * @type {LoadingStrategy}
       */
      this.strategy_ =
        options.strategy !== undefined ? options.strategy : all$1;

      const useSpatialIndex =
        options.useSpatialIndex !== undefined ? options.useSpatialIndex : true;

      /**
       * @private
       * @type {RBush<FeatureType>}
       */
      this.featuresRtree_ = useSpatialIndex ? new RBush() : null;

      /**
       * @private
       * @type {RBush<{extent: import("../extent.js").Extent}>}
       */
      this.loadedExtentsRtree_ = new RBush();

      /**
       * @type {number}
       * @private
       */
      this.loadingExtentsCount_ = 0;

      /**
       * @private
       * @type {!Object<string, FeatureType>}
       */
      this.nullGeometryFeatures_ = {};

      /**
       * A lookup of features by id (the return from feature.getId()).
       * @private
       * @type {!Object<string, import('../Feature.js').FeatureLike|Array<import('../Feature.js').FeatureLike>>}
       */
      this.idIndex_ = {};

      /**
       * A lookup of features by uid (using getUid(feature)).
       * @private
       * @type {!Object<string, FeatureType>}
       */
      this.uidIndex_ = {};

      /**
       * @private
       * @type {Object<string, Array<import("../events.js").EventsKey>>}
       */
      this.featureChangeKeys_ = {};

      /**
       * @private
       * @type {Collection<FeatureType>|null}
       */
      this.featuresCollection_ = null;

      /** @type {Collection<FeatureType>} */
      let collection;
      /** @type {Array<FeatureType>} */
      let features;
      if (Array.isArray(options.features)) {
        features = options.features;
      } else if (options.features) {
        collection = options.features;
        features = collection.getArray();
      }
      if (!useSpatialIndex && collection === undefined) {
        collection = new Collection(features);
      }
      if (features !== undefined) {
        this.addFeaturesInternal(features);
      }
      if (collection !== undefined) {
        this.bindFeaturesCollection_(collection);
      }
    }

    /**
     * Add a single feature to the source.  If you want to add a batch of features
     * at once, call {@link module:ol/source/Vector~VectorSource#addFeatures #addFeatures()}
     * instead. A feature will not be added to the source if feature with
     * the same id is already there. The reason for this behavior is to avoid
     * feature duplication when using bbox or tile loading strategies.
     * Note: this also applies if a {@link module:ol/Collection~Collection} is used for features,
     * meaning that if a feature with a duplicate id is added in the collection, it will
     * be removed from it right away.
     * @param {FeatureType} feature Feature to add.
     * @api
     */
    addFeature(feature) {
      this.addFeatureInternal(feature);
      this.changed();
    }

    /**
     * Add a feature without firing a `change` event.
     * @param {FeatureType} feature Feature.
     * @protected
     */
    addFeatureInternal(feature) {
      const featureKey = getUid(feature);

      if (!this.addToIndex_(featureKey, feature)) {
        if (this.featuresCollection_) {
          this.featuresCollection_.remove(feature);
        }
        return;
      }

      this.setupChangeEvents_(featureKey, feature);

      const geometry = feature.getGeometry();
      if (geometry) {
        const extent = geometry.getExtent();
        if (this.featuresRtree_) {
          this.featuresRtree_.insert(extent, feature);
        }
      } else {
        this.nullGeometryFeatures_[featureKey] = feature;
      }

      this.dispatchEvent(
        new VectorSourceEvent(VectorEventType.ADDFEATURE, feature),
      );
    }

    /**
     * @param {string} featureKey Unique identifier for the feature.
     * @param {FeatureType} feature The feature.
     * @private
     */
    setupChangeEvents_(featureKey, feature) {
      if (feature instanceof RenderFeature) {
        return;
      }
      this.featureChangeKeys_[featureKey] = [
        listen(feature, EventType.CHANGE, this.handleFeatureChange_, this),
        listen(
          feature,
          ObjectEventType.PROPERTYCHANGE,
          this.handleFeatureChange_,
          this,
        ),
      ];
    }

    /**
     * @param {string} featureKey Unique identifier for the feature.
     * @param {FeatureType} feature The feature.
     * @return {boolean} The feature is "valid", in the sense that it is also a
     *     candidate for insertion into the Rtree.
     * @private
     */
    addToIndex_(featureKey, feature) {
      let valid = true;
      if (feature.getId() !== undefined) {
        const id = String(feature.getId());
        if (!(id in this.idIndex_)) {
          this.idIndex_[id] = feature;
        } else if (feature instanceof RenderFeature) {
          const indexedFeature = this.idIndex_[id];
          if (!(indexedFeature instanceof RenderFeature)) {
            valid = false;
          } else if (!Array.isArray(indexedFeature)) {
            this.idIndex_[id] = [indexedFeature, feature];
          } else {
            indexedFeature.push(feature);
          }
        } else {
          valid = false;
        }
      }
      if (valid) {
        assert(
          !(featureKey in this.uidIndex_),
          'The passed `feature` was already added to the source',
        );
        this.uidIndex_[featureKey] = feature;
      }
      return valid;
    }

    /**
     * Add a batch of features to the source.
     * @param {Array<FeatureType>} features Features to add.
     * @api
     */
    addFeatures(features) {
      this.addFeaturesInternal(features);
      this.changed();
    }

    /**
     * Add features without firing a `change` event.
     * @param {Array<FeatureType>} features Features.
     * @protected
     */
    addFeaturesInternal(features) {
      const extents = [];
      /** @type {Array<FeatureType>} */
      const newFeatures = [];
      /** @type {Array<FeatureType>} */
      const geometryFeatures = [];

      for (let i = 0, length = features.length; i < length; i++) {
        const feature = features[i];
        const featureKey = getUid(feature);
        if (this.addToIndex_(featureKey, feature)) {
          newFeatures.push(feature);
        }
      }

      for (let i = 0, length = newFeatures.length; i < length; i++) {
        const feature = newFeatures[i];
        const featureKey = getUid(feature);
        this.setupChangeEvents_(featureKey, feature);

        const geometry = feature.getGeometry();
        if (geometry) {
          const extent = geometry.getExtent();
          extents.push(extent);
          geometryFeatures.push(feature);
        } else {
          this.nullGeometryFeatures_[featureKey] = feature;
        }
      }
      if (this.featuresRtree_) {
        this.featuresRtree_.load(extents, geometryFeatures);
      }

      if (this.hasListener(VectorEventType.ADDFEATURE)) {
        for (let i = 0, length = newFeatures.length; i < length; i++) {
          this.dispatchEvent(
            new VectorSourceEvent(VectorEventType.ADDFEATURE, newFeatures[i]),
          );
        }
      }
    }

    /**
     * @param {!Collection<FeatureType>} collection Collection.
     * @private
     */
    bindFeaturesCollection_(collection) {
      let modifyingCollection = false;
      this.addEventListener(
        VectorEventType.ADDFEATURE,
        /**
         * @param {VectorSourceEvent<FeatureType>} evt The vector source event
         */
        function (evt) {
          if (!modifyingCollection) {
            modifyingCollection = true;
            collection.push(evt.feature);
            modifyingCollection = false;
          }
        },
      );
      this.addEventListener(
        VectorEventType.REMOVEFEATURE,
        /**
         * @param {VectorSourceEvent<FeatureType>} evt The vector source event
         */
        function (evt) {
          if (!modifyingCollection) {
            modifyingCollection = true;
            collection.remove(evt.feature);
            modifyingCollection = false;
          }
        },
      );
      collection.addEventListener(
        CollectionEventType.ADD,
        /**
         * @param {import("../Collection.js").CollectionEvent<FeatureType>} evt The collection event
         */
        (evt) => {
          if (!modifyingCollection) {
            modifyingCollection = true;
            this.addFeature(evt.element);
            modifyingCollection = false;
          }
        },
      );
      collection.addEventListener(
        CollectionEventType.REMOVE,
        /**
         * @param {import("../Collection.js").CollectionEvent<FeatureType>} evt The collection event
         */
        (evt) => {
          if (!modifyingCollection) {
            modifyingCollection = true;
            this.removeFeature(evt.element);
            modifyingCollection = false;
          }
        },
      );
      this.featuresCollection_ = collection;
    }

    /**
     * Remove all features from the source.
     * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/Vector.VectorSourceEvent#event:removefeature} events.
     * @api
     */
    clear(fast) {
      if (fast) {
        for (const featureId in this.featureChangeKeys_) {
          const keys = this.featureChangeKeys_[featureId];
          keys.forEach(unlistenByKey);
        }
        if (!this.featuresCollection_) {
          this.featureChangeKeys_ = {};
          this.idIndex_ = {};
          this.uidIndex_ = {};
        }
      } else {
        if (this.featuresRtree_) {
          this.featuresRtree_.forEach((feature) => {
            this.removeFeatureInternal(feature);
          });
          for (const id in this.nullGeometryFeatures_) {
            this.removeFeatureInternal(this.nullGeometryFeatures_[id]);
          }
        }
      }
      if (this.featuresCollection_) {
        this.featuresCollection_.clear();
      }

      if (this.featuresRtree_) {
        this.featuresRtree_.clear();
      }
      this.nullGeometryFeatures_ = {};

      const clearEvent = new VectorSourceEvent(VectorEventType.CLEAR);
      this.dispatchEvent(clearEvent);
      this.changed();
    }

    /**
     * Iterate through all features on the source, calling the provided callback
     * with each one.  If the callback returns any "truthy" value, iteration will
     * stop and the function will return the same value.
     * Note: this function only iterate through the feature that have a defined geometry.
     *
     * @param {function(FeatureType): T} callback Called with each feature
     *     on the source.  Return a truthy value to stop iteration.
     * @return {T|undefined} The return value from the last call to the callback.
     * @template T
     * @api
     */
    forEachFeature(callback) {
      if (this.featuresRtree_) {
        return this.featuresRtree_.forEach(callback);
      }
      if (this.featuresCollection_) {
        this.featuresCollection_.forEach(callback);
      }
    }

    /**
     * Iterate through all features whose geometries contain the provided
     * coordinate, calling the callback with each feature.  If the callback returns
     * a "truthy" value, iteration will stop and the function will return the same
     * value.
     *
     * For {@link module:ol/render/Feature~RenderFeature} features, the callback will be
     * called for all features.
     *
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {function(FeatureType): T} callback Called with each feature
     *     whose goemetry contains the provided coordinate.
     * @return {T|undefined} The return value from the last call to the callback.
     * @template T
     */
    forEachFeatureAtCoordinateDirect(coordinate, callback) {
      const extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]];
      return this.forEachFeatureInExtent(extent, function (feature) {
        const geometry = feature.getGeometry();
        if (
          geometry instanceof RenderFeature ||
          geometry.intersectsCoordinate(coordinate)
        ) {
          return callback(feature);
        }
        return undefined;
      });
    }

    /**
     * Iterate through all features whose bounding box intersects the provided
     * extent (note that the feature's geometry may not intersect the extent),
     * calling the callback with each feature.  If the callback returns a "truthy"
     * value, iteration will stop and the function will return the same value.
     *
     * If you are interested in features whose geometry intersects an extent, call
     * the {@link module:ol/source/Vector~VectorSource#forEachFeatureIntersectingExtent #forEachFeatureIntersectingExtent()} method instead.
     *
     * When `useSpatialIndex` is set to false, this method will loop through all
     * features, equivalent to {@link module:ol/source/Vector~VectorSource#forEachFeature #forEachFeature()}.
     *
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {function(FeatureType): T} callback Called with each feature
     *     whose bounding box intersects the provided extent.
     * @return {T|undefined} The return value from the last call to the callback.
     * @template T
     * @api
     */
    forEachFeatureInExtent(extent, callback) {
      if (this.featuresRtree_) {
        return this.featuresRtree_.forEachInExtent(extent, callback);
      }
      if (this.featuresCollection_) {
        this.featuresCollection_.forEach(callback);
      }
    }

    /**
     * Iterate through all features whose geometry intersects the provided extent,
     * calling the callback with each feature.  If the callback returns a "truthy"
     * value, iteration will stop and the function will return the same value.
     *
     * If you only want to test for bounding box intersection, call the
     * {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent #forEachFeatureInExtent()} method instead.
     *
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {function(FeatureType): T} callback Called with each feature
     *     whose geometry intersects the provided extent.
     * @return {T|undefined} The return value from the last call to the callback.
     * @template T
     * @api
     */
    forEachFeatureIntersectingExtent(extent, callback) {
      return this.forEachFeatureInExtent(
        extent,
        /**
         * @param {FeatureType} feature Feature.
         * @return {T|undefined} The return value from the last call to the callback.
         */
        function (feature) {
          const geometry = feature.getGeometry();
          if (
            geometry instanceof RenderFeature ||
            geometry.intersectsExtent(extent)
          ) {
            const result = callback(feature);
            if (result) {
              return result;
            }
          }
        },
      );
    }

    /**
     * Get the features collection associated with this source. Will be `null`
     * unless the source was configured with `useSpatialIndex` set to `false`, or
     * with a {@link module:ol/Collection~Collection} as `features`.
     * @return {Collection<FeatureType>|null} The collection of features.
     * @api
     */
    getFeaturesCollection() {
      return this.featuresCollection_;
    }

    /**
     * Get a snapshot of the features currently on the source in random order. The returned array
     * is a copy, the features are references to the features in the source.
     * @return {Array<FeatureType>} Features.
     * @api
     */
    getFeatures() {
      let features;
      if (this.featuresCollection_) {
        features = this.featuresCollection_.getArray().slice(0);
      } else if (this.featuresRtree_) {
        features = this.featuresRtree_.getAll();
        if (!isEmpty$1(this.nullGeometryFeatures_)) {
          extend$2(features, Object.values(this.nullGeometryFeatures_));
        }
      }
      return features;
    }

    /**
     * Get all features whose geometry intersects the provided coordinate.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @return {Array<FeatureType>} Features.
     * @api
     */
    getFeaturesAtCoordinate(coordinate) {
      /** @type {Array<FeatureType>} */
      const features = [];
      this.forEachFeatureAtCoordinateDirect(coordinate, function (feature) {
        features.push(feature);
      });
      return features;
    }

    /**
     * Get all features whose bounding box intersects the provided extent.  Note that this returns an array of
     * all features intersecting the given extent in random order (so it may include
     * features whose geometries do not intersect the extent).
     *
     * When `useSpatialIndex` is set to false, this method will return all
     * features.
     *
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {import("../proj/Projection.js").default} [projection] Include features
     * where `extent` exceeds the x-axis bounds of `projection` and wraps around the world.
     * @return {Array<FeatureType>} Features.
     * @api
     */
    getFeaturesInExtent(extent, projection) {
      if (this.featuresRtree_) {
        const multiWorld = projection && projection.canWrapX() && this.getWrapX();

        if (!multiWorld) {
          return this.featuresRtree_.getInExtent(extent);
        }

        const extents = wrapAndSliceX(extent, projection);

        return [].concat(
          ...extents.map((anExtent) => this.featuresRtree_.getInExtent(anExtent)),
        );
      }
      if (this.featuresCollection_) {
        return this.featuresCollection_.getArray().slice(0);
      }
      return [];
    }

    /**
     * Get the closest feature to the provided coordinate.
     *
     * This method is not available when the source is configured with
     * `useSpatialIndex` set to `false` and the features in this source are of type
     * {@link module:ol/Feature~Feature}.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {function(FeatureType):boolean} [filter] Feature filter function.
     *     The filter function will receive one argument, the {@link module:ol/Feature~Feature feature}
     *     and it should return a boolean value. By default, no filtering is made.
     * @return {FeatureType|null} Closest feature (or `null` if none found).
     * @api
     */
    getClosestFeatureToCoordinate(coordinate, filter) {
      // Find the closest feature using branch and bound.  We start searching an
      // infinite extent, and find the distance from the first feature found.  This
      // becomes the closest feature.  We then compute a smaller extent which any
      // closer feature must intersect.  We continue searching with this smaller
      // extent, trying to find a closer feature.  Every time we find a closer
      // feature, we update the extent being searched so that any even closer
      // feature must intersect it.  We continue until we run out of features.
      const x = coordinate[0];
      const y = coordinate[1];
      let closestFeature = null;
      const closestPoint = [NaN, NaN];
      let minSquaredDistance = Infinity;
      const extent = [-Infinity, -Infinity, Infinity, Infinity];
      filter = filter ? filter : TRUE;
      this.featuresRtree_.forEachInExtent(
        extent,
        /**
         * @param {FeatureType} feature Feature.
         */
        function (feature) {
          if (filter(feature)) {
            const geometry = feature.getGeometry();
            const previousMinSquaredDistance = minSquaredDistance;
            minSquaredDistance =
              geometry instanceof RenderFeature
                ? 0
                : geometry.closestPointXY(x, y, closestPoint, minSquaredDistance);
            if (minSquaredDistance < previousMinSquaredDistance) {
              closestFeature = feature;
              // This is sneaky.  Reduce the extent that it is currently being
              // searched while the R-Tree traversal using this same extent object
              // is still in progress.  This is safe because the new extent is
              // strictly contained by the old extent.
              const minDistance = Math.sqrt(minSquaredDistance);
              extent[0] = x - minDistance;
              extent[1] = y - minDistance;
              extent[2] = x + minDistance;
              extent[3] = y + minDistance;
            }
          }
        },
      );
      return closestFeature;
    }

    /**
     * Get the extent of the features currently in the source.
     *
     * This method is not available when the source is configured with
     * `useSpatialIndex` set to `false`.
     * @param {import("../extent.js").Extent} [extent] Destination extent. If provided, no new extent
     *     will be created. Instead, that extent's coordinates will be overwritten.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getExtent(extent) {
      return this.featuresRtree_.getExtent(extent);
    }

    /**
     * Get a feature by its identifier (the value returned by feature.getId()). When `RenderFeature`s
     * are used, `getFeatureById()` can return an array of `RenderFeature`s. This allows for handling
     * of `GeometryCollection` geometries, where format readers create one `RenderFeature` per
     * `GeometryCollection` member.
     * Note that the index treats string and numeric identifiers as the same.  So
     * `source.getFeatureById(2)` will return a feature with id `'2'` or `2`.
     *
     * @param {string|number} id Feature identifier.
     * @return {FeatureClassOrArrayOfRenderFeatures<FeatureType>|null} The feature (or `null` if not found).
     * @api
     */
    getFeatureById(id) {
      const feature = this.idIndex_[id.toString()];
      return feature !== undefined
        ? /** @type {FeatureClassOrArrayOfRenderFeatures<FeatureType>} */ (
            feature
          )
        : null;
    }

    /**
     * Get a feature by its internal unique identifier (using `getUid`).
     *
     * @param {string} uid Feature identifier.
     * @return {FeatureType|null} The feature (or `null` if not found).
     */
    getFeatureByUid(uid) {
      const feature = this.uidIndex_[uid];
      return feature !== undefined ? feature : null;
    }

    /**
     * Get the format associated with this source.
     *
     * @return {import("../format/Feature.js").default<FeatureType>|null}} The feature format.
     * @api
     */
    getFormat() {
      return this.format_;
    }

    /**
     * @return {boolean} The source can have overlapping geometries.
     */
    getOverlaps() {
      return this.overlaps_;
    }

    /**
     * Get the url associated with this source.
     *
     * @return {string|import("../featureloader.js").FeatureUrlFunction|undefined} The url.
     * @api
     */
    getUrl() {
      return this.url_;
    }

    /**
     * @param {Event} event Event.
     * @private
     */
    handleFeatureChange_(event) {
      const feature = /** @type {FeatureType} */ (event.target);
      const featureKey = getUid(feature);
      const geometry = feature.getGeometry();
      if (!geometry) {
        if (!(featureKey in this.nullGeometryFeatures_)) {
          if (this.featuresRtree_) {
            this.featuresRtree_.remove(feature);
          }
          this.nullGeometryFeatures_[featureKey] = feature;
        }
      } else {
        const extent = geometry.getExtent();
        if (featureKey in this.nullGeometryFeatures_) {
          delete this.nullGeometryFeatures_[featureKey];
          if (this.featuresRtree_) {
            this.featuresRtree_.insert(extent, feature);
          }
        } else {
          if (this.featuresRtree_) {
            this.featuresRtree_.update(extent, feature);
          }
        }
      }
      const id = feature.getId();
      if (id !== undefined) {
        const sid = id.toString();
        if (this.idIndex_[sid] !== feature) {
          this.removeFromIdIndex_(feature);
          this.idIndex_[sid] = feature;
        }
      } else {
        this.removeFromIdIndex_(feature);
        this.uidIndex_[featureKey] = feature;
      }
      this.changed();
      this.dispatchEvent(
        new VectorSourceEvent(VectorEventType.CHANGEFEATURE, feature),
      );
    }

    /**
     * Returns true if the feature is contained within the source.
     * @param {FeatureType} feature Feature.
     * @return {boolean} Has feature.
     * @api
     */
    hasFeature(feature) {
      const id = feature.getId();
      if (id !== undefined) {
        return id in this.idIndex_;
      }
      return getUid(feature) in this.uidIndex_;
    }

    /**
     * @return {boolean} Is empty.
     */
    isEmpty() {
      if (this.featuresRtree_) {
        return (
          this.featuresRtree_.isEmpty() && isEmpty$1(this.nullGeometryFeatures_)
        );
      }
      if (this.featuresCollection_) {
        return this.featuresCollection_.getLength() === 0;
      }
      return true;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {import("../proj/Projection.js").default} projection Projection.
     */
    loadFeatures(extent, resolution, projection) {
      const loadedExtentsRtree = this.loadedExtentsRtree_;
      const extentsToLoad = this.strategy_(extent, resolution, projection);
      for (let i = 0, ii = extentsToLoad.length; i < ii; ++i) {
        const extentToLoad = extentsToLoad[i];
        const alreadyLoaded = loadedExtentsRtree.forEachInExtent(
          extentToLoad,
          /**
           * @param {{extent: import("../extent.js").Extent}} object Object.
           * @return {boolean} Contains.
           */
          function (object) {
            return containsExtent(object.extent, extentToLoad);
          },
        );
        if (!alreadyLoaded) {
          ++this.loadingExtentsCount_;
          this.dispatchEvent(
            new VectorSourceEvent(VectorEventType.FEATURESLOADSTART),
          );
          this.loader_.call(
            this,
            extentToLoad,
            resolution,
            projection,
            /**
             * @param {Array<FeatureType>} features Loaded features
             */
            (features) => {
              --this.loadingExtentsCount_;
              this.dispatchEvent(
                new VectorSourceEvent(
                  VectorEventType.FEATURESLOADEND,
                  undefined,
                  features,
                ),
              );
            },
            () => {
              --this.loadingExtentsCount_;
              this.dispatchEvent(
                new VectorSourceEvent(VectorEventType.FEATURESLOADERROR),
              );
            },
          );
          loadedExtentsRtree.insert(extentToLoad, {extent: extentToLoad.slice()});
        }
      }
      this.loading =
        this.loader_.length < 4 ? false : this.loadingExtentsCount_ > 0;
    }

    /**
     * @override
     */
    refresh() {
      this.clear(true);
      this.loadedExtentsRtree_.clear();
      super.refresh();
    }

    /**
     * Remove an extent from the list of loaded extents.
     * @param {import("../extent.js").Extent} extent Extent.
     * @api
     */
    removeLoadedExtent(extent) {
      const loadedExtentsRtree = this.loadedExtentsRtree_;
      const obj = loadedExtentsRtree.forEachInExtent(extent, function (object) {
        if (equals$1(object.extent, extent)) {
          return object;
        }
      });
      if (obj) {
        loadedExtentsRtree.remove(obj);
      }
    }

    /**
     * Batch remove features from the source.  If you want to remove all features
     * at once, use the {@link module:ol/source/Vector~VectorSource#clear #clear()} method
     * instead.
     * @param {Array<FeatureType>} features Features to remove.
     * @api
     */
    removeFeatures(features) {
      let removed = false;
      for (let i = 0, ii = features.length; i < ii; ++i) {
        removed = this.removeFeatureInternal(features[i]) || removed;
      }
      if (removed) {
        this.changed();
      }
    }

    /**
     * Remove a single feature from the source. If you want to batch remove
     * features, use the {@link module:ol/source/Vector~VectorSource#removeFeatures #removeFeatures()} method
     * instead.
     * @param {FeatureType} feature Feature to remove.
     * @api
     */
    removeFeature(feature) {
      if (!feature) {
        return;
      }
      const removed = this.removeFeatureInternal(feature);
      if (removed) {
        this.changed();
      }
    }

    /**
     * Remove feature without firing a `change` event.
     * @param {FeatureType} feature Feature.
     * @return {boolean} True if the feature was removed, false if it was not found.
     * @protected
     */
    removeFeatureInternal(feature) {
      const featureKey = getUid(feature);
      if (!(featureKey in this.uidIndex_)) {
        return false;
      }

      if (featureKey in this.nullGeometryFeatures_) {
        delete this.nullGeometryFeatures_[featureKey];
      } else {
        if (this.featuresRtree_) {
          this.featuresRtree_.remove(feature);
        }
      }

      const featureChangeKeys = this.featureChangeKeys_[featureKey];
      featureChangeKeys?.forEach(unlistenByKey);
      delete this.featureChangeKeys_[featureKey];

      const id = feature.getId();
      if (id !== undefined) {
        const idString = id.toString();
        const indexedFeature = this.idIndex_[idString];
        if (indexedFeature === feature) {
          delete this.idIndex_[idString];
        } else if (Array.isArray(indexedFeature)) {
          indexedFeature.splice(indexedFeature.indexOf(feature), 1);
          if (indexedFeature.length === 1) {
            this.idIndex_[idString] = indexedFeature[0];
          }
        }
      }
      delete this.uidIndex_[featureKey];
      if (this.hasListener(VectorEventType.REMOVEFEATURE)) {
        this.dispatchEvent(
          new VectorSourceEvent(VectorEventType.REMOVEFEATURE, feature),
        );
      }
      return true;
    }

    /**
     * Remove a feature from the id index.  Called internally when the feature id
     * may have changed.
     * @param {FeatureType} feature The feature.
     * @private
     */
    removeFromIdIndex_(feature) {
      for (const id in this.idIndex_) {
        if (this.idIndex_[id] === feature) {
          delete this.idIndex_[id];
          break;
        }
      }
    }

    /**
     * Set the new loader of the source. The next render cycle will use the
     * new loader.
     * @param {import("../featureloader.js").FeatureLoader} loader The loader to set.
     * @api
     */
    setLoader(loader) {
      this.loader_ = loader;
    }

    /**
     * Points the source to a new url. The next render cycle will use the new url.
     * @param {string|import("../featureloader.js").FeatureUrlFunction} url Url.
     * @api
     */
    setUrl(url) {
      assert(this.format_, '`format` must be set when `url` is set');
      this.url_ = url;
      this.setLoader(xhr(url, this.format_));
    }

    /**
     * @param {boolean} overlaps The source can have overlapping geometries.
     */
    setOverlaps(overlaps) {
      this.overlaps_ = overlaps;
      this.changed();
    }
  }

  /**
   * @module ol/style/Fill
   */


  /**
   * @typedef {Object} Options
   * @property {import("../color.js").Color|import("../colorlike.js").ColorLike|import('../colorlike.js').PatternDescriptor|null} [color=null] A color,
   * gradient or pattern.
   * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats. For polygon fills (not for {@link import("./RegularShape.js").default} fills),
   * a pattern can also be provided as {@link module:ol/colorlike~PatternDescriptor}.
   * Default null; if null, the Canvas/renderer default black will be used.
   */

  /**
   * @classdesc
   * Set fill style for vector features.
   * @api
   */
  class Fill {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @private
       * @type {import("./IconImage.js").default|null}
       */
      this.patternImage_ = null;

      /**
       * @private
       * @type {import("../color.js").Color|import("../colorlike.js").ColorLike|import('../colorlike.js').PatternDescriptor|null}
       */
      this.color_ = null;
      if (options.color !== undefined) {
        this.setColor(options.color);
      }
    }

    /**
     * Clones the style. The color is not cloned if it is a {@link module:ol/colorlike~ColorLike}.
     * @return {Fill} The cloned style.
     * @api
     */
    clone() {
      const color = this.getColor();
      return new Fill({
        color: Array.isArray(color) ? color.slice() : color || undefined,
      });
    }

    /**
     * Get the fill color.
     * @return {import("../color.js").Color|import("../colorlike.js").ColorLike|import('../colorlike.js').PatternDescriptor|null} Color.
     * @api
     */
    getColor() {
      return this.color_;
    }

    /**
     * Set the color.
     *
     * @param {import("../color.js").Color|import("../colorlike.js").ColorLike|import('../colorlike.js').PatternDescriptor|null} color Color.
     * @api
     */
    setColor(color) {
      if (color !== null && typeof color === 'object' && 'src' in color) {
        const patternImage = get$1(
          null,
          color.src,
          'anonymous',
          undefined,
          color.offset ? null : color.color ? color.color : null,
          !(color.offset && color.size),
        );
        patternImage.ready().then(() => {
          this.patternImage_ = null;
        });
        if (patternImage.getImageState() === ImageState.IDLE) {
          patternImage.load();
        }
        if (patternImage.getImageState() === ImageState.LOADING) {
          this.patternImage_ = patternImage;
        }
      }
      this.color_ = color;
    }

    /**
     * @return {string} Key of the fill for cache lookup.
     */
    getKey() {
      const fill = this.getColor();
      if (!fill) {
        return '';
      }
      return fill instanceof CanvasPattern || fill instanceof CanvasGradient
        ? getUid(fill)
        : typeof fill === 'object' && 'src' in fill
          ? fill.src + ':' + fill.offset
          : asArray(fill).toString();
    }

    /**
     * @return {boolean} The fill style is loading an image pattern.
     */
    loading() {
      return !!this.patternImage_;
    }

    /**
     * @return {Promise<void>} `false` or a promise that resolves when the style is ready to use.
     */
    ready() {
      return this.patternImage_ ? this.patternImage_.ready() : Promise.resolve();
    }
  }

  /**
   * @module ol/style/Stroke
   */

  /**
   * @typedef {Object} Options
   * @property {import("../color.js").Color|import("../colorlike.js").ColorLike} [color] A color, gradient or pattern.
   * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.
   * Default null; if null, the Canvas/renderer default black will be used.
   * @property {CanvasLineCap} [lineCap='round'] Line cap style: `butt`, `round`, or `square`.
   * @property {CanvasLineJoin} [lineJoin='round'] Line join style: `bevel`, `round`, or `miter`.
   * @property {Array<number>} [lineDash] Line dash pattern. Default is `null` (no dash).
   * @property {number} [lineDashOffset=0] Line dash offset.
   * @property {number} [miterLimit=10] Miter limit.
   * @property {number} [width] Width.
   */

  /**
   * @classdesc
   * Set stroke style for vector features.
   * Note that the defaults given are the Canvas defaults, which will be used if
   * option is not defined. The `get` functions return whatever was entered in
   * the options; they will not return the default.
   * @api
   */
  class Stroke {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @private
       * @type {import("../color.js").Color|import("../colorlike.js").ColorLike}
       */
      this.color_ = options.color !== undefined ? options.color : null;

      /**
       * @private
       * @type {CanvasLineCap|undefined}
       */
      this.lineCap_ = options.lineCap;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.lineDash_ = options.lineDash !== undefined ? options.lineDash : null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lineDashOffset_ = options.lineDashOffset;

      /**
       * @private
       * @type {CanvasLineJoin|undefined}
       */
      this.lineJoin_ = options.lineJoin;

      /**
       * @private
       * @type {number|undefined}
       */
      this.miterLimit_ = options.miterLimit;

      /**
       * @private
       * @type {number|undefined}
       */
      this.width_ = options.width;
    }

    /**
     * Clones the style.
     * @return {Stroke} The cloned style.
     * @api
     */
    clone() {
      const color = this.getColor();
      return new Stroke({
        color: Array.isArray(color) ? color.slice() : color || undefined,
        lineCap: this.getLineCap(),
        lineDash: this.getLineDash() ? this.getLineDash().slice() : undefined,
        lineDashOffset: this.getLineDashOffset(),
        lineJoin: this.getLineJoin(),
        miterLimit: this.getMiterLimit(),
        width: this.getWidth(),
      });
    }

    /**
     * Get the stroke color.
     * @return {import("../color.js").Color|import("../colorlike.js").ColorLike} Color.
     * @api
     */
    getColor() {
      return this.color_;
    }

    /**
     * Get the line cap type for the stroke.
     * @return {CanvasLineCap|undefined} Line cap.
     * @api
     */
    getLineCap() {
      return this.lineCap_;
    }

    /**
     * Get the line dash style for the stroke.
     * @return {Array<number>|null} Line dash.
     * @api
     */
    getLineDash() {
      return this.lineDash_;
    }

    /**
     * Get the line dash offset for the stroke.
     * @return {number|undefined} Line dash offset.
     * @api
     */
    getLineDashOffset() {
      return this.lineDashOffset_;
    }

    /**
     * Get the line join type for the stroke.
     * @return {CanvasLineJoin|undefined} Line join.
     * @api
     */
    getLineJoin() {
      return this.lineJoin_;
    }

    /**
     * Get the miter limit for the stroke.
     * @return {number|undefined} Miter limit.
     * @api
     */
    getMiterLimit() {
      return this.miterLimit_;
    }

    /**
     * Get the stroke width.
     * @return {number|undefined} Width.
     * @api
     */
    getWidth() {
      return this.width_;
    }

    /**
     * Set the color.
     *
     * @param {import("../color.js").Color|import("../colorlike.js").ColorLike} color Color.
     * @api
     */
    setColor(color) {
      this.color_ = color;
    }

    /**
     * Set the line cap.
     *
     * @param {CanvasLineCap|undefined} lineCap Line cap.
     * @api
     */
    setLineCap(lineCap) {
      this.lineCap_ = lineCap;
    }

    /**
     * Set the line dash.
     *
     * @param {Array<number>|null} lineDash Line dash.
     * @api
     */
    setLineDash(lineDash) {
      this.lineDash_ = lineDash;
    }

    /**
     * Set the line dash offset.
     *
     * @param {number|undefined} lineDashOffset Line dash offset.
     * @api
     */
    setLineDashOffset(lineDashOffset) {
      this.lineDashOffset_ = lineDashOffset;
    }

    /**
     * Set the line join.
     *
     * @param {CanvasLineJoin|undefined} lineJoin Line join.
     * @api
     */
    setLineJoin(lineJoin) {
      this.lineJoin_ = lineJoin;
    }

    /**
     * Set the miter limit.
     *
     * @param {number|undefined} miterLimit Miter limit.
     * @api
     */
    setMiterLimit(miterLimit) {
      this.miterLimit_ = miterLimit;
    }

    /**
     * Set the width.
     *
     * @param {number|undefined} width Width.
     * @api
     */
    setWidth(width) {
      this.width_ = width;
    }
  }

  /**
   * @module ol/size
   */


  /**
   * Determines if a size has a positive area.
   * @param {Size} size The size to test.
   * @return {boolean} The size has a positive area.
   */
  function hasArea(size) {
    return size[0] > 0 && size[1] > 0;
  }

  /**
   * Returns a size scaled by a ratio. The result will be an array of integers.
   * @param {Size} size Size.
   * @param {number} ratio Ratio.
   * @param {Size} [dest] Optional reusable size array.
   * @return {Size} The scaled size.
   */
  function scale$1(size, ratio, dest) {
    if (dest === undefined) {
      dest = [0, 0];
    }
    dest[0] = (size[0] * ratio + 0.5) | 0;
    dest[1] = (size[1] * ratio + 0.5) | 0;
    return dest;
  }

  /**
   * Returns an `Size` array for the passed in number (meaning: square) or
   * `Size` array.
   * (meaning: non-square),
   * @param {number|Size} size Width and height.
   * @param {Size} [dest] Optional reusable size array.
   * @return {Size} Size.
   * @api
   */
  function toSize(size, dest) {
    if (Array.isArray(size)) {
      return size;
    }
    if (dest === undefined) {
      dest = [size, size];
    } else {
      dest[0] = size;
      dest[1] = size;
    }
    return dest;
  }

  /**
   * @module ol/style/Image
   */

  /**
   * @typedef {Object} Options
   * @property {number} opacity Opacity.
   * @property {boolean} rotateWithView If the image should get rotated with the view.
   * @property {number} rotation Rotation.
   * @property {number|import("../size.js").Size} scale Scale.
   * @property {Array<number>} displacement Displacement.
   * @property {import('../style/Style.js').DeclutterMode} declutterMode Declutter mode: `declutter`, `obstacle`, `none`.
   */

  /**
   * @classdesc
   * A base class used for creating subclasses and not instantiated in
   * apps. Base class for {@link module:ol/style/Icon~Icon}, {@link module:ol/style/Circle~CircleStyle} and
   * {@link module:ol/style/RegularShape~RegularShape}.
   * @abstract
   * @api
   */
  class ImageStyle {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      /**
       * @private
       * @type {number}
       */
      this.opacity_ = options.opacity;

      /**
       * @private
       * @type {boolean}
       */
      this.rotateWithView_ = options.rotateWithView;

      /**
       * @private
       * @type {number}
       */
      this.rotation_ = options.rotation;

      /**
       * @private
       * @type {number|import("../size.js").Size}
       */
      this.scale_ = options.scale;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.scaleArray_ = toSize(options.scale);

      /**
       * @private
       * @type {Array<number>}
       */
      this.displacement_ = options.displacement;

      /**
       * @private
       * @type {import('../style/Style.js').DeclutterMode}
       */
      this.declutterMode_ = options.declutterMode;
    }

    /**
     * Clones the style.
     * @return {ImageStyle} The cloned style.
     * @api
     */
    clone() {
      const scale = this.getScale();
      return new ImageStyle({
        opacity: this.getOpacity(),
        scale: Array.isArray(scale) ? scale.slice() : scale,
        rotation: this.getRotation(),
        rotateWithView: this.getRotateWithView(),
        displacement: this.getDisplacement().slice(),
        declutterMode: this.getDeclutterMode(),
      });
    }

    /**
     * Get the symbolizer opacity.
     * @return {number} Opacity.
     * @api
     */
    getOpacity() {
      return this.opacity_;
    }

    /**
     * Determine whether the symbolizer rotates with the map.
     * @return {boolean} Rotate with map.
     * @api
     */
    getRotateWithView() {
      return this.rotateWithView_;
    }

    /**
     * Get the symoblizer rotation.
     * @return {number} Rotation.
     * @api
     */
    getRotation() {
      return this.rotation_;
    }

    /**
     * Get the symbolizer scale.
     * @return {number|import("../size.js").Size} Scale.
     * @api
     */
    getScale() {
      return this.scale_;
    }

    /**
     * Get the symbolizer scale array.
     * @return {import("../size.js").Size} Scale array.
     */
    getScaleArray() {
      return this.scaleArray_;
    }

    /**
     * Get the displacement of the shape
     * @return {Array<number>} Shape's center displacement
     * @api
     */
    getDisplacement() {
      return this.displacement_;
    }

    /**
     * Get the declutter mode of the shape
     * @return {import("./Style.js").DeclutterMode} Shape's declutter mode
     * @api
     */
    getDeclutterMode() {
      return this.declutterMode_;
    }

    /**
     * Get the anchor point in pixels. The anchor determines the center point for the
     * symbolizer.
     * @abstract
     * @return {Array<number>} Anchor.
     */
    getAnchor() {
      return abstract();
    }

    /**
     * Get the image element for the symbolizer.
     * @abstract
     * @param {number} pixelRatio Pixel ratio.
     * @return {import('../DataTile.js').ImageLike} Image element.
     */
    getImage(pixelRatio) {
      return abstract();
    }

    /**
     * @abstract
     * @return {import('../DataTile.js').ImageLike} Image element.
     */
    getHitDetectionImage() {
      return abstract();
    }

    /**
     * Get the image pixel ratio.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Pixel ratio.
     */
    getPixelRatio(pixelRatio) {
      return 1;
    }

    /**
     * @abstract
     * @return {import("../ImageState.js").default} Image state.
     */
    getImageState() {
      return abstract();
    }

    /**
     * @abstract
     * @return {import("../size.js").Size} Image size.
     */
    getImageSize() {
      return abstract();
    }

    /**
     * Get the origin of the symbolizer.
     * @abstract
     * @return {Array<number>} Origin.
     */
    getOrigin() {
      return abstract();
    }

    /**
     * Get the size of the symbolizer (in pixels).
     * @abstract
     * @return {import("../size.js").Size} Size.
     */
    getSize() {
      return abstract();
    }

    /**
     * Set the displacement.
     *
     * @param {Array<number>} displacement Displacement.
     * @api
     */
    setDisplacement(displacement) {
      this.displacement_ = displacement;
    }

    /**
     * Set the opacity.
     *
     * @param {number} opacity Opacity.
     * @api
     */
    setOpacity(opacity) {
      this.opacity_ = opacity;
    }

    /**
     * Set whether to rotate the style with the view.
     *
     * @param {boolean} rotateWithView Rotate with map.
     * @api
     */
    setRotateWithView(rotateWithView) {
      this.rotateWithView_ = rotateWithView;
    }

    /**
     * Set the rotation.
     *
     * @param {number} rotation Rotation.
     * @api
     */
    setRotation(rotation) {
      this.rotation_ = rotation;
    }

    /**
     * Set the scale.
     *
     * @param {number|import("../size.js").Size} scale Scale.
     * @api
     */
    setScale(scale) {
      this.scale_ = scale;
      this.scaleArray_ = toSize(scale);
    }

    /**
     * @abstract
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     */
    listenImageChange(listener) {
      abstract();
    }

    /**
     * Load not yet loaded URI.
     * @abstract
     */
    load() {
      abstract();
    }

    /**
     * @abstract
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     */
    unlistenImageChange(listener) {
      abstract();
    }

    /**
     * @return {Promise<void>} `false` or Promise that resolves when the style is ready to use.
     */
    ready() {
      return Promise.resolve();
    }
  }

  /**
   * @module ol/style/RegularShape
   */


  /**
   * Specify radius for regular polygons, or both radius and radius2 for stars.
   * @typedef {Object} Options
   * @property {import("./Fill.js").default} [fill] Fill style.
   * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points
   * is the number of sides.
   * @property {number} radius Radius of a regular polygon.
   * @property {number} [radius2] Second radius to make a star instead of a regular polygon.
   * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's points facing up.
   * @property {Array<number>} [displacement=[0, 0]] Displacement of the shape in pixels.
   * Positive values will shift the shape right and up.
   * @property {import("./Stroke.js").default} [stroke] Stroke style.
   * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.
   * @property {number|import("../size.js").Size} [scale=1] Scale. Unless two dimensional scaling is required a better
   * result may be obtained with appropriate settings for `radius` and `radius2`.
   * @property {import('./Style.js').DeclutterMode} [declutterMode] Declutter mode.
   */

  /**
   * @typedef {Object} RenderOptions
   * @property {import("../colorlike.js").ColorLike|undefined} strokeStyle StrokeStyle.
   * @property {number} strokeWidth StrokeWidth.
   * @property {number} size Size.
   * @property {CanvasLineCap} lineCap LineCap.
   * @property {Array<number>|null} lineDash LineDash.
   * @property {number} lineDashOffset LineDashOffset.
   * @property {CanvasLineJoin} lineJoin LineJoin.
   * @property {number} miterLimit MiterLimit.
   */

  /**
   * @classdesc
   * Set regular shape style for vector features. The resulting shape will be
   * a regular polygon when `radius` is provided, or a star when both `radius` and
   * `radius2` are provided.
   * @api
   */
  class RegularShape extends ImageStyle {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      super({
        opacity: 1,
        rotateWithView:
          options.rotateWithView !== undefined ? options.rotateWithView : false,
        rotation: options.rotation !== undefined ? options.rotation : 0,
        scale: options.scale !== undefined ? options.scale : 1,
        displacement:
          options.displacement !== undefined ? options.displacement : [0, 0],
        declutterMode: options.declutterMode,
      });

      /**
       * @private
       * @type {HTMLCanvasElement|null}
       */
      this.hitDetectionCanvas_ = null;

      /**
       * @private
       * @type {import("./Fill.js").default|null}
       */
      this.fill_ = options.fill !== undefined ? options.fill : null;

      /**
       * @private
       * @type {Array<number>}
       */
      this.origin_ = [0, 0];

      /**
       * @private
       * @type {number}
       */
      this.points_ = options.points;

      /**
       * @protected
       * @type {number}
       */
      this.radius = options.radius;

      /**
       * @private
       * @type {number|undefined}
       */
      this.radius2_ = options.radius2;

      /**
       * @private
       * @type {number}
       */
      this.angle_ = options.angle !== undefined ? options.angle : 0;

      /**
       * @private
       * @type {import("./Stroke.js").default|null}
       */
      this.stroke_ = options.stroke !== undefined ? options.stroke : null;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.size_;

      /**
       * @private
       * @type {RenderOptions}
       */
      this.renderOptions_;

      /**
       * @private
       */
      this.imageState_ =
        this.fill_ && this.fill_.loading()
          ? ImageState.LOADING
          : ImageState.LOADED;
      if (this.imageState_ === ImageState.LOADING) {
        this.ready().then(() => (this.imageState_ = ImageState.LOADED));
      }
      this.render();
    }

    /**
     * Clones the style.
     * @return {RegularShape} The cloned style.
     * @api
     * @override
     */
    clone() {
      const scale = this.getScale();
      const style = new RegularShape({
        fill: this.getFill() ? this.getFill().clone() : undefined,
        points: this.getPoints(),
        radius: this.getRadius(),
        radius2: this.getRadius2(),
        angle: this.getAngle(),
        stroke: this.getStroke() ? this.getStroke().clone() : undefined,
        rotation: this.getRotation(),
        rotateWithView: this.getRotateWithView(),
        scale: Array.isArray(scale) ? scale.slice() : scale,
        displacement: this.getDisplacement().slice(),
        declutterMode: this.getDeclutterMode(),
      });
      style.setOpacity(this.getOpacity());
      return style;
    }

    /**
     * Get the anchor point in pixels. The anchor determines the center point for the
     * symbolizer.
     * @return {Array<number>} Anchor.
     * @api
     * @override
     */
    getAnchor() {
      const size = this.size_;
      const displacement = this.getDisplacement();
      const scale = this.getScaleArray();
      // anchor is scaled by renderer but displacement should not be scaled
      // so divide by scale here
      return [
        size[0] / 2 - displacement[0] / scale[0],
        size[1] / 2 + displacement[1] / scale[1],
      ];
    }

    /**
     * Get the angle used in generating the shape.
     * @return {number} Shape's rotation in radians.
     * @api
     */
    getAngle() {
      return this.angle_;
    }

    /**
     * Get the fill style for the shape.
     * @return {import("./Fill.js").default|null} Fill style.
     * @api
     */
    getFill() {
      return this.fill_;
    }

    /**
     * Set the fill style.
     * @param {import("./Fill.js").default|null} fill Fill style.
     * @api
     */
    setFill(fill) {
      this.fill_ = fill;
      this.render();
    }

    /**
     * @return {HTMLCanvasElement} Image element.
     * @override
     */
    getHitDetectionImage() {
      if (!this.hitDetectionCanvas_) {
        this.hitDetectionCanvas_ = this.createHitDetectionCanvas_(
          this.renderOptions_,
        );
      }
      return this.hitDetectionCanvas_;
    }

    /**
     * Get the image icon.
     * @param {number} pixelRatio Pixel ratio.
     * @return {HTMLCanvasElement} Image or Canvas element.
     * @api
     * @override
     */
    getImage(pixelRatio) {
      const fillKey = this.fill_?.getKey();
      const cacheKey =
        `${pixelRatio},${this.angle_},${this.radius},${this.radius2_},${this.points_},${fillKey}` +
        Object.values(this.renderOptions_).join(',');
      let image = /** @type {HTMLCanvasElement} */ (
        shared.get(cacheKey, null, null)?.getImage(1)
      );
      if (!image) {
        const renderOptions = this.renderOptions_;
        const size = Math.ceil(renderOptions.size * pixelRatio);
        const context = createCanvasContext2D(size, size);
        this.draw_(renderOptions, context, pixelRatio);

        image = context.canvas;
        shared.set(
          cacheKey,
          null,
          null,
          new IconImage(image, undefined, null, ImageState.LOADED, null),
        );
      }
      return image;
    }

    /**
     * Get the image pixel ratio.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Pixel ratio.
     * @override
     */
    getPixelRatio(pixelRatio) {
      return pixelRatio;
    }

    /**
     * @return {import("../size.js").Size} Image size.
     * @override
     */
    getImageSize() {
      return this.size_;
    }

    /**
     * @return {import("../ImageState.js").default} Image state.
     * @override
     */
    getImageState() {
      return this.imageState_;
    }

    /**
     * Get the origin of the symbolizer.
     * @return {Array<number>} Origin.
     * @api
     * @override
     */
    getOrigin() {
      return this.origin_;
    }

    /**
     * Get the number of points for generating the shape.
     * @return {number} Number of points for stars and regular polygons.
     * @api
     */
    getPoints() {
      return this.points_;
    }

    /**
     * Get the (primary) radius for the shape.
     * @return {number} Radius.
     * @api
     */
    getRadius() {
      return this.radius;
    }

    /**
     * Get the secondary radius for the shape.
     * @return {number|undefined} Radius2.
     * @api
     */
    getRadius2() {
      return this.radius2_;
    }

    /**
     * Get the size of the symbolizer (in pixels).
     * @return {import("../size.js").Size} Size.
     * @api
     * @override
     */
    getSize() {
      return this.size_;
    }

    /**
     * Get the stroke style for the shape.
     * @return {import("./Stroke.js").default|null} Stroke style.
     * @api
     */
    getStroke() {
      return this.stroke_;
    }

    /**
     * Set the stroke style.
     * @param {import("./Stroke.js").default|null} stroke Stroke style.
     * @api
     */
    setStroke(stroke) {
      this.stroke_ = stroke;
      this.render();
    }

    /**
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     * @override
     */
    listenImageChange(listener) {}

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {}

    /**
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     * @override
     */
    unlistenImageChange(listener) {}

    /**
     * Calculate additional canvas size needed for the miter.
     * @param {string} lineJoin Line join
     * @param {number} strokeWidth Stroke width
     * @param {number} miterLimit Miter limit
     * @return {number} Additional canvas size needed
     * @private
     */
    calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit) {
      if (
        strokeWidth === 0 ||
        this.points_ === Infinity ||
        (lineJoin !== 'bevel' && lineJoin !== 'miter')
      ) {
        return strokeWidth;
      }
      // m  | ^
      // i  | |\                  .
      // t >|  #\
      // e  | |\ \              .
      // r      \s\
      //      |  \t\          .                 .
      //          \r\                      .   .
      //      |    \o\      .          .  . . .
      //          e \k\            .  .    . .
      //      |      \e\  .    .  .       . .
      //       d      \ \  .  .          . .
      //      | _ _a_ _\#  .            . .
      //   r1          / `             . .
      //      |                       . .
      //       b     /               . .
      //      |                     . .
      //           / r2            . .
      //      |                        .   .
      //         /                           .   .
      //      |α                                   .   .
      //       /                                         .   .
      //      ° center
      let r1 = this.radius;
      let r2 = this.radius2_ === undefined ? r1 : this.radius2_;
      if (r1 < r2) {
        const tmp = r1;
        r1 = r2;
        r2 = tmp;
      }
      const points =
        this.radius2_ === undefined ? this.points_ : this.points_ * 2;
      const alpha = (2 * Math.PI) / points;
      const a = r2 * Math.sin(alpha);
      const b = Math.sqrt(r2 * r2 - a * a);
      const d = r1 - b;
      const e = Math.sqrt(a * a + d * d);
      const miterRatio = e / a;
      if (lineJoin === 'miter' && miterRatio <= miterLimit) {
        return miterRatio * strokeWidth;
      }
      // Calculate the distance from center to the stroke corner where
      // it was cut short because of the miter limit.
      //              l
      //        ----+---- <= distance from center to here is maxr
      //       /####|k ##\
      //      /#####^#####\
      //     /#### /+\# s #\
      //    /### h/+++\# t #\
      //   /### t/+++++\# r #\
      //  /### a/+++++++\# o #\
      // /### p/++ fill +\# k #\
      ///#### /+++++^+++++\# e #\
      //#####/+++++/+\+++++\#####\
      const k = strokeWidth / 2 / miterRatio;
      const l = (strokeWidth / 2) * (d / e);
      const maxr = Math.sqrt((r1 + k) * (r1 + k) + l * l);
      const bevelAdd = maxr - r1;
      if (this.radius2_ === undefined || lineJoin === 'bevel') {
        return bevelAdd * 2;
      }
      // If outer miter is over the miter limit the inner miter may reach through the
      // center and be longer than the bevel, same calculation as above but swap r1 / r2.
      const aa = r1 * Math.sin(alpha);
      const bb = Math.sqrt(r1 * r1 - aa * aa);
      const dd = r2 - bb;
      const ee = Math.sqrt(aa * aa + dd * dd);
      const innerMiterRatio = ee / aa;
      if (innerMiterRatio <= miterLimit) {
        const innerLength = (innerMiterRatio * strokeWidth) / 2 - r2 - r1;
        return 2 * Math.max(bevelAdd, innerLength);
      }
      return bevelAdd * 2;
    }

    /**
     * @return {RenderOptions}  The render options
     * @protected
     */
    createRenderOptions() {
      let lineCap = defaultLineCap;
      let lineJoin = defaultLineJoin;
      let miterLimit = 0;
      let lineDash = null;
      let lineDashOffset = 0;
      let strokeStyle;
      let strokeWidth = 0;

      if (this.stroke_) {
        strokeStyle = asColorLike(this.stroke_.getColor() ?? defaultStrokeStyle);
        strokeWidth = this.stroke_.getWidth() ?? defaultLineWidth;
        lineDash = this.stroke_.getLineDash();
        lineDashOffset = this.stroke_.getLineDashOffset() ?? 0;
        lineJoin = this.stroke_.getLineJoin() ?? defaultLineJoin;
        lineCap = this.stroke_.getLineCap() ?? defaultLineCap;
        miterLimit = this.stroke_.getMiterLimit() ?? defaultMiterLimit;
      }

      const add = this.calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit);
      const maxRadius = Math.max(this.radius, this.radius2_ || 0);
      const size = Math.ceil(2 * maxRadius + add);

      return {
        strokeStyle: strokeStyle,
        strokeWidth: strokeWidth,
        size: size,
        lineCap: lineCap,
        lineDash: lineDash,
        lineDashOffset: lineDashOffset,
        lineJoin: lineJoin,
        miterLimit: miterLimit,
      };
    }

    /**
     * @protected
     */
    render() {
      this.renderOptions_ = this.createRenderOptions();
      const size = this.renderOptions_.size;
      this.hitDetectionCanvas_ = null;
      this.size_ = [size, size];
    }

    /**
     * @private
     * @param {RenderOptions} renderOptions Render options.
     * @param {CanvasRenderingContext2D} context The rendering context.
     * @param {number} pixelRatio The pixel ratio.
     */
    draw_(renderOptions, context, pixelRatio) {
      context.scale(pixelRatio, pixelRatio);
      // set origin to canvas center
      context.translate(renderOptions.size / 2, renderOptions.size / 2);

      this.createPath_(context);

      if (this.fill_) {
        let color = this.fill_.getColor();
        if (color === null) {
          color = defaultFillStyle;
        }
        context.fillStyle = asColorLike(color);
        context.fill();
      }
      if (renderOptions.strokeStyle) {
        context.strokeStyle = renderOptions.strokeStyle;
        context.lineWidth = renderOptions.strokeWidth;
        if (renderOptions.lineDash) {
          context.setLineDash(renderOptions.lineDash);
          context.lineDashOffset = renderOptions.lineDashOffset;
        }
        context.lineCap = renderOptions.lineCap;
        context.lineJoin = renderOptions.lineJoin;
        context.miterLimit = renderOptions.miterLimit;
        context.stroke();
      }
    }

    /**
     * @private
     * @param {RenderOptions} renderOptions Render options.
     * @return {HTMLCanvasElement} Canvas containing the icon
     */
    createHitDetectionCanvas_(renderOptions) {
      let context;
      if (this.fill_) {
        let color = this.fill_.getColor();

        // determine if fill is transparent (or pattern or gradient)
        let opacity = 0;
        if (typeof color === 'string') {
          color = asArray(color);
        }
        if (color === null) {
          opacity = 1;
        } else if (Array.isArray(color)) {
          opacity = color.length === 4 ? color[3] : 1;
        }
        if (opacity === 0) {
          // if a transparent fill style is set, create an extra hit-detection image
          // with a default fill style
          context = createCanvasContext2D(renderOptions.size, renderOptions.size);
          this.drawHitDetectionCanvas_(renderOptions, context);
        }
      }
      return context ? context.canvas : this.getImage(1);
    }

    /**
     * @private
     * @param {CanvasRenderingContext2D} context The context to draw in.
     */
    createPath_(context) {
      let points = this.points_;
      const radius = this.radius;
      if (points === Infinity) {
        context.arc(0, 0, radius, 0, 2 * Math.PI);
      } else {
        const radius2 = this.radius2_ === undefined ? radius : this.radius2_;
        if (this.radius2_ !== undefined) {
          points *= 2;
        }
        const startAngle = this.angle_ - Math.PI / 2;
        const step = (2 * Math.PI) / points;
        for (let i = 0; i < points; i++) {
          const angle0 = startAngle + i * step;
          const radiusC = i % 2 === 0 ? radius : radius2;
          context.lineTo(radiusC * Math.cos(angle0), radiusC * Math.sin(angle0));
        }
        context.closePath();
      }
    }

    /**
     * @private
     * @param {RenderOptions} renderOptions Render options.
     * @param {CanvasRenderingContext2D} context The context.
     */
    drawHitDetectionCanvas_(renderOptions, context) {
      // set origin to canvas center
      context.translate(renderOptions.size / 2, renderOptions.size / 2);

      this.createPath_(context);

      context.fillStyle = defaultFillStyle;
      context.fill();
      if (renderOptions.strokeStyle) {
        context.strokeStyle = renderOptions.strokeStyle;
        context.lineWidth = renderOptions.strokeWidth;
        if (renderOptions.lineDash) {
          context.setLineDash(renderOptions.lineDash);
          context.lineDashOffset = renderOptions.lineDashOffset;
        }
        context.lineJoin = renderOptions.lineJoin;
        context.miterLimit = renderOptions.miterLimit;
        context.stroke();
      }
    }

    /**
     * @override
     */
    ready() {
      return this.fill_ ? this.fill_.ready() : Promise.resolve();
    }
  }

  /**
   * @module ol/style/Circle
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Fill.js").default} [fill] Fill style.
   * @property {number} radius Circle radius.
   * @property {import("./Stroke.js").default} [stroke] Stroke style.
   * @property {Array<number>} [displacement=[0,0]] displacement
   * @property {number|import("../size.js").Size} [scale=1] Scale. A two dimensional scale will produce an ellipse.
   * Unless two dimensional scaling is required a better result may be obtained with an appropriate setting for `radius`.
   * @property {number} [rotation=0] Rotation in radians
   * (positive rotation clockwise, meaningful only when used in conjunction with a two dimensional scale).
   * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view
   * (meaningful only when used in conjunction with a two dimensional scale).
   * @property {import('./Style.js').DeclutterMode} [declutterMode] Declutter mode
   */

  /**
   * @classdesc
   * Set circle style for vector features.
   * @api
   */
  class CircleStyle extends RegularShape {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {radius: 5};

      super({
        points: Infinity,
        fill: options.fill,
        radius: options.radius,
        stroke: options.stroke,
        scale: options.scale !== undefined ? options.scale : 1,
        rotation: options.rotation !== undefined ? options.rotation : 0,
        rotateWithView:
          options.rotateWithView !== undefined ? options.rotateWithView : false,
        displacement:
          options.displacement !== undefined ? options.displacement : [0, 0],
        declutterMode: options.declutterMode,
      });
    }

    /**
     * Clones the style.
     * @return {CircleStyle} The cloned style.
     * @api
     * @override
     */
    clone() {
      const scale = this.getScale();
      const style = new CircleStyle({
        fill: this.getFill() ? this.getFill().clone() : undefined,
        stroke: this.getStroke() ? this.getStroke().clone() : undefined,
        radius: this.getRadius(),
        scale: Array.isArray(scale) ? scale.slice() : scale,
        rotation: this.getRotation(),
        rotateWithView: this.getRotateWithView(),
        displacement: this.getDisplacement().slice(),
        declutterMode: this.getDeclutterMode(),
      });
      style.setOpacity(this.getOpacity());
      return style;
    }

    /**
     * Set the circle radius.
     *
     * @param {number} radius Circle radius.
     * @api
     */
    setRadius(radius) {
      this.radius = radius;
      this.render();
    }
  }

  /**
   * @module ol/style/Style
   */


  /**
   * Defines how symbols and text are decluttered on layers ith `declutter` set to `true`
   * **declutter**: Overlapping symbols and text are decluttered.
   * **obstacle**: Symbols and text are rendered, but serve as obstacle for subsequent attempts
   *   to place a symbol or text at the same location.
   * **none**: No decluttering is done.
   *
   * @typedef {"declutter"|"obstacle"|"none"} DeclutterMode
   */

  /**
   * A function that takes a {@link module:ol/Feature~Feature} and a `{number}`
   * representing the view's resolution. The function should return a
   * {@link module:ol/style/Style~Style} or an array of them. This way e.g. a
   * vector layer can be styled. If the function returns `undefined`, the
   * feature will not be rendered.
   *
   * @typedef {function(import("../Feature.js").FeatureLike, number):(Style|Array<Style>|void)} StyleFunction
   */

  /**
   * A {@link Style}, an array of {@link Style}, or a {@link StyleFunction}.
   * @typedef {Style|Array<Style>|StyleFunction} StyleLike
   */

  /**
   * A function that takes a {@link module:ol/Feature~Feature} as argument and returns an
   * {@link module:ol/geom/Geometry~Geometry} that will be rendered and styled for the feature.
   *
   * @typedef {function(import("../Feature.js").FeatureLike):
   *     (import("../geom/Geometry.js").default|import("../render/Feature.js").default|undefined)} GeometryFunction
   */

  /**
   * Custom renderer function. Takes two arguments:
   *
   * 1. The pixel coordinates of the geometry in GeoJSON notation.
   * 2. The {@link module:ol/render~State} of the layer renderer.
   *
   * @typedef {function((import("../coordinate.js").Coordinate|Array<import("../coordinate.js").Coordinate>|Array<Array<import("../coordinate.js").Coordinate>>|Array<Array<Array<import("../coordinate.js").Coordinate>>>),import("../render.js").State): void} RenderFunction
   */

  /**
   * @typedef {Object} Options
   * @property {string|import("../geom/Geometry.js").default|GeometryFunction} [geometry] Feature property or geometry
   * or function returning a geometry to render for this style.
   * @property {import("./Fill.js").default} [fill] Fill style.
   * @property {import("./Image.js").default} [image] Image style.
   * @property {RenderFunction} [renderer] Custom renderer. When configured, `fill`, `stroke` and `image` will be
   * ignored, and the provided function will be called with each render frame for each geometry.
   * @property {RenderFunction} [hitDetectionRenderer] Custom renderer for hit detection. If provided will be used
   * in hit detection rendering.
   * @property {import("./Stroke.js").default} [stroke] Stroke style.
   * @property {import("./Text.js").default} [text] Text style.
   * @property {number} [zIndex] Z index.
   */

  /**
   * @classdesc
   * Container for vector feature rendering styles. Any changes made to the style
   * or its children through `set*()` methods will not take effect until the
   * feature or layer that uses the style is re-rendered.
   *
   * ## Feature styles
   *
   * If no style is defined, the following default style is used:
   * ```js
   *  import {Circle, Fill, Stroke, Style} from 'ol/style.js';
   *
   *  const fill = new Fill({
   *    color: 'rgba(255,255,255,0.4)',
   *  });
   *  const stroke = new Stroke({
   *    color: '#3399CC',
   *    width: 1.25,
   *  });
   *  const styles = [
   *    new Style({
   *      image: new Circle({
   *        fill: fill,
   *        stroke: stroke,
   *        radius: 5,
   *      }),
   *      fill: fill,
   *      stroke: stroke,
   *    }),
   *  ];
   * ```
   *
   * A separate editing style has the following defaults:
   * ```js
   *  import {Circle, Fill, Stroke, Style} from 'ol/style.js';
   *
   *  const styles = {};
   *  const white = [255, 255, 255, 1];
   *  const blue = [0, 153, 255, 1];
   *  const width = 3;
   *  styles['Polygon'] = [
   *    new Style({
   *      fill: new Fill({
   *        color: [255, 255, 255, 0.5],
   *      }),
   *    }),
   *  ];
   *  styles['MultiPolygon'] =
   *      styles['Polygon'];
   *  styles['LineString'] = [
   *    new Style({
   *      stroke: new Stroke({
   *        color: white,
   *        width: width + 2,
   *      }),
   *    }),
   *    new Style({
   *      stroke: new Stroke({
   *        color: blue,
   *        width: width,
   *      }),
   *    }),
   *  ];
   *  styles['MultiLineString'] = styles['LineString'];
   *
   *  styles['Circle'] = styles['Polygon'].concat(
   *    styles['LineString']
   *  );
   *
   *  styles['Point'] = [
   *    new Style({
   *      image: new Circle({
   *        radius: width * 2,
   *        fill: new Fill({
   *          color: blue,
   *        }),
   *        stroke: new Stroke({
   *          color: white,
   *          width: width / 2,
   *        }),
   *      }),
   *      zIndex: Infinity,
   *    }),
   *  ];
   *  styles['MultiPoint'] =
   *      styles['Point'];
   *  styles['GeometryCollection'] =
   *      styles['Polygon'].concat(
   *          styles['LineString'],
   *          styles['Point']
   *      );
   * ```
   *
   * @api
   */
  class Style {
    /**
     * @param {Options} [options] Style options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @private
       * @type {string|import("../geom/Geometry.js").default|GeometryFunction|null}
       */
      this.geometry_ = null;

      /**
       * @private
       * @type {!GeometryFunction}
       */
      this.geometryFunction_ = defaultGeometryFunction;

      if (options.geometry !== undefined) {
        this.setGeometry(options.geometry);
      }

      /**
       * @private
       * @type {import("./Fill.js").default|null}
       */
      this.fill_ = options.fill !== undefined ? options.fill : null;

      /**
       * @private
       * @type {import("./Image.js").default|null}
       */
      this.image_ = options.image !== undefined ? options.image : null;

      /**
       * @private
       * @type {RenderFunction|null}
       */
      this.renderer_ = options.renderer !== undefined ? options.renderer : null;

      /**
       * @private
       * @type {RenderFunction|null}
       */
      this.hitDetectionRenderer_ =
        options.hitDetectionRenderer !== undefined
          ? options.hitDetectionRenderer
          : null;

      /**
       * @private
       * @type {import("./Stroke.js").default|null}
       */
      this.stroke_ = options.stroke !== undefined ? options.stroke : null;

      /**
       * @private
       * @type {import("./Text.js").default|null}
       */
      this.text_ = options.text !== undefined ? options.text : null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.zIndex_ = options.zIndex;
    }

    /**
     * Clones the style.
     * @return {Style} The cloned style.
     * @api
     */
    clone() {
      let geometry = this.getGeometry();
      if (geometry && typeof geometry === 'object') {
        geometry = /** @type {import("../geom/Geometry.js").default} */ (
          geometry
        ).clone();
      }
      return new Style({
        geometry: geometry ?? undefined,
        fill: this.getFill() ? this.getFill().clone() : undefined,
        image: this.getImage() ? this.getImage().clone() : undefined,
        renderer: this.getRenderer() ?? undefined,
        stroke: this.getStroke() ? this.getStroke().clone() : undefined,
        text: this.getText() ? this.getText().clone() : undefined,
        zIndex: this.getZIndex(),
      });
    }

    /**
     * Get the custom renderer function that was configured with
     * {@link #setRenderer} or the `renderer` constructor option.
     * @return {RenderFunction|null} Custom renderer function.
     * @api
     */
    getRenderer() {
      return this.renderer_;
    }

    /**
     * Sets a custom renderer function for this style. When set, `fill`, `stroke`
     * and `image` options of the style will be ignored.
     * @param {RenderFunction|null} renderer Custom renderer function.
     * @api
     */
    setRenderer(renderer) {
      this.renderer_ = renderer;
    }

    /**
     * Sets a custom renderer function for this style used
     * in hit detection.
     * @param {RenderFunction|null} renderer Custom renderer function.
     * @api
     */
    setHitDetectionRenderer(renderer) {
      this.hitDetectionRenderer_ = renderer;
    }

    /**
     * Get the custom renderer function that was configured with
     * {@link #setHitDetectionRenderer} or the `hitDetectionRenderer` constructor option.
     * @return {RenderFunction|null} Custom renderer function.
     * @api
     */
    getHitDetectionRenderer() {
      return this.hitDetectionRenderer_;
    }

    /**
     * Get the geometry to be rendered.
     * @return {string|import("../geom/Geometry.js").default|GeometryFunction|null}
     * Feature property or geometry or function that returns the geometry that will
     * be rendered with this style.
     * @api
     */
    getGeometry() {
      return this.geometry_;
    }

    /**
     * Get the function used to generate a geometry for rendering.
     * @return {!GeometryFunction} Function that is called with a feature
     * and returns the geometry to render instead of the feature's geometry.
     * @api
     */
    getGeometryFunction() {
      return this.geometryFunction_;
    }

    /**
     * Get the fill style.
     * @return {import("./Fill.js").default|null} Fill style.
     * @api
     */
    getFill() {
      return this.fill_;
    }

    /**
     * Set the fill style.
     * @param {import("./Fill.js").default|null} fill Fill style.
     * @api
     */
    setFill(fill) {
      this.fill_ = fill;
    }

    /**
     * Get the image style.
     * @return {import("./Image.js").default|null} Image style.
     * @api
     */
    getImage() {
      return this.image_;
    }

    /**
     * Set the image style.
     * @param {import("./Image.js").default} image Image style.
     * @api
     */
    setImage(image) {
      this.image_ = image;
    }

    /**
     * Get the stroke style.
     * @return {import("./Stroke.js").default|null} Stroke style.
     * @api
     */
    getStroke() {
      return this.stroke_;
    }

    /**
     * Set the stroke style.
     * @param {import("./Stroke.js").default|null} stroke Stroke style.
     * @api
     */
    setStroke(stroke) {
      this.stroke_ = stroke;
    }

    /**
     * Get the text style.
     * @return {import("./Text.js").default|null} Text style.
     * @api
     */
    getText() {
      return this.text_;
    }

    /**
     * Set the text style.
     * @param {import("./Text.js").default} text Text style.
     * @api
     */
    setText(text) {
      this.text_ = text;
    }

    /**
     * Get the z-index for the style.
     * @return {number|undefined} ZIndex.
     * @api
     */
    getZIndex() {
      return this.zIndex_;
    }

    /**
     * Set a geometry that is rendered instead of the feature's geometry.
     *
     * @param {string|import("../geom/Geometry.js").default|GeometryFunction|null} geometry
     *     Feature property or geometry or function returning a geometry to render
     *     for this style.
     * @api
     */
    setGeometry(geometry) {
      if (typeof geometry === 'function') {
        this.geometryFunction_ = geometry;
      } else if (typeof geometry === 'string') {
        this.geometryFunction_ = function (feature) {
          return /** @type {import("../geom/Geometry.js").default} */ (
            feature.get(geometry)
          );
        };
      } else if (!geometry) {
        this.geometryFunction_ = defaultGeometryFunction;
      } else if (geometry !== undefined) {
        this.geometryFunction_ = function () {
          return /** @type {import("../geom/Geometry.js").default} */ (geometry);
        };
      }
      this.geometry_ = geometry;
    }

    /**
     * Set the z-index.
     *
     * @param {number|undefined} zIndex ZIndex.
     * @api
     */
    setZIndex(zIndex) {
      this.zIndex_ = zIndex;
    }
  }

  /**
   * Convert the provided object into a style function.  Functions passed through
   * unchanged.  Arrays of Style or single style objects wrapped in a
   * new style function.
   * @param {StyleFunction|Array<Style>|Style} obj
   *     A style function, a single style, or an array of styles.
   * @return {StyleFunction} A style function.
   */
  function toFunction(obj) {
    let styleFunction;

    if (typeof obj === 'function') {
      styleFunction = obj;
    } else {
      /**
       * @type {Array<Style>}
       */
      let styles;
      if (Array.isArray(obj)) {
        styles = obj;
      } else {
        assert(
          typeof (/** @type {?} */ (obj).getZIndex) === 'function',
          'Expected an `Style` or an array of `Style`',
        );
        const style = /** @type {Style} */ (obj);
        styles = [style];
      }
      styleFunction = function () {
        return styles;
      };
    }
    return styleFunction;
  }

  /**
   * @type {Array<Style>|null}
   */
  let defaultStyles = null;

  /**
   * @param {import("../Feature.js").FeatureLike} feature Feature.
   * @param {number} resolution Resolution.
   * @return {Array<Style>} Style.
   */
  function createDefaultStyle$1(feature, resolution) {
    // We don't use an immediately-invoked function
    // and a closure so we don't get an error at script evaluation time in
    // browsers that do not support Canvas. (import("./Circle.js").CircleStyle does
    // canvas.getContext('2d') at construction time, which will cause an.error
    // in such browsers.)
    if (!defaultStyles) {
      const fill = new Fill({
        color: 'rgba(255,255,255,0.4)',
      });
      const stroke = new Stroke({
        color: '#3399CC',
        width: 1.25,
      });
      defaultStyles = [
        new Style({
          image: new CircleStyle({
            fill: fill,
            stroke: stroke,
            radius: 5,
          }),
          fill: fill,
          stroke: stroke,
        }),
      ];
    }
    return defaultStyles;
  }

  /**
   * Default styles for editing features.
   * @return {Object<import("../geom/Geometry.js").Type, Array<Style>>} Styles
   */
  function createEditingStyle() {
    /** @type {Object<import("../geom/Geometry.js").Type, Array<Style>>} */
    const styles = {};
    const white = [255, 255, 255, 1];
    const blue = [0, 153, 255, 1];
    const width = 3;
    styles['Polygon'] = [
      new Style({
        fill: new Fill({
          color: [255, 255, 255, 0.5],
        }),
      }),
    ];
    styles['MultiPolygon'] = styles['Polygon'];

    styles['LineString'] = [
      new Style({
        stroke: new Stroke({
          color: white,
          width: width + 2,
        }),
      }),
      new Style({
        stroke: new Stroke({
          color: blue,
          width: width,
        }),
      }),
    ];
    styles['MultiLineString'] = styles['LineString'];

    styles['Circle'] = styles['Polygon'].concat(styles['LineString']);

    styles['Point'] = [
      new Style({
        image: new CircleStyle({
          radius: width * 2,
          fill: new Fill({
            color: blue,
          }),
          stroke: new Stroke({
            color: white,
            width: width / 2,
          }),
        }),
        zIndex: Infinity,
      }),
    ];
    styles['MultiPoint'] = styles['Point'];

    styles['GeometryCollection'] = styles['Polygon'].concat(
      styles['LineString'],
      styles['Point'],
    );

    return styles;
  }

  /**
   * Function that is called with a feature and returns its default geometry.
   * @param {import("../Feature.js").FeatureLike} feature Feature to get the geometry for.
   * @return {import("../geom/Geometry.js").default|import("../render/Feature.js").default|undefined} Geometry to render.
   */
  function defaultGeometryFunction(feature) {
    return feature.getGeometry();
  }

  /**
   * @module ol/style/Text
   */

  /**
   * @typedef {'point' | 'line'} TextPlacement
   * Default text placement is `'point'`. Note that
   * `'line'` requires the underlying geometry to be a {@link module:ol/geom/LineString~LineString},
   * {@link module:ol/geom/Polygon~Polygon}, {@link module:ol/geom/MultiLineString~MultiLineString} or
   * {@link module:ol/geom/MultiPolygon~MultiPolygon}.
   */

  /**
   * @typedef {'left' | 'center' | 'right'} TextJustify
   */

  /**
   * The default fill color to use if no fill was set at construction time; a
   * blackish `#333`.
   *
   * @const {string}
   */
  const DEFAULT_FILL_COLOR = '#333';

  /**
   * @typedef {Object} Options
   * @property {string} [font] Font style as CSS `font` value, see:
   * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font. Default is `'10px sans-serif'`
   * @property {number} [maxAngle=Math.PI/4] When `placement` is set to `'line'`, allow a maximum angle between adjacent characters.
   * The expected value is in radians, and the default is 45° (`Math.PI / 4`).
   * @property {number} [offsetX=0] Horizontal text offset in pixels. A positive will shift the text right.
   * @property {number} [offsetY=0] Vertical text offset in pixels. A positive will shift the text down.
   * @property {boolean} [overflow=false] For polygon labels or when `placement` is set to `'line'`, allow text to exceed
   * the width of the polygon at the label position or the length of the path that it follows.
   * @property {TextPlacement} [placement='point'] Text placement.
   * @property {number} [repeat] Repeat interval. When set, the text will be repeated at this interval, which specifies
   * the distance between two text anchors in pixels. Only available when `placement` is set to `'line'`. Overrides 'textAlign'.
   * @property {number|import("../size.js").Size} [scale] Scale.
   * @property {boolean} [rotateWithView=false] Whether to rotate the text with the view.
   * @property {boolean} [keepUpright=true] Whether the text can be rotated 180° to prevent being rendered upside down.
   * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {string|Array<string>} [text] Text content or rich text content. For plain text provide a string, which can
   * contain line breaks (`\n`). For rich text provide an array of text/font tuples. A tuple consists of the text to
   * render and the font to use (or `''` to use the text style's font). A line break has to be a separate tuple (i.e. `'\n', ''`).
   * **Example:** `['foo', 'bold 10px sans-serif', ' bar', 'italic 10px sans-serif', ' baz', '']` will yield "**foo** *bar* baz".
   * **Note:** Rich text is not supported for `placement: 'line'` or the immediate rendering API.
   * @property {CanvasTextAlign} [textAlign] Text alignment. Possible values: `'left'`, `'right'`, `'center'`, `'end'` or `'start'`.
   * Default is `'center'` for `placement: 'point'`. For `placement: 'line'`, the default is to let the renderer choose a
   * placement where `maxAngle` is not exceeded.
   * @property {TextJustify} [justify] Text justification within the text box.
   * If not set, text is justified towards the `textAlign` anchor.
   * Otherwise, use options `'left'`, `'center'`, or `'right'` to justify the text within the text box.
   * **Note:** `justify` is ignored for immediate rendering and also for `placement: 'line'`.
   * @property {CanvasTextBaseline} [textBaseline='middle'] Text base line. Possible values: `'bottom'`, `'top'`, `'middle'`, `'alphabetic'`,
   * `'hanging'`, `'ideographic'`.
   * @property {import("./Fill.js").default|null} [fill] Fill style. If none is provided, we'll use a dark fill-style (#333). Specify `null` for no fill.
   * @property {import("./Stroke.js").default} [stroke] Stroke style.
   * @property {import("./Fill.js").default} [backgroundFill] Fill style for the text background when `placement` is
   * `'point'`. Default is no fill.
   * @property {import("./Stroke.js").default} [backgroundStroke] Stroke style for the text background  when `placement`
   * is `'point'`. Default is no stroke.
   * @property {Array<number>} [padding=[0, 0, 0, 0]] Padding in pixels around the text for decluttering and background. The order of
   * values in the array is `[top, right, bottom, left]`.
   * @property {import('../style/Style.js').DeclutterMode} [declutterMode] Declutter mode: `declutter`, `obstacle`, `none`
   */

  /**
   * @classdesc
   * Set text style for vector features.
   * @api
   */
  class Text {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @private
       * @type {string|undefined}
       */
      this.font_ = options.font;

      /**
       * @private
       * @type {number|undefined}
       */
      this.rotation_ = options.rotation;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.rotateWithView_ = options.rotateWithView;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.keepUpright_ = options.keepUpright;

      /**
       * @private
       * @type {number|import("../size.js").Size|undefined}
       */
      this.scale_ = options.scale;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.scaleArray_ = toSize(options.scale !== undefined ? options.scale : 1);

      /**
       * @private
       * @type {string|Array<string>|undefined}
       */
      this.text_ = options.text;

      /**
       * @private
       * @type {CanvasTextAlign|undefined}
       */
      this.textAlign_ = options.textAlign;

      /**
       * @private
       * @type {TextJustify|undefined}
       */
      this.justify_ = options.justify;

      /**
       * @private
       * @type {number|undefined}
       */
      this.repeat_ = options.repeat;

      /**
       * @private
       * @type {CanvasTextBaseline|undefined}
       */
      this.textBaseline_ = options.textBaseline;

      /**
       * @private
       * @type {import("./Fill.js").default|null}
       */
      this.fill_ =
        options.fill !== undefined
          ? options.fill
          : new Fill({color: DEFAULT_FILL_COLOR});

      /**
       * @private
       * @type {number}
       */
      this.maxAngle_ =
        options.maxAngle !== undefined ? options.maxAngle : Math.PI / 4;

      /**
       * @private
       * @type {TextPlacement}
       */
      this.placement_ =
        options.placement !== undefined ? options.placement : 'point';

      /**
       * @private
       * @type {boolean}
       */
      this.overflow_ = !!options.overflow;

      /**
       * @private
       * @type {import("./Stroke.js").default|null}
       */
      this.stroke_ = options.stroke !== undefined ? options.stroke : null;

      /**
       * @private
       * @type {number}
       */
      this.offsetX_ = options.offsetX !== undefined ? options.offsetX : 0;

      /**
       * @private
       * @type {number}
       */
      this.offsetY_ = options.offsetY !== undefined ? options.offsetY : 0;

      /**
       * @private
       * @type {import("./Fill.js").default|null}
       */
      this.backgroundFill_ = options.backgroundFill
        ? options.backgroundFill
        : null;

      /**
       * @private
       * @type {import("./Stroke.js").default|null}
       */
      this.backgroundStroke_ = options.backgroundStroke
        ? options.backgroundStroke
        : null;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.padding_ = options.padding === undefined ? null : options.padding;

      /**
       * @private
       * @type {import('../style/Style.js').DeclutterMode}
       */
      this.declutterMode_ = options.declutterMode;
    }

    /**
     * Clones the style.
     * @return {Text} The cloned style.
     * @api
     */
    clone() {
      const scale = this.getScale();
      return new Text({
        font: this.getFont(),
        placement: this.getPlacement(),
        repeat: this.getRepeat(),
        maxAngle: this.getMaxAngle(),
        overflow: this.getOverflow(),
        rotation: this.getRotation(),
        rotateWithView: this.getRotateWithView(),
        keepUpright: this.getKeepUpright(),
        scale: Array.isArray(scale) ? scale.slice() : scale,
        text: this.getText(),
        textAlign: this.getTextAlign(),
        justify: this.getJustify(),
        textBaseline: this.getTextBaseline(),
        fill: this.getFill() ? this.getFill().clone() : undefined,
        stroke: this.getStroke() ? this.getStroke().clone() : undefined,
        offsetX: this.getOffsetX(),
        offsetY: this.getOffsetY(),
        backgroundFill: this.getBackgroundFill()
          ? this.getBackgroundFill().clone()
          : undefined,
        backgroundStroke: this.getBackgroundStroke()
          ? this.getBackgroundStroke().clone()
          : undefined,
        padding: this.getPadding() || undefined,
        declutterMode: this.getDeclutterMode(),
      });
    }

    /**
     * Get the `overflow` configuration.
     * @return {boolean} Let text overflow the length of the path they follow.
     * @api
     */
    getOverflow() {
      return this.overflow_;
    }

    /**
     * Get the font name.
     * @return {string|undefined} Font.
     * @api
     */
    getFont() {
      return this.font_;
    }

    /**
     * Get the maximum angle between adjacent characters.
     * @return {number} Angle in radians.
     * @api
     */
    getMaxAngle() {
      return this.maxAngle_;
    }

    /**
     * Get the label placement.
     * @return {TextPlacement} Text placement.
     * @api
     */
    getPlacement() {
      return this.placement_;
    }

    /**
     * Get the repeat interval of the text.
     * @return {number|undefined} Repeat interval in pixels.
     * @api
     */
    getRepeat() {
      return this.repeat_;
    }

    /**
     * Get the x-offset for the text.
     * @return {number} Horizontal text offset.
     * @api
     */
    getOffsetX() {
      return this.offsetX_;
    }

    /**
     * Get the y-offset for the text.
     * @return {number} Vertical text offset.
     * @api
     */
    getOffsetY() {
      return this.offsetY_;
    }

    /**
     * Get the fill style for the text.
     * @return {import("./Fill.js").default|null} Fill style.
     * @api
     */
    getFill() {
      return this.fill_;
    }

    /**
     * Determine whether the text rotates with the map.
     * @return {boolean|undefined} Rotate with map.
     * @api
     */
    getRotateWithView() {
      return this.rotateWithView_;
    }

    /**
     * Determine whether the text can be rendered upside down.
     * @return {boolean|undefined} Keep text upright.
     * @api
     */
    getKeepUpright() {
      return this.keepUpright_;
    }

    /**
     * Get the text rotation.
     * @return {number|undefined} Rotation.
     * @api
     */
    getRotation() {
      return this.rotation_;
    }

    /**
     * Get the text scale.
     * @return {number|import("../size.js").Size|undefined} Scale.
     * @api
     */
    getScale() {
      return this.scale_;
    }

    /**
     * Get the symbolizer scale array.
     * @return {import("../size.js").Size} Scale array.
     */
    getScaleArray() {
      return this.scaleArray_;
    }

    /**
     * Get the stroke style for the text.
     * @return {import("./Stroke.js").default|null} Stroke style.
     * @api
     */
    getStroke() {
      return this.stroke_;
    }

    /**
     * Get the text to be rendered.
     * @return {string|Array<string>|undefined} Text.
     * @api
     */
    getText() {
      return this.text_;
    }

    /**
     * Get the text alignment.
     * @return {CanvasTextAlign|undefined} Text align.
     * @api
     */
    getTextAlign() {
      return this.textAlign_;
    }

    /**
     * Get the justification.
     * @return {TextJustify|undefined} Justification.
     * @api
     */
    getJustify() {
      return this.justify_;
    }

    /**
     * Get the text baseline.
     * @return {CanvasTextBaseline|undefined} Text baseline.
     * @api
     */
    getTextBaseline() {
      return this.textBaseline_;
    }

    /**
     * Get the background fill style for the text.
     * @return {import("./Fill.js").default|null} Fill style.
     * @api
     */
    getBackgroundFill() {
      return this.backgroundFill_;
    }

    /**
     * Get the background stroke style for the text.
     * @return {import("./Stroke.js").default|null} Stroke style.
     * @api
     */
    getBackgroundStroke() {
      return this.backgroundStroke_;
    }

    /**
     * Get the padding for the text.
     * @return {Array<number>|null} Padding.
     * @api
     */
    getPadding() {
      return this.padding_;
    }

    /**
     * Get the declutter mode of the shape
     * @return {import("./Style.js").DeclutterMode} Shape's declutter mode
     * @api
     */
    getDeclutterMode() {
      return this.declutterMode_;
    }

    /**
     * Set the `overflow` property.
     *
     * @param {boolean} overflow Let text overflow the path that it follows.
     * @api
     */
    setOverflow(overflow) {
      this.overflow_ = overflow;
    }

    /**
     * Set the font.
     *
     * @param {string|undefined} font Font.
     * @api
     */
    setFont(font) {
      this.font_ = font;
    }

    /**
     * Set the maximum angle between adjacent characters.
     *
     * @param {number} maxAngle Angle in radians.
     * @api
     */
    setMaxAngle(maxAngle) {
      this.maxAngle_ = maxAngle;
    }

    /**
     * Set the x offset.
     *
     * @param {number} offsetX Horizontal text offset.
     * @api
     */
    setOffsetX(offsetX) {
      this.offsetX_ = offsetX;
    }

    /**
     * Set the y offset.
     *
     * @param {number} offsetY Vertical text offset.
     * @api
     */
    setOffsetY(offsetY) {
      this.offsetY_ = offsetY;
    }

    /**
     * Set the text placement.
     *
     * @param {TextPlacement} placement Placement.
     * @api
     */
    setPlacement(placement) {
      this.placement_ = placement;
    }

    /**
     * Set the repeat interval of the text.
     * @param {number|undefined} [repeat] Repeat interval in pixels.
     * @api
     */
    setRepeat(repeat) {
      this.repeat_ = repeat;
    }

    /**
     * Set whether to rotate the text with the view.
     *
     * @param {boolean} rotateWithView Rotate with map.
     * @api
     */
    setRotateWithView(rotateWithView) {
      this.rotateWithView_ = rotateWithView;
    }

    /**
     * Set whether the text can be rendered upside down.
     *
     * @param {boolean} keepUpright Keep text upright.
     * @api
     */
    setKeepUpright(keepUpright) {
      this.keepUpright_ = keepUpright;
    }

    /**
     * Set the fill.
     *
     * @param {import("./Fill.js").default|null} fill Fill style.
     * @api
     */
    setFill(fill) {
      this.fill_ = fill;
    }

    /**
     * Set the rotation.
     *
     * @param {number|undefined} rotation Rotation.
     * @api
     */
    setRotation(rotation) {
      this.rotation_ = rotation;
    }

    /**
     * Set the scale.
     *
     * @param {number|import("../size.js").Size|undefined} scale Scale.
     * @api
     */
    setScale(scale) {
      this.scale_ = scale;
      this.scaleArray_ = toSize(scale !== undefined ? scale : 1);
    }

    /**
     * Set the stroke.
     *
     * @param {import("./Stroke.js").default|null} stroke Stroke style.
     * @api
     */
    setStroke(stroke) {
      this.stroke_ = stroke;
    }

    /**
     * Set the text.
     *
     * @param {string|Array<string>|undefined} text Text.
     * @api
     */
    setText(text) {
      this.text_ = text;
    }

    /**
     * Set the text alignment.
     *
     * @param {CanvasTextAlign|undefined} textAlign Text align.
     * @api
     */
    setTextAlign(textAlign) {
      this.textAlign_ = textAlign;
    }

    /**
     * Set the justification.
     *
     * @param {TextJustify|undefined} justify Justification.
     * @api
     */
    setJustify(justify) {
      this.justify_ = justify;
    }

    /**
     * Set the text baseline.
     *
     * @param {CanvasTextBaseline|undefined} textBaseline Text baseline.
     * @api
     */
    setTextBaseline(textBaseline) {
      this.textBaseline_ = textBaseline;
    }

    /**
     * Set the background fill.
     *
     * @param {import("./Fill.js").default|null} fill Fill style.
     * @api
     */
    setBackgroundFill(fill) {
      this.backgroundFill_ = fill;
    }

    /**
     * Set the background stroke.
     *
     * @param {import("./Stroke.js").default|null} stroke Stroke style.
     * @api
     */
    setBackgroundStroke(stroke) {
      this.backgroundStroke_ = stroke;
    }

    /**
     * Set the padding (`[top, right, bottom, left]`).
     *
     * @param {Array<number>|null} padding Padding.
     * @api
     */
    setPadding(padding) {
      this.padding_ = padding;
    }
  }

  /**
   * @module ol/ViewHint
   */

  /**
   * @enum {number}
   */
  var ViewHint = {
    ANIMATING: 0,
    INTERACTING: 1,
  };

  /**
   * @module ol/render/canvas/Instruction
   */

  /**
   * @enum {number}
   */
  const Instruction = {
    BEGIN_GEOMETRY: 0,
    BEGIN_PATH: 1,
    CIRCLE: 2,
    CLOSE_PATH: 3,
    CUSTOM: 4,
    DRAW_CHARS: 5,
    DRAW_IMAGE: 6,
    END_GEOMETRY: 7,
    FILL: 8,
    MOVE_TO_LINE_TO: 9,
    SET_FILL_STYLE: 10,
    SET_STROKE_STYLE: 11,
    STROKE: 12,
  };

  /**
   * @type {Array<Instruction>}
   */
  const fillInstruction = [Instruction.FILL];

  /**
   * @type {Array<Instruction>}
   */
  const strokeInstruction = [Instruction.STROKE];

  /**
   * @type {Array<Instruction>}
   */
  const beginPathInstruction = [Instruction.BEGIN_PATH];

  /**
   * @type {Array<Instruction>}
   */
  const closePathInstruction = [Instruction.CLOSE_PATH];

  /**
   * @module ol/render/canvas/Builder
   */

  class CanvasBuilder extends VectorContext {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      super();

      /**
       * @protected
       * @type {number}
       */
      this.tolerance = tolerance;

      /**
       * @protected
       * @const
       * @type {import("../../extent.js").Extent}
       */
      this.maxExtent = maxExtent;

      /**
       * @protected
       * @type {number}
       */
      this.pixelRatio = pixelRatio;

      /**
       * @protected
       * @type {number}
       */
      this.maxLineWidth = 0;

      /**
       * @protected
       * @const
       * @type {number}
       */
      this.resolution = resolution;

      /**
       * @private
       * @type {Array<*>}
       */
      this.beginGeometryInstruction1_ = null;

      /**
       * @private
       * @type {Array<*>}
       */
      this.beginGeometryInstruction2_ = null;

      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.bufferedMaxExtent_ = null;

      /**
       * @protected
       * @type {Array<*>}
       */
      this.instructions = [];

      /**
       * @protected
       * @type {Array<number>}
       */
      this.coordinates = [];

      /**
       * @private
       * @type {import("../../coordinate.js").Coordinate}
       */
      this.tmpCoordinate_ = [];

      /**
       * @protected
       * @type {Array<*>}
       */
      this.hitDetectionInstructions = [];

      /**
       * @protected
       * @type {import("../canvas.js").FillStrokeState}
       */
      this.state = /** @type {import("../canvas.js").FillStrokeState} */ ({});
    }

    /**
     * @protected
     * @param {Array<number>} dashArray Dash array.
     * @return {Array<number>} Dash array with pixel ratio applied
     */
    applyPixelRatio(dashArray) {
      const pixelRatio = this.pixelRatio;
      return pixelRatio == 1
        ? dashArray
        : dashArray.map(function (dash) {
            return dash * pixelRatio;
          });
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} stride Stride.
     * @protected
     * @return {number} My end
     */
    appendFlatPointCoordinates(flatCoordinates, stride) {
      const extent = this.getBufferedMaxExtent();
      const tmpCoord = this.tmpCoordinate_;
      const coordinates = this.coordinates;
      let myEnd = coordinates.length;
      for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) {
        tmpCoord[0] = flatCoordinates[i];
        tmpCoord[1] = flatCoordinates[i + 1];
        if (containsCoordinate(extent, tmpCoord)) {
          coordinates[myEnd++] = tmpCoord[0];
          coordinates[myEnd++] = tmpCoord[1];
        }
      }
      return myEnd;
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {number} end End.
     * @param {number} stride Stride.
     * @param {boolean} closed Last input coordinate equals first.
     * @param {boolean} skipFirst Skip first coordinate.
     * @protected
     * @return {number} My end.
     */
    appendFlatLineCoordinates(
      flatCoordinates,
      offset,
      end,
      stride,
      closed,
      skipFirst,
    ) {
      const coordinates = this.coordinates;
      let myEnd = coordinates.length;
      const extent = this.getBufferedMaxExtent();
      if (skipFirst) {
        offset += stride;
      }
      let lastXCoord = flatCoordinates[offset];
      let lastYCoord = flatCoordinates[offset + 1];
      const nextCoord = this.tmpCoordinate_;
      let skipped = true;

      let i, lastRel, nextRel;
      for (i = offset + stride; i < end; i += stride) {
        nextCoord[0] = flatCoordinates[i];
        nextCoord[1] = flatCoordinates[i + 1];
        nextRel = coordinateRelationship(extent, nextCoord);
        if (nextRel !== lastRel) {
          if (skipped) {
            coordinates[myEnd++] = lastXCoord;
            coordinates[myEnd++] = lastYCoord;
            skipped = false;
          }
          coordinates[myEnd++] = nextCoord[0];
          coordinates[myEnd++] = nextCoord[1];
        } else if (nextRel === Relationship.INTERSECTING) {
          coordinates[myEnd++] = nextCoord[0];
          coordinates[myEnd++] = nextCoord[1];
          skipped = false;
        } else {
          skipped = true;
        }
        lastXCoord = nextCoord[0];
        lastYCoord = nextCoord[1];
        lastRel = nextRel;
      }

      // Last coordinate equals first or only one point to append:
      if ((closed && skipped) || i === offset + stride) {
        coordinates[myEnd++] = lastXCoord;
        coordinates[myEnd++] = lastYCoord;
      }
      return myEnd;
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {Array<number>} ends Ends.
     * @param {number} stride Stride.
     * @param {Array<number>} builderEnds Builder ends.
     * @return {number} Offset.
     */
    drawCustomCoordinates_(flatCoordinates, offset, ends, stride, builderEnds) {
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        const builderEnd = this.appendFlatLineCoordinates(
          flatCoordinates,
          offset,
          end,
          stride,
          false,
          false,
        );
        builderEnds.push(builderEnd);
        offset = end;
      }
      return offset;
    }

    /**
     * @param {import("../../geom/SimpleGeometry.js").default} geometry Geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {Function} renderer Renderer.
     * @param {Function} hitDetectionRenderer Renderer.
     * @param {number} [index] Render order index.
     * @override
     */
    drawCustom(geometry, feature, renderer, hitDetectionRenderer, index) {
      this.beginGeometry(geometry, feature, index);

      const type = geometry.getType();
      const stride = geometry.getStride();
      const builderBegin = this.coordinates.length;

      let flatCoordinates, builderEnd, builderEnds, builderEndss;
      let offset;

      switch (type) {
        case 'MultiPolygon':
          flatCoordinates =
            /** @type {import("../../geom/MultiPolygon.js").default} */ (
              geometry
            ).getOrientedFlatCoordinates();
          builderEndss = [];
          const endss =
            /** @type {import("../../geom/MultiPolygon.js").default} */ (
              geometry
            ).getEndss();
          offset = 0;
          for (let i = 0, ii = endss.length; i < ii; ++i) {
            const myEnds = [];
            offset = this.drawCustomCoordinates_(
              flatCoordinates,
              offset,
              endss[i],
              stride,
              myEnds,
            );
            builderEndss.push(myEnds);
          }
          this.instructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEndss,
            geometry,
            renderer,
            inflateMultiCoordinatesArray,
            index,
          ]);
          this.hitDetectionInstructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEndss,
            geometry,
            hitDetectionRenderer || renderer,
            inflateMultiCoordinatesArray,
            index,
          ]);
          break;
        case 'Polygon':
        case 'MultiLineString':
          builderEnds = [];
          flatCoordinates =
            type == 'Polygon'
              ? /** @type {import("../../geom/Polygon.js").default} */ (
                  geometry
                ).getOrientedFlatCoordinates()
              : geometry.getFlatCoordinates();
          offset = this.drawCustomCoordinates_(
            flatCoordinates,
            0,
            /** @type {import("../../geom/Polygon.js").default|import("../../geom/MultiLineString.js").default} */ (
              geometry
            ).getEnds(),
            stride,
            builderEnds,
          );
          this.instructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnds,
            geometry,
            renderer,
            inflateCoordinatesArray,
            index,
          ]);
          this.hitDetectionInstructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnds,
            geometry,
            hitDetectionRenderer || renderer,
            inflateCoordinatesArray,
            index,
          ]);
          break;
        case 'LineString':
        case 'Circle':
          flatCoordinates = geometry.getFlatCoordinates();
          builderEnd = this.appendFlatLineCoordinates(
            flatCoordinates,
            0,
            flatCoordinates.length,
            stride,
            false,
            false,
          );
          this.instructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnd,
            geometry,
            renderer,
            inflateCoordinates,
            index,
          ]);
          this.hitDetectionInstructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnd,
            geometry,
            hitDetectionRenderer || renderer,
            inflateCoordinates,
            index,
          ]);
          break;
        case 'MultiPoint':
          flatCoordinates = geometry.getFlatCoordinates();
          builderEnd = this.appendFlatPointCoordinates(flatCoordinates, stride);

          if (builderEnd > builderBegin) {
            this.instructions.push([
              Instruction.CUSTOM,
              builderBegin,
              builderEnd,
              geometry,
              renderer,
              inflateCoordinates,
              index,
            ]);
            this.hitDetectionInstructions.push([
              Instruction.CUSTOM,
              builderBegin,
              builderEnd,
              geometry,
              hitDetectionRenderer || renderer,
              inflateCoordinates,
              index,
            ]);
          }
          break;
        case 'Point':
          flatCoordinates = geometry.getFlatCoordinates();
          this.coordinates.push(flatCoordinates[0], flatCoordinates[1]);
          builderEnd = this.coordinates.length;

          this.instructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnd,
            geometry,
            renderer,
            undefined,
            index,
          ]);
          this.hitDetectionInstructions.push([
            Instruction.CUSTOM,
            builderBegin,
            builderEnd,
            geometry,
            hitDetectionRenderer || renderer,
            undefined,
            index,
          ]);
          break;
      }
      this.endGeometry(feature);
    }

    /**
     * @protected
     * @param {import("../../geom/Geometry").default|import("../Feature.js").default} geometry The geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} index Render order index
     */
    beginGeometry(geometry, feature, index) {
      this.beginGeometryInstruction1_ = [
        Instruction.BEGIN_GEOMETRY,
        feature,
        0,
        geometry,
        index,
      ];
      this.instructions.push(this.beginGeometryInstruction1_);
      this.beginGeometryInstruction2_ = [
        Instruction.BEGIN_GEOMETRY,
        feature,
        0,
        geometry,
        index,
      ];
      this.hitDetectionInstructions.push(this.beginGeometryInstruction2_);
    }

    /**
     * @return {import("../canvas.js").SerializableInstructions} the serializable instructions.
     */
    finish() {
      return {
        instructions: this.instructions,
        hitDetectionInstructions: this.hitDetectionInstructions,
        coordinates: this.coordinates,
      };
    }

    /**
     * Reverse the hit detection instructions.
     */
    reverseHitDetectionInstructions() {
      const hitDetectionInstructions = this.hitDetectionInstructions;
      // step 1 - reverse array
      hitDetectionInstructions.reverse();
      // step 2 - reverse instructions within geometry blocks
      let i;
      const n = hitDetectionInstructions.length;
      let instruction;
      let type;
      let begin = -1;
      for (i = 0; i < n; ++i) {
        instruction = hitDetectionInstructions[i];
        type = /** @type {import("./Instruction.js").default} */ (instruction[0]);
        if (type == Instruction.END_GEOMETRY) {
          begin = i;
        } else if (type == Instruction.BEGIN_GEOMETRY) {
          instruction[2] = i;
          reverseSubArray(this.hitDetectionInstructions, begin, i);
          begin = -1;
        }
      }
    }

    /**
     * @param {import("../../style/Fill.js").default} fillStyle Fill style.
     * @param {import('../canvas.js').FillStrokeState} [state] State.
     * @return {import('../canvas.js').FillStrokeState} State.
     */
    fillStyleToState(
      fillStyle,
      state = /** @type {import('../canvas.js').FillStrokeState} */ ({}),
    ) {
      if (fillStyle) {
        const fillStyleColor = fillStyle.getColor();
        state.fillPatternScale =
          fillStyleColor &&
          typeof fillStyleColor === 'object' &&
          'src' in fillStyleColor
            ? this.pixelRatio
            : 1;
        state.fillStyle = asColorLike(
          fillStyleColor ? fillStyleColor : defaultFillStyle,
        );
      } else {
        state.fillStyle = undefined;
      }
      return state;
    }

    /**
     * @param {import("../../style/Stroke.js").default} strokeStyle Stroke style.
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @return {import("../canvas.js").FillStrokeState} State.
     */
    strokeStyleToState(
      strokeStyle,
      state = /** @type {import('../canvas.js').FillStrokeState} */ ({}),
    ) {
      if (strokeStyle) {
        const strokeStyleColor = strokeStyle.getColor();
        state.strokeStyle = asColorLike(
          strokeStyleColor ? strokeStyleColor : defaultStrokeStyle,
        );
        const strokeStyleLineCap = strokeStyle.getLineCap();
        state.lineCap =
          strokeStyleLineCap !== undefined ? strokeStyleLineCap : defaultLineCap;
        const strokeStyleLineDash = strokeStyle.getLineDash();
        state.lineDash = strokeStyleLineDash
          ? strokeStyleLineDash.slice()
          : defaultLineDash;
        const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset();
        state.lineDashOffset = strokeStyleLineDashOffset
          ? strokeStyleLineDashOffset
          : defaultLineDashOffset;
        const strokeStyleLineJoin = strokeStyle.getLineJoin();
        state.lineJoin =
          strokeStyleLineJoin !== undefined
            ? strokeStyleLineJoin
            : defaultLineJoin;
        const strokeStyleWidth = strokeStyle.getWidth();
        state.lineWidth =
          strokeStyleWidth !== undefined ? strokeStyleWidth : defaultLineWidth;
        const strokeStyleMiterLimit = strokeStyle.getMiterLimit();
        state.miterLimit =
          strokeStyleMiterLimit !== undefined
            ? strokeStyleMiterLimit
            : defaultMiterLimit;

        if (state.lineWidth > this.maxLineWidth) {
          this.maxLineWidth = state.lineWidth;
          // invalidate the buffered max extent cache
          this.bufferedMaxExtent_ = null;
        }
      } else {
        state.strokeStyle = undefined;
        state.lineCap = undefined;
        state.lineDash = null;
        state.lineDashOffset = undefined;
        state.lineJoin = undefined;
        state.lineWidth = undefined;
        state.miterLimit = undefined;
      }
      return state;
    }

    /**
     * @param {import("../../style/Fill.js").default} fillStyle Fill style.
     * @param {import("../../style/Stroke.js").default} strokeStyle Stroke style.
     * @override
     */
    setFillStrokeStyle(fillStyle, strokeStyle) {
      const state = this.state;
      this.fillStyleToState(fillStyle, state);
      this.strokeStyleToState(strokeStyle, state);
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @return {Array<*>} Fill instruction.
     */
    createFill(state) {
      const fillStyle = state.fillStyle;
      /** @type {Array<*>} */
      const fillInstruction = [Instruction.SET_FILL_STYLE, fillStyle];
      if (typeof fillStyle !== 'string') {
        // Fill is a pattern or gradient - align and scale it!
        fillInstruction.push(state.fillPatternScale);
      }
      return fillInstruction;
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     */
    applyStroke(state) {
      this.instructions.push(this.createStroke(state));
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @return {Array<*>} Stroke instruction.
     */
    createStroke(state) {
      return [
        Instruction.SET_STROKE_STYLE,
        state.strokeStyle,
        state.lineWidth * this.pixelRatio,
        state.lineCap,
        state.lineJoin,
        state.miterLimit,
        state.lineDash ? this.applyPixelRatio(state.lineDash) : null,
        state.lineDashOffset * this.pixelRatio,
      ];
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @param {function(this:CanvasBuilder, import("../canvas.js").FillStrokeState):Array<*>} createFill Create fill.
     */
    updateFillStyle(state, createFill) {
      const fillStyle = state.fillStyle;
      if (typeof fillStyle !== 'string' || state.currentFillStyle != fillStyle) {
        this.instructions.push(createFill.call(this, state));
        state.currentFillStyle = fillStyle;
      }
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @param {function(this:CanvasBuilder, import("../canvas.js").FillStrokeState): void} applyStroke Apply stroke.
     */
    updateStrokeStyle(state, applyStroke) {
      const strokeStyle = state.strokeStyle;
      const lineCap = state.lineCap;
      const lineDash = state.lineDash;
      const lineDashOffset = state.lineDashOffset;
      const lineJoin = state.lineJoin;
      const lineWidth = state.lineWidth;
      const miterLimit = state.miterLimit;
      if (
        state.currentStrokeStyle != strokeStyle ||
        state.currentLineCap != lineCap ||
        (lineDash != state.currentLineDash &&
          !equals$2(state.currentLineDash, lineDash)) ||
        state.currentLineDashOffset != lineDashOffset ||
        state.currentLineJoin != lineJoin ||
        state.currentLineWidth != lineWidth ||
        state.currentMiterLimit != miterLimit
      ) {
        applyStroke.call(this, state);
        state.currentStrokeStyle = strokeStyle;
        state.currentLineCap = lineCap;
        state.currentLineDash = lineDash;
        state.currentLineDashOffset = lineDashOffset;
        state.currentLineJoin = lineJoin;
        state.currentLineWidth = lineWidth;
        state.currentMiterLimit = miterLimit;
      }
    }

    /**
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     */
    endGeometry(feature) {
      this.beginGeometryInstruction1_[2] = this.instructions.length;
      this.beginGeometryInstruction1_ = null;
      this.beginGeometryInstruction2_[2] = this.hitDetectionInstructions.length;
      this.beginGeometryInstruction2_ = null;
      const endGeometryInstruction = [Instruction.END_GEOMETRY, feature];
      this.instructions.push(endGeometryInstruction);
      this.hitDetectionInstructions.push(endGeometryInstruction);
    }

    /**
     * Get the buffered rendering extent.  Rendering will be clipped to the extent
     * provided to the constructor.  To account for symbolizers that may intersect
     * this extent, we calculate a buffered extent (e.g. based on stroke width).
     * @return {import("../../extent.js").Extent} The buffered rendering extent.
     * @protected
     */
    getBufferedMaxExtent() {
      if (!this.bufferedMaxExtent_) {
        this.bufferedMaxExtent_ = clone(this.maxExtent);
        if (this.maxLineWidth > 0) {
          const width = (this.resolution * (this.maxLineWidth + 1)) / 2;
          buffer$1(this.bufferedMaxExtent_, width, this.bufferedMaxExtent_);
        }
      }
      return this.bufferedMaxExtent_;
    }
  }

  /**
   * @module ol/render/canvas/ImageBuilder
   */

  class CanvasImageBuilder extends CanvasBuilder {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      super(tolerance, maxExtent, resolution, pixelRatio);

      /**
       * @private
       * @type {import('../../DataTile.js').ImageLike}
       */
      this.hitDetectionImage_ = null;

      /**
       * @private
       * @type {import('../../DataTile.js').ImageLike}
       */
      this.image_ = null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.imagePixelRatio_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.anchorX_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.anchorY_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.height_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.opacity_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.originX_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.originY_ = undefined;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.rotateWithView_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.rotation_ = undefined;

      /**
       * @private
       * @type {import("../../size.js").Size|undefined}
       */
      this.scale_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.width_ = undefined;

      /**
       * @private
       * @type {import('../../style/Style.js').DeclutterMode}
       */
      this.declutterMode_ = undefined;

      /**
       * Data shared with a text builder for combined decluttering.
       * @private
       * @type {import("../canvas.js").DeclutterImageWithText}
       */
      this.declutterImageWithText_ = undefined;
    }

    /**
     * @param {import("../../geom/Point.js").default|import("../Feature.js").default} pointGeometry Point geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawPoint(pointGeometry, feature, index) {
      if (
        !this.image_ ||
        (this.maxExtent &&
          !containsCoordinate(this.maxExtent, pointGeometry.getFlatCoordinates()))
      ) {
        return;
      }
      this.beginGeometry(pointGeometry, feature, index);
      const flatCoordinates = pointGeometry.getFlatCoordinates();
      const stride = pointGeometry.getStride();
      const myBegin = this.coordinates.length;
      const myEnd = this.appendFlatPointCoordinates(flatCoordinates, stride);
      this.instructions.push([
        Instruction.DRAW_IMAGE,
        myBegin,
        myEnd,
        this.image_,
        // Remaining arguments to DRAW_IMAGE are in alphabetical order
        this.anchorX_ * this.imagePixelRatio_,
        this.anchorY_ * this.imagePixelRatio_,
        Math.ceil(this.height_ * this.imagePixelRatio_),
        this.opacity_,
        this.originX_ * this.imagePixelRatio_,
        this.originY_ * this.imagePixelRatio_,
        this.rotateWithView_,
        this.rotation_,
        [
          (this.scale_[0] * this.pixelRatio) / this.imagePixelRatio_,
          (this.scale_[1] * this.pixelRatio) / this.imagePixelRatio_,
        ],
        Math.ceil(this.width_ * this.imagePixelRatio_),
        this.declutterMode_,
        this.declutterImageWithText_,
      ]);
      this.hitDetectionInstructions.push([
        Instruction.DRAW_IMAGE,
        myBegin,
        myEnd,
        this.hitDetectionImage_,
        // Remaining arguments to DRAW_IMAGE are in alphabetical order
        this.anchorX_,
        this.anchorY_,
        this.height_,
        1,
        this.originX_,
        this.originY_,
        this.rotateWithView_,
        this.rotation_,
        this.scale_,
        this.width_,
        this.declutterMode_,
        this.declutterImageWithText_,
      ]);
      this.endGeometry(feature);
    }

    /**
     * @param {import("../../geom/MultiPoint.js").default|import("../Feature.js").default} multiPointGeometry MultiPoint geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawMultiPoint(multiPointGeometry, feature, index) {
      if (!this.image_) {
        return;
      }
      this.beginGeometry(multiPointGeometry, feature, index);
      const flatCoordinates = multiPointGeometry.getFlatCoordinates();
      const filteredFlatCoordinates = [];
      for (
        let i = 0, ii = flatCoordinates.length;
        i < ii;
        i += multiPointGeometry.getStride()
      ) {
        if (
          !this.maxExtent ||
          containsCoordinate(this.maxExtent, flatCoordinates.slice(i, i + 2))
        ) {
          filteredFlatCoordinates.push(
            flatCoordinates[i],
            flatCoordinates[i + 1],
          );
        }
      }
      const myBegin = this.coordinates.length;
      const myEnd = this.appendFlatPointCoordinates(filteredFlatCoordinates, 2);
      this.instructions.push([
        Instruction.DRAW_IMAGE,
        myBegin,
        myEnd,
        this.image_,
        // Remaining arguments to DRAW_IMAGE are in alphabetical order
        this.anchorX_ * this.imagePixelRatio_,
        this.anchorY_ * this.imagePixelRatio_,
        Math.ceil(this.height_ * this.imagePixelRatio_),
        this.opacity_,
        this.originX_ * this.imagePixelRatio_,
        this.originY_ * this.imagePixelRatio_,
        this.rotateWithView_,
        this.rotation_,
        [
          (this.scale_[0] * this.pixelRatio) / this.imagePixelRatio_,
          (this.scale_[1] * this.pixelRatio) / this.imagePixelRatio_,
        ],
        Math.ceil(this.width_ * this.imagePixelRatio_),
        this.declutterMode_,
        this.declutterImageWithText_,
      ]);
      this.hitDetectionInstructions.push([
        Instruction.DRAW_IMAGE,
        myBegin,
        myEnd,
        this.hitDetectionImage_,
        // Remaining arguments to DRAW_IMAGE are in alphabetical order
        this.anchorX_,
        this.anchorY_,
        this.height_,
        1,
        this.originX_,
        this.originY_,
        this.rotateWithView_,
        this.rotation_,
        this.scale_,
        this.width_,
        this.declutterMode_,
        this.declutterImageWithText_,
      ]);
      this.endGeometry(feature);
    }

    /**
     * @return {import("../canvas.js").SerializableInstructions} the serializable instructions.
     * @override
     */
    finish() {
      this.reverseHitDetectionInstructions();
      // FIXME this doesn't really protect us against further calls to draw*Geometry
      this.anchorX_ = undefined;
      this.anchorY_ = undefined;
      this.hitDetectionImage_ = null;
      this.image_ = null;
      this.imagePixelRatio_ = undefined;
      this.height_ = undefined;
      this.scale_ = undefined;
      this.opacity_ = undefined;
      this.originX_ = undefined;
      this.originY_ = undefined;
      this.rotateWithView_ = undefined;
      this.rotation_ = undefined;
      this.width_ = undefined;
      return super.finish();
    }

    /**
     * @param {import("../../style/Image.js").default} imageStyle Image style.
     * @param {Object} [sharedData] Shared data.
     * @override
     */
    setImageStyle(imageStyle, sharedData) {
      const anchor = imageStyle.getAnchor();
      const size = imageStyle.getSize();
      const origin = imageStyle.getOrigin();
      this.imagePixelRatio_ = imageStyle.getPixelRatio(this.pixelRatio);
      this.anchorX_ = anchor[0];
      this.anchorY_ = anchor[1];
      this.hitDetectionImage_ = imageStyle.getHitDetectionImage();
      this.image_ = imageStyle.getImage(this.pixelRatio);
      this.height_ = size[1];
      this.opacity_ = imageStyle.getOpacity();
      this.originX_ = origin[0];
      this.originY_ = origin[1];
      this.rotateWithView_ = imageStyle.getRotateWithView();
      this.rotation_ = imageStyle.getRotation();
      this.scale_ = imageStyle.getScaleArray();
      this.width_ = size[0];
      this.declutterMode_ = imageStyle.getDeclutterMode();
      this.declutterImageWithText_ = sharedData;
    }
  }

  /**
   * @module ol/render/canvas/LineStringBuilder
   */

  class CanvasLineStringBuilder extends CanvasBuilder {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      super(tolerance, maxExtent, resolution, pixelRatio);
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {number} end End.
     * @param {number} stride Stride.
     * @private
     * @return {number} end.
     */
    drawFlatCoordinates_(flatCoordinates, offset, end, stride) {
      const myBegin = this.coordinates.length;
      const myEnd = this.appendFlatLineCoordinates(
        flatCoordinates,
        offset,
        end,
        stride,
        false,
        false,
      );
      const moveToLineToInstruction = [
        Instruction.MOVE_TO_LINE_TO,
        myBegin,
        myEnd,
      ];
      this.instructions.push(moveToLineToInstruction);
      this.hitDetectionInstructions.push(moveToLineToInstruction);
      return end;
    }

    /**
     * @param {import("../../geom/LineString.js").default|import("../Feature.js").default} lineStringGeometry Line string geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawLineString(lineStringGeometry, feature, index) {
      const state = this.state;
      const strokeStyle = state.strokeStyle;
      const lineWidth = state.lineWidth;
      if (strokeStyle === undefined || lineWidth === undefined) {
        return;
      }
      this.updateStrokeStyle(state, this.applyStroke);
      this.beginGeometry(lineStringGeometry, feature, index);
      this.hitDetectionInstructions.push(
        [
          Instruction.SET_STROKE_STYLE,
          state.strokeStyle,
          state.lineWidth,
          state.lineCap,
          state.lineJoin,
          state.miterLimit,
          defaultLineDash,
          defaultLineDashOffset,
        ],
        beginPathInstruction,
      );
      const flatCoordinates = lineStringGeometry.getFlatCoordinates();
      const stride = lineStringGeometry.getStride();
      this.drawFlatCoordinates_(
        flatCoordinates,
        0,
        flatCoordinates.length,
        stride,
      );
      this.hitDetectionInstructions.push(strokeInstruction);
      this.endGeometry(feature);
    }

    /**
     * @param {import("../../geom/MultiLineString.js").default|import("../Feature.js").default} multiLineStringGeometry MultiLineString geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawMultiLineString(multiLineStringGeometry, feature, index) {
      const state = this.state;
      const strokeStyle = state.strokeStyle;
      const lineWidth = state.lineWidth;
      if (strokeStyle === undefined || lineWidth === undefined) {
        return;
      }
      this.updateStrokeStyle(state, this.applyStroke);
      this.beginGeometry(multiLineStringGeometry, feature, index);
      this.hitDetectionInstructions.push(
        [
          Instruction.SET_STROKE_STYLE,
          state.strokeStyle,
          state.lineWidth,
          state.lineCap,
          state.lineJoin,
          state.miterLimit,
          defaultLineDash,
          defaultLineDashOffset,
        ],
        beginPathInstruction,
      );
      const ends = multiLineStringGeometry.getEnds();
      const flatCoordinates = multiLineStringGeometry.getFlatCoordinates();
      const stride = multiLineStringGeometry.getStride();
      let offset = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        offset = this.drawFlatCoordinates_(
          flatCoordinates,
          offset,
          /** @type {number} */ (ends[i]),
          stride,
        );
      }
      this.hitDetectionInstructions.push(strokeInstruction);
      this.endGeometry(feature);
    }

    /**
     * @return {import("../canvas.js").SerializableInstructions} the serializable instructions.
     * @override
     */
    finish() {
      const state = this.state;
      if (
        state.lastStroke != undefined &&
        state.lastStroke != this.coordinates.length
      ) {
        this.instructions.push(strokeInstruction);
      }
      this.reverseHitDetectionInstructions();
      this.state = null;
      return super.finish();
    }

    /**
     * @param {import("../canvas.js").FillStrokeState} state State.
     * @override
     */
    applyStroke(state) {
      if (
        state.lastStroke != undefined &&
        state.lastStroke != this.coordinates.length
      ) {
        this.instructions.push(strokeInstruction);
        state.lastStroke = this.coordinates.length;
      }
      state.lastStroke = 0;
      super.applyStroke(state);
      this.instructions.push(beginPathInstruction);
    }
  }

  /**
   * @module ol/render/canvas/PolygonBuilder
   */

  class CanvasPolygonBuilder extends CanvasBuilder {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      super(tolerance, maxExtent, resolution, pixelRatio);
    }

    /**
     * @param {Array<number>} flatCoordinates Flat coordinates.
     * @param {number} offset Offset.
     * @param {Array<number>} ends Ends.
     * @param {number} stride Stride.
     * @private
     * @return {number} End.
     */
    drawFlatCoordinatess_(flatCoordinates, offset, ends, stride) {
      const state = this.state;
      const fill = state.fillStyle !== undefined;
      const stroke = state.strokeStyle !== undefined;
      const numEnds = ends.length;
      this.instructions.push(beginPathInstruction);
      this.hitDetectionInstructions.push(beginPathInstruction);
      for (let i = 0; i < numEnds; ++i) {
        const end = ends[i];
        const myBegin = this.coordinates.length;
        const myEnd = this.appendFlatLineCoordinates(
          flatCoordinates,
          offset,
          end,
          stride,
          true,
          !stroke,
        );
        const moveToLineToInstruction = [
          Instruction.MOVE_TO_LINE_TO,
          myBegin,
          myEnd,
        ];
        this.instructions.push(moveToLineToInstruction);
        this.hitDetectionInstructions.push(moveToLineToInstruction);
        if (stroke) {
          // Performance optimization: only call closePath() when we have a stroke.
          // Otherwise the ring is closed already (see appendFlatLineCoordinates above).
          this.instructions.push(closePathInstruction);
          this.hitDetectionInstructions.push(closePathInstruction);
        }
        offset = end;
      }
      if (fill) {
        this.instructions.push(fillInstruction);
        this.hitDetectionInstructions.push(fillInstruction);
      }
      if (stroke) {
        this.instructions.push(strokeInstruction);
        this.hitDetectionInstructions.push(strokeInstruction);
      }
      return offset;
    }

    /**
     * @param {import("../../geom/Circle.js").default} circleGeometry Circle geometry.
     * @param {import("../../Feature.js").default} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawCircle(circleGeometry, feature, index) {
      const state = this.state;
      const fillStyle = state.fillStyle;
      const strokeStyle = state.strokeStyle;
      if (fillStyle === undefined && strokeStyle === undefined) {
        return;
      }
      this.setFillStrokeStyles_();
      this.beginGeometry(circleGeometry, feature, index);
      if (state.fillStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_FILL_STYLE,
          defaultFillStyle,
        ]);
      }
      if (state.strokeStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_STROKE_STYLE,
          state.strokeStyle,
          state.lineWidth,
          state.lineCap,
          state.lineJoin,
          state.miterLimit,
          defaultLineDash,
          defaultLineDashOffset,
        ]);
      }
      const flatCoordinates = circleGeometry.getFlatCoordinates();
      const stride = circleGeometry.getStride();
      const myBegin = this.coordinates.length;
      this.appendFlatLineCoordinates(
        flatCoordinates,
        0,
        flatCoordinates.length,
        stride,
        false,
        false,
      );
      const circleInstruction = [Instruction.CIRCLE, myBegin];
      this.instructions.push(beginPathInstruction, circleInstruction);
      this.hitDetectionInstructions.push(beginPathInstruction, circleInstruction);
      if (state.fillStyle !== undefined) {
        this.instructions.push(fillInstruction);
        this.hitDetectionInstructions.push(fillInstruction);
      }
      if (state.strokeStyle !== undefined) {
        this.instructions.push(strokeInstruction);
        this.hitDetectionInstructions.push(strokeInstruction);
      }
      this.endGeometry(feature);
    }

    /**
     * @param {import("../../geom/Polygon.js").default|import("../Feature.js").default} polygonGeometry Polygon geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawPolygon(polygonGeometry, feature, index) {
      const state = this.state;
      const fillStyle = state.fillStyle;
      const strokeStyle = state.strokeStyle;
      if (fillStyle === undefined && strokeStyle === undefined) {
        return;
      }
      this.setFillStrokeStyles_();
      this.beginGeometry(polygonGeometry, feature, index);
      if (state.fillStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_FILL_STYLE,
          defaultFillStyle,
        ]);
      }
      if (state.strokeStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_STROKE_STYLE,
          state.strokeStyle,
          state.lineWidth,
          state.lineCap,
          state.lineJoin,
          state.miterLimit,
          defaultLineDash,
          defaultLineDashOffset,
        ]);
      }
      const ends = polygonGeometry.getEnds();
      const flatCoordinates = polygonGeometry.getOrientedFlatCoordinates();
      const stride = polygonGeometry.getStride();
      this.drawFlatCoordinatess_(
        flatCoordinates,
        0,
        /** @type {Array<number>} */ (ends),
        stride,
      );
      this.endGeometry(feature);
    }

    /**
     * @param {import("../../geom/MultiPolygon.js").default} multiPolygonGeometry MultiPolygon geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawMultiPolygon(multiPolygonGeometry, feature, index) {
      const state = this.state;
      const fillStyle = state.fillStyle;
      const strokeStyle = state.strokeStyle;
      if (fillStyle === undefined && strokeStyle === undefined) {
        return;
      }
      this.setFillStrokeStyles_();
      this.beginGeometry(multiPolygonGeometry, feature, index);
      if (state.fillStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_FILL_STYLE,
          defaultFillStyle,
        ]);
      }
      if (state.strokeStyle !== undefined) {
        this.hitDetectionInstructions.push([
          Instruction.SET_STROKE_STYLE,
          state.strokeStyle,
          state.lineWidth,
          state.lineCap,
          state.lineJoin,
          state.miterLimit,
          defaultLineDash,
          defaultLineDashOffset,
        ]);
      }
      const endss = multiPolygonGeometry.getEndss();
      const flatCoordinates = multiPolygonGeometry.getOrientedFlatCoordinates();
      const stride = multiPolygonGeometry.getStride();
      let offset = 0;
      for (let i = 0, ii = endss.length; i < ii; ++i) {
        offset = this.drawFlatCoordinatess_(
          flatCoordinates,
          offset,
          endss[i],
          stride,
        );
      }
      this.endGeometry(feature);
    }

    /**
     * @return {import("../canvas.js").SerializableInstructions} the serializable instructions.
     * @override
     */
    finish() {
      this.reverseHitDetectionInstructions();
      this.state = null;
      // We want to preserve topology when drawing polygons.  Polygons are
      // simplified using quantization and point elimination. However, we might
      // have received a mix of quantized and non-quantized geometries, so ensure
      // that all are quantized by quantizing all coordinates in the batch.
      const tolerance = this.tolerance;
      if (tolerance !== 0) {
        const coordinates = this.coordinates;
        for (let i = 0, ii = coordinates.length; i < ii; ++i) {
          coordinates[i] = snap(coordinates[i], tolerance);
        }
      }
      return super.finish();
    }

    /**
     * @private
     */
    setFillStrokeStyles_() {
      const state = this.state;
      this.updateFillStyle(state, this.createFill);
      this.updateStrokeStyle(state, this.applyStroke);
    }
  }

  /**
   * Creates chunks of equal length from a linestring
   * @param {number} chunkLength Length of each chunk.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Start offset of the `flatCoordinates`.
   * @param {number} end End offset of the `flatCoordinates`.
   * @param {number} stride Stride.
   * @return {Array<Array<number>>} Chunks of linestrings with stride 2.
   */
  function lineChunk(chunkLength, flatCoordinates, offset, end, stride) {
    const chunks = [];
    let cursor = offset;
    let chunkM = 0;
    let currentChunk = flatCoordinates.slice(offset, 2);
    while (chunkM < chunkLength && cursor + stride < end) {
      const [x1, y1] = currentChunk.slice(-2);
      const x2 = flatCoordinates[cursor + stride];
      const y2 = flatCoordinates[cursor + stride + 1];
      const segmentLength = Math.sqrt(
        (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1),
      );
      chunkM += segmentLength;
      if (chunkM >= chunkLength) {
        const m = (chunkLength - chunkM + segmentLength) / segmentLength;
        const x = lerp$1(x1, x2, m);
        const y = lerp$1(y1, y2, m);
        currentChunk.push(x, y);
        chunks.push(currentChunk);
        currentChunk = [x, y];
        if (chunkM == chunkLength) {
          cursor += stride;
        }
        chunkM = 0;
      } else if (chunkM < chunkLength) {
        currentChunk.push(
          flatCoordinates[cursor + stride],
          flatCoordinates[cursor + stride + 1],
        );
        cursor += stride;
      } else {
        const missing = segmentLength - chunkM;
        const x = lerp$1(x1, x2, missing / segmentLength);
        const y = lerp$1(y1, y2, missing / segmentLength);
        currentChunk.push(x, y);
        chunks.push(currentChunk);
        currentChunk = [x, y];
        chunkM = 0;
        cursor += stride;
      }
    }
    if (chunkM > 0) {
      chunks.push(currentChunk);
    }
    return chunks;
  }

  /**
   * @module ol/geom/flat/straightchunk
   */

  /**
   * @param {number} maxAngle Maximum acceptable angle delta between segments.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @return {Array<number>} Start and end of the first suitable chunk of the
   * given `flatCoordinates`.
   */
  function matchingChunk(maxAngle, flatCoordinates, offset, end, stride) {
    let chunkStart = offset;
    let chunkEnd = offset;
    let chunkM = 0;
    let m = 0;
    let start = offset;
    let acos, i, m12, m23, x1, y1, x12, y12, x23, y23;
    for (i = offset; i < end; i += stride) {
      const x2 = flatCoordinates[i];
      const y2 = flatCoordinates[i + 1];
      if (x1 !== undefined) {
        x23 = x2 - x1;
        y23 = y2 - y1;
        m23 = Math.sqrt(x23 * x23 + y23 * y23);
        if (x12 !== undefined) {
          m += m12;
          acos = Math.acos((x12 * x23 + y12 * y23) / (m12 * m23));
          if (acos > maxAngle) {
            if (m > chunkM) {
              chunkM = m;
              chunkStart = start;
              chunkEnd = i;
            }
            m = 0;
            start = i - stride;
          }
        }
        m12 = m23;
        x12 = x23;
        y12 = y23;
      }
      x1 = x2;
      y1 = y2;
    }
    m += m23;
    return m > chunkM ? [start, i] : [chunkStart, chunkEnd];
  }

  /**
   * @module ol/render/canvas/TextBuilder
   */
  /**
   * @const
   * @type {{left: 0, center: 0.5, right: 1, top: 0, middle: 0.5, hanging: 0.2, alphabetic: 0.8, ideographic: 0.8, bottom: 1}}
   */
  const TEXT_ALIGN = {
    'left': 0,
    'center': 0.5,
    'right': 1,
    'top': 0,
    'middle': 0.5,
    'hanging': 0.2,
    'alphabetic': 0.8,
    'ideographic': 0.8,
    'bottom': 1,
  };

  class CanvasTextBuilder extends CanvasBuilder {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      super(tolerance, maxExtent, resolution, pixelRatio);

      /**
       * @private
       * @type {Array<HTMLCanvasElement>}
       */
      this.labels_ = null;

      /**
       * @private
       * @type {string|Array<string>}
       */
      this.text_ = '';

      /**
       * @private
       * @type {number}
       */
      this.textOffsetX_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.textOffsetY_ = 0;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.textRotateWithView_ = undefined;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.textKeepUpright_ = undefined;

      /**
       * @private
       * @type {number}
       */
      this.textRotation_ = 0;

      /**
       * @private
       * @type {?import("../canvas.js").FillState}
       */
      this.textFillState_ = null;

      /**
       * @type {!Object<string, import("../canvas.js").FillState>}
       */
      this.fillStates = {};
      this.fillStates[defaultFillStyle] = {fillStyle: defaultFillStyle};

      /**
       * @private
       * @type {?import("../canvas.js").StrokeState}
       */
      this.textStrokeState_ = null;

      /**
       * @type {!Object<string, import("../canvas.js").StrokeState>}
       */
      this.strokeStates = {};

      /**
       * @private
       * @type {import("../canvas.js").TextState}
       */
      this.textState_ = /** @type {import("../canvas.js").TextState} */ ({});

      /**
       * @type {!Object<string, import("../canvas.js").TextState>}
       */
      this.textStates = {};

      /**
       * @private
       * @type {string}
       */
      this.textKey_ = '';

      /**
       * @private
       * @type {string}
       */
      this.fillKey_ = '';

      /**
       * @private
       * @type {string}
       */
      this.strokeKey_ = '';

      /**
       * @private
       * @type {import('../../style/Style.js').DeclutterMode}
       */
      this.declutterMode_ = undefined;

      /**
       * Data shared with an image builder for combined decluttering.
       * @private
       * @type {import("../canvas.js").DeclutterImageWithText}
       */
      this.declutterImageWithText_ = undefined;
    }

    /**
     * @return {import("../canvas.js").SerializableInstructions} the serializable instructions.
     * @override
     */
    finish() {
      const instructions = super.finish();
      instructions.textStates = this.textStates;
      instructions.fillStates = this.fillStates;
      instructions.strokeStates = this.strokeStates;
      return instructions;
    }

    /**
     * @param {import("../../geom/SimpleGeometry.js").default|import("../Feature.js").default} geometry Geometry.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} [index] Render order index.
     * @override
     */
    drawText(geometry, feature, index) {
      const fillState = this.textFillState_;
      const strokeState = this.textStrokeState_;
      const textState = this.textState_;
      if (this.text_ === '' || !textState || (!fillState && !strokeState)) {
        return;
      }

      const coordinates = this.coordinates;
      let begin = coordinates.length;

      const geometryType = geometry.getType();
      let flatCoordinates = null;
      let stride = geometry.getStride();

      if (
        textState.placement === 'line' &&
        (geometryType == 'LineString' ||
          geometryType == 'MultiLineString' ||
          geometryType == 'Polygon' ||
          geometryType == 'MultiPolygon')
      ) {
        if (!intersects$2(this.maxExtent, geometry.getExtent())) {
          return;
        }
        let ends;
        flatCoordinates = geometry.getFlatCoordinates();
        if (geometryType == 'LineString') {
          ends = [flatCoordinates.length];
        } else if (geometryType == 'MultiLineString') {
          ends = /** @type {import("../../geom/MultiLineString.js").default} */ (
            geometry
          ).getEnds();
        } else if (geometryType == 'Polygon') {
          ends = /** @type {import("../../geom/Polygon.js").default} */ (geometry)
            .getEnds()
            .slice(0, 1);
        } else if (geometryType == 'MultiPolygon') {
          const endss =
            /** @type {import("../../geom/MultiPolygon.js").default} */ (
              geometry
            ).getEndss();
          ends = [];
          for (let i = 0, ii = endss.length; i < ii; ++i) {
            ends.push(endss[i][0]);
          }
        }
        this.beginGeometry(geometry, feature, index);
        const repeat = textState.repeat;
        const textAlign = repeat ? undefined : textState.textAlign;
        // No `justify` support for line placement.
        let flatOffset = 0;
        for (let o = 0, oo = ends.length; o < oo; ++o) {
          let chunks;
          if (repeat) {
            chunks = lineChunk(
              repeat * this.resolution,
              flatCoordinates,
              flatOffset,
              ends[o],
              stride,
            );
          } else {
            chunks = [flatCoordinates.slice(flatOffset, ends[o])];
          }
          for (let c = 0, cc = chunks.length; c < cc; ++c) {
            const chunk = chunks[c];
            let chunkBegin = 0;
            let chunkEnd = chunk.length;
            if (textAlign == undefined) {
              const range = matchingChunk(
                textState.maxAngle,
                chunk,
                0,
                chunk.length,
                2,
              );
              chunkBegin = range[0];
              chunkEnd = range[1];
            }
            for (let i = chunkBegin; i < chunkEnd; i += stride) {
              coordinates.push(chunk[i], chunk[i + 1]);
            }
            const end = coordinates.length;
            flatOffset = ends[o];
            this.drawChars_(begin, end);
            begin = end;
          }
        }
        this.endGeometry(feature);
      } else {
        let geometryWidths = textState.overflow ? null : [];
        switch (geometryType) {
          case 'Point':
          case 'MultiPoint':
            flatCoordinates =
              /** @type {import("../../geom/MultiPoint.js").default} */ (
                geometry
              ).getFlatCoordinates();
            break;
          case 'LineString':
            flatCoordinates =
              /** @type {import("../../geom/LineString.js").default} */ (
                geometry
              ).getFlatMidpoint();
            break;
          case 'Circle':
            flatCoordinates =
              /** @type {import("../../geom/Circle.js").default} */ (
                geometry
              ).getCenter();
            break;
          case 'MultiLineString':
            flatCoordinates =
              /** @type {import("../../geom/MultiLineString.js").default} */ (
                geometry
              ).getFlatMidpoints();
            stride = 2;
            break;
          case 'Polygon':
            flatCoordinates =
              /** @type {import("../../geom/Polygon.js").default} */ (
                geometry
              ).getFlatInteriorPoint();
            if (!textState.overflow) {
              geometryWidths.push(flatCoordinates[2] / this.resolution);
            }
            stride = 3;
            break;
          case 'MultiPolygon':
            const interiorPoints =
              /** @type {import("../../geom/MultiPolygon.js").default} */ (
                geometry
              ).getFlatInteriorPoints();
            flatCoordinates = [];
            for (let i = 0, ii = interiorPoints.length; i < ii; i += 3) {
              if (!textState.overflow) {
                geometryWidths.push(interiorPoints[i + 2] / this.resolution);
              }
              flatCoordinates.push(interiorPoints[i], interiorPoints[i + 1]);
            }
            if (flatCoordinates.length === 0) {
              return;
            }
            stride = 2;
            break;
        }
        const end = this.appendFlatPointCoordinates(flatCoordinates, stride);
        if (end === begin) {
          return;
        }
        if (
          geometryWidths &&
          (end - begin) / 2 !== flatCoordinates.length / stride
        ) {
          let beg = begin / 2;
          geometryWidths = geometryWidths.filter((w, i) => {
            const keep =
              coordinates[(beg + i) * 2] === flatCoordinates[i * stride] &&
              coordinates[(beg + i) * 2 + 1] === flatCoordinates[i * stride + 1];
            if (!keep) {
              --beg;
            }
            return keep;
          });
        }

        this.saveTextStates_();

        const backgroundFill = textState.backgroundFill
          ? this.createFill(this.fillStyleToState(textState.backgroundFill))
          : null;
        const backgroundStroke = textState.backgroundStroke
          ? this.createStroke(this.strokeStyleToState(textState.backgroundStroke))
          : null;

        this.beginGeometry(geometry, feature, index);

        // adjust padding for negative scale
        let padding = textState.padding;
        if (
          padding != defaultPadding &&
          (textState.scale[0] < 0 || textState.scale[1] < 0)
        ) {
          let p0 = textState.padding[0];
          let p1 = textState.padding[1];
          let p2 = textState.padding[2];
          let p3 = textState.padding[3];
          if (textState.scale[0] < 0) {
            p1 = -p1;
            p3 = -p3;
          }
          if (textState.scale[1] < 0) {
            p0 = -p0;
            p2 = -p2;
          }
          padding = [p0, p1, p2, p3];
        }

        // The image is unknown at this stage so we pass null; it will be computed at render time.
        // For clarity, we pass NaN for offsetX, offsetY, width and height, which will be computed at
        // render time.
        const pixelRatio = this.pixelRatio;
        this.instructions.push([
          Instruction.DRAW_IMAGE,
          begin,
          end,
          null,
          NaN,
          NaN,
          NaN,
          1,
          0,
          0,
          this.textRotateWithView_,
          this.textRotation_,
          [1, 1],
          NaN,
          this.declutterMode_,
          this.declutterImageWithText_,
          padding == defaultPadding
            ? defaultPadding
            : padding.map(function (p) {
                return p * pixelRatio;
              }),
          backgroundFill,
          backgroundStroke,
          this.text_,
          this.textKey_,
          this.strokeKey_,
          this.fillKey_,
          this.textOffsetX_,
          this.textOffsetY_,
          geometryWidths,
        ]);
        const scale = 1 / pixelRatio;
        // Set default fill for hit detection background
        const hitDetectionBackgroundFill = backgroundFill
          ? backgroundFill.slice(0)
          : null;
        if (hitDetectionBackgroundFill) {
          hitDetectionBackgroundFill[1] = defaultFillStyle;
        }
        this.hitDetectionInstructions.push([
          Instruction.DRAW_IMAGE,
          begin,
          end,
          null,
          NaN,
          NaN,
          NaN,
          1,
          0,
          0,
          this.textRotateWithView_,
          this.textRotation_,
          [scale, scale],
          NaN,
          this.declutterMode_,
          this.declutterImageWithText_,
          padding,
          hitDetectionBackgroundFill,
          backgroundStroke,
          this.text_,
          this.textKey_,
          this.strokeKey_,
          this.fillKey_ ? defaultFillStyle : this.fillKey_,
          this.textOffsetX_,
          this.textOffsetY_,
          geometryWidths,
        ]);

        this.endGeometry(feature);
      }
    }

    /**
     * @private
     */
    saveTextStates_() {
      const strokeState = this.textStrokeState_;
      const textState = this.textState_;
      const fillState = this.textFillState_;

      const strokeKey = this.strokeKey_;
      if (strokeState) {
        if (!(strokeKey in this.strokeStates)) {
          this.strokeStates[strokeKey] = {
            strokeStyle: strokeState.strokeStyle,
            lineCap: strokeState.lineCap,
            lineDashOffset: strokeState.lineDashOffset,
            lineWidth: strokeState.lineWidth,
            lineJoin: strokeState.lineJoin,
            miterLimit: strokeState.miterLimit,
            lineDash: strokeState.lineDash,
          };
        }
      }
      const textKey = this.textKey_;
      if (!(textKey in this.textStates)) {
        this.textStates[textKey] = {
          font: textState.font,
          textAlign: textState.textAlign || defaultTextAlign,
          justify: textState.justify,
          textBaseline: textState.textBaseline || defaultTextBaseline,
          scale: textState.scale,
        };
      }
      const fillKey = this.fillKey_;
      if (fillState) {
        if (!(fillKey in this.fillStates)) {
          this.fillStates[fillKey] = {
            fillStyle: fillState.fillStyle,
          };
        }
      }
    }

    /**
     * @private
     * @param {number} begin Begin.
     * @param {number} end End.
     */
    drawChars_(begin, end) {
      const strokeState = this.textStrokeState_;
      const textState = this.textState_;

      const strokeKey = this.strokeKey_;
      const textKey = this.textKey_;
      const fillKey = this.fillKey_;
      this.saveTextStates_();

      const pixelRatio = this.pixelRatio;
      const baseline = TEXT_ALIGN[textState.textBaseline];

      const offsetY = this.textOffsetY_ * pixelRatio;
      const text = this.text_;
      const strokeWidth = strokeState
        ? (strokeState.lineWidth * Math.abs(textState.scale[0])) / 2
        : 0;

      this.instructions.push([
        Instruction.DRAW_CHARS,
        begin,
        end,
        baseline,
        textState.overflow,
        fillKey,
        textState.maxAngle,
        pixelRatio,
        offsetY,
        strokeKey,
        strokeWidth * pixelRatio,
        text,
        textKey,
        1,
        this.declutterMode_,
        this.textKeepUpright_,
      ]);
      this.hitDetectionInstructions.push([
        Instruction.DRAW_CHARS,
        begin,
        end,
        baseline,
        textState.overflow,
        fillKey ? defaultFillStyle : fillKey,
        textState.maxAngle,
        pixelRatio,
        offsetY,
        strokeKey,
        strokeWidth * pixelRatio,
        text,
        textKey,
        1 / pixelRatio,
        this.declutterMode_,
        this.textKeepUpright_,
      ]);
    }

    /**
     * @param {import("../../style/Text.js").default} textStyle Text style.
     * @param {Object} [sharedData] Shared data.
     * @override
     */
    setTextStyle(textStyle, sharedData) {
      let textState, fillState, strokeState;
      if (!textStyle) {
        this.text_ = '';
      } else {
        const textFillStyle = textStyle.getFill();
        if (!textFillStyle) {
          fillState = null;
          this.textFillState_ = fillState;
        } else {
          fillState = this.textFillState_;
          if (!fillState) {
            fillState = /** @type {import("../canvas.js").FillState} */ ({});
            this.textFillState_ = fillState;
          }
          fillState.fillStyle = asColorLike(
            textFillStyle.getColor() || defaultFillStyle,
          );
        }

        const textStrokeStyle = textStyle.getStroke();
        if (!textStrokeStyle) {
          strokeState = null;
          this.textStrokeState_ = strokeState;
        } else {
          strokeState = this.textStrokeState_;
          if (!strokeState) {
            strokeState = /** @type {import("../canvas.js").StrokeState} */ ({});
            this.textStrokeState_ = strokeState;
          }
          const lineDash = textStrokeStyle.getLineDash();
          const lineDashOffset = textStrokeStyle.getLineDashOffset();
          const lineWidth = textStrokeStyle.getWidth();
          const miterLimit = textStrokeStyle.getMiterLimit();
          strokeState.lineCap = textStrokeStyle.getLineCap() || defaultLineCap;
          strokeState.lineDash = lineDash ? lineDash.slice() : defaultLineDash;
          strokeState.lineDashOffset =
            lineDashOffset === undefined ? defaultLineDashOffset : lineDashOffset;
          strokeState.lineJoin = textStrokeStyle.getLineJoin() || defaultLineJoin;
          strokeState.lineWidth =
            lineWidth === undefined ? defaultLineWidth : lineWidth;
          strokeState.miterLimit =
            miterLimit === undefined ? defaultMiterLimit : miterLimit;
          strokeState.strokeStyle = asColorLike(
            textStrokeStyle.getColor() || defaultStrokeStyle,
          );
        }

        textState = this.textState_;
        const font = textStyle.getFont() || defaultFont;
        registerFont(font);
        const textScale = textStyle.getScaleArray();
        textState.overflow = textStyle.getOverflow();
        textState.font = font;
        textState.maxAngle = textStyle.getMaxAngle();
        textState.placement = textStyle.getPlacement();
        textState.textAlign = textStyle.getTextAlign();
        textState.repeat = textStyle.getRepeat();
        textState.justify = textStyle.getJustify();
        textState.textBaseline =
          textStyle.getTextBaseline() || defaultTextBaseline;
        textState.backgroundFill = textStyle.getBackgroundFill();
        textState.backgroundStroke = textStyle.getBackgroundStroke();
        textState.padding = textStyle.getPadding() || defaultPadding;
        textState.scale = textScale === undefined ? [1, 1] : textScale;

        const textOffsetX = textStyle.getOffsetX();
        const textOffsetY = textStyle.getOffsetY();
        const textRotateWithView = textStyle.getRotateWithView();
        const textKeepUpright = textStyle.getKeepUpright();
        const textRotation = textStyle.getRotation();
        this.text_ = textStyle.getText() || '';
        this.textOffsetX_ = textOffsetX === undefined ? 0 : textOffsetX;
        this.textOffsetY_ = textOffsetY === undefined ? 0 : textOffsetY;
        this.textRotateWithView_ =
          textRotateWithView === undefined ? false : textRotateWithView;
        this.textKeepUpright_ =
          textKeepUpright === undefined ? true : textKeepUpright;
        this.textRotation_ = textRotation === undefined ? 0 : textRotation;

        this.strokeKey_ = strokeState
          ? (typeof strokeState.strokeStyle == 'string'
              ? strokeState.strokeStyle
              : getUid(strokeState.strokeStyle)) +
            strokeState.lineCap +
            strokeState.lineDashOffset +
            '|' +
            strokeState.lineWidth +
            strokeState.lineJoin +
            strokeState.miterLimit +
            '[' +
            strokeState.lineDash.join() +
            ']'
          : '';
        this.textKey_ =
          textState.font +
          textState.scale +
          (textState.textAlign || '?') +
          (textState.repeat || '?') +
          (textState.justify || '?') +
          (textState.textBaseline || '?');
        this.fillKey_ =
          fillState && fillState.fillStyle
            ? typeof fillState.fillStyle == 'string'
              ? fillState.fillStyle
              : '|' + getUid(fillState.fillStyle)
            : '';
      }
      this.declutterMode_ = textStyle.getDeclutterMode();
      this.declutterImageWithText_ = sharedData;
    }
  }

  /**
   * @module ol/render/canvas/BuilderGroup
   */


  /**
   * @type {Object<import("../canvas.js").BuilderType, typeof Builder>}
   */
  const BATCH_CONSTRUCTORS = {
    'Circle': CanvasPolygonBuilder,
    'Default': CanvasBuilder,
    'Image': CanvasImageBuilder,
    'LineString': CanvasLineStringBuilder,
    'Polygon': CanvasPolygonBuilder,
    'Text': CanvasTextBuilder,
  };

  class BuilderGroup {
    /**
     * @param {number} tolerance Tolerance.
     * @param {import("../../extent.js").Extent} maxExtent Max extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     */
    constructor(tolerance, maxExtent, resolution, pixelRatio) {
      /**
       * @private
       * @type {number}
       */
      this.tolerance_ = tolerance;

      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.maxExtent_ = maxExtent;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = pixelRatio;

      /**
       * @private
       * @type {number}
       */
      this.resolution_ = resolution;

      /**
       * @private
       * @type {!Object<string, !Object<import("../canvas.js").BuilderType, Builder>>}
       */
      this.buildersByZIndex_ = {};
    }

    /**
     * @return {!Object<string, !Object<import("../canvas.js").BuilderType, import("./Builder.js").SerializableInstructions>>} The serializable instructions
     */
    finish() {
      const builderInstructions = {};
      for (const zKey in this.buildersByZIndex_) {
        builderInstructions[zKey] = builderInstructions[zKey] || {};
        const builders = this.buildersByZIndex_[zKey];
        for (const builderKey in builders) {
          const builderInstruction = builders[builderKey].finish();
          builderInstructions[zKey][builderKey] = builderInstruction;
        }
      }
      return builderInstructions;
    }

    /**
     * @param {number|undefined} zIndex Z index.
     * @param {import("../canvas.js").BuilderType} builderType Replay type.
     * @return {import("../VectorContext.js").default} Replay.
     */
    getBuilder(zIndex, builderType) {
      const zIndexKey = zIndex !== undefined ? zIndex.toString() : '0';
      let replays = this.buildersByZIndex_[zIndexKey];
      if (replays === undefined) {
        replays = {};
        this.buildersByZIndex_[zIndexKey] = replays;
      }
      let replay = replays[builderType];
      if (replay === undefined) {
        const Constructor = BATCH_CONSTRUCTORS[builderType];
        replay = new Constructor(
          this.tolerance_,
          this.maxExtent_,
          this.resolution_,
          this.pixelRatio_,
        );
        replays[builderType] = replay;
      }
      return replay;
    }
  }

  /**
   * @module ol/geom/flat/textpath
   */

  /**
   * @param {Array<number>} flatCoordinates Path to put text on.
   * @param {number} offset Start offset of the `flatCoordinates`.
   * @param {number} end End offset of the `flatCoordinates`.
   * @param {number} stride Stride.
   * @param {string} text Text to place on the path.
   * @param {number} startM m along the path where the text starts.
   * @param {number} maxAngle Max angle between adjacent chars in radians.
   * @param {number} scale The product of the text scale and the device pixel ratio.
   * @param {function(string, string, Object<string, number>):number} measureAndCacheTextWidth Measure and cache text width.
   * @param {string} font The font.
   * @param {Object<string, number>} cache A cache of measured widths.
   * @param {number} rotation Rotation to apply to the flatCoordinates to determine whether text needs to be reversed.
   * @param {boolean} keepUpright Whether the text needs to be kept upright
   * @return {Array<Array<*>>|null} The result array (or null if `maxAngle` was
   * exceeded). Entries of the array are x, y, anchorX, angle, chunk.
   */
  function drawTextOnPath(
    flatCoordinates,
    offset,
    end,
    stride,
    text,
    startM,
    maxAngle,
    scale,
    measureAndCacheTextWidth,
    font,
    cache,
    rotation,
    keepUpright = true,
  ) {
    let x2 = flatCoordinates[offset];
    let y2 = flatCoordinates[offset + 1];
    let x1 = 0;
    let y1 = 0;
    let segmentLength = 0;
    let segmentM = 0;

    function advance() {
      x1 = x2;
      y1 = y2;
      offset += stride;
      x2 = flatCoordinates[offset];
      y2 = flatCoordinates[offset + 1];
      segmentM += segmentLength;
      segmentLength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    }
    do {
      advance();
    } while (offset < end - stride && segmentM + segmentLength < startM);

    let interpolate =
      segmentLength === 0 ? 0 : (startM - segmentM) / segmentLength;
    const beginX = lerp$1(x1, x2, interpolate);
    const beginY = lerp$1(y1, y2, interpolate);

    const startOffset = offset - stride;
    const startLength = segmentM;
    const endM = startM + scale * measureAndCacheTextWidth(font, text, cache);
    while (offset < end - stride && segmentM + segmentLength < endM) {
      advance();
    }
    interpolate = segmentLength === 0 ? 0 : (endM - segmentM) / segmentLength;
    const endX = lerp$1(x1, x2, interpolate);
    const endY = lerp$1(y1, y2, interpolate);

    // Keep text upright if the option is selected
    let reverse = false;
    if (keepUpright) {
      if (rotation) {
        const flat = [beginX, beginY, endX, endY];
        rotate(flat, 0, 4, 2, rotation, flat, flat);
        reverse = flat[0] > flat[2];
      } else {
        reverse = beginX > endX;
      }
    }

    const PI = Math.PI;
    const result = [];
    const singleSegment = startOffset + stride === offset;

    offset = startOffset;
    segmentLength = 0;
    segmentM = startLength;
    x2 = flatCoordinates[offset];
    y2 = flatCoordinates[offset + 1];

    let previousAngle;
    // All on the same segment
    if (singleSegment) {
      advance();

      previousAngle = Math.atan2(y2 - y1, x2 - x1);
      if (reverse) {
        previousAngle += previousAngle > 0 ? -PI : PI;
      }
      const x = (endX + beginX) / 2;
      const y = (endY + beginY) / 2;
      result[0] = [x, y, (endM - startM) / 2, previousAngle, text];
      return result;
    }

    // rendering across line segments
    text = text.replace(/\n/g, ' '); // ensure rendering in single-line as all calculations below don't handle multi-lines

    for (let i = 0, ii = text.length; i < ii; ) {
      advance();
      let angle = Math.atan2(y2 - y1, x2 - x1);
      if (reverse) {
        angle += angle > 0 ? -PI : PI;
      }
      if (previousAngle !== undefined) {
        let delta = angle - previousAngle;
        delta += delta > PI ? -2 * PI : delta < -PI ? 2 * PI : 0;
        if (Math.abs(delta) > maxAngle) {
          return null;
        }
      }
      previousAngle = angle;

      const iStart = i;
      let charLength = 0;
      for (; i < ii; ++i) {
        const index = reverse ? ii - i - 1 : i;
        const len = scale * measureAndCacheTextWidth(font, text[index], cache);
        if (
          offset + stride < end &&
          segmentM + segmentLength < startM + charLength + len / 2
        ) {
          break;
        }
        charLength += len;
      }
      if (i === iStart) {
        continue;
      }
      const chars = reverse
        ? text.substring(ii - iStart, ii - i)
        : text.substring(iStart, i);
      interpolate =
        segmentLength === 0
          ? 0
          : (startM + charLength / 2 - segmentM) / segmentLength;
      const x = lerp$1(x1, x2, interpolate);
      const y = lerp$1(y1, y2, interpolate);
      result.push([x, y, charLength / 2, angle, chars]);
      startM += charLength;
    }
    return result;
  }

  /**
   * @module ol/render/canvas/ZIndexContext
   */


  /** @typedef {CanvasRenderingContext2D & {globalAlpha: any}} ZIndexContextProxy */

  /**
   * @extends {CanvasRenderingContext2D}
   */
  class ZIndexContext {
    constructor() {
      /**
       * @private
       * @type {Array<Array<*>>}
       */
      this.instructions_ = [];
      /**
       * @type {number}
       */
      this.zIndex = 0;
      /**
       * @private
       * @type {number}
       */
      this.offset_ = 0;

      /**
       * @private
       * @type {ZIndexContextProxy}
       */
      this.context_ = /** @type {ZIndexContextProxy} */ (
        new Proxy(getSharedCanvasContext2D(), {
          get: (target, property) => {
            if (
              typeof (/** @type {*} */ (getSharedCanvasContext2D())[property]) !==
              'function'
            ) {
              // we only accept calling functions on the proxy, not accessing properties
              return undefined;
            }
            this.push_(property);
            return this.pushMethodArgs_;
          },
          set: (target, property, value) => {
            this.push_(property, value);
            return true;
          },
        })
      );
    }

    /**
     * @param {...*} args Arguments to push to the instructions array.
     * @private
     */
    push_(...args) {
      const instructions = this.instructions_;
      const index = this.zIndex + this.offset_;
      if (!instructions[index]) {
        instructions[index] = [];
      }
      instructions[index].push(...args);
    }

    /**
     * @private
     * @param {...*} args Args.
     * @return {ZIndexContext} This.
     */
    pushMethodArgs_ = (...args) => {
      this.push_(args);
      return this;
    };

    /**
     * Push a function that renders to the context directly.
     * @param {function(CanvasRenderingContext2D): void} render Function.
     */
    pushFunction(render) {
      this.push_(render);
    }

    /**
     * Get a proxy for CanvasRenderingContext2D which does not support getting state
     * (e.g. `context.globalAlpha`, which will return `undefined`). To set state, if it relies on a
     * previous state (e.g. `context.globalAlpha = context.globalAlpha / 2`), set a function,
     * e.g. `context.globalAlpha = (context) => context.globalAlpha / 2`.
     * @return {ZIndexContextProxy} Context.
     */
    getContext() {
      return this.context_;
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     */
    draw(context) {
      this.instructions_.forEach((instructionsAtIndex) => {
        for (let i = 0, ii = instructionsAtIndex.length; i < ii; ++i) {
          const property = instructionsAtIndex[i];
          if (typeof property === 'function') {
            property(context);
            continue;
          }
          const instructionAtIndex = instructionsAtIndex[++i];
          if (typeof (/** @type {*} */ (context)[property]) === 'function') {
            /** @type {*} */ (context)[property](...instructionAtIndex);
          } else {
            if (typeof instructionAtIndex === 'function') {
              /** @type {*} */ (context)[property] = instructionAtIndex(context);
              continue;
            }
            /** @type {*} */ (context)[property] = instructionAtIndex;
          }
        }
      });
    }

    clear() {
      this.instructions_.length = 0;
      this.zIndex = 0;
      this.offset_ = 0;
    }

    /**
     * Offsets the zIndex by the highest current zIndex. Useful for rendering multiple worlds or tiles, to
     * avoid conflicting context.clip() or context.save()/restore() calls.
     */
    offset() {
      this.offset_ = this.instructions_.length;
      this.zIndex = 0;
    }
  }

  /**
   * @module ol/render/canvas/Executor
   */

  /**
   * @typedef {import('../../structs/RBush.js').Entry<import('../../Feature.js').FeatureLike>} DeclutterEntry
   */

  /**
   * @typedef {Object} ImageOrLabelDimensions
   * @property {number} drawImageX DrawImageX.
   * @property {number} drawImageY DrawImageY.
   * @property {number} drawImageW DrawImageW.
   * @property {number} drawImageH DrawImageH.
   * @property {number} originX OriginX.
   * @property {number} originY OriginY.
   * @property {Array<number>} scale Scale.
   * @property {DeclutterEntry} declutterBox DeclutterBox.
   * @property {import("../../transform.js").Transform} canvasTransform CanvasTransform.
   */

  /**
   * @typedef {{0: CanvasRenderingContext2D, 1: import('../../size.js').Size, 2: import("../canvas.js").Label|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement, 3: ImageOrLabelDimensions, 4: number, 5: Array<*>, 6: Array<*>}} ReplayImageOrLabelArgs
   */

  /**
   * @template T
   * @typedef {function(import("../../Feature.js").FeatureLike, import("../../geom/SimpleGeometry.js").default, import("../../style/Style.js").DeclutterMode): T} FeatureCallback
   */

  /**
   * @type {import("../../extent.js").Extent}
   */
  const tmpExtent = createEmpty();

  /** @type {import("../../coordinate.js").Coordinate} */
  const p1 = [];
  /** @type {import("../../coordinate.js").Coordinate} */
  const p2 = [];
  /** @type {import("../../coordinate.js").Coordinate} */
  const p3 = [];
  /** @type {import("../../coordinate.js").Coordinate} */
  const p4 = [];

  /**
   * @param {ReplayImageOrLabelArgs} replayImageOrLabelArgs Arguments to replayImageOrLabel
   * @return {DeclutterEntry} Declutter rbush entry.
   */
  function getDeclutterBox(replayImageOrLabelArgs) {
    return replayImageOrLabelArgs[3].declutterBox;
  }

  const rtlRegEx = new RegExp(
    /* eslint-disable prettier/prettier */
    '[' +
      String.fromCharCode(0x00591) + '-' + String.fromCharCode(0x008ff) +
      String.fromCharCode(0x0fb1d) + '-' + String.fromCharCode(0x0fdff) +
      String.fromCharCode(0x0fe70) + '-' + String.fromCharCode(0x0fefc) +
      String.fromCharCode(0x10800) + '-' + String.fromCharCode(0x10fff) +
      String.fromCharCode(0x1e800) + '-' + String.fromCharCode(0x1efff) +
    ']'
    /* eslint-enable prettier/prettier */
  );

  /**
   * @param {string} text Text.
   * @param {CanvasTextAlign} align Alignment.
   * @return {number} Text alignment.
   */
  function horizontalTextAlign(text, align) {
    if (align === 'start') {
      align = rtlRegEx.test(text) ? 'right' : 'left';
    } else if (align === 'end') {
      align = rtlRegEx.test(text) ? 'left' : 'right';
    }
    return TEXT_ALIGN[align];
  }

  /**
   * @param {Array<string>} acc Accumulator.
   * @param {string} line Line of text.
   * @param {number} i Index
   * @return {Array<string>} Accumulator.
   */
  function createTextChunks(acc, line, i) {
    if (i > 0) {
      acc.push('\n', '');
    }
    acc.push(line, '');
    return acc;
  }

  /**
   * Converts rich text to plain text for text along lines.
   * @param {string} result The resulting plain text.
   * @param {string} part Item of the rich text array.
   * @param {number} index Index of the item in the rich text array.
   * @return {string} The resulting plain text.
   */
  function richTextToPlainText(result, part, index) {
    if (index % 2 === 0) {
      result += part;
    }
    return result;
  }

  class Executor {
    /**
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {boolean} overlaps The replay can have overlapping geometries.
     * @param {import("../canvas.js").SerializableInstructions} instructions The serializable instructions.
     * @param {boolean} [deferredRendering] Enable deferred rendering.
     */
    constructor(
      resolution,
      pixelRatio,
      overlaps,
      instructions,
      deferredRendering,
    ) {
      /**
       * @protected
       * @type {boolean}
       */
      this.overlaps = overlaps;

      /**
       * @protected
       * @type {number}
       */
      this.pixelRatio = pixelRatio;

      /**
       * @protected
       * @const
       * @type {number}
       */
      this.resolution = resolution;

      /**
       * @private
       * @type {number}
       */
      this.alignAndScaleFill_;

      /**
       * @protected
       * @type {Array<*>}
       */
      this.instructions = instructions.instructions;

      /**
       * @protected
       * @type {Array<number>}
       */
      this.coordinates = instructions.coordinates;

      /**
       * @private
       * @type {!Object<number,import("../../coordinate.js").Coordinate|Array<import("../../coordinate.js").Coordinate>|Array<Array<import("../../coordinate.js").Coordinate>>>}
       */
      this.coordinateCache_ = {};

      /**
       * @private
       * @type {!import("../../transform.js").Transform}
       */
      this.renderedTransform_ = create$3();

      /**
       * @protected
       * @type {Array<*>}
       */
      this.hitDetectionInstructions = instructions.hitDetectionInstructions;

      /**
       * @private
       * @type {Array<number>}
       */
      this.pixelCoordinates_ = null;

      /**
       * @private
       * @type {number}
       */
      this.viewRotation_ = 0;

      /**
       * @type {!Object<string, import("../canvas.js").FillState>}
       */
      this.fillStates = instructions.fillStates || {};

      /**
       * @type {!Object<string, import("../canvas.js").StrokeState>}
       */
      this.strokeStates = instructions.strokeStates || {};

      /**
       * @type {!Object<string, import("../canvas.js").TextState>}
       */
      this.textStates = instructions.textStates || {};

      /**
       * @private
       * @type {Object<string, Object<string, number>>}
       */
      this.widths_ = {};

      /**
       * @private
       * @type {Object<string, import("../canvas.js").Label>}
       */
      this.labels_ = {};

      /**
       * @private
       * @type {import("../canvas/ZIndexContext.js").default}
       */
      this.zIndexContext_ = deferredRendering ? new ZIndexContext() : null;
    }

    /**
     * @return {ZIndexContext} ZIndex context.
     */
    getZIndexContext() {
      return this.zIndexContext_;
    }

    /**
     * @param {string|Array<string>} text Text.
     * @param {string} textKey Text style key.
     * @param {string} fillKey Fill style key.
     * @param {string} strokeKey Stroke style key.
     * @return {import("../canvas.js").Label} Label.
     */
    createLabel(text, textKey, fillKey, strokeKey) {
      const key = text + textKey + fillKey + strokeKey;
      if (this.labels_[key]) {
        return this.labels_[key];
      }
      const strokeState = strokeKey ? this.strokeStates[strokeKey] : null;
      const fillState = fillKey ? this.fillStates[fillKey] : null;
      const textState = this.textStates[textKey];
      const pixelRatio = this.pixelRatio;
      const scale = [
        textState.scale[0] * pixelRatio,
        textState.scale[1] * pixelRatio,
      ];
      const align = textState.justify
        ? TEXT_ALIGN[textState.justify]
        : horizontalTextAlign(
            Array.isArray(text) ? text[0] : text,
            textState.textAlign || defaultTextAlign,
          );
      const strokeWidth =
        strokeKey && strokeState.lineWidth ? strokeState.lineWidth : 0;

      const chunks = Array.isArray(text)
        ? text
        : String(text).split('\n').reduce(createTextChunks, []);

      const {width, height, widths, heights, lineWidths} = getTextDimensions(
        textState,
        chunks,
      );
      const renderWidth = width + strokeWidth;
      const contextInstructions = [];
      // make canvas 2 pixels wider to account for italic text width measurement errors
      const w = (renderWidth + 2) * scale[0];
      const h = (height + strokeWidth) * scale[1];
      /** @type {import("../canvas.js").Label} */
      const label = {
        width: w < 0 ? Math.floor(w) : Math.ceil(w),
        height: h < 0 ? Math.floor(h) : Math.ceil(h),
        contextInstructions: contextInstructions,
      };
      if (scale[0] != 1 || scale[1] != 1) {
        contextInstructions.push('scale', scale);
      }
      if (strokeKey) {
        contextInstructions.push('strokeStyle', strokeState.strokeStyle);
        contextInstructions.push('lineWidth', strokeWidth);
        contextInstructions.push('lineCap', strokeState.lineCap);
        contextInstructions.push('lineJoin', strokeState.lineJoin);
        contextInstructions.push('miterLimit', strokeState.miterLimit);
        contextInstructions.push('setLineDash', [strokeState.lineDash]);
        contextInstructions.push('lineDashOffset', strokeState.lineDashOffset);
      }
      if (fillKey) {
        contextInstructions.push('fillStyle', fillState.fillStyle);
      }
      contextInstructions.push('textBaseline', 'middle');
      contextInstructions.push('textAlign', 'center');
      const leftRight = 0.5 - align;
      let x = align * renderWidth + leftRight * strokeWidth;
      const strokeInstructions = [];
      const fillInstructions = [];
      let lineHeight = 0;
      let lineOffset = 0;
      let widthHeightIndex = 0;
      let lineWidthIndex = 0;
      let previousFont;
      for (let i = 0, ii = chunks.length; i < ii; i += 2) {
        const text = chunks[i];
        if (text === '\n') {
          lineOffset += lineHeight;
          lineHeight = 0;
          x = align * renderWidth + leftRight * strokeWidth;
          ++lineWidthIndex;
          continue;
        }
        const font = chunks[i + 1] || textState.font;
        if (font !== previousFont) {
          if (strokeKey) {
            strokeInstructions.push('font', font);
          }
          if (fillKey) {
            fillInstructions.push('font', font);
          }
          previousFont = font;
        }
        lineHeight = Math.max(lineHeight, heights[widthHeightIndex]);
        const fillStrokeArgs = [
          text,
          x +
            leftRight * widths[widthHeightIndex] +
            align * (widths[widthHeightIndex] - lineWidths[lineWidthIndex]),
          0.5 * (strokeWidth + lineHeight) + lineOffset,
        ];
        x += widths[widthHeightIndex];
        if (strokeKey) {
          strokeInstructions.push('strokeText', fillStrokeArgs);
        }
        if (fillKey) {
          fillInstructions.push('fillText', fillStrokeArgs);
        }
        ++widthHeightIndex;
      }
      Array.prototype.push.apply(contextInstructions, strokeInstructions);
      Array.prototype.push.apply(contextInstructions, fillInstructions);
      this.labels_[key] = label;
      return label;
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../coordinate.js").Coordinate} p1 1st point of the background box.
     * @param {import("../../coordinate.js").Coordinate} p2 2nd point of the background box.
     * @param {import("../../coordinate.js").Coordinate} p3 3rd point of the background box.
     * @param {import("../../coordinate.js").Coordinate} p4 4th point of the background box.
     * @param {Array<*>} fillInstruction Fill instruction.
     * @param {Array<*>} strokeInstruction Stroke instruction.
     */
    replayTextBackground_(
      context,
      p1,
      p2,
      p3,
      p4,
      fillInstruction,
      strokeInstruction,
    ) {
      context.beginPath();
      context.moveTo.apply(context, p1);
      context.lineTo.apply(context, p2);
      context.lineTo.apply(context, p3);
      context.lineTo.apply(context, p4);
      context.lineTo.apply(context, p1);
      if (fillInstruction) {
        this.alignAndScaleFill_ = /** @type {number} */ (fillInstruction[2]);
        context.fillStyle = /** @type {string} */ (fillInstruction[1]);
        this.fill_(context);
      }
      if (strokeInstruction) {
        this.setStrokeStyle_(
          context,
          /** @type {Array<*>} */ (strokeInstruction),
        );
        context.stroke();
      }
    }

    /**
     * @private
     * @param {number} sheetWidth Width of the sprite sheet.
     * @param {number} sheetHeight Height of the sprite sheet.
     * @param {number} centerX X.
     * @param {number} centerY Y.
     * @param {number} width Width.
     * @param {number} height Height.
     * @param {number} anchorX Anchor X.
     * @param {number} anchorY Anchor Y.
     * @param {number} originX Origin X.
     * @param {number} originY Origin Y.
     * @param {number} rotation Rotation.
     * @param {import("../../size.js").Size} scale Scale.
     * @param {boolean} snapToPixel Snap to pixel.
     * @param {Array<number>} padding Padding.
     * @param {boolean} fillStroke Background fill or stroke.
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @return {ImageOrLabelDimensions} Dimensions for positioning and decluttering the image or label.
     */
    calculateImageOrLabelDimensions_(
      sheetWidth,
      sheetHeight,
      centerX,
      centerY,
      width,
      height,
      anchorX,
      anchorY,
      originX,
      originY,
      rotation,
      scale,
      snapToPixel,
      padding,
      fillStroke,
      feature,
    ) {
      anchorX *= scale[0];
      anchorY *= scale[1];
      let x = centerX - anchorX;
      let y = centerY - anchorY;

      const w = width + originX > sheetWidth ? sheetWidth - originX : width;
      const h = height + originY > sheetHeight ? sheetHeight - originY : height;
      const boxW = padding[3] + w * scale[0] + padding[1];
      const boxH = padding[0] + h * scale[1] + padding[2];
      const boxX = x - padding[3];
      const boxY = y - padding[0];

      if (fillStroke || rotation !== 0) {
        p1[0] = boxX;
        p4[0] = boxX;
        p1[1] = boxY;
        p2[1] = boxY;
        p2[0] = boxX + boxW;
        p3[0] = p2[0];
        p3[1] = boxY + boxH;
        p4[1] = p3[1];
      }

      let transform;
      if (rotation !== 0) {
        transform = compose(
          create$3(),
          centerX,
          centerY,
          1,
          1,
          rotation,
          -centerX,
          -centerY,
        );

        apply(transform, p1);
        apply(transform, p2);
        apply(transform, p3);
        apply(transform, p4);
        createOrUpdate$2(
          Math.min(p1[0], p2[0], p3[0], p4[0]),
          Math.min(p1[1], p2[1], p3[1], p4[1]),
          Math.max(p1[0], p2[0], p3[0], p4[0]),
          Math.max(p1[1], p2[1], p3[1], p4[1]),
          tmpExtent,
        );
      } else {
        createOrUpdate$2(
          Math.min(boxX, boxX + boxW),
          Math.min(boxY, boxY + boxH),
          Math.max(boxX, boxX + boxW),
          Math.max(boxY, boxY + boxH),
          tmpExtent,
        );
      }
      if (snapToPixel) {
        x = Math.round(x);
        y = Math.round(y);
      }
      return {
        drawImageX: x,
        drawImageY: y,
        drawImageW: w,
        drawImageH: h,
        originX: originX,
        originY: originY,
        declutterBox: {
          minX: tmpExtent[0],
          minY: tmpExtent[1],
          maxX: tmpExtent[2],
          maxY: tmpExtent[3],
          value: feature,
        },
        canvasTransform: transform,
        scale: scale,
      };
    }

    /**
     * @private
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size.
     * @param {import("../canvas.js").Label|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} imageOrLabel Image.
     * @param {ImageOrLabelDimensions} dimensions Dimensions.
     * @param {number} opacity Opacity.
     * @param {Array<*>} fillInstruction Fill instruction.
     * @param {Array<*>} strokeInstruction Stroke instruction.
     * @return {boolean} The image or label was rendered.
     */
    replayImageOrLabel_(
      context,
      scaledCanvasSize,
      imageOrLabel,
      dimensions,
      opacity,
      fillInstruction,
      strokeInstruction,
    ) {
      const fillStroke = !!(fillInstruction || strokeInstruction);

      const box = dimensions.declutterBox;
      const strokePadding = strokeInstruction
        ? (strokeInstruction[2] * dimensions.scale[0]) / 2
        : 0;
      const intersects =
        box.minX - strokePadding <= scaledCanvasSize[0] &&
        box.maxX + strokePadding >= 0 &&
        box.minY - strokePadding <= scaledCanvasSize[1] &&
        box.maxY + strokePadding >= 0;

      if (intersects) {
        if (fillStroke) {
          this.replayTextBackground_(
            context,
            p1,
            p2,
            p3,
            p4,
            /** @type {Array<*>} */ (fillInstruction),
            /** @type {Array<*>} */ (strokeInstruction),
          );
        }
        drawImageOrLabel(
          context,
          dimensions.canvasTransform,
          opacity,
          imageOrLabel,
          dimensions.originX,
          dimensions.originY,
          dimensions.drawImageW,
          dimensions.drawImageH,
          dimensions.drawImageX,
          dimensions.drawImageY,
          dimensions.scale,
        );
      }
      return true;
    }

    /**
     * @private
     * @param {CanvasRenderingContext2D} context Context.
     */
    fill_(context) {
      const alignAndScale = this.alignAndScaleFill_;
      if (alignAndScale) {
        const origin = apply(this.renderedTransform_, [0, 0]);
        const repeatSize = 512 * this.pixelRatio;
        context.save();
        context.translate(origin[0] % repeatSize, origin[1] % repeatSize);
        if (alignAndScale !== 1) {
          context.scale(alignAndScale, alignAndScale);
        }
        context.rotate(this.viewRotation_);
      }
      context.fill();
      if (alignAndScale) {
        context.restore();
      }
    }

    /**
     * @private
     * @param {CanvasRenderingContext2D} context Context.
     * @param {Array<*>} instruction Instruction.
     */
    setStrokeStyle_(context, instruction) {
      context.strokeStyle =
        /** @type {import("../../colorlike.js").ColorLike} */ (instruction[1]);
      if (!instruction[1]) {
        return;
      }
      context.lineWidth = /** @type {number} */ (instruction[2]);
      context.lineCap = /** @type {CanvasLineCap} */ (instruction[3]);
      context.lineJoin = /** @type {CanvasLineJoin} */ (instruction[4]);
      context.miterLimit = /** @type {number} */ (instruction[5]);
      context.lineDashOffset = /** @type {number} */ (instruction[7]);
      context.setLineDash(/** @type {Array<number>} */ (instruction[6]));
    }

    /**
     * @private
     * @param {string|Array<string>} text The text to draw.
     * @param {string} textKey The key of the text state.
     * @param {string} strokeKey The key for the stroke state.
     * @param {string} fillKey The key for the fill state.
     * @return {{label: import("../canvas.js").Label, anchorX: number, anchorY: number}} The text image and its anchor.
     */
    drawLabelWithPointPlacement_(text, textKey, strokeKey, fillKey) {
      const textState = this.textStates[textKey];

      const label = this.createLabel(text, textKey, fillKey, strokeKey);

      const strokeState = this.strokeStates[strokeKey];
      const pixelRatio = this.pixelRatio;
      const align = horizontalTextAlign(
        Array.isArray(text) ? text[0] : text,
        textState.textAlign || defaultTextAlign,
      );
      const baseline = TEXT_ALIGN[textState.textBaseline || defaultTextBaseline];
      const strokeWidth =
        strokeState && strokeState.lineWidth ? strokeState.lineWidth : 0;

      // Remove the 2 pixels we added in createLabel() for the anchor
      const width = label.width / pixelRatio - 2 * textState.scale[0];
      const anchorX = align * width + 2 * (0.5 - align) * strokeWidth;
      const anchorY =
        (baseline * label.height) / pixelRatio +
        2 * (0.5 - baseline) * strokeWidth;

      return {
        label: label,
        anchorX: anchorX,
        anchorY: anchorY,
      };
    }

    /**
     * @private
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size
     * @param {import("../../transform.js").Transform} transform Transform.
     * @param {Array<*>} instructions Instructions array.
     * @param {boolean} snapToPixel Snap point symbols and text to integer pixels.
     * @param {FeatureCallback<T>} [featureCallback] Feature callback.
     * @param {import("../../extent.js").Extent} [hitExtent] Only check
     *     features that intersect this extent.
     * @param {import("rbush").default<DeclutterEntry>} [declutterTree] Declutter tree.
     * @return {T|undefined} Callback result.
     * @template T
     */
    execute_(
      context,
      scaledCanvasSize,
      transform,
      instructions,
      snapToPixel,
      featureCallback,
      hitExtent,
      declutterTree,
    ) {
      const zIndexContext = this.zIndexContext_;
      /** @type {Array<number>} */
      let pixelCoordinates;
      if (this.pixelCoordinates_ && equals$2(transform, this.renderedTransform_)) {
        pixelCoordinates = this.pixelCoordinates_;
      } else {
        if (!this.pixelCoordinates_) {
          this.pixelCoordinates_ = [];
        }
        pixelCoordinates = transform2D(
          this.coordinates,
          0,
          this.coordinates.length,
          2,
          transform,
          this.pixelCoordinates_,
        );
        setFromArray(this.renderedTransform_, transform);
      }
      let i = 0; // instruction index
      const ii = instructions.length; // end of instructions
      let d = 0; // data index
      let dd; // end of per-instruction data
      let anchorX,
        anchorY,
        /** @type {import('../../style/Style.js').DeclutterMode} */
        declutterMode,
        prevX,
        prevY,
        roundX,
        roundY,
        image,
        text,
        textKey,
        strokeKey,
        fillKey;
      let pendingFill = 0;
      let pendingStroke = 0;
      const coordinateCache = this.coordinateCache_;
      const viewRotation = this.viewRotation_;
      const viewRotationFromTransform =
        Math.round(Math.atan2(-transform[1], transform[0]) * 1e12) / 1e12;

      const state = /** @type {import("../../render.js").State} */ ({
        context: context,
        pixelRatio: this.pixelRatio,
        resolution: this.resolution,
        rotation: viewRotation,
      });

      // When the batch size gets too big, performance decreases. 200 is a good
      // balance between batch size and number of fill/stroke instructions.
      const batchSize =
        this.instructions != instructions || this.overlaps ? 0 : 200;
      let /** @type {import("../../Feature.js").FeatureLike} */ feature;
      let x, y, currentGeometry;
      while (i < ii) {
        const instruction = instructions[i];
        const type = /** @type {import("./Instruction.js").default} */ (
          instruction[0]
        );
        switch (type) {
          case Instruction.BEGIN_GEOMETRY:
            feature = /** @type {import("../../Feature.js").FeatureLike} */ (
              instruction[1]
            );
            currentGeometry = instruction[3];
            if (!feature.getGeometry()) {
              i = /** @type {number} */ (instruction[2]);
            } else if (
              hitExtent !== undefined &&
              !intersects$2(hitExtent, currentGeometry.getExtent())
            ) {
              i = /** @type {number} */ (instruction[2]) + 1;
            } else {
              ++i;
            }
            if (zIndexContext) {
              zIndexContext.zIndex = instruction[4];
            }
            break;
          case Instruction.BEGIN_PATH:
            if (pendingFill > batchSize) {
              this.fill_(context);
              pendingFill = 0;
            }
            if (pendingStroke > batchSize) {
              context.stroke();
              pendingStroke = 0;
            }
            if (!pendingFill && !pendingStroke) {
              context.beginPath();
              prevX = NaN;
              prevY = NaN;
            }
            ++i;
            break;
          case Instruction.CIRCLE:
            d = /** @type {number} */ (instruction[1]);
            const x1 = pixelCoordinates[d];
            const y1 = pixelCoordinates[d + 1];
            const x2 = pixelCoordinates[d + 2];
            const y2 = pixelCoordinates[d + 3];
            const dx = x2 - x1;
            const dy = y2 - y1;
            const r = Math.sqrt(dx * dx + dy * dy);
            context.moveTo(x1 + r, y1);
            context.arc(x1, y1, r, 0, 2 * Math.PI, true);
            ++i;
            break;
          case Instruction.CLOSE_PATH:
            context.closePath();
            ++i;
            break;
          case Instruction.CUSTOM:
            d = /** @type {number} */ (instruction[1]);
            dd = instruction[2];
            const geometry =
              /** @type {import("../../geom/SimpleGeometry.js").default} */ (
                instruction[3]
              );
            const renderer = instruction[4];
            const fn = instruction[5];
            state.geometry = geometry;
            state.feature = feature;
            if (!(i in coordinateCache)) {
              coordinateCache[i] = [];
            }
            const coords = coordinateCache[i];
            if (fn) {
              fn(pixelCoordinates, d, dd, 2, coords);
            } else {
              coords[0] = pixelCoordinates[d];
              coords[1] = pixelCoordinates[d + 1];
              coords.length = 2;
            }
            if (zIndexContext) {
              zIndexContext.zIndex = instruction[6];
            }
            renderer(coords, state);
            ++i;
            break;
          case Instruction.DRAW_IMAGE:
            d = /** @type {number} */ (instruction[1]);
            dd = /** @type {number} */ (instruction[2]);
            image =
              /** @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} */ (
                instruction[3]
              );

            // Remaining arguments in DRAW_IMAGE are in alphabetical order
            anchorX = /** @type {number} */ (instruction[4]);
            anchorY = /** @type {number} */ (instruction[5]);
            let height = /** @type {number} */ (instruction[6]);
            const opacity = /** @type {number} */ (instruction[7]);
            const originX = /** @type {number} */ (instruction[8]);
            const originY = /** @type {number} */ (instruction[9]);
            const rotateWithView = /** @type {boolean} */ (instruction[10]);
            let rotation = /** @type {number} */ (instruction[11]);
            const scale = /** @type {import("../../size.js").Size} */ (
              instruction[12]
            );
            let width = /** @type {number} */ (instruction[13]);
            declutterMode = instruction[14] || 'declutter';
            const declutterImageWithText =
              /** @type {{args: import("../canvas.js").DeclutterImageWithText, declutterMode: import('../../style/Style.js').DeclutterMode}} */ (
                instruction[15]
              );

            if (!image && instruction.length >= 20) {
              // create label images
              text = /** @type {string} */ (instruction[19]);
              textKey = /** @type {string} */ (instruction[20]);
              strokeKey = /** @type {string} */ (instruction[21]);
              fillKey = /** @type {string} */ (instruction[22]);
              const labelWithAnchor = this.drawLabelWithPointPlacement_(
                text,
                textKey,
                strokeKey,
                fillKey,
              );
              image = labelWithAnchor.label;
              instruction[3] = image;
              const textOffsetX = /** @type {number} */ (instruction[23]);
              anchorX = (labelWithAnchor.anchorX - textOffsetX) * this.pixelRatio;
              instruction[4] = anchorX;
              const textOffsetY = /** @type {number} */ (instruction[24]);
              anchorY = (labelWithAnchor.anchorY - textOffsetY) * this.pixelRatio;
              instruction[5] = anchorY;
              height = image.height;
              instruction[6] = height;
              width = image.width;
              instruction[13] = width;
            }

            let geometryWidths;
            if (instruction.length > 25) {
              geometryWidths = /** @type {number} */ (instruction[25]);
            }

            let padding, backgroundFillInstruction, backgroundStrokeInstruction;
            if (instruction.length > 17) {
              padding = /** @type {Array<number>} */ (instruction[16]);
              backgroundFillInstruction = /** @type {Array<*>} */ (
                instruction[17]
              );
              backgroundStrokeInstruction = /** @type {Array<*>} */ (
                instruction[18]
              );
            } else {
              padding = defaultPadding;
              backgroundFillInstruction = null;
              backgroundStrokeInstruction = null;
            }

            if (rotateWithView && viewRotationFromTransform) {
              // Canvas is expected to be rotated to reverse view rotation.
              rotation += viewRotation;
            } else if (!rotateWithView && !viewRotationFromTransform) {
              // Canvas is not rotated, images need to be rotated back to be north-up.
              rotation -= viewRotation;
            }
            let widthIndex = 0;
            for (; d < dd; d += 2) {
              if (
                geometryWidths &&
                geometryWidths[widthIndex++] < width / this.pixelRatio
              ) {
                continue;
              }
              const dimensions = this.calculateImageOrLabelDimensions_(
                image.width,
                image.height,
                pixelCoordinates[d],
                pixelCoordinates[d + 1],
                width,
                height,
                anchorX,
                anchorY,
                originX,
                originY,
                rotation,
                scale,
                snapToPixel,
                padding,
                !!backgroundFillInstruction || !!backgroundStrokeInstruction,
                feature,
              );
              /** @type {ReplayImageOrLabelArgs} */
              const args = [
                context,
                scaledCanvasSize,
                image,
                dimensions,
                opacity,
                backgroundFillInstruction,
                backgroundStrokeInstruction,
              ];
              if (declutterTree) {
                let imageArgs, imageDeclutterMode, imageDeclutterBox;
                if (declutterImageWithText) {
                  const index = dd - d;
                  if (!declutterImageWithText[index]) {
                    // We now have the image for an image+text combination.
                    declutterImageWithText[index] = {args, declutterMode};
                    // Don't render anything for now, wait for the text.
                    continue;
                  }
                  const imageDeclutter = declutterImageWithText[index];
                  imageArgs = imageDeclutter.args;
                  imageDeclutterMode = imageDeclutter.declutterMode;
                  delete declutterImageWithText[index];
                  imageDeclutterBox = getDeclutterBox(imageArgs);
                }
                // We now have image and text for an image+text combination.
                let renderImage, renderText;
                if (
                  imageArgs &&
                  (imageDeclutterMode !== 'declutter' ||
                    !declutterTree.collides(imageDeclutterBox))
                ) {
                  renderImage = true;
                }
                if (
                  declutterMode !== 'declutter' ||
                  !declutterTree.collides(dimensions.declutterBox)
                ) {
                  renderText = true;
                }
                if (
                  imageDeclutterMode === 'declutter' &&
                  declutterMode === 'declutter'
                ) {
                  const render = renderImage && renderText;
                  renderImage = render;
                  renderText = render;
                }
                if (renderImage) {
                  if (imageDeclutterMode !== 'none') {
                    declutterTree.insert(imageDeclutterBox);
                  }
                  this.replayImageOrLabel_.apply(this, imageArgs);
                }
                if (renderText) {
                  if (declutterMode !== 'none') {
                    declutterTree.insert(dimensions.declutterBox);
                  }
                  this.replayImageOrLabel_.apply(this, args);
                }
              } else {
                this.replayImageOrLabel_.apply(this, args);
              }
            }
            ++i;
            break;
          case Instruction.DRAW_CHARS:
            const begin = /** @type {number} */ (instruction[1]);
            const end = /** @type {number} */ (instruction[2]);
            const baseline = /** @type {number} */ (instruction[3]);
            const overflow = /** @type {number} */ (instruction[4]);
            fillKey = /** @type {string} */ (instruction[5]);
            const maxAngle = /** @type {number} */ (instruction[6]);
            const measurePixelRatio = /** @type {number} */ (instruction[7]);
            const offsetY = /** @type {number} */ (instruction[8]);
            strokeKey = /** @type {string} */ (instruction[9]);
            const strokeWidth = /** @type {number} */ (instruction[10]);
            text = /** @type {string|Array<string>} */ (instruction[11]);
            if (Array.isArray(text)) {
              //FIXME Add support for rich text along lines
              text = text.reduce(richTextToPlainText, '');
            }
            textKey = /** @type {string} */ (instruction[12]);
            const pixelRatioScale = [
              /** @type {number} */ (instruction[13]),
              /** @type {number} */ (instruction[13]),
            ];
            declutterMode = instruction[14] || 'declutter';

            const textKeepUpright = /** @type {boolean} */ (instruction[15]);
            const textState = this.textStates[textKey];
            const font = textState.font;
            const textScale = [
              textState.scale[0] * measurePixelRatio,
              textState.scale[1] * measurePixelRatio,
            ];

            let cachedWidths;
            if (font in this.widths_) {
              cachedWidths = this.widths_[font];
            } else {
              cachedWidths = {};
              this.widths_[font] = cachedWidths;
            }

            const pathLength = lineStringLength(pixelCoordinates, begin, end, 2);
            const textLength =
              Math.abs(textScale[0]) *
              measureAndCacheTextWidth(font, text, cachedWidths);
            if (overflow || textLength <= pathLength) {
              const textAlign = this.textStates[textKey].textAlign;
              const startM =
                (pathLength - textLength) * horizontalTextAlign(text, textAlign);
              const parts = drawTextOnPath(
                pixelCoordinates,
                begin,
                end,
                2,
                text,
                startM,
                maxAngle,
                Math.abs(textScale[0]),
                measureAndCacheTextWidth,
                font,
                cachedWidths,
                viewRotationFromTransform ? 0 : this.viewRotation_,
                textKeepUpright,
              );
              drawChars: if (parts) {
                /** @type {Array<ReplayImageOrLabelArgs>} */
                const replayImageOrLabelArgs = [];
                let c, cc, chars, label, part;
                if (strokeKey) {
                  for (c = 0, cc = parts.length; c < cc; ++c) {
                    part = parts[c]; // x, y, anchorX, rotation, chunk
                    chars = /** @type {string} */ (part[4]);
                    label = this.createLabel(chars, textKey, '', strokeKey);
                    anchorX =
                      /** @type {number} */ (part[2]) +
                      (textScale[0] < 0 ? -strokeWidth : strokeWidth);
                    anchorY =
                      baseline * label.height +
                      ((0.5 - baseline) * 2 * strokeWidth * textScale[1]) /
                        textScale[0] -
                      offsetY;
                    const dimensions = this.calculateImageOrLabelDimensions_(
                      label.width,
                      label.height,
                      part[0],
                      part[1],
                      label.width,
                      label.height,
                      anchorX,
                      anchorY,
                      0,
                      0,
                      part[3],
                      pixelRatioScale,
                      false,
                      defaultPadding,
                      false,
                      feature,
                    );
                    if (
                      declutterTree &&
                      declutterMode === 'declutter' &&
                      declutterTree.collides(dimensions.declutterBox)
                    ) {
                      break drawChars;
                    }
                    replayImageOrLabelArgs.push([
                      context,
                      scaledCanvasSize,
                      label,
                      dimensions,
                      1,
                      null,
                      null,
                    ]);
                  }
                }
                if (fillKey) {
                  for (c = 0, cc = parts.length; c < cc; ++c) {
                    part = parts[c]; // x, y, anchorX, rotation, chunk
                    chars = /** @type {string} */ (part[4]);
                    label = this.createLabel(chars, textKey, fillKey, '');
                    anchorX = /** @type {number} */ (part[2]);
                    anchorY = baseline * label.height - offsetY;
                    const dimensions = this.calculateImageOrLabelDimensions_(
                      label.width,
                      label.height,
                      part[0],
                      part[1],
                      label.width,
                      label.height,
                      anchorX,
                      anchorY,
                      0,
                      0,
                      part[3],
                      pixelRatioScale,
                      false,
                      defaultPadding,
                      false,
                      feature,
                    );
                    if (
                      declutterTree &&
                      declutterMode === 'declutter' &&
                      declutterTree.collides(dimensions.declutterBox)
                    ) {
                      break drawChars;
                    }
                    replayImageOrLabelArgs.push([
                      context,
                      scaledCanvasSize,
                      label,
                      dimensions,
                      1,
                      null,
                      null,
                    ]);
                  }
                }
                if (declutterTree && declutterMode !== 'none') {
                  declutterTree.load(replayImageOrLabelArgs.map(getDeclutterBox));
                }
                for (let i = 0, ii = replayImageOrLabelArgs.length; i < ii; ++i) {
                  this.replayImageOrLabel_.apply(this, replayImageOrLabelArgs[i]);
                }
              }
            }
            ++i;
            break;
          case Instruction.END_GEOMETRY:
            if (featureCallback !== undefined) {
              feature = /** @type {import("../../Feature.js").FeatureLike} */ (
                instruction[1]
              );
              const result = featureCallback(
                feature,
                currentGeometry,
                declutterMode,
              );
              if (result) {
                return result;
              }
            }
            ++i;
            break;
          case Instruction.FILL:
            if (batchSize) {
              pendingFill++;
            } else {
              this.fill_(context);
            }
            ++i;
            break;
          case Instruction.MOVE_TO_LINE_TO:
            d = /** @type {number} */ (instruction[1]);
            dd = /** @type {number} */ (instruction[2]);
            x = pixelCoordinates[d];
            y = pixelCoordinates[d + 1];
            context.moveTo(x, y);
            prevX = (x + 0.5) | 0;
            prevY = (y + 0.5) | 0;
            for (d += 2; d < dd; d += 2) {
              x = pixelCoordinates[d];
              y = pixelCoordinates[d + 1];
              roundX = (x + 0.5) | 0;
              roundY = (y + 0.5) | 0;
              if (d == dd - 2 || roundX !== prevX || roundY !== prevY) {
                context.lineTo(x, y);
                prevX = roundX;
                prevY = roundY;
              }
            }
            ++i;
            break;
          case Instruction.SET_FILL_STYLE:
            this.alignAndScaleFill_ = instruction[2];

            if (pendingFill) {
              this.fill_(context);
              pendingFill = 0;
              if (pendingStroke) {
                context.stroke();
                pendingStroke = 0;
              }
            }

            /** @type {import("../../colorlike.js").ColorLike} */
            context.fillStyle = instruction[1];
            ++i;
            break;
          case Instruction.SET_STROKE_STYLE:
            if (pendingStroke) {
              context.stroke();
              pendingStroke = 0;
            }
            this.setStrokeStyle_(context, /** @type {Array<*>} */ (instruction));
            ++i;
            break;
          case Instruction.STROKE:
            if (batchSize) {
              pendingStroke++;
            } else {
              context.stroke();
            }
            ++i;
            break;
          default: // consume the instruction anyway, to avoid an infinite loop
            ++i;
            break;
        }
      }
      if (pendingFill) {
        this.fill_(context);
      }
      if (pendingStroke) {
        context.stroke();
      }
      return undefined;
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import('../../size.js').Size} scaledCanvasSize Scaled canvas size.
     * @param {import("../../transform.js").Transform} transform Transform.
     * @param {number} viewRotation View rotation.
     * @param {boolean} snapToPixel Snap point symbols and text to integer pixels.
     * @param {import("rbush").default<DeclutterEntry>} [declutterTree] Declutter tree.
     */
    execute(
      context,
      scaledCanvasSize,
      transform,
      viewRotation,
      snapToPixel,
      declutterTree,
    ) {
      this.viewRotation_ = viewRotation;
      this.execute_(
        context,
        scaledCanvasSize,
        transform,
        this.instructions,
        snapToPixel,
        undefined,
        undefined,
        declutterTree,
      );
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../transform.js").Transform} transform Transform.
     * @param {number} viewRotation View rotation.
     * @param {FeatureCallback<T>} [featureCallback] Feature callback.
     * @param {import("../../extent.js").Extent} [hitExtent] Only check
     *     features that intersect this extent.
     * @return {T|undefined} Callback result.
     * @template T
     */
    executeHitDetection(
      context,
      transform,
      viewRotation,
      featureCallback,
      hitExtent,
    ) {
      this.viewRotation_ = viewRotation;
      return this.execute_(
        context,
        [context.canvas.width, context.canvas.height],
        transform,
        this.hitDetectionInstructions,
        true,
        featureCallback,
        hitExtent,
      );
    }
  }

  /**
   * @module ol/render/canvas/ExecutorGroup
   */


  /**
   * @const
   * @type {Array<import("../canvas.js").BuilderType>}
   */
  const ALL = [
    'Polygon',
    'Circle',
    'LineString',
    'Image',
    'Text',
    'Default',
  ];

  /**
   * @const
   * @type {Array<import("../canvas.js").BuilderType>}
   */
  const DECLUTTER = ['Image', 'Text'];

  /**
   * @const
   * @type {Array<import("../canvas.js").BuilderType>}
   */
  const NON_DECLUTTER = ALL.filter(
    (builderType) => !DECLUTTER.includes(builderType),
  );

  class ExecutorGroup {
    /**
     * @param {import("../../extent.js").Extent} maxExtent Max extent for clipping. When a
     * `maxExtent` was set on the Builder for this executor group, the same `maxExtent`
     * should be set here, unless the target context does not exceed that extent (which
     * can be the case when rendering to tiles).
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {boolean} overlaps The executor group can have overlapping geometries.
     * @param {!Object<string, !Object<import("../canvas.js").BuilderType, import("../canvas.js").SerializableInstructions>>} allInstructions
     * The serializable instructions.
     * @param {number} [renderBuffer] Optional rendering buffer.
     * @param {boolean} [deferredRendering] Enable deferred rendering with renderDeferred().
     */
    constructor(
      maxExtent,
      resolution,
      pixelRatio,
      overlaps,
      allInstructions,
      renderBuffer,
      deferredRendering,
    ) {
      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.maxExtent_ = maxExtent;

      /**
       * @private
       * @type {boolean}
       */
      this.overlaps_ = overlaps;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = pixelRatio;

      /**
       * @private
       * @type {number}
       */
      this.resolution_ = resolution;

      /**
       * @private
       * @type {number|undefined}
       */
      this.renderBuffer_ = renderBuffer;

      /**
       * @private
       * @type {!Object<string, !Object<string, import("./Executor").default>>}
       */
      this.executorsByZIndex_ = {};

      /**
       * @private
       * @type {CanvasRenderingContext2D}
       */
      this.hitDetectionContext_ = null;

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.hitDetectionTransform_ = create$3();

      /**
       * @private
       * @type {CanvasRenderingContext2D}
       */
      this.renderedContext_ = null;

      /**
       * @private
       * @type {Object<number, Array<import("./ZIndexContext.js").default>>}
       */
      this.deferredZIndexContexts_ = {};

      this.createExecutors_(allInstructions, deferredRendering);
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../transform.js").Transform} transform Transform.
     */
    clip(context, transform) {
      const flatClipCoords = this.getClipCoords(transform);
      context.beginPath();
      context.moveTo(flatClipCoords[0], flatClipCoords[1]);
      context.lineTo(flatClipCoords[2], flatClipCoords[3]);
      context.lineTo(flatClipCoords[4], flatClipCoords[5]);
      context.lineTo(flatClipCoords[6], flatClipCoords[7]);
      context.clip();
    }

    /**
     * Create executors and populate them using the provided instructions.
     * @private
     * @param {!Object<string, !Object<string, import("../canvas.js").SerializableInstructions>>} allInstructions The serializable instructions
     * @param {boolean} deferredRendering Enable deferred rendering.
     */
    createExecutors_(allInstructions, deferredRendering) {
      for (const zIndex in allInstructions) {
        let executors = this.executorsByZIndex_[zIndex];
        if (executors === undefined) {
          executors = {};
          this.executorsByZIndex_[zIndex] = executors;
        }
        const instructionByZindex = allInstructions[zIndex];
        for (const builderType in instructionByZindex) {
          const instructions = instructionByZindex[builderType];
          executors[builderType] = new Executor(
            this.resolution_,
            this.pixelRatio_,
            this.overlaps_,
            instructions,
            deferredRendering,
          );
        }
      }
    }

    /**
     * @param {Array<import("../canvas.js").BuilderType>} executors Executors.
     * @return {boolean} Has executors of the provided types.
     */
    hasExecutors(executors) {
      for (const zIndex in this.executorsByZIndex_) {
        const candidates = this.executorsByZIndex_[zIndex];
        for (let i = 0, ii = executors.length; i < ii; ++i) {
          if (executors[i] in candidates) {
            return true;
          }
        }
      }
      return false;
    }

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} resolution Resolution.
     * @param {number} rotation Rotation.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {function(import("../../Feature.js").FeatureLike, import("../../geom/SimpleGeometry.js").default, number): T} callback Feature callback.
     * @param {Array<import("../../Feature.js").FeatureLike>} declutteredFeatures Decluttered features.
     * @return {T|undefined} Callback result.
     * @template T
     */
    forEachFeatureAtCoordinate(
      coordinate,
      resolution,
      rotation,
      hitTolerance,
      callback,
      declutteredFeatures,
    ) {
      hitTolerance = Math.round(hitTolerance);
      const contextSize = hitTolerance * 2 + 1;
      const transform = compose(
        this.hitDetectionTransform_,
        hitTolerance + 0.5,
        hitTolerance + 0.5,
        1 / resolution,
        -1 / resolution,
        -rotation,
        -coordinate[0],
        -coordinate[1],
      );

      const newContext = !this.hitDetectionContext_;
      if (newContext) {
        // Refrain from adding a 'willReadFrequently' hint in the options here.
        // While it will remove the "Canvas2D: Multiple readback operations using
        // getImageData are faster with the willReadFrequently attribute set
        // to true" warnings in the console, it makes hitDetection extremely
        // slow in Chrome when there are many features on the map
        this.hitDetectionContext_ = createCanvasContext2D(
          contextSize,
          contextSize,
        );
      }
      const context = this.hitDetectionContext_;

      if (
        context.canvas.width !== contextSize ||
        context.canvas.height !== contextSize
      ) {
        context.canvas.width = contextSize;
        context.canvas.height = contextSize;
      } else if (!newContext) {
        context.clearRect(0, 0, contextSize, contextSize);
      }

      /** @type {import("../../extent.js").Extent|undefined} */
      let hitExtent;
      if (this.renderBuffer_ !== undefined) {
        hitExtent = createEmpty();
        extendCoordinate(hitExtent, coordinate);
        buffer$1(
          hitExtent,
          resolution * (this.renderBuffer_ + hitTolerance),
          hitExtent,
        );
      }

      const indexes = getPixelIndexArray(hitTolerance);

      /** @type {import("../canvas.js").BuilderType} */
      let builderType;

      /**
       * @param {import("../../Feature.js").FeatureLike} feature Feature.
       * @param {import("../../geom/SimpleGeometry.js").default} geometry Geometry.
       * @param {import('../../style/Style.js').DeclutterMode} declutterMode Declutter mode.
       * @return {T|undefined} Callback result.
       */
      function featureCallback(feature, geometry, declutterMode) {
        const imageData = context.getImageData(
          0,
          0,
          contextSize,
          contextSize,
        ).data;
        for (let i = 0, ii = indexes.length; i < ii; i++) {
          if (imageData[indexes[i]] > 0) {
            if (
              !declutteredFeatures ||
              declutterMode === 'none' ||
              (builderType !== 'Image' && builderType !== 'Text') ||
              declutteredFeatures.includes(feature)
            ) {
              const idx = (indexes[i] - 3) / 4;
              const x = hitTolerance - (idx % contextSize);
              const y = hitTolerance - ((idx / contextSize) | 0);
              const result = callback(feature, geometry, x * x + y * y);
              if (result) {
                return result;
              }
            }
            context.clearRect(0, 0, contextSize, contextSize);
            break;
          }
        }
        return undefined;
      }

      /** @type {Array<number>} */
      const zs = Object.keys(this.executorsByZIndex_).map(Number);
      zs.sort(ascending);

      let i, j, executors, executor, result;
      for (i = zs.length - 1; i >= 0; --i) {
        const zIndexKey = zs[i].toString();
        executors = this.executorsByZIndex_[zIndexKey];
        for (j = ALL.length - 1; j >= 0; --j) {
          builderType = ALL[j];
          executor = executors[builderType];
          if (executor !== undefined) {
            result = executor.executeHitDetection(
              context,
              transform,
              rotation,
              featureCallback,
              hitExtent,
            );
            if (result) {
              return result;
            }
          }
        }
      }
      return undefined;
    }

    /**
     * @param {import("../../transform.js").Transform} transform Transform.
     * @return {Array<number>|null} Clip coordinates.
     */
    getClipCoords(transform) {
      const maxExtent = this.maxExtent_;
      if (!maxExtent) {
        return null;
      }
      const minX = maxExtent[0];
      const minY = maxExtent[1];
      const maxX = maxExtent[2];
      const maxY = maxExtent[3];
      const flatClipCoords = [minX, minY, minX, maxY, maxX, maxY, maxX, minY];
      transform2D(flatClipCoords, 0, 8, 2, transform, flatClipCoords);
      return flatClipCoords;
    }

    /**
     * @return {boolean} Is empty.
     */
    isEmpty() {
      return isEmpty$1(this.executorsByZIndex_);
    }

    /**
     * @param {CanvasRenderingContext2D} targetContext Context.
     * @param {import('../../size.js').Size} scaledCanvasSize Scale of the context.
     * @param {import("../../transform.js").Transform} transform Transform.
     * @param {number} viewRotation View rotation.
     * @param {boolean} snapToPixel Snap point symbols and test to integer pixel.
     * @param {Array<import("../canvas.js").BuilderType>} [builderTypes] Ordered replay types to replay.
     *     Default is {@link module:ol/render/replay~ALL}
     * @param {import("rbush").default<import('./Executor.js').DeclutterEntry>|null} [declutterTree] Declutter tree.
     *     When set to null, no decluttering is done, even when the executor group has a `ZIndexContext`.
     */
    execute(
      targetContext,
      scaledCanvasSize,
      transform,
      viewRotation,
      snapToPixel,
      builderTypes,
      declutterTree,
    ) {
      const zs = Object.keys(this.executorsByZIndex_).map(Number);
      zs.sort(declutterTree ? descending : ascending);

      builderTypes = builderTypes ? builderTypes : ALL;
      const maxBuilderTypes = ALL.length;
      for (let i = 0, ii = zs.length; i < ii; ++i) {
        const zIndexKey = zs[i].toString();
        const replays = this.executorsByZIndex_[zIndexKey];
        for (let j = 0, jj = builderTypes.length; j < jj; ++j) {
          const builderType = builderTypes[j];
          const replay = replays[builderType];
          if (replay !== undefined) {
            const zIndexContext =
              declutterTree === null ? undefined : replay.getZIndexContext();
            const context = zIndexContext
              ? zIndexContext.getContext()
              : targetContext;
            const requireClip =
              this.maxExtent_ &&
              builderType !== 'Image' &&
              builderType !== 'Text';
            if (requireClip) {
              context.save();
              // setup clipping so that the parts of over-simplified geometries are not
              // visible outside the current extent when panning
              this.clip(context, transform);
            }
            if (
              !zIndexContext ||
              builderType === 'Text' ||
              builderType === 'Image'
            ) {
              replay.execute(
                context,
                scaledCanvasSize,
                transform,
                viewRotation,
                snapToPixel,
                declutterTree,
              );
            } else {
              zIndexContext.pushFunction((context) =>
                replay.execute(
                  context,
                  scaledCanvasSize,
                  transform,
                  viewRotation,
                  snapToPixel,
                  declutterTree,
                ),
              );
            }
            if (requireClip) {
              context.restore();
            }
            if (zIndexContext) {
              zIndexContext.offset();
              const index = zs[i] * maxBuilderTypes + ALL.indexOf(builderType);
              if (!this.deferredZIndexContexts_[index]) {
                this.deferredZIndexContexts_[index] = [];
              }
              this.deferredZIndexContexts_[index].push(zIndexContext);
            }
          }
        }
      }

      this.renderedContext_ = targetContext;
    }

    getDeferredZIndexContexts() {
      return this.deferredZIndexContexts_;
    }

    getRenderedContext() {
      return this.renderedContext_;
    }

    renderDeferred() {
      const deferredZIndexContexts = this.deferredZIndexContexts_;
      const zs = Object.keys(deferredZIndexContexts).map(Number).sort(ascending);
      for (let i = 0, ii = zs.length; i < ii; ++i) {
        deferredZIndexContexts[zs[i]].forEach((zIndexContext) => {
          zIndexContext.draw(this.renderedContext_); // FIXME Pass clip to replay for temporarily enabling clip
          zIndexContext.clear();
        });
        deferredZIndexContexts[zs[i]].length = 0;
      }
    }
  }

  /**
   * This cache is used to store arrays of indexes for calculated pixel circles
   * to increase performance.
   * It is a static property to allow each Replaygroup to access it.
   * @type {Object<number, Array<number>>}
   */
  const circlePixelIndexArrayCache = {};

  /**
   * This methods creates an array with indexes of all pixels within a circle,
   * ordered by how close they are to the center.
   * A cache is used to increase performance.
   * @param {number} radius Radius.
   * @return {Array<number>} An array with indexes within a circle.
   */
  function getPixelIndexArray(radius) {
    if (circlePixelIndexArrayCache[radius] !== undefined) {
      return circlePixelIndexArrayCache[radius];
    }

    const size = radius * 2 + 1;
    const maxDistanceSq = radius * radius;
    const distances = new Array(maxDistanceSq + 1);
    for (let i = 0; i <= radius; ++i) {
      for (let j = 0; j <= radius; ++j) {
        const distanceSq = i * i + j * j;
        if (distanceSq > maxDistanceSq) {
          break;
        }
        let distance = distances[distanceSq];
        if (!distance) {
          distance = [];
          distances[distanceSq] = distance;
        }
        distance.push(((radius + i) * size + (radius + j)) * 4 + 3);
        if (i > 0) {
          distance.push(((radius - i) * size + (radius + j)) * 4 + 3);
        }
        if (j > 0) {
          distance.push(((radius + i) * size + (radius - j)) * 4 + 3);
          if (i > 0) {
            distance.push(((radius - i) * size + (radius - j)) * 4 + 3);
          }
        }
      }
    }

    const pixelIndex = [];
    for (let i = 0, ii = distances.length; i < ii; ++i) {
      if (distances[i]) {
        pixelIndex.push(...distances[i]);
      }
    }

    circlePixelIndexArrayCache[radius] = pixelIndex;
    return pixelIndex;
  }

  /**
   * @module ol/style/Icon
   */

  /**
   * @typedef {'fraction' | 'pixels'} IconAnchorUnits
   * Anchor unit can be either a fraction of the icon size or in pixels.
   */

  /**
   * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} IconOrigin
   * Icon origin. One of 'bottom-left', 'bottom-right', 'top-left', 'top-right'.
   */

  /**
   * @typedef {Object} Options
   * @property {Array<number>} [anchor=[0.5, 0.5]] Anchor. Default value is the icon center.
   * @property {IconOrigin} [anchorOrigin='top-left'] Origin of the anchor: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`.
   * @property {IconAnchorUnits} [anchorXUnits='fraction'] Units in which the anchor x value is
   * specified. A value of `'fraction'` indicates the x value is a fraction of the icon. A value of `'pixels'` indicates
   * the x value in pixels.
   * @property {IconAnchorUnits} [anchorYUnits='fraction'] Units in which the anchor y value is
   * specified. A value of `'fraction'` indicates the y value is a fraction of the icon. A value of `'pixels'` indicates
   * the y value in pixels.
   * @property {import("../color.js").Color|string} [color] Color to tint the icon. If not specified,
   * the icon will be left as is.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that you must provide a
   * `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {HTMLImageElement|HTMLCanvasElement|ImageBitmap} [img] Image object for the icon.
   * @property {Array<number>} [displacement=[0, 0]] Displacement of the icon in pixels.
   * Positive values will shift the icon right and up.
   * @property {number} [opacity=1] Opacity of the icon.
   * @property {number} [width] The width of the icon in pixels. This can't be used together with `scale`.
   * @property {number} [height] The height of the icon in pixels. This can't be used together with `scale`.
   * @property {number|import("../size.js").Size} [scale=1] Scale.
   * @property {boolean} [rotateWithView=false] Whether to rotate the icon with the view.
   * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {Array<number>} [offset=[0, 0]] Offset which, together with `size` and `offsetOrigin`, defines the
   * sub-rectangle to use from the original (sprite) image.
   * @property {IconOrigin} [offsetOrigin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`.
   * @property {import("../size.js").Size} [size] Icon size in pixels. Used together with `offset` to define the
   * sub-rectangle to use from the original (sprite) image.
   * @property {string} [src] Image source URI.
   * @property {import("./Style.js").DeclutterMode} [declutterMode] Declutter mode.
   */

  /**
   * @param {number} width The width.
   * @param {number} height The height.
   * @param {number|undefined} wantedWidth The wanted width.
   * @param {number|undefined} wantedHeight The wanted height.
   * @return {number|Array<number>} The scale.
   */
  function calculateScale(width, height, wantedWidth, wantedHeight) {
    if (wantedWidth !== undefined && wantedHeight !== undefined) {
      return [wantedWidth / width, wantedHeight / height];
    }
    if (wantedWidth !== undefined) {
      return wantedWidth / width;
    }
    if (wantedHeight !== undefined) {
      return wantedHeight / height;
    }
    return 1;
  }

  /**
   * @classdesc
   * Set icon style for vector features.
   * @api
   */
  class Icon extends ImageStyle {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @type {number}
       */
      const opacity = options.opacity !== undefined ? options.opacity : 1;

      /**
       * @type {number}
       */
      const rotation = options.rotation !== undefined ? options.rotation : 0;

      /**
       * @type {number|import("../size.js").Size}
       */
      const scale = options.scale !== undefined ? options.scale : 1;

      /**
       * @type {boolean}
       */
      const rotateWithView =
        options.rotateWithView !== undefined ? options.rotateWithView : false;

      super({
        opacity: opacity,
        rotation: rotation,
        scale: scale,
        displacement:
          options.displacement !== undefined ? options.displacement : [0, 0],
        rotateWithView: rotateWithView,
        declutterMode: options.declutterMode,
      });

      /**
       * @private
       * @type {Array<number>}
       */
      this.anchor_ = options.anchor !== undefined ? options.anchor : [0.5, 0.5];

      /**
       * @private
       * @type {Array<number>}
       */
      this.normalizedAnchor_ = null;

      /**
       * @private
       * @type {IconOrigin}
       */
      this.anchorOrigin_ =
        options.anchorOrigin !== undefined ? options.anchorOrigin : 'top-left';

      /**
       * @private
       * @type {IconAnchorUnits}
       */
      this.anchorXUnits_ =
        options.anchorXUnits !== undefined ? options.anchorXUnits : 'fraction';

      /**
       * @private
       * @type {IconAnchorUnits}
       */
      this.anchorYUnits_ =
        options.anchorYUnits !== undefined ? options.anchorYUnits : 'fraction';

      /**
       * @private
       * @type {?string}
       */
      this.crossOrigin_ =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      const image = options.img !== undefined ? options.img : null;

      let cacheKey = options.src;

      assert(
        !(cacheKey !== undefined && image),
        '`image` and `src` cannot be provided at the same time',
      );

      if ((cacheKey === undefined || cacheKey.length === 0) && image) {
        cacheKey = /** @type {HTMLImageElement} */ (image).src || getUid(image);
      }
      assert(
        cacheKey !== undefined && cacheKey.length > 0,
        'A defined and non-empty `src` or `image` must be provided',
      );

      assert(
        !(
          (options.width !== undefined || options.height !== undefined) &&
          options.scale !== undefined
        ),
        '`width` or `height` cannot be provided together with `scale`',
      );

      let imageState;
      if (options.src !== undefined) {
        imageState = ImageState.IDLE;
      } else if (image !== undefined) {
        if ('complete' in image) {
          if (image.complete) {
            imageState = image.src ? ImageState.LOADED : ImageState.IDLE;
          } else {
            imageState = ImageState.LOADING;
          }
        } else {
          imageState = ImageState.LOADED;
        }
      }

      /**
       * @private
       * @type {import("../color.js").Color}
       */
      this.color_ = options.color !== undefined ? asArray(options.color) : null;

      /**
       * @private
       * @type {import("./IconImage.js").default}
       */
      this.iconImage_ = get$1(
        image,
        /** @type {string} */ (cacheKey),
        this.crossOrigin_,
        imageState,
        this.color_,
      );

      /**
       * @private
       * @type {Array<number>}
       */
      this.offset_ = options.offset !== undefined ? options.offset : [0, 0];
      /**
       * @private
       * @type {IconOrigin}
       */
      this.offsetOrigin_ =
        options.offsetOrigin !== undefined ? options.offsetOrigin : 'top-left';

      /**
       * @private
       * @type {Array<number>}
       */
      this.origin_ = null;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.size_ = options.size !== undefined ? options.size : null;

      /**
       * @private
       */
      this.initialOptions_;

      /**
       * Calculate the scale if width or height were given.
       */
      if (options.width !== undefined || options.height !== undefined) {
        let width, height;
        if (options.size) {
          [width, height] = options.size;
        } else {
          const image = this.getImage(1);
          if (image.width && image.height) {
            width = image.width;
            height = image.height;
          } else if (image instanceof HTMLImageElement) {
            this.initialOptions_ = options;
            const onload = () => {
              this.unlistenImageChange(onload);
              if (!this.initialOptions_) {
                return;
              }
              const imageSize = this.iconImage_.getSize();
              this.setScale(
                calculateScale(
                  imageSize[0],
                  imageSize[1],
                  options.width,
                  options.height,
                ),
              );
            };
            this.listenImageChange(onload);
            return;
          }
        }
        if (width !== undefined) {
          this.setScale(
            calculateScale(width, height, options.width, options.height),
          );
        }
      }
    }

    /**
     * Clones the style. The underlying Image/HTMLCanvasElement is not cloned.
     * @return {Icon} The cloned style.
     * @api
     * @override
     */
    clone() {
      let scale, width, height;
      if (this.initialOptions_) {
        width = this.initialOptions_.width;
        height = this.initialOptions_.height;
      } else {
        scale = this.getScale();
        scale = Array.isArray(scale) ? scale.slice() : scale;
      }
      return new Icon({
        anchor: this.anchor_.slice(),
        anchorOrigin: this.anchorOrigin_,
        anchorXUnits: this.anchorXUnits_,
        anchorYUnits: this.anchorYUnits_,
        color:
          this.color_ && this.color_.slice
            ? this.color_.slice()
            : this.color_ || undefined,
        crossOrigin: this.crossOrigin_,
        offset: this.offset_.slice(),
        offsetOrigin: this.offsetOrigin_,
        opacity: this.getOpacity(),
        rotateWithView: this.getRotateWithView(),
        rotation: this.getRotation(),
        scale,
        width,
        height,
        size: this.size_ !== null ? this.size_.slice() : undefined,
        src: this.getSrc(),
        displacement: this.getDisplacement().slice(),
        declutterMode: this.getDeclutterMode(),
      });
    }

    /**
     * Get the anchor point in pixels. The anchor determines the center point for the
     * symbolizer.
     * @return {Array<number>} Anchor.
     * @api
     * @override
     */
    getAnchor() {
      let anchor = this.normalizedAnchor_;
      if (!anchor) {
        anchor = this.anchor_;
        const size = this.getSize();
        if (
          this.anchorXUnits_ == 'fraction' ||
          this.anchorYUnits_ == 'fraction'
        ) {
          if (!size) {
            return null;
          }
          anchor = this.anchor_.slice();
          if (this.anchorXUnits_ == 'fraction') {
            anchor[0] *= size[0];
          }
          if (this.anchorYUnits_ == 'fraction') {
            anchor[1] *= size[1];
          }
        }

        if (this.anchorOrigin_ != 'top-left') {
          if (!size) {
            return null;
          }
          if (anchor === this.anchor_) {
            anchor = this.anchor_.slice();
          }
          if (
            this.anchorOrigin_ == 'top-right' ||
            this.anchorOrigin_ == 'bottom-right'
          ) {
            anchor[0] = -anchor[0] + size[0];
          }
          if (
            this.anchorOrigin_ == 'bottom-left' ||
            this.anchorOrigin_ == 'bottom-right'
          ) {
            anchor[1] = -anchor[1] + size[1];
          }
        }
        this.normalizedAnchor_ = anchor;
      }
      const displacement = this.getDisplacement();
      const scale = this.getScaleArray();
      // anchor is scaled by renderer but displacement should not be scaled
      // so divide by scale here
      return [
        anchor[0] - displacement[0] / scale[0],
        anchor[1] + displacement[1] / scale[1],
      ];
    }

    /**
     * Set the anchor point. The anchor determines the center point for the
     * symbolizer.
     *
     * @param {Array<number>} anchor Anchor.
     * @api
     */
    setAnchor(anchor) {
      this.anchor_ = anchor;
      this.normalizedAnchor_ = null;
    }

    /**
     * Get the icon color.
     * @return {import("../color.js").Color} Color.
     * @api
     */
    getColor() {
      return this.color_;
    }

    /**
     * Get the image icon.
     * @param {number} pixelRatio Pixel ratio.
     * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image or Canvas element. If the Icon
     * style was configured with `src` or with a not let loaded `img`, an `ImageBitmap` will be returned.
     * @api
     * @override
     */
    getImage(pixelRatio) {
      return this.iconImage_.getImage(pixelRatio);
    }

    /**
     * Get the pixel ratio.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} The pixel ratio of the image.
     * @api
     * @override
     */
    getPixelRatio(pixelRatio) {
      return this.iconImage_.getPixelRatio(pixelRatio);
    }

    /**
     * @return {import("../size.js").Size} Image size.
     * @override
     */
    getImageSize() {
      return this.iconImage_.getSize();
    }

    /**
     * @return {import("../ImageState.js").default} Image state.
     * @override
     */
    getImageState() {
      return this.iconImage_.getImageState();
    }

    /**
     * @return {HTMLImageElement|HTMLCanvasElement|ImageBitmap} Image element.
     * @override
     */
    getHitDetectionImage() {
      return this.iconImage_.getHitDetectionImage();
    }

    /**
     * Get the origin of the symbolizer.
     * @return {Array<number>} Origin.
     * @api
     * @override
     */
    getOrigin() {
      if (this.origin_) {
        return this.origin_;
      }
      let offset = this.offset_;

      if (this.offsetOrigin_ != 'top-left') {
        const size = this.getSize();
        const iconImageSize = this.iconImage_.getSize();
        if (!size || !iconImageSize) {
          return null;
        }
        offset = offset.slice();
        if (
          this.offsetOrigin_ == 'top-right' ||
          this.offsetOrigin_ == 'bottom-right'
        ) {
          offset[0] = iconImageSize[0] - size[0] - offset[0];
        }
        if (
          this.offsetOrigin_ == 'bottom-left' ||
          this.offsetOrigin_ == 'bottom-right'
        ) {
          offset[1] = iconImageSize[1] - size[1] - offset[1];
        }
      }
      this.origin_ = offset;
      return this.origin_;
    }

    /**
     * Get the image URL.
     * @return {string|undefined} Image src.
     * @api
     */
    getSrc() {
      return this.iconImage_.getSrc();
    }

    /**
     * Get the size of the icon (in pixels).
     * @return {import("../size.js").Size} Image size.
     * @api
     * @override
     */
    getSize() {
      return !this.size_ ? this.iconImage_.getSize() : this.size_;
    }

    /**
     * Get the width of the icon (in pixels). Will return undefined when the icon image is not yet loaded.
     * @return {number} Icon width (in pixels).
     * @api
     */
    getWidth() {
      const scale = this.getScaleArray();
      if (this.size_) {
        return this.size_[0] * scale[0];
      }
      if (this.iconImage_.getImageState() == ImageState.LOADED) {
        return this.iconImage_.getSize()[0] * scale[0];
      }
      return undefined;
    }

    /**
     * Get the height of the icon (in pixels). Will return undefined when the icon image is not yet loaded.
     * @return {number} Icon height (in pixels).
     * @api
     */
    getHeight() {
      const scale = this.getScaleArray();
      if (this.size_) {
        return this.size_[1] * scale[1];
      }
      if (this.iconImage_.getImageState() == ImageState.LOADED) {
        return this.iconImage_.getSize()[1] * scale[1];
      }
      return undefined;
    }

    /**
     * Set the scale.
     *
     * @param {number|import("../size.js").Size} scale Scale.
     * @api
     * @override
     */
    setScale(scale) {
      delete this.initialOptions_;
      super.setScale(scale);
    }

    /**
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     * @override
     */
    listenImageChange(listener) {
      this.iconImage_.addEventListener(EventType.CHANGE, listener);
    }

    /**
     * Load not yet loaded URI.
     * When rendering a feature with an icon style, the vector renderer will
     * automatically call this method. However, you might want to call this
     * method yourself for preloading or other purposes.
     * @api
     * @override
     */
    load() {
      this.iconImage_.load();
    }

    /**
     * @param {function(import("../events/Event.js").default): void} listener Listener function.
     * @override
     */
    unlistenImageChange(listener) {
      this.iconImage_.removeEventListener(EventType.CHANGE, listener);
    }

    /**
     * @override
     */
    ready() {
      return this.iconImage_.ready();
    }
  }

  /**
   * @module ol/style
   */

  var style0 = {
    __proto__: null,
    Circle: CircleStyle,
    Fill: Fill,
    Icon: Icon,
    IconImage: IconImage,
    Image: ImageStyle,
    RegularShape: RegularShape,
    Stroke: Stroke,
    Style: Style,
    Text: Text
  };

  /**
   * @module ol/render/canvas/hitdetect
   */


  const HIT_DETECT_RESOLUTION = 0.5;

  /**
   * @param {import("../../size.js").Size} size Canvas size in css pixels.
   * @param {Array<import("../../transform.js").Transform>} transforms Transforms
   * for rendering features to all worlds of the viewport, from coordinates to css
   * pixels.
   * @param {Array<import("../../Feature.js").FeatureLike>} features
   * Features to consider for hit detection.
   * @param {import("../../style/Style.js").StyleFunction|undefined} styleFunction
   * Layer style function.
   * @param {import("../../extent.js").Extent} extent Extent in render projection.
   * @param {number} resolution Resolution.
   * @param {number} rotation Rotation.
   * @param {number} [squaredTolerance] Squared tolerance.
   * @param {import("../../proj/Projection.js").default} [projection] Render projection.
   * @return {ImageData} Hit detection image data.
   */
  function createHitDetectionImageData(
    size,
    transforms,
    features,
    styleFunction,
    extent,
    resolution,
    rotation,
    squaredTolerance,
    projection,
  ) {
    const userExtent = projection ? toUserExtent(extent, projection) : extent;
    const width = size[0] * HIT_DETECT_RESOLUTION;
    const height = size[1] * HIT_DETECT_RESOLUTION;
    const context = createCanvasContext2D(width, height);
    context.imageSmoothingEnabled = false;
    const canvas = context.canvas;
    const renderer = new CanvasImmediateRenderer(
      context,
      HIT_DETECT_RESOLUTION,
      extent,
      null,
      rotation,
      squaredTolerance,
      projection
        ? getTransformFromProjections(getUserProjection(), projection)
        : null,
    );
    const featureCount = features.length;
    // Stretch hit detection index to use the whole available color range
    const indexFactor = Math.floor((256 * 256 * 256 - 1) / featureCount);
    const featuresByZIndex = {};
    for (let i = 1; i <= featureCount; ++i) {
      const feature = features[i - 1];
      const featureStyleFunction = feature.getStyleFunction() || styleFunction;
      if (!featureStyleFunction) {
        continue;
      }
      let styles = featureStyleFunction(feature, resolution);
      if (!styles) {
        continue;
      }
      if (!Array.isArray(styles)) {
        styles = [styles];
      }
      const index = i * indexFactor;
      const color = index.toString(16).padStart(7, '#00000');
      for (let j = 0, jj = styles.length; j < jj; ++j) {
        const originalStyle = styles[j];
        const geometry = originalStyle.getGeometryFunction()(feature);
        if (!geometry || !intersects$2(userExtent, geometry.getExtent())) {
          continue;
        }
        const style = originalStyle.clone();
        const fill = style.getFill();
        if (fill) {
          fill.setColor(color);
        }
        const stroke = style.getStroke();
        if (stroke) {
          stroke.setColor(color);
          stroke.setLineDash(null);
        }
        style.setText(undefined);
        const image = originalStyle.getImage();
        if (image) {
          const imgSize = image.getImageSize();
          if (!imgSize) {
            continue;
          }

          const imgContext = createCanvasContext2D(
            imgSize[0],
            imgSize[1],
            undefined,
            {alpha: false},
          );
          const img = imgContext.canvas;
          imgContext.fillStyle = color;
          imgContext.fillRect(0, 0, img.width, img.height);
          style.setImage(
            new Icon({
              img: img,
              anchor: image.getAnchor(),
              anchorXUnits: 'pixels',
              anchorYUnits: 'pixels',
              offset: image.getOrigin(),
              opacity: 1,
              size: image.getSize(),
              scale: image.getScale(),
              rotation: image.getRotation(),
              rotateWithView: image.getRotateWithView(),
            }),
          );
        }
        const zIndex = style.getZIndex() || 0;
        let byGeometryType = featuresByZIndex[zIndex];
        if (!byGeometryType) {
          byGeometryType = {};
          featuresByZIndex[zIndex] = byGeometryType;
          byGeometryType['Polygon'] = [];
          byGeometryType['Circle'] = [];
          byGeometryType['LineString'] = [];
          byGeometryType['Point'] = [];
        }
        const type = geometry.getType();
        if (type === 'GeometryCollection') {
          const geometries =
            /** @type {import("../../geom/GeometryCollection.js").default} */ (
              geometry
            ).getGeometriesArrayRecursive();
          for (let i = 0, ii = geometries.length; i < ii; ++i) {
            const geometry = geometries[i];
            byGeometryType[geometry.getType().replace('Multi', '')].push(
              geometry,
              style,
            );
          }
        } else {
          byGeometryType[type.replace('Multi', '')].push(geometry, style);
        }
      }
    }

    const zIndexKeys = Object.keys(featuresByZIndex).map(Number).sort(ascending);
    for (let i = 0, ii = zIndexKeys.length; i < ii; ++i) {
      const byGeometryType = featuresByZIndex[zIndexKeys[i]];
      for (const type in byGeometryType) {
        const geomAndStyle = byGeometryType[type];
        for (let j = 0, jj = geomAndStyle.length; j < jj; j += 2) {
          renderer.setStyle(geomAndStyle[j + 1]);
          for (let k = 0, kk = transforms.length; k < kk; ++k) {
            renderer.setTransform(transforms[k]);
            renderer.drawGeometry(geomAndStyle[j]);
          }
        }
      }
    }
    return context.getImageData(0, 0, canvas.width, canvas.height);
  }

  /**
   * @param {import("../../pixel").Pixel} pixel Pixel coordinate on the hit
   * detection canvas in css pixels.
   * @param {Array<F>} features Features. Has to
   * match the `features` array that was passed to `createHitDetectionImageData()`.
   * @param {ImageData} imageData Hit detection image data generated by
   * `createHitDetectionImageData()`.
   * @return {Array<F>} Features.
   * @template {import("../../Feature.js").FeatureLike} F
   */
  function hitDetect(pixel, features, imageData) {
    /** @type {Array<F>} */
    const resultFeatures = [];
    if (imageData) {
      const x = Math.floor(Math.round(pixel[0]) * HIT_DETECT_RESOLUTION);
      const y = Math.floor(Math.round(pixel[1]) * HIT_DETECT_RESOLUTION);
      // The pixel coordinate is clamped down to the hit-detect canvas' size to account
      // for browsers returning coordinates slightly larger than the actual canvas size
      // due to a non-integer pixel ratio.
      const index =
        (clamp$1(x, 0, imageData.width - 1) +
          clamp$1(y, 0, imageData.height - 1) * imageData.width) *
        4;
      const r = imageData.data[index];
      const g = imageData.data[index + 1];
      const b = imageData.data[index + 2];
      const i = b + 256 * (g + 256 * r);
      const indexFactor = Math.floor((256 * 256 * 256 - 1) / features.length);
      if (i && i % indexFactor === 0) {
        resultFeatures.push(features[i / indexFactor - 1]);
      }
    }
    return resultFeatures;
  }

  /**
   * @module ol/render/Event
   */


  class RenderEvent extends BaseEvent {
    /**
     * @param {import("./EventType.js").default} type Type.
     * @param {import("../transform.js").Transform} [inversePixelTransform] Transform for
     *     CSS pixels to rendered pixels.
     * @param {import("../Map.js").FrameState} [frameState] Frame state.
     * @param {?(CanvasRenderingContext2D|WebGLRenderingContext)} [context] Context.
     */
    constructor(type, inversePixelTransform, frameState, context) {
      super(type);

      /**
       * Transform from CSS pixels (relative to the top-left corner of the map viewport)
       * to rendered pixels on this event's `context`. Only available when a Canvas renderer is used, null otherwise.
       * @type {import("../transform.js").Transform|undefined}
       * @api
       */
      this.inversePixelTransform = inversePixelTransform;

      /**
       * An object representing the current render frame state.
       * @type {import("../Map.js").FrameState|undefined}
       * @api
       */
      this.frameState = frameState;

      /**
       * Canvas context. Not available when the event is dispatched by the map. For Canvas 2D layers,
       * the context will be the 2D rendering context.  For WebGL layers, the context will be the WebGL
       * context.
       * @type {CanvasRenderingContext2D|WebGLRenderingContext|undefined}
       * @api
       */
      this.context = context;
    }
  }

  /**
   * @module ol/renderer/Layer
   */

  const maxStaleKeys = 5;

  /**
   * @template {import("../layer/Layer.js").default} LayerType
   */
  class LayerRenderer extends Observable {
    /**
     * @param {LayerType} layer Layer.
     */
    constructor(layer) {
      super();

      /**
       * The renderer is initialized and ready to render.
       * @type {boolean}
       */
      this.ready = true;

      /** @private */
      this.boundHandleImageChange_ = this.handleImageChange_.bind(this);

      /**
       * @private
       * @type {LayerType}
       */
      this.layer_ = layer;

      /**
       * @type {Array<string>}
       * @private
       */
      this.staleKeys_ = new Array();

      /**
       * @type {number}
       * @protected
       */
      this.maxStaleKeys = maxStaleKeys;
    }

    /**
     * @return {Array<string>} Get the list of stale keys.
     */
    getStaleKeys() {
      return this.staleKeys_;
    }

    /**
     * @param {string} key The new stale key.
     */
    prependStaleKey(key) {
      this.staleKeys_.unshift(key);
      if (this.staleKeys_.length > this.maxStaleKeys) {
        this.staleKeys_.length = this.maxStaleKeys;
      }
    }

    /**
     * Asynchronous layer level hit detection.
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../Feature").FeatureLike>>} Promise that resolves with
     * an array of features.
     */
    getFeatures(pixel) {
      return abstract();
    }

    /**
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.
     */
    getData(pixel) {
      return null;
    }

    /**
     * Determine whether render should be called.
     * @abstract
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     */
    prepareFrame(frameState) {
      return abstract();
    }

    /**
     * Render the layer.
     * @abstract
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement|null} target Target that may be used to render content to.
     * @return {HTMLElement} The rendered element.
     */
    renderFrame(frameState, target) {
      return abstract();
    }

    /**
     * @abstract
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("./vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("./Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      return undefined;
    }

    /**
     * @return {LayerType} Layer.
     */
    getLayer() {
      return this.layer_;
    }

    /**
     * Perform action necessary to get the layer rendered after new fonts have loaded
     * @abstract
     */
    handleFontsChanged() {}

    /**
     * Handle changes in image state.
     * @param {import("../events/Event.js").default} event Image change event.
     * @private
     */
    handleImageChange_(event) {
      const image = /** @type {import("../Image.js").default} */ (event.target);
      if (
        image.getState() === ImageState.LOADED ||
        image.getState() === ImageState.ERROR
      ) {
        this.renderIfReadyAndVisible();
      }
    }

    /**
     * Load the image if not already loaded, and register the image change
     * listener if needed.
     * @param {import("../Image.js").default} image Image.
     * @return {boolean} `true` if the image is already loaded, `false` otherwise.
     * @protected
     */
    loadImage(image) {
      let imageState = image.getState();
      if (imageState != ImageState.LOADED && imageState != ImageState.ERROR) {
        image.addEventListener(EventType.CHANGE, this.boundHandleImageChange_);
      }
      if (imageState == ImageState.IDLE) {
        image.load();
        imageState = image.getState();
      }
      return imageState == ImageState.LOADED;
    }

    /**
     * @protected
     */
    renderIfReadyAndVisible() {
      const layer = this.getLayer();
      if (layer && layer.getVisible() && layer.getSourceState() === 'ready') {
        layer.changed();
      }
    }

    /**
     * @param {import("../Map.js").FrameState} frameState Frame state.
     */
    renderDeferred(frameState) {}

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      delete this.layer_;
      super.disposeInternal();
    }
  }

  /**
   * @module ol/renderer/canvas/Layer
   */

  /**
   * @type {Array<HTMLCanvasElement>}
   */
  const canvasPool$2 = [];

  /**
   * @type {CanvasRenderingContext2D}
   */
  let pixelContext$1 = null;

  function createPixelContext$1() {
    pixelContext$1 = createCanvasContext2D(1, 1, undefined, {
      willReadFrequently: true,
    });
  }

  /**
   * @abstract
   * @template {import("../../layer/Layer.js").default} LayerType
   * @extends {LayerRenderer<LayerType>}
   */
  class CanvasLayerRenderer extends LayerRenderer {
    /**
     * @param {LayerType} layer Layer.
     */
    constructor(layer) {
      super(layer);

      /**
       * @protected
       * @type {HTMLElement}
       */
      this.container = null;

      /**
       * @protected
       * @type {number}
       */
      this.renderedResolution;

      /**
       * A temporary transform.  The values in this transform should only be used in a
       * function that sets the values.
       * @protected
       * @type {import("../../transform.js").Transform}
       */
      this.tempTransform = create$3();

      /**
       * The transform for rendered pixels to viewport CSS pixels.  This transform must
       * be set when rendering a frame and may be used by other functions after rendering.
       * @protected
       * @type {import("../../transform.js").Transform}
       */
      this.pixelTransform = create$3();

      /**
       * The transform for viewport CSS pixels to rendered pixels.  This transform must
       * be set when rendering a frame and may be used by other functions after rendering.
       * @protected
       * @type {import("../../transform.js").Transform}
       */
      this.inversePixelTransform = create$3();

      /**
       * @type {CanvasRenderingContext2D}
       */
      this.context = null;

      /**
       * @private
       * @type {ZIndexContext}
       */
      this.deferredContext_ = null;

      /**
       * @type {boolean}
       */
      this.containerReused = false;

      /**
       * @protected
       * @type {import("../../Map.js").FrameState|null}
       */
      this.frameState = null;
    }

    /**
     * @param {import('../../DataTile.js').ImageLike} image Image.
     * @param {number} col The column index.
     * @param {number} row The row index.
     * @return {Uint8ClampedArray|null} The image data.
     */
    getImageData(image, col, row) {
      if (!pixelContext$1) {
        createPixelContext$1();
      }
      pixelContext$1.clearRect(0, 0, 1, 1);

      let data;
      try {
        pixelContext$1.drawImage(image, col, row, 1, 1, 0, 0, 1, 1);
        data = pixelContext$1.getImageData(0, 0, 1, 1).data;
      } catch {
        pixelContext$1 = null;
        return null;
      }
      return data;
    }

    /**
     * @param {import('../../Map.js').FrameState} frameState Frame state.
     * @return {string} Background color.
     */
    getBackground(frameState) {
      const layer = this.getLayer();
      let background = layer.getBackground();
      if (typeof background === 'function') {
        background = background(frameState.viewState.resolution);
      }
      return background || undefined;
    }

    /**
     * Get a rendering container from an existing target, if compatible.
     * @param {HTMLElement} target Potential render target.
     * @param {string} transform CSS transform matrix.
     * @param {string} [backgroundColor] Background color.
     */
    useContainer(target, transform, backgroundColor) {
      const layerClassName = this.getLayer().getClassName();
      let container, context;
      if (
        target &&
        target.className === layerClassName &&
        (!backgroundColor ||
          (target &&
            target.style.backgroundColor &&
            equals$2(
              asArray(target.style.backgroundColor),
              asArray(backgroundColor),
            )))
      ) {
        const canvas = target.firstElementChild;
        if (canvas instanceof HTMLCanvasElement) {
          context = canvas.getContext('2d');
        }
      }
      if (context && equivalent(context.canvas.style.transform, transform)) {
        // Container of the previous layer renderer can be used.
        this.container = target;
        this.context = context;
        this.containerReused = true;
      } else if (this.containerReused) {
        // Previously reused container cannot be used any more.
        this.container = null;
        this.context = null;
        this.containerReused = false;
      } else if (this.container) {
        this.container.style.backgroundColor = null;
      }
      if (!this.container) {
        container = document.createElement('div');
        container.className = layerClassName;
        let style = container.style;
        style.position = 'absolute';
        style.width = '100%';
        style.height = '100%';
        context = createCanvasContext2D();
        const canvas = context.canvas;
        container.appendChild(canvas);
        style = canvas.style;
        style.position = 'absolute';
        style.left = '0';
        style.transformOrigin = 'top left';
        this.container = container;
        this.context = context;
      }
      if (
        !this.containerReused &&
        backgroundColor &&
        !this.container.style.backgroundColor
      ) {
        this.container.style.backgroundColor = backgroundColor;
      }
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {import("../../extent.js").Extent} extent Clip extent.
     * @protected
     */
    clipUnrotated(context, frameState, extent) {
      const topLeft = getTopLeft(extent);
      const topRight = getTopRight(extent);
      const bottomRight = getBottomRight(extent);
      const bottomLeft = getBottomLeft(extent);

      apply(frameState.coordinateToPixelTransform, topLeft);
      apply(frameState.coordinateToPixelTransform, topRight);
      apply(frameState.coordinateToPixelTransform, bottomRight);
      apply(frameState.coordinateToPixelTransform, bottomLeft);

      const inverted = this.inversePixelTransform;
      apply(inverted, topLeft);
      apply(inverted, topRight);
      apply(inverted, bottomRight);
      apply(inverted, bottomLeft);

      context.save();
      context.beginPath();
      context.moveTo(Math.round(topLeft[0]), Math.round(topLeft[1]));
      context.lineTo(Math.round(topRight[0]), Math.round(topRight[1]));
      context.lineTo(Math.round(bottomRight[0]), Math.round(bottomRight[1]));
      context.lineTo(Math.round(bottomLeft[0]), Math.round(bottomLeft[1]));
      context.clip();
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement} target Target that may be used to render content to.
     * @protected
     */
    prepareContainer(frameState, target) {
      const extent = frameState.extent;
      const resolution = frameState.viewState.resolution;
      const rotation = frameState.viewState.rotation;
      const pixelRatio = frameState.pixelRatio;
      const width = Math.round((getWidth(extent) / resolution) * pixelRatio);
      const height = Math.round((getHeight(extent) / resolution) * pixelRatio);
      // set forward and inverse pixel transforms
      compose(
        this.pixelTransform,
        frameState.size[0] / 2,
        frameState.size[1] / 2,
        1 / pixelRatio,
        1 / pixelRatio,
        rotation,
        -width / 2,
        -height / 2,
      );
      makeInverse(this.inversePixelTransform, this.pixelTransform);

      const canvasTransform = toString$2(this.pixelTransform);
      this.useContainer(target, canvasTransform, this.getBackground(frameState));

      if (!this.containerReused) {
        const canvas = this.context.canvas;
        if (canvas.width != width || canvas.height != height) {
          canvas.width = width;
          canvas.height = height;
        } else {
          this.context.clearRect(0, 0, width, height);
        }
        if (canvasTransform !== canvas.style.transform) {
          canvas.style.transform = canvasTransform;
        }
      }
    }

    /**
     * @param {import("../../render/EventType.js").default} type Event type.
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @private
     */
    dispatchRenderEvent_(type, context, frameState) {
      const layer = this.getLayer();
      if (layer.hasListener(type)) {
        const event = new RenderEvent(
          type,
          this.inversePixelTransform,
          frameState,
          context,
        );
        layer.dispatchEvent(event);
      }
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    preRender(context, frameState) {
      this.frameState = frameState;
      if (frameState.declutter) {
        return;
      }
      this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState);
    }

    /**
     * @param {CanvasRenderingContext2D} context Context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    postRender(context, frameState) {
      if (frameState.declutter) {
        return;
      }
      this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState);
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     */
    renderDeferredInternal(frameState) {}

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {import('../../render/canvas/ZIndexContext.js').ZIndexContextProxy} Context.
     */
    getRenderContext(frameState) {
      if (frameState.declutter && !this.deferredContext_) {
        this.deferredContext_ = new ZIndexContext();
      }
      return frameState.declutter
        ? this.deferredContext_.getContext()
        : this.context;
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @override
     */
    renderDeferred(frameState) {
      if (!frameState.declutter) {
        return;
      }
      this.dispatchRenderEvent_(
        RenderEventType.PRERENDER,
        this.context,
        frameState,
      );
      if (frameState.declutter && this.deferredContext_) {
        this.deferredContext_.draw(this.context);
        this.deferredContext_.clear();
      }
      this.renderDeferredInternal(frameState);
      this.dispatchRenderEvent_(
        RenderEventType.POSTRENDER,
        this.context,
        frameState,
      );
    }

    /**
     * Creates a transform for rendering to an element that will be rotated after rendering.
     * @param {import("../../coordinate.js").Coordinate} center Center.
     * @param {number} resolution Resolution.
     * @param {number} rotation Rotation.
     * @param {number} pixelRatio Pixel ratio.
     * @param {number} width Width of the rendered element (in pixels).
     * @param {number} height Height of the rendered element (in pixels).
     * @param {number} offsetX Offset on the x-axis in view coordinates.
     * @protected
     * @return {!import("../../transform.js").Transform} Transform.
     */
    getRenderTransform(
      center,
      resolution,
      rotation,
      pixelRatio,
      width,
      height,
      offsetX,
    ) {
      const dx1 = width / 2;
      const dy1 = height / 2;
      const sx = pixelRatio / resolution;
      const sy = -sx;
      const dx2 = -center[0] + offsetX;
      const dy2 = -center[1];
      return compose(
        this.tempTransform,
        dx1,
        dy1,
        sx,
        sy,
        -rotation,
        dx2,
        dy2,
      );
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      delete this.frameState;
      super.disposeInternal();
    }
  }

  /**
   * @module ol/renderer/canvas/VectorLayer
   */

  /**
   * @classdesc
   * Canvas renderer for vector layers.
   * @api
   */
  class CanvasVectorLayerRenderer extends CanvasLayerRenderer {
    /**
     * @param {import("../../layer/BaseVector.js").default} vectorLayer Vector layer.
     */
    constructor(vectorLayer) {
      super(vectorLayer);

      /** @private */
      this.boundHandleStyleImageChange_ = this.handleStyleImageChange_.bind(this);

      /**
       * @private
       * @type {boolean}
       */
      this.animatingOrInteracting_;

      /**
       * @private
       * @type {ImageData|null}
       */
      this.hitDetectionImageData_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.clipped_ = false;

      /**
       * @private
       * @type {Array<import("../../Feature.js").default>}
       */
      this.renderedFeatures_ = null;

      /**
       * @private
       * @type {number}
       */
      this.renderedRevision_ = -1;

      /**
       * @private
       * @type {number}
       */
      this.renderedResolution_ = NaN;

      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.renderedExtent_ = createEmpty();

      /**
       * @private
       * @type {import("../../extent.js").Extent}
       */
      this.wrappedRenderedExtent_ = createEmpty();

      /**
       * @private
       * @type {number}
       */
      this.renderedRotation_;

      /**
       * @private
       * @type {import("../../coordinate").Coordinate}
       */
      this.renderedCenter_ = null;

      /**
       * @private
       * @type {import("../../proj/Projection").default}
       */
      this.renderedProjection_ = null;

      /**
       * @private
       * @type {number}
       */
      this.renderedPixelRatio_ = 1;

      /**
       * @private
       * @type {import("../../render.js").OrderFunction|null}
       */
      this.renderedRenderOrder_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.renderedFrameDeclutter_;

      /**
       * @private
       * @type {import("../../render/canvas/ExecutorGroup").default}
       */
      this.replayGroup_ = null;

      /**
       * A new replay group had to be created by `prepareFrame()`
       * @type {boolean}
       */
      this.replayGroupChanged = true;

      /**
       * Clipping to be performed by `renderFrame()`
       * @type {boolean}
       */
      this.clipping = true;

      /**
       * @private
       * @type {CanvasRenderingContext2D}
       */
      this.targetContext_ = null;

      /**
       * @private
       * @type {number}
       */
      this.opacity_ = 1;
    }

    /**
     * @param {ExecutorGroup} executorGroup Executor group.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {boolean} [declutterable] `true` to only render declutterable items,
     *     `false` to only render non-declutterable items, `undefined` to render all.
     */
    renderWorlds(executorGroup, frameState, declutterable) {
      const extent = frameState.extent;
      const viewState = frameState.viewState;
      const center = viewState.center;
      const resolution = viewState.resolution;
      const projection = viewState.projection;
      const rotation = viewState.rotation;
      const projectionExtent = projection.getExtent();
      const vectorSource = this.getLayer().getSource();
      const declutter = this.getLayer().getDeclutter();
      const pixelRatio = frameState.pixelRatio;
      const viewHints = frameState.viewHints;
      const snapToPixel = !(
        viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]
      );
      const context = this.context;
      const width = Math.round((getWidth(extent) / resolution) * pixelRatio);
      const height = Math.round((getHeight(extent) / resolution) * pixelRatio);

      const multiWorld = vectorSource.getWrapX() && projection.canWrapX();
      const worldWidth = multiWorld ? getWidth(projectionExtent) : null;
      const endWorld = multiWorld
        ? Math.ceil((extent[2] - projectionExtent[2]) / worldWidth) + 1
        : 1;
      let world = multiWorld
        ? Math.floor((extent[0] - projectionExtent[0]) / worldWidth)
        : 0;
      do {
        let transform = this.getRenderTransform(
          center,
          resolution,
          0,
          pixelRatio,
          width,
          height,
          world * worldWidth,
        );
        if (frameState.declutter) {
          transform = transform.slice(0);
        }
        executorGroup.execute(
          context,
          [context.canvas.width, context.canvas.height],
          transform,
          rotation,
          snapToPixel,
          declutterable === undefined
            ? ALL
            : declutterable
              ? DECLUTTER
              : NON_DECLUTTER,
          declutterable
            ? declutter && frameState.declutter[declutter]
            : undefined,
        );
      } while (++world < endWorld);
    }

    /**
     * @private
     */
    setDrawContext_() {
      if (this.opacity_ !== 1) {
        this.targetContext_ = this.context;
        this.context = createCanvasContext2D(
          this.context.canvas.width,
          this.context.canvas.height,
          canvasPool$2,
        );
      }
    }

    /**
     * @private
     */
    resetDrawContext_() {
      if (this.opacity_ !== 1 && this.targetContext_) {
        const alpha = this.targetContext_.globalAlpha;
        this.targetContext_.globalAlpha = this.opacity_;
        this.targetContext_.drawImage(this.context.canvas, 0, 0);
        this.targetContext_.globalAlpha = alpha;
        releaseCanvas$1(this.context);
        canvasPool$2.push(this.context.canvas);
        this.context = this.targetContext_;
        this.targetContext_ = null;
      }
    }

    /**
     * Render declutter items for this layer
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     */
    renderDeclutter(frameState) {
      if (!this.replayGroup_ || !this.getLayer().getDeclutter()) {
        return;
      }
      this.renderWorlds(this.replayGroup_, frameState, true);
    }

    /**
     * Render deferred instructions.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @override
     */
    renderDeferredInternal(frameState) {
      if (!this.replayGroup_) {
        return;
      }
      this.replayGroup_.renderDeferred();
      if (this.clipped_) {
        this.context.restore();
      }
      this.resetDrawContext_();
    }

    /**
     * Render the layer.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement|null} target Target that may be used to render content to.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState, target) {
      const layerState = frameState.layerStatesArray[frameState.layerIndex];
      this.opacity_ = layerState.opacity;
      const viewState = frameState.viewState;

      this.prepareContainer(frameState, target);
      const context = this.context;

      const replayGroup = this.replayGroup_;
      let render = replayGroup && !replayGroup.isEmpty();
      if (!render) {
        const hasRenderListeners =
          this.getLayer().hasListener(RenderEventType.PRERENDER) ||
          this.getLayer().hasListener(RenderEventType.POSTRENDER);
        if (!hasRenderListeners) {
          return this.container;
        }
      }

      this.setDrawContext_();

      this.preRender(context, frameState);

      const projection = viewState.projection;

      // clipped rendering if layer extent is set
      this.clipped_ = false;
      if (render && layerState.extent && this.clipping) {
        const layerExtent = fromUserExtent(layerState.extent, projection);
        render = intersects$2(layerExtent, frameState.extent);
        this.clipped_ = render && !containsExtent(layerExtent, frameState.extent);
        if (this.clipped_) {
          this.clipUnrotated(context, frameState, layerExtent);
        }
      }

      if (render) {
        this.renderWorlds(
          replayGroup,
          frameState,
          this.getLayer().getDeclutter() ? false : undefined,
        );
      }

      if (!frameState.declutter && this.clipped_) {
        context.restore();
      }

      this.postRender(context, frameState);

      if (this.renderedRotation_ !== viewState.rotation) {
        this.renderedRotation_ = viewState.rotation;
        this.hitDetectionImageData_ = null;
      }
      if (!frameState.declutter) {
        this.resetDrawContext_();
      }
      return this.container;
    }

    /**
     * Asynchronous layer level hit detection.
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../../Feature").default>>} Promise
     * that resolves with an array of features.
     * @override
     */
    getFeatures(pixel) {
      return new Promise((resolve) => {
        if (
          this.frameState &&
          !this.hitDetectionImageData_ &&
          !this.animatingOrInteracting_
        ) {
          const size = this.frameState.size.slice();
          const center = this.renderedCenter_;
          const resolution = this.renderedResolution_;
          const rotation = this.renderedRotation_;
          const projection = this.renderedProjection_;
          const extent = this.wrappedRenderedExtent_;
          const layer = this.getLayer();
          const transforms = [];
          const width = size[0] * HIT_DETECT_RESOLUTION;
          const height = size[1] * HIT_DETECT_RESOLUTION;
          transforms.push(
            this.getRenderTransform(
              center,
              resolution,
              rotation,
              HIT_DETECT_RESOLUTION,
              width,
              height,
              0,
            ).slice(),
          );
          const source = layer.getSource();
          const projectionExtent = projection.getExtent();
          if (
            source.getWrapX() &&
            projection.canWrapX() &&
            !containsExtent(projectionExtent, extent)
          ) {
            let startX = extent[0];
            const worldWidth = getWidth(projectionExtent);
            let world = 0;
            let offsetX;
            while (startX < projectionExtent[0]) {
              --world;
              offsetX = worldWidth * world;
              transforms.push(
                this.getRenderTransform(
                  center,
                  resolution,
                  rotation,
                  HIT_DETECT_RESOLUTION,
                  width,
                  height,
                  offsetX,
                ).slice(),
              );
              startX += worldWidth;
            }
            world = 0;
            startX = extent[2];
            while (startX > projectionExtent[2]) {
              ++world;
              offsetX = worldWidth * world;
              transforms.push(
                this.getRenderTransform(
                  center,
                  resolution,
                  rotation,
                  HIT_DETECT_RESOLUTION,
                  width,
                  height,
                  offsetX,
                ).slice(),
              );
              startX -= worldWidth;
            }
          }
          const userProjection = getUserProjection();
          this.hitDetectionImageData_ = createHitDetectionImageData(
            size,
            transforms,
            this.renderedFeatures_,
            layer.getStyleFunction(),
            extent,
            resolution,
            rotation,
            getSquaredTolerance(resolution, this.renderedPixelRatio_),
            userProjection ? projection : null,
          );
        }
        resolve(
          hitDetect(pixel, this.renderedFeatures_, this.hitDetectionImageData_),
        );
      });
    }

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("../vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("../Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     * @override
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      if (!this.replayGroup_) {
        return undefined;
      }
      const resolution = frameState.viewState.resolution;
      const rotation = frameState.viewState.rotation;
      const layer = this.getLayer();

      /** @type {!Object<string, import("../Map.js").HitMatch<T>|true>} */
      const features = {};

      /**
       * @param {import("../../Feature.js").FeatureLike} feature Feature.
       * @param {import("../../geom/SimpleGeometry.js").default} geometry Geometry.
       * @param {number} distanceSq The squared distance to the click position
       * @return {T|undefined} Callback result.
       */
      const featureCallback = function (feature, geometry, distanceSq) {
        const key = getUid(feature);
        const match = features[key];
        if (!match) {
          if (distanceSq === 0) {
            features[key] = true;
            return callback(feature, layer, geometry);
          }
          matches.push(
            (features[key] = {
              feature: feature,
              layer: layer,
              geometry: geometry,
              distanceSq: distanceSq,
              callback: callback,
            }),
          );
        } else if (match !== true && distanceSq < match.distanceSq) {
          if (distanceSq === 0) {
            features[key] = true;
            matches.splice(matches.lastIndexOf(match), 1);
            return callback(feature, layer, geometry);
          }
          match.geometry = geometry;
          match.distanceSq = distanceSq;
        }
        return undefined;
      };

      const declutter = this.getLayer().getDeclutter();
      return this.replayGroup_.forEachFeatureAtCoordinate(
        coordinate,
        resolution,
        rotation,
        hitTolerance,
        featureCallback,
        declutter
          ? frameState.declutter?.[declutter]?.all().map((item) => item.value)
          : null,
      );
    }

    /**
     * Perform action necessary to get the layer rendered after new fonts have loaded
     * @override
     */
    handleFontsChanged() {
      const layer = this.getLayer();
      if (layer.getVisible() && this.replayGroup_) {
        layer.changed();
      }
    }

    /**
     * Handle changes in image style state.
     * @param {import("../../events/Event.js").default} event Image style change event.
     * @private
     */
    handleStyleImageChange_(event) {
      this.renderIfReadyAndVisible();
    }

    /**
     * Determine whether render should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      const vectorLayer = this.getLayer();
      const vectorSource = vectorLayer.getSource();
      if (!vectorSource) {
        return false;
      }

      const animating = frameState.viewHints[ViewHint.ANIMATING];
      const interacting = frameState.viewHints[ViewHint.INTERACTING];
      const updateWhileAnimating = vectorLayer.getUpdateWhileAnimating();
      const updateWhileInteracting = vectorLayer.getUpdateWhileInteracting();

      if (
        (this.ready && !updateWhileAnimating && animating) ||
        (!updateWhileInteracting && interacting)
      ) {
        this.animatingOrInteracting_ = true;
        return true;
      }
      this.animatingOrInteracting_ = false;

      const frameStateExtent = frameState.extent;
      const viewState = frameState.viewState;
      const projection = viewState.projection;
      const resolution = viewState.resolution;
      const pixelRatio = frameState.pixelRatio;
      const vectorLayerRevision = vectorLayer.getRevision();
      const vectorLayerRenderBuffer = vectorLayer.getRenderBuffer();
      let vectorLayerRenderOrder = vectorLayer.getRenderOrder();

      if (vectorLayerRenderOrder === undefined) {
        vectorLayerRenderOrder = defaultOrder;
      }

      const center = viewState.center.slice();
      const extent = buffer$1(
        frameStateExtent,
        vectorLayerRenderBuffer * resolution,
      );
      const renderedExtent = extent.slice();
      const loadExtents = [extent.slice()];
      const projectionExtent = projection.getExtent();

      if (
        vectorSource.getWrapX() &&
        projection.canWrapX() &&
        !containsExtent(projectionExtent, frameState.extent)
      ) {
        // For the replay group, we need an extent that intersects the real world
        // (-180° to +180°). To support geometries in a coordinate range from -540°
        // to +540°, we add at least 1 world width on each side of the projection
        // extent. If the viewport is wider than the world, we need to add half of
        // the viewport width to make sure we cover the whole viewport.
        const worldWidth = getWidth(projectionExtent);
        const gutter = Math.max(getWidth(extent) / 2, worldWidth);
        extent[0] = projectionExtent[0] - gutter;
        extent[2] = projectionExtent[2] + gutter;
        wrapX$1(center, projection);
        const loadExtent = wrapX$2(loadExtents[0], projection);
        // If the extent crosses the date line, we load data for both edges of the worlds
        if (
          loadExtent[0] < projectionExtent[0] &&
          loadExtent[2] < projectionExtent[2]
        ) {
          loadExtents.push([
            loadExtent[0] + worldWidth,
            loadExtent[1],
            loadExtent[2] + worldWidth,
            loadExtent[3],
          ]);
        } else if (
          loadExtent[0] > projectionExtent[0] &&
          loadExtent[2] > projectionExtent[2]
        ) {
          loadExtents.push([
            loadExtent[0] - worldWidth,
            loadExtent[1],
            loadExtent[2] - worldWidth,
            loadExtent[3],
          ]);
        }
      }

      if (
        this.ready &&
        this.renderedResolution_ == resolution &&
        this.renderedRevision_ == vectorLayerRevision &&
        this.renderedRenderOrder_ == vectorLayerRenderOrder &&
        this.renderedFrameDeclutter_ === !!frameState.declutter &&
        containsExtent(this.wrappedRenderedExtent_, extent)
      ) {
        if (!equals$2(this.renderedExtent_, renderedExtent)) {
          this.hitDetectionImageData_ = null;
          this.renderedExtent_ = renderedExtent;
        }
        this.renderedCenter_ = center;
        this.replayGroupChanged = false;
        return true;
      }

      this.replayGroup_ = null;

      const replayGroup = new BuilderGroup(
        getTolerance(resolution, pixelRatio),
        extent,
        resolution,
        pixelRatio,
      );

      const userProjection = getUserProjection();
      let userTransform;
      if (userProjection) {
        for (let i = 0, ii = loadExtents.length; i < ii; ++i) {
          const extent = loadExtents[i];
          const userExtent = toUserExtent(extent, projection);
          vectorSource.loadFeatures(
            userExtent,
            toUserResolution(resolution, projection),
            userProjection,
          );
        }
        userTransform = getTransformFromProjections(userProjection, projection);
      } else {
        for (let i = 0, ii = loadExtents.length; i < ii; ++i) {
          vectorSource.loadFeatures(loadExtents[i], resolution, projection);
        }
      }

      const squaredTolerance = getSquaredTolerance(resolution, pixelRatio);
      let ready = true;
      const render =
        /**
         * @param {import("../../Feature.js").default} feature Feature.
         * @param {number} index Index.
         */
        (feature, index) => {
          let styles;
          const styleFunction =
            feature.getStyleFunction() || vectorLayer.getStyleFunction();
          if (styleFunction) {
            styles = styleFunction(feature, resolution);
          }
          if (styles) {
            const dirty = this.renderFeature(
              feature,
              squaredTolerance,
              styles,
              replayGroup,
              userTransform,
              this.getLayer().getDeclutter(),
              index,
            );
            ready = ready && !dirty;
          }
        };

      const userExtent = toUserExtent(extent, projection);
      /** @type {Array<import("../../Feature.js").default>} */
      const features = vectorSource.getFeaturesInExtent(userExtent);
      if (vectorLayerRenderOrder) {
        features.sort(vectorLayerRenderOrder);
      }
      for (let i = 0, ii = features.length; i < ii; ++i) {
        render(features[i], i);
      }
      this.renderedFeatures_ = features;
      this.ready = ready;

      const replayGroupInstructions = replayGroup.finish();
      const executorGroup = new ExecutorGroup(
        extent,
        resolution,
        pixelRatio,
        vectorSource.getOverlaps(),
        replayGroupInstructions,
        vectorLayer.getRenderBuffer(),
        !!frameState.declutter,
      );

      this.renderedResolution_ = resolution;
      this.renderedRevision_ = vectorLayerRevision;
      this.renderedRenderOrder_ = vectorLayerRenderOrder;
      this.renderedFrameDeclutter_ = !!frameState.declutter;
      this.renderedExtent_ = renderedExtent;
      this.wrappedRenderedExtent_ = extent;
      this.renderedCenter_ = center;
      this.renderedProjection_ = projection;
      this.renderedPixelRatio_ = pixelRatio;
      this.replayGroup_ = executorGroup;
      this.hitDetectionImageData_ = null;

      this.replayGroupChanged = true;
      return true;
    }

    /**
     * @param {import("../../Feature.js").default} feature Feature.
     * @param {number} squaredTolerance Squared render tolerance.
     * @param {import("../../style/Style.js").default|Array<import("../../style/Style.js").default>} styles The style or array of styles.
     * @param {import("../../render/canvas/BuilderGroup.js").default} builderGroup Builder group.
     * @param {import("../../proj.js").TransformFunction} [transform] Transform from user to view projection.
     * @param {boolean} [declutter] Enable decluttering.
     * @param {number} [index] Render order index.
     * @return {boolean} `true` if an image is loading.
     */
    renderFeature(
      feature,
      squaredTolerance,
      styles,
      builderGroup,
      transform,
      declutter,
      index,
    ) {
      if (!styles) {
        return false;
      }
      let loading = false;
      if (Array.isArray(styles)) {
        for (let i = 0, ii = styles.length; i < ii; ++i) {
          loading =
            renderFeature$1(
              builderGroup,
              feature,
              styles[i],
              squaredTolerance,
              this.boundHandleStyleImageChange_,
              transform,
              declutter,
              index,
            ) || loading;
        }
      } else {
        loading = renderFeature$1(
          builderGroup,
          feature,
          styles,
          squaredTolerance,
          this.boundHandleStyleImageChange_,
          transform,
          declutter,
          index,
        );
      }
      return loading;
    }
  }

  /**
   * @module ol/expr/expression
   */

  /**
   * @fileoverview This module includes types and functions for parsing array encoded expressions.
   * The result of parsing an encoded expression is one of the specific expression classes.
   * During parsing, information is added to the parsing context about the data accessed by the
   * expression.
   */

  /**
   * Base type used for literal style parameters; can be a number literal or the output of an operator,
   * which in turns takes {@link import("./expression.js").ExpressionValue} arguments.
   *
   * See below for details on the available operators (with notes for those that are WebGL or Canvas only).
   *
   * Reading operators:
   *   * `['band', bandIndex, xOffset, yOffset]` For tile layers only. Fetches pixel values from band
   *     `bandIndex` of the source's data. The first `bandIndex` of the source data is `1`. Fetched values
   *     are in the 0..1 range. {@link import("../source/TileImage.js").default} sources have 4 bands: red,
   *     green, blue and alpha. {@link import("../source/DataTile.js").default} sources can have any number
   *     of bands, depending on the underlying data source and
   *     {@link import("../source/GeoTIFF.js").Options configuration}. `xOffset` and `yOffset` are optional
   *     and allow specifying pixel offsets for x and y. This is used for sampling data from neighboring pixels (WebGL only).
   *   * `['get', attributeName]` fetches a feature property value, similar to `feature.get('attributeName')`.
   *   * `['get', attributeName, keyOrArrayIndex, ...]` (Canvas only) Access nested properties and array items of a
   *     feature property. The result is `undefined` when there is nothing at the specified key or index.
   *   * `['geometry-type']` returns a feature's geometry type as string, either: 'LineString', 'Point' or 'Polygon'
   *     `Multi*` values are returned as their singular equivalent
   *     `Circle` geometries are returned as 'Polygon'
   *     `GeometryCollection` geometries are returned as the type of the first geometry found in the collection (WebGL only).
   *   * `['resolution']` returns the current resolution
   *   * `['time']` The time in seconds since the creation of the layer (WebGL only).
   *   * `['var', 'varName']` fetches a value from the style variables; will throw an error if that variable is undefined
   *   * `['zoom']` The current zoom level (WebGL only).
   *   * `['line-metric']` returns the M component of the current point on a line (WebGL only); in case where the geometry layout of the line
   *      does not contain an M component (e.g. XY or XYZ), 0 is returned; 0 is also returned for geometries other than lines.
   *      Please note that the M component will be linearly interpolated between the two points composing a segment.
   *
   * Math operators:
   *   * `['*', value1, value2, ...]` multiplies the values (either numbers or colors)
   *   * `['/', value1, value2]` divides `value1` by `value2`
   *   * `['+', value1, value2, ...]` adds the values
   *   * `['-', value1, value2]` subtracts `value2` from `value1`
   *   * `['clamp', value, low, high]` clamps `value` between `low` and `high`
   *   * `['%', value1, value2]` returns the result of `value1 % value2` (modulo)
   *   * `['^', value1, value2]` returns the value of `value1` raised to the `value2` power
   *   * `['abs', value1]` returns the absolute value of `value1`
   *   * `['floor', value1]` returns the nearest integer less than or equal to `value1`
   *   * `['round', value1]` returns the nearest integer to `value1`
   *   * `['ceil', value1]` returns the nearest integer greater than or equal to `value1`
   *   * `['sin', value1]` returns the sine of `value1`
   *   * `['cos', value1]` returns the cosine of `value1`
   *   * `['atan', value1, value2]` returns `atan2(value1, value2)`. If `value2` is not provided, returns `atan(value1)`
   *   * `['sqrt', value1]` returns the square root of `value1`
   *
   * * Transform operators:
   *   * `['case', condition1, output1, ...conditionN, outputN, fallback]` selects the first output whose corresponding
   *     condition evaluates to `true`. If no match is found, returns the `fallback` value.
   *     All conditions should be `boolean`, output and fallback can be any kind.
   *   * `['match', input, match1, output1, ...matchN, outputN, fallback]` compares the `input` value against all
   *     provided `matchX` values, returning the output associated with the first valid match. If no match is found,
   *     returns the `fallback` value.
   *     `input` and `matchX` values must all be of the same type, and can be `number` or `string`. `outputX` and
   *     `fallback` values must be of the same type, and can be of any kind.
   *   * `['interpolate', interpolation, input, stop1, output1, ...stopN, outputN]` returns a value by interpolating between
   *     pairs of inputs and outputs; `interpolation` can either be `['linear']` or `['exponential', base]` where `base` is
   *     the rate of increase from stop A to stop B (i.e. power to which the interpolation ratio is raised); a value
   *     of 1 is equivalent to `['linear']`.
   *     `input` and `stopX` values must all be of type `number`. `outputX` values can be `number` or `color` values.
   *     Note: `input` will be clamped between `stop1` and `stopN`, meaning that all output values will be comprised
   *     between `output1` and `outputN`.
   *   * `['string', value1, value2, ...]` returns the first value in the list that evaluates to a string.
   *     An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 'default value']]`
   *     (Canvas only).
   *   * `['number', value1, value2, ...]` returns the first value in the list that evaluates to a number.
   *     An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 42]]`
   *     (Canvas only).
   *   * `['coalesce', value1, value2, ...]` returns the first value in the list which is not null or undefined.
   *     An example would be to provide a default value for get: `['coalesce', ['get','propertyname'], 'default value']]`
   *     (Canvas only).
   *
   * * Logical operators:
   *   * `['<', value1, value2]` returns `true` if `value1` is strictly lower than `value2`, or `false` otherwise.
   *   * `['<=', value1, value2]` returns `true` if `value1` is lower than or equals `value2`, or `false` otherwise.
   *   * `['>', value1, value2]` returns `true` if `value1` is strictly greater than `value2`, or `false` otherwise.
   *   * `['>=', value1, value2]` returns `true` if `value1` is greater than or equals `value2`, or `false` otherwise.
   *   * `['==', value1, value2]` returns `true` if `value1` equals `value2`, or `false` otherwise.
   *   * `['!=', value1, value2]` returns `true` if `value1` does not equal `value2`, or `false` otherwise.
   *   * `['!', value1]` returns `false` if `value1` is `true` or greater than `0`, or `true` otherwise.
   *   * `['all', value1, value2, ...]` returns `true` if all the inputs are `true`, `false` otherwise.
   *   * `['any', value1, value2, ...]` returns `true` if any of the inputs are `true`, `false` otherwise.
   *   * `['has', attributeName, keyOrArrayIndex, ...]` returns `true` if feature properties include the (nested) key `attributeName`,
   *     `false` otherwise.
   *     Note that for WebGL layers, the hardcoded value `-9999999` is used to distinguish when a property is not defined.
   *   * `['between', value1, value2, value3]` returns `true` if `value1` is contained between `value2` and `value3`
   *     (inclusively), or `false` otherwise.
   *   * `['in', needle, haystack]` returns `true` if `needle` is found in `haystack`, and
   *     `false` otherwise.
   *     This operator has the following limitations:
   *     * `haystack` has to be an array of numbers or strings (searching for a substring in a string is not supported yet)
   *     * Only literal arrays are supported as `haystack` for now; this means that `haystack` cannot be the result of an
   *     expression. If `haystack` is an array of strings, use the `literal` operator to disambiguate from an expression:
   *     `['literal', ['abc', 'def', 'ghi']]`
   *
   * * Conversion operators:
   *   * `['array', value1, ...valueN]` creates a numerical array from `number` values; please note that the amount of
   *     values can currently only be 2, 3 or 4 (WebGL only).
   *   * `['color', red, green, blue, alpha]` or `['color', shade, alpha]` creates a `color` value from `number` values;
   *     the `alpha` parameter is optional; if not specified, it will be set to 1 (WebGL only).
   *     Note: `red`, `green` and `blue` or `shade` components must be values between 0 and 255; `alpha` between 0 and 1.
   *   * `['palette', index, colors]` picks a `color` value from an array of colors using the given index; the `index`
   *     expression must evaluate to a number; the items in the `colors` array must be strings with hex colors
   *     (e.g. `'#86A136'`), colors using the rgba[a] functional notation (e.g. `'rgb(134, 161, 54)'` or `'rgba(134, 161, 54, 1)'`),
   *     named colors (e.g. `'red'`), or array literals with 3 ([r, g, b]) or 4 ([r, g, b, a]) values (with r, g, and b
   *     in the 0-255 range and a in the 0-1 range) (WebGL only).
   *   * `['to-string', value]` converts the input value to a string. If the input is a boolean, the result is "true" or "false".
   *     If the input is a number, it is converted to a string as specified by the "NumberToString" algorithm of the ECMAScript
   *     Language Specification. If the input is a color, it is converted to a string of the form "rgba(r,g,b,a)". (Canvas only)
   *
   * Values can either be literals or another operator, as they will be evaluated recursively.
   * Literal values can be of the following types:
   * * `boolean`
   * * `number`
   * * `number[]` (number arrays can only have a length of 2, 3 or 4)
   * * `string`
   * * {@link module:ol/color~Color}
   *
   * @typedef {Array<*>|import("../color.js").Color|string|number|boolean} ExpressionValue
   * @api
   */

  let numTypes = 0;
  const NoneType = 0;
  const BooleanType$1 = 1 << numTypes++;
  const NumberType$1 = 1 << numTypes++;
  const StringType$1 = 1 << numTypes++;
  const ColorType$1 = 1 << numTypes++;
  const NumberArrayType$1 = 1 << numTypes++;
  const SizeType = 1 << numTypes++;
  const AnyType = Math.pow(2, numTypes) - 1;

  const typeNames = {
    [BooleanType$1]: 'boolean',
    [NumberType$1]: 'number',
    [StringType$1]: 'string',
    [ColorType$1]: 'color',
    [NumberArrayType$1]: 'number[]',
    [SizeType]: 'size',
  };

  const namedTypes = Object.keys(typeNames).map(Number).sort(ascending);

  /**
   * @param {number} type The type.
   * @return {boolean} The type is one of the specific types (not any or a union type).
   */
  function isSpecific(type) {
    return type in typeNames;
  }

  /**
   * Get a string representation for a type.
   * @param {number} type The type.
   * @return {string} The type name.
   */
  function typeName(type) {
    const names = [];
    for (const namedType of namedTypes) {
      if (includesType(type, namedType)) {
        names.push(typeNames[namedType]);
      }
    }
    if (names.length === 0) {
      return 'untyped';
    }
    if (names.length < 3) {
      return names.join(' or ');
    }
    return names.slice(0, -1).join(', ') + ', or ' + names[names.length - 1];
  }

  /**
   * @param {number} broad The broad type.
   * @param {number} specific The specific type.
   * @return {boolean} The broad type includes the specific type.
   */
  function includesType(broad, specific) {
    return (broad & specific) === specific;
  }

  /**
   * @param {number} oneType One type.
   * @param {number} otherType Another type.
   * @return {boolean} The set of types overlap (share a common specific type)
   */
  function overlapsType(oneType, otherType) {
    return !!(oneType & otherType);
  }

  /**
   * @param {number} type The type.
   * @param {number} expected The expected type.
   * @return {boolean} The given type is exactly the expected type.
   */
  function isType(type, expected) {
    return type === expected;
  }

  /**
   * @typedef {boolean|number|string|Array<number>} LiteralValue
   */

  class LiteralExpression {
    /**
     * @param {number} type The value type.
     * @param {LiteralValue} value The literal value.
     */
    constructor(type, value) {
      if (!isSpecific(type)) {
        throw new Error(
          `literal expressions must have a specific type, got ${typeName(type)}`,
        );
      }
      this.type = type;
      this.value = value;
    }
  }

  class CallExpression {
    /**
     * @param {number} type The return type.
     * @param {string} operator The operator.
     * @param {...Expression} args The arguments.
     */
    constructor(type, operator, ...args) {
      this.type = type;
      this.operator = operator;
      this.args = args;
    }
  }

  /**
   * @typedef {LiteralExpression|CallExpression} Expression
   */

  /**
   * @typedef {Object} ParsingContext
   * @property {Set<string>} variables Variables referenced with the 'var' operator.
   * @property {Set<string>} properties Properties referenced with the 'get' operator.
   * @property {boolean} featureId The style uses the feature id.
   * @property {boolean} geometryType The style uses the feature geometry type.
   * @property {boolean} mapState The style uses the map state (view state or time elapsed).
   */

  /**
   * @return {ParsingContext} A new parsing context.
   */
  function newParsingContext() {
    return {
      variables: new Set(),
      properties: new Set(),
      featureId: false,
      geometryType: false,
      mapState: false,
    };
  }

  /**
   * @typedef {LiteralValue|Array} EncodedExpression
   */

  /**
   * @param {EncodedExpression} encoded The encoded expression.
   * @param {number} expectedType The expected type.
   * @param {ParsingContext} context The parsing context.
   * @return {Expression} The parsed expression result.
   */
  function parse$1(encoded, expectedType, context) {
    switch (typeof encoded) {
      case 'boolean': {
        if (isType(expectedType, StringType$1)) {
          return new LiteralExpression(StringType$1, encoded ? 'true' : 'false');
        }
        if (!includesType(expectedType, BooleanType$1)) {
          throw new Error(
            `got a boolean, but expected ${typeName(expectedType)}`,
          );
        }
        return new LiteralExpression(BooleanType$1, encoded);
      }
      case 'number': {
        if (isType(expectedType, SizeType)) {
          return new LiteralExpression(SizeType, toSize(encoded));
        }
        if (isType(expectedType, BooleanType$1)) {
          return new LiteralExpression(BooleanType$1, !!encoded);
        }
        if (isType(expectedType, StringType$1)) {
          return new LiteralExpression(StringType$1, encoded.toString());
        }
        if (!includesType(expectedType, NumberType$1)) {
          throw new Error(`got a number, but expected ${typeName(expectedType)}`);
        }
        return new LiteralExpression(NumberType$1, encoded);
      }
      case 'string': {
        if (isType(expectedType, ColorType$1)) {
          return new LiteralExpression(ColorType$1, fromString(encoded));
        }
        if (isType(expectedType, BooleanType$1)) {
          return new LiteralExpression(BooleanType$1, !!encoded);
        }
        if (!includesType(expectedType, StringType$1)) {
          throw new Error(`got a string, but expected ${typeName(expectedType)}`);
        }
        return new LiteralExpression(StringType$1, encoded);
      }
    }

    if (!Array.isArray(encoded)) {
      throw new Error('expression must be an array or a primitive value');
    }

    if (encoded.length === 0) {
      throw new Error('empty expression');
    }

    if (typeof encoded[0] === 'string') {
      return parseCallExpression(encoded, expectedType, context);
    }

    for (const item of encoded) {
      if (typeof item !== 'number') {
        throw new Error('expected an array of numbers');
      }
    }

    if (isType(expectedType, SizeType)) {
      if (encoded.length !== 2) {
        throw new Error(
          `expected an array of two values for a size, got ${encoded.length}`,
        );
      }
      return new LiteralExpression(SizeType, encoded);
    }

    if (isType(expectedType, ColorType$1)) {
      if (encoded.length === 3) {
        return new LiteralExpression(ColorType$1, [...encoded, 1]);
      }
      if (encoded.length === 4) {
        return new LiteralExpression(ColorType$1, encoded);
      }
      throw new Error(
        `expected an array of 3 or 4 values for a color, got ${encoded.length}`,
      );
    }

    if (!includesType(expectedType, NumberArrayType$1)) {
      throw new Error(
        `got an array of numbers, but expected ${typeName(expectedType)}`,
      );
    }

    return new LiteralExpression(NumberArrayType$1, encoded);
  }

  /**
   * @type {Object<string, string>}
   */
  const Ops = {
    Get: 'get',
    Var: 'var',
    Concat: 'concat',
    GeometryType: 'geometry-type',
    LineMetric: 'line-metric',
    Any: 'any',
    All: 'all',
    Not: '!',
    Resolution: 'resolution',
    Zoom: 'zoom',
    Time: 'time',
    Equal: '==',
    NotEqual: '!=',
    GreaterThan: '>',
    GreaterThanOrEqualTo: '>=',
    LessThan: '<',
    LessThanOrEqualTo: '<=',
    Multiply: '*',
    Divide: '/',
    Add: '+',
    Subtract: '-',
    Clamp: 'clamp',
    Mod: '%',
    Pow: '^',
    Abs: 'abs',
    Floor: 'floor',
    Ceil: 'ceil',
    Round: 'round',
    Sin: 'sin',
    Cos: 'cos',
    Atan: 'atan',
    Sqrt: 'sqrt',
    Match: 'match',
    Between: 'between',
    Interpolate: 'interpolate',
    Coalesce: 'coalesce',
    Case: 'case',
    In: 'in',
    Number: 'number',
    String: 'string',
    Array: 'array',
    Color: 'color',
    Id: 'id',
    Band: 'band',
    Palette: 'palette',
    ToString: 'to-string',
    Has: 'has',
  };

  /**
   * @typedef {function(Array, number, ParsingContext):Expression} Parser
   *
   * Second argument is the expected type.
   */

  /**
   * @type {Object<string, Parser>}
   */
  const parsers = {
    [Ops.Get]: createCallExpressionParser(hasArgsCount(1, Infinity), withGetArgs),
    [Ops.Var]: createCallExpressionParser(hasArgsCount(1, 1), withVarArgs),
    [Ops.Has]: createCallExpressionParser(hasArgsCount(1, Infinity), withGetArgs),
    [Ops.Id]: createCallExpressionParser(usesFeatureId, withNoArgs),
    [Ops.Concat]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfType(StringType$1),
    ),
    [Ops.GeometryType]: createCallExpressionParser(usesGeometryType, withNoArgs),
    [Ops.LineMetric]: createCallExpressionParser(withNoArgs),
    [Ops.Resolution]: createCallExpressionParser(usesMapState, withNoArgs),
    [Ops.Zoom]: createCallExpressionParser(usesMapState, withNoArgs),
    [Ops.Time]: createCallExpressionParser(usesMapState, withNoArgs),
    [Ops.Any]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfType(BooleanType$1),
    ),
    [Ops.All]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfType(BooleanType$1),
    ),
    [Ops.Not]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(BooleanType$1),
    ),
    [Ops.Equal]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(AnyType),
    ),
    [Ops.NotEqual]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(AnyType),
    ),
    [Ops.GreaterThan]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.GreaterThanOrEqualTo]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.LessThan]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.LessThanOrEqualTo]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Multiply]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfReturnType,
    ),
    [Ops.Coalesce]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfReturnType,
    ),
    [Ops.Divide]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Add]: createCallExpressionParser(
      hasArgsCount(2, Infinity),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Subtract]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Clamp]: createCallExpressionParser(
      hasArgsCount(3, 3),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Mod]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Pow]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Abs]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Floor]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Ceil]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Round]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Sin]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Cos]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Atan]: createCallExpressionParser(
      hasArgsCount(1, 2),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Sqrt]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Match]: createCallExpressionParser(
      hasArgsCount(4, Infinity),
      hasEvenArgs,
      withMatchArgs,
    ),
    [Ops.Between]: createCallExpressionParser(
      hasArgsCount(3, 3),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Interpolate]: createCallExpressionParser(
      hasArgsCount(6, Infinity),
      hasEvenArgs,
      withInterpolateArgs,
    ),
    [Ops.Case]: createCallExpressionParser(
      hasArgsCount(3, Infinity),
      hasOddArgs,
      withCaseArgs,
    ),
    [Ops.In]: createCallExpressionParser(hasArgsCount(2, 2), withInArgs),
    [Ops.Number]: createCallExpressionParser(
      hasArgsCount(1, Infinity),
      withArgsOfType(AnyType),
    ),
    [Ops.String]: createCallExpressionParser(
      hasArgsCount(1, Infinity),
      withArgsOfType(AnyType),
    ),
    [Ops.Array]: createCallExpressionParser(
      hasArgsCount(1, Infinity),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Color]: createCallExpressionParser(
      hasArgsCount(1, 4),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Band]: createCallExpressionParser(
      hasArgsCount(1, 3),
      withArgsOfType(NumberType$1),
    ),
    [Ops.Palette]: createCallExpressionParser(
      hasArgsCount(2, 2),
      withPaletteArgs,
    ),
    [Ops.ToString]: createCallExpressionParser(
      hasArgsCount(1, 1),
      withArgsOfType(BooleanType$1 | NumberType$1 | StringType$1 | ColorType$1),
    ),
  };

  /**
   * @typedef {function(Array<EncodedExpression>, number, ParsingContext):Array<Expression>|void} ArgValidator
   *
   * An argument validator applies various checks to an encoded expression arguments and
   * returns the parsed arguments if any.  The second argument is the return type of the call expression.
   */

  /**
   * @type {ArgValidator}
   */
  function withGetArgs(encoded, returnType, context) {
    const argsCount = encoded.length - 1;
    const args = new Array(argsCount);
    for (let i = 0; i < argsCount; ++i) {
      const key = encoded[i + 1];
      switch (typeof key) {
        case 'number': {
          args[i] = new LiteralExpression(NumberType$1, key);
          break;
        }
        case 'string': {
          args[i] = new LiteralExpression(StringType$1, key);
          break;
        }
        default: {
          throw new Error(
            `expected a string key or numeric array index for a get operation, got ${key}`,
          );
        }
      }
      if (i === 0) {
        context.properties.add(String(key));
      }
    }
    return args;
  }

  /**
   * @type {ArgValidator}
   */
  function withVarArgs(encoded, returnType, context) {
    const name = encoded[1];
    if (typeof name !== 'string') {
      throw new Error('expected a string argument for var operation');
    }
    context.variables.add(name);

    return [new LiteralExpression(StringType$1, name)];
  }

  /**
   * @type {ArgValidator}
   */
  function usesFeatureId(encoded, returnType, context) {
    context.featureId = true;
  }

  /**
   * @type {ArgValidator}
   */
  function usesGeometryType(encoded, returnType, context) {
    context.geometryType = true;
  }

  /**
   * @type {ArgValidator}
   */
  function usesMapState(encoded, returnType, context) {
    context.mapState = true;
  }

  /**
   * @type {ArgValidator}
   */
  function withNoArgs(encoded, returnType, context) {
    const operation = encoded[0];
    if (encoded.length !== 1) {
      throw new Error(`expected no arguments for ${operation} operation`);
    }
    return [];
  }

  /**
   * @param {number} minArgs The minimum number of arguments.
   * @param {number} maxArgs The maximum number of arguments.
   * @return {ArgValidator} The argument validator
   */
  function hasArgsCount(minArgs, maxArgs) {
    return function (encoded, returnType, context) {
      const operation = encoded[0];
      const argCount = encoded.length - 1;
      if (minArgs === maxArgs) {
        if (argCount !== minArgs) {
          const plural = minArgs === 1 ? '' : 's';
          throw new Error(
            `expected ${minArgs} argument${plural} for ${operation}, got ${argCount}`,
          );
        }
      } else if (argCount < minArgs || argCount > maxArgs) {
        const range =
          maxArgs === Infinity
            ? `${minArgs} or more`
            : `${minArgs} to ${maxArgs}`;
        throw new Error(
          `expected ${range} arguments for ${operation}, got ${argCount}`,
        );
      }
    };
  }

  /**
   * @type {ArgValidator}
   */
  function withArgsOfReturnType(encoded, returnType, context) {
    const argCount = encoded.length - 1;
    /**
     * @type {Array<Expression>}
     */
    const args = new Array(argCount);
    for (let i = 0; i < argCount; ++i) {
      const expression = parse$1(encoded[i + 1], returnType, context);
      args[i] = expression;
    }
    return args;
  }

  /**
   * @param {number} argType The argument type.
   * @return {ArgValidator} The argument validator
   */
  function withArgsOfType(argType) {
    return function (encoded, returnType, context) {
      const argCount = encoded.length - 1;
      /**
       * @type {Array<Expression>}
       */
      const args = new Array(argCount);
      for (let i = 0; i < argCount; ++i) {
        const expression = parse$1(encoded[i + 1], argType, context);
        args[i] = expression;
      }
      return args;
    };
  }

  /**
   * @type {ArgValidator}
   */
  function hasOddArgs(encoded, returnType, context) {
    const operation = encoded[0];
    const argCount = encoded.length - 1;
    if (argCount % 2 === 0) {
      throw new Error(
        `expected an odd number of arguments for ${operation}, got ${argCount} instead`,
      );
    }
  }

  /**
   * @type {ArgValidator}
   */
  function hasEvenArgs(encoded, returnType, context) {
    const operation = encoded[0];
    const argCount = encoded.length - 1;
    if (argCount % 2 === 1) {
      throw new Error(
        `expected an even number of arguments for operation ${operation}, got ${argCount} instead`,
      );
    }
  }

  /**
   * @type {ArgValidator}
   */
  function withMatchArgs(encoded, returnType, context) {
    const argsCount = encoded.length - 1;

    const inputType = StringType$1 | NumberType$1 | BooleanType$1;

    const input = parse$1(encoded[1], inputType, context);

    const fallback = parse$1(encoded[encoded.length - 1], returnType, context);

    const args = new Array(argsCount - 2);
    for (let i = 0; i < argsCount - 2; i += 2) {
      try {
        const match = parse$1(encoded[i + 2], input.type, context);
        args[i] = match;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i + 1} of match expression: ${err.message}`,
        );
      }
      try {
        const output = parse$1(encoded[i + 3], fallback.type, context);
        args[i + 1] = output;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i + 2} of match expression: ${err.message}`,
        );
      }
    }

    return [input, ...args, fallback];
  }

  /**
   * @type {ArgValidator}
   */
  function withInterpolateArgs(encoded, returnType, context) {
    const interpolationType = encoded[1];
    /**
     * @type {number}
     */
    let base;
    switch (interpolationType[0]) {
      case 'linear':
        base = 1;
        break;
      case 'exponential':
        const b = interpolationType[1];
        if (typeof b !== 'number' || b <= 0) {
          throw new Error(
            `expected a number base for exponential interpolation` +
              `, got ${JSON.stringify(b)} instead`,
          );
        }
        base = b;
        break;
      default:
        throw new Error(
          `invalid interpolation type: ${JSON.stringify(interpolationType)}`,
        );
    }

    const interpolation = new LiteralExpression(NumberType$1, base);

    let input;
    try {
      input = parse$1(encoded[2], NumberType$1, context);
    } catch (err) {
      throw new Error(
        `failed to parse argument 1 in interpolate expression: ${err.message}`,
      );
    }

    const args = new Array(encoded.length - 3);
    for (let i = 0; i < args.length; i += 2) {
      try {
        const stop = parse$1(encoded[i + 3], NumberType$1, context);
        args[i] = stop;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i + 2} for interpolate expression: ${err.message}`,
        );
      }
      try {
        const output = parse$1(encoded[i + 4], returnType, context);
        args[i + 1] = output;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i + 3} for interpolate expression: ${err.message}`,
        );
      }
    }

    return [interpolation, input, ...args];
  }

  /**
   * @type {ArgValidator}
   */
  function withCaseArgs(encoded, returnType, context) {
    const fallback = parse$1(encoded[encoded.length - 1], returnType, context);

    const args = new Array(encoded.length - 1);
    for (let i = 0; i < args.length - 1; i += 2) {
      try {
        const condition = parse$1(encoded[i + 1], BooleanType$1, context);
        args[i] = condition;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i} of case expression: ${err.message}`,
        );
      }
      try {
        const output = parse$1(encoded[i + 2], fallback.type, context);
        args[i + 1] = output;
      } catch (err) {
        throw new Error(
          `failed to parse argument ${i + 1} of case expression: ${err.message}`,
        );
      }
    }

    args[args.length - 1] = fallback;
    return args;
  }

  /**
   * @type {ArgValidator}
   */
  function withInArgs(encoded, returnType, context) {
    let haystack = encoded[2];
    if (!Array.isArray(haystack)) {
      throw new Error(
        `the second argument for the "in" operator must be an array`,
      );
    }
    /**
     * @type {number}
     */
    let needleType;
    if (typeof haystack[0] === 'string') {
      if (haystack[0] !== 'literal') {
        throw new Error(
          `for the "in" operator, a string array should be wrapped in a "literal" operator to disambiguate from expressions`,
        );
      }
      if (!Array.isArray(haystack[1])) {
        throw new Error(
          `failed to parse "in" expression: the literal operator must be followed by an array`,
        );
      }
      haystack = haystack[1];
      needleType = StringType$1;
    } else {
      needleType = NumberType$1;
    }

    const args = new Array(haystack.length);
    for (let i = 0; i < args.length; i++) {
      try {
        const arg = parse$1(haystack[i], needleType, context);
        args[i] = arg;
      } catch (err) {
        throw new Error(
          `failed to parse haystack item ${i} for "in" expression: ${err.message}`,
        );
      }
    }

    const needle = parse$1(encoded[1], needleType, context);
    return [needle, ...args];
  }

  /**
   * @type {ArgValidator}
   */
  function withPaletteArgs(encoded, returnType, context) {
    let index;
    try {
      index = parse$1(encoded[1], NumberType$1, context);
    } catch (err) {
      throw new Error(
        `failed to parse first argument in palette expression: ${err.message}`,
      );
    }
    const colors = encoded[2];
    if (!Array.isArray(colors)) {
      throw new Error('the second argument of palette must be an array');
    }
    const parsedColors = new Array(colors.length);
    for (let i = 0; i < parsedColors.length; i++) {
      let color;
      try {
        color = parse$1(colors[i], ColorType$1, context);
      } catch (err) {
        throw new Error(
          `failed to parse color at index ${i} in palette expression: ${err.message}`,
        );
      }
      if (!(color instanceof LiteralExpression)) {
        throw new Error(
          `the palette color at index ${i} must be a literal value`,
        );
      }
      parsedColors[i] = color;
    }
    return [index, ...parsedColors];
  }

  /**
   * @param {Array<ArgValidator>} validators A chain of argument validators.  The last validator is expected
   * to return the parsed arguments.
   * @return {Parser} The parser.
   */
  function createCallExpressionParser(...validators) {
    return function (encoded, returnType, context) {
      const operator = encoded[0];

      /**
       * @type {Array<Expression>}
       */
      let args;
      for (let i = 0; i < validators.length; i++) {
        const parsed = validators[i](encoded, returnType, context);
        if (i == validators.length - 1) {
          if (!parsed) {
            throw new Error(
              'expected last argument validator to return the parsed args',
            );
          }
          args = parsed;
        }
      }
      return new CallExpression(returnType, operator, ...args);
    };
  }

  /**
   * @param {Array} encoded The encoded expression.
   * @param {number} returnType The expected return type of the call expression.
   * @param {ParsingContext} context The parsing context.
   * @return {Expression} The parsed expression.
   */
  function parseCallExpression(encoded, returnType, context) {
    const operator = encoded[0];

    const parser = parsers[operator];
    if (!parser) {
      throw new Error(`unknown operator: ${operator}`);
    }
    return parser(encoded, returnType, context);
  }

  /**
   * Returns a simplified geometry type suited for the `geometry-type` operator
   * @param {import('../geom/Geometry.js').default|import('../render/Feature.js').default} geometry Geometry object
   * @return {'Point'|'LineString'|'Polygon'|''} Simplified geometry type; empty string of no geometry found
   */
  function computeGeometryType(geometry) {
    if (!geometry) {
      return '';
    }
    const type = geometry.getType();
    switch (type) {
      case 'Point':
      case 'LineString':
      case 'Polygon':
        return type;
      case 'MultiPoint':
      case 'MultiLineString':
      case 'MultiPolygon':
        return /** @type {'Point'|'LineString'|'Polygon'} */ (type.substring(5));
      case 'Circle':
        return 'Polygon';
      case 'GeometryCollection':
        return computeGeometryType(
          /** @type {import("../geom/GeometryCollection.js").default} */ (
            geometry
          ).getGeometries()[0],
        );
      default:
        return '';
    }
  }

  var style_expressions = {
    __proto__: null,
    AnyType: AnyType,
    BooleanType: BooleanType$1,
    CallExpression: CallExpression,
    ColorType: ColorType$1,
    LiteralExpression: LiteralExpression,
    NoneType: NoneType,
    NumberArrayType: NumberArrayType$1,
    NumberType: NumberType$1,
    Ops: Ops,
    SizeType: SizeType,
    StringType: StringType$1,
    computeGeometryType: computeGeometryType,
    includesType: includesType,
    isType: isType,
    newParsingContext: newParsingContext,
    overlapsType: overlapsType,
    parse: parse$1,
    typeName: typeName
  };

  /**
   * @module ol/expr/cpu
   */


  /**
   * @fileoverview This module includes functions to build expressions for evaluation on the CPU.
   * Building is composed of two steps: parsing and compiling.  The parsing step takes an encoded
   * expression and returns an instance of one of the expression classes.  The compiling step takes
   * the expression instance and returns a function that can be evaluated in to return a literal
   * value.  The evaluator function should do as little allocation and work as possible.
   */

  /**
   * @typedef {Object} EvaluationContext
   * @property {Object} properties The values for properties used in 'get' expressions.
   * @property {Object} variables The values for variables used in 'var' expressions.
   * @property {number} resolution The map resolution.
   * @property {string|number|null} featureId The feature id.
   * @property {string} geometryType Geometry type of the current object.
   */

  /**
   * @return {EvaluationContext} A new evaluation context.
   */
  function newEvaluationContext() {
    return {
      variables: {},
      properties: {},
      resolution: NaN,
      featureId: null,
      geometryType: '',
    };
  }

  /**
   * @typedef {function(EvaluationContext):import("./expression.js").LiteralValue} ExpressionEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):boolean} BooleanEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):number} NumberEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):string} StringEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):(Array<number>|string)} ColorLikeEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):Array<number>} NumberArrayEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):Array<number>} CoordinateEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):(Array<number>)} SizeEvaluator
   */

  /**
   * @typedef {function(EvaluationContext):(Array<number>|number)} SizeLikeEvaluator
   */

  /**
   * @param {import('./expression.js').EncodedExpression} encoded The encoded expression.
   * @param {number} type The expected type.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The expression evaluator.
   */
  function buildExpression$1(encoded, type, context) {
    const expression = parse$1(encoded, type, context);
    return compileExpression(expression);
  }

  /**
   * @param {import("./expression.js").Expression} expression The expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileExpression(expression, context) {
    if (expression instanceof LiteralExpression) {
      // convert colors to array if possible
      if (expression.type === ColorType$1 && typeof expression.value === 'string') {
        const colorValue = fromString(expression.value);
        return function () {
          return colorValue;
        };
      }
      return function () {
        return expression.value;
      };
    }
    const operator = expression.operator;
    switch (operator) {
      case Ops.Number:
      case Ops.String:
      case Ops.Coalesce: {
        return compileAssertionExpression(expression);
      }
      case Ops.Get:
      case Ops.Var:
      case Ops.Has: {
        return compileAccessorExpression(expression);
      }
      case Ops.Id: {
        return (context) => context.featureId;
      }
      case Ops.GeometryType: {
        return (context) => context.geometryType;
      }
      case Ops.Concat: {
        const args = expression.args.map((e) => compileExpression(e));
        return (context) =>
          ''.concat(...args.map((arg) => arg(context).toString()));
      }
      case Ops.Resolution: {
        return (context) => context.resolution;
      }
      case Ops.Any:
      case Ops.All:
      case Ops.Between:
      case Ops.In:
      case Ops.Not: {
        return compileLogicalExpression(expression);
      }
      case Ops.Equal:
      case Ops.NotEqual:
      case Ops.LessThan:
      case Ops.LessThanOrEqualTo:
      case Ops.GreaterThan:
      case Ops.GreaterThanOrEqualTo: {
        return compileComparisonExpression(expression);
      }
      case Ops.Multiply:
      case Ops.Divide:
      case Ops.Add:
      case Ops.Subtract:
      case Ops.Clamp:
      case Ops.Mod:
      case Ops.Pow:
      case Ops.Abs:
      case Ops.Floor:
      case Ops.Ceil:
      case Ops.Round:
      case Ops.Sin:
      case Ops.Cos:
      case Ops.Atan:
      case Ops.Sqrt: {
        return compileNumericExpression(expression);
      }
      case Ops.Case: {
        return compileCaseExpression(expression);
      }
      case Ops.Match: {
        return compileMatchExpression(expression);
      }
      case Ops.Interpolate: {
        return compileInterpolateExpression(expression);
      }
      case Ops.ToString: {
        return compileConvertExpression(expression);
      }
      default: {
        throw new Error(`Unsupported operator ${operator}`);
      }
      // TODO: unimplemented
      // Ops.Zoom
      // Ops.Time
      // Ops.Array
      // Ops.Color
      // Ops.Band
      // Ops.Palette
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileAssertionExpression(expression, context) {
    const type = expression.operator;
    const length = expression.args.length;

    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    switch (type) {
      case Ops.Coalesce: {
        return (context) => {
          for (let i = 0; i < length; ++i) {
            const value = args[i](context);
            if (typeof value !== 'undefined' && value !== null) {
              return value;
            }
          }
          throw new Error('Expected one of the values to be non-null');
        };
      }
      case Ops.Number:
      case Ops.String: {
        return (context) => {
          for (let i = 0; i < length; ++i) {
            const value = args[i](context);
            if (typeof value === type) {
              return value;
            }
          }
          throw new Error(`Expected one of the values to be a ${type}`);
        };
      }
      default: {
        throw new Error(`Unsupported assertion operator ${type}`);
      }
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileAccessorExpression(expression, context) {
    const nameExpression = /** @type {LiteralExpression} */ (expression.args[0]);
    const name = /** @type {string} */ (nameExpression.value);
    switch (expression.operator) {
      case Ops.Get: {
        return (context) => {
          const args = expression.args;
          let value = context.properties[name];
          for (let i = 1, ii = args.length; i < ii; ++i) {
            const keyExpression = /** @type {LiteralExpression} */ (args[i]);
            const key = /** @type {string|number} */ (keyExpression.value);
            value = value[key];
          }
          return value;
        };
      }
      case Ops.Var: {
        return (context) => context.variables[name];
      }
      case Ops.Has: {
        return (context) => {
          const args = expression.args;
          if (!(name in context.properties)) {
            return false;
          }
          let value = context.properties[name];
          for (let i = 1, ii = args.length; i < ii; ++i) {
            const keyExpression = /** @type {LiteralExpression} */ (args[i]);
            const key = /** @type {string|number} */ (keyExpression.value);
            if (!value || !Object.hasOwn(value, key)) {
              return false;
            }
            value = value[key];
          }
          return true;
        };
      }
      default: {
        throw new Error(`Unsupported accessor operator ${expression.operator}`);
      }
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {BooleanEvaluator} The evaluator function.
   */
  function compileComparisonExpression(expression, context) {
    const op = expression.operator;
    const left = compileExpression(expression.args[0]);
    const right = compileExpression(expression.args[1]);
    switch (op) {
      case Ops.Equal: {
        return (context) => left(context) === right(context);
      }
      case Ops.NotEqual: {
        return (context) => left(context) !== right(context);
      }
      case Ops.LessThan: {
        return (context) => left(context) < right(context);
      }
      case Ops.LessThanOrEqualTo: {
        return (context) => left(context) <= right(context);
      }
      case Ops.GreaterThan: {
        return (context) => left(context) > right(context);
      }
      case Ops.GreaterThanOrEqualTo: {
        return (context) => left(context) >= right(context);
      }
      default: {
        throw new Error(`Unsupported comparison operator ${op}`);
      }
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {BooleanEvaluator} The evaluator function.
   */
  function compileLogicalExpression(expression, context) {
    const op = expression.operator;
    const length = expression.args.length;

    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    switch (op) {
      case Ops.Any: {
        return (context) => {
          for (let i = 0; i < length; ++i) {
            if (args[i](context)) {
              return true;
            }
          }
          return false;
        };
      }
      case Ops.All: {
        return (context) => {
          for (let i = 0; i < length; ++i) {
            if (!args[i](context)) {
              return false;
            }
          }
          return true;
        };
      }
      case Ops.Between: {
        return (context) => {
          const value = args[0](context);
          const min = args[1](context);
          const max = args[2](context);
          return value >= min && value <= max;
        };
      }
      case Ops.In: {
        return (context) => {
          const value = args[0](context);
          for (let i = 1; i < length; ++i) {
            if (value === args[i](context)) {
              return true;
            }
          }
          return false;
        };
      }
      case Ops.Not: {
        return (context) => !args[0](context);
      }
      default: {
        throw new Error(`Unsupported logical operator ${op}`);
      }
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {NumberEvaluator} The evaluator function.
   */
  function compileNumericExpression(expression, context) {
    const op = expression.operator;
    const length = expression.args.length;

    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    switch (op) {
      case Ops.Multiply: {
        return (context) => {
          let value = 1;
          for (let i = 0; i < length; ++i) {
            value *= args[i](context);
          }
          return value;
        };
      }
      case Ops.Divide: {
        return (context) => args[0](context) / args[1](context);
      }
      case Ops.Add: {
        return (context) => {
          let value = 0;
          for (let i = 0; i < length; ++i) {
            value += args[i](context);
          }
          return value;
        };
      }
      case Ops.Subtract: {
        return (context) => args[0](context) - args[1](context);
      }
      case Ops.Clamp: {
        return (context) => {
          const value = args[0](context);
          const min = args[1](context);
          if (value < min) {
            return min;
          }
          const max = args[2](context);
          if (value > max) {
            return max;
          }
          return value;
        };
      }
      case Ops.Mod: {
        return (context) => args[0](context) % args[1](context);
      }
      case Ops.Pow: {
        return (context) => Math.pow(args[0](context), args[1](context));
      }
      case Ops.Abs: {
        return (context) => Math.abs(args[0](context));
      }
      case Ops.Floor: {
        return (context) => Math.floor(args[0](context));
      }
      case Ops.Ceil: {
        return (context) => Math.ceil(args[0](context));
      }
      case Ops.Round: {
        return (context) => Math.round(args[0](context));
      }
      case Ops.Sin: {
        return (context) => Math.sin(args[0](context));
      }
      case Ops.Cos: {
        return (context) => Math.cos(args[0](context));
      }
      case Ops.Atan: {
        if (length === 2) {
          return (context) => Math.atan2(args[0](context), args[1](context));
        }
        return (context) => Math.atan(args[0](context));
      }
      case Ops.Sqrt: {
        return (context) => Math.sqrt(args[0](context));
      }
      default: {
        throw new Error(`Unsupported numeric operator ${op}`);
      }
    }
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileCaseExpression(expression, context) {
    const length = expression.args.length;
    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    return (context) => {
      for (let i = 0; i < length - 1; i += 2) {
        const condition = args[i](context);
        if (condition) {
          return args[i + 1](context);
        }
      }
      return args[length - 1](context);
    };
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileMatchExpression(expression, context) {
    const length = expression.args.length;
    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    return (context) => {
      const value = args[0](context);
      for (let i = 1; i < length - 1; i += 2) {
        if (value === args[i](context)) {
          return args[i + 1](context);
        }
      }
      return args[length - 1](context);
    };
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileInterpolateExpression(expression, context) {
    const length = expression.args.length;
    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    return (context) => {
      const base = args[0](context);
      const value = args[1](context);

      let previousInput;
      let previousOutput;
      for (let i = 2; i < length; i += 2) {
        const input = args[i](context);
        let output = args[i + 1](context);
        const isColor = Array.isArray(output);
        if (isColor) {
          output = withAlpha(output);
        }
        if (input >= value) {
          if (i === 2) {
            return output;
          }
          if (isColor) {
            return interpolateColor(
              base,
              value,
              previousInput,
              previousOutput,
              input,
              output,
            );
          }
          return interpolateNumber$1(
            base,
            value,
            previousInput,
            previousOutput,
            input,
            output,
          );
        }
        previousInput = input;
        previousOutput = output;
      }
      return previousOutput;
    };
  }

  /**
   * @param {import('./expression.js').CallExpression} expression The call expression.
   * @param {import('./expression.js').ParsingContext} context The parsing context.
   * @return {ExpressionEvaluator} The evaluator function.
   */
  function compileConvertExpression(expression, context) {
    const op = expression.operator;
    const length = expression.args.length;

    const args = new Array(length);
    for (let i = 0; i < length; ++i) {
      args[i] = compileExpression(expression.args[i]);
    }
    switch (op) {
      case Ops.ToString: {
        return (context) => {
          const value = args[0](context);
          if (expression.args[0].type === ColorType$1) {
            return toString$1(value);
          }
          return value.toString();
        };
      }
      default: {
        throw new Error(`Unsupported convert operator ${op}`);
      }
    }
  }

  /**
   * @param {number} base The base.
   * @param {number} value The value.
   * @param {number} input1 The first input value.
   * @param {number} output1 The first output value.
   * @param {number} input2 The second input value.
   * @param {number} output2 The second output value.
   * @return {number} The interpolated value.
   */
  function interpolateNumber$1(base, value, input1, output1, input2, output2) {
    const delta = input2 - input1;
    if (delta === 0) {
      return output1;
    }
    const along = value - input1;
    const factor =
      base === 1
        ? along / delta
        : (Math.pow(base, along) - 1) / (Math.pow(base, delta) - 1);
    return output1 + factor * (output2 - output1);
  }

  /**
   * @param {number} base The base.
   * @param {number} value The value.
   * @param {number} input1 The first input value.
   * @param {import('../color.js').Color} rgba1 The first output value.
   * @param {number} input2 The second input value.
   * @param {import('../color.js').Color} rgba2 The second output value.
   * @return {import('../color.js').Color} The interpolated color.
   */
  function interpolateColor(base, value, input1, rgba1, input2, rgba2) {
    const delta = input2 - input1;
    if (delta === 0) {
      return rgba1;
    }
    const lcha1 = rgbaToLcha(rgba1);
    const lcha2 = rgbaToLcha(rgba2);
    let deltaHue = lcha2[2] - lcha1[2];
    if (deltaHue > 180) {
      deltaHue -= 360;
    } else if (deltaHue < -180) {
      deltaHue += 360;
    }

    const lcha = [
      interpolateNumber$1(base, value, input1, lcha1[0], input2, lcha2[0]),
      interpolateNumber$1(base, value, input1, lcha1[1], input2, lcha2[1]),
      lcha1[2] + interpolateNumber$1(base, value, input1, 0, input2, deltaHue),
      interpolateNumber$1(base, value, input1, rgba1[3], input2, rgba2[3]),
    ];
    return lchaToRgba(lcha);
  }

  /**
   * @module ol/render/canvas/style
   */


  /**
   * @fileoverview This module includes functions to build styles for the canvas renderer.  Building
   * is composed of two steps: parsing and compiling.  The parsing step takes an encoded expression
   * and returns an instance of one of the expression classes.  The compiling step takes the
   * expression instance and returns a function that can be evaluated to return a literal value.  The
   * evaluator function should do as little allocation and work as possible.
   */

  /**
   * @typedef {import("../../style/flat.js").FlatStyle} FlatStyle
   */

  /**
   * @typedef {import("../../expr/expression.js").EncodedExpression} EncodedExpression
   */

  /**
   * @typedef {import("../../expr/expression.js").ParsingContext} ParsingContext
   */

  /**
   * @typedef {import("../../expr/expression.js").CallExpression} CallExpression
   */

  /**
   * @typedef {import("../../expr/cpu.js").EvaluationContext} EvaluationContext
   */

  /**
   * @typedef {import("../../expr/cpu.js").ExpressionEvaluator} ExpressionEvaluator
   */

  /**
   * @param {EvaluationContext} context The evaluation context.
   * @return {boolean} Always true.
   */
  function always$1(context) {
    return true;
  }

  /**
   * This function adapts a rule evaluator to the existing style function interface.
   * After we have deprecated the style function, we can use the compiled rules directly
   * and pass a more complete evaluation context (variables, zoom, time, etc.).
   *
   * @param {Array<import('../../style/flat.js').Rule>} rules The rules.
   * @return {import('../../style/Style.js').StyleFunction} A style function.
   */
  function rulesToStyleFunction(rules) {
    const parsingContext = newParsingContext();
    const evaluator = buildRuleSet(rules, parsingContext);
    const evaluationContext = newEvaluationContext();
    return function (feature, resolution) {
      evaluationContext.properties = feature.getPropertiesInternal();
      evaluationContext.resolution = resolution;
      if (parsingContext.featureId) {
        const id = feature.getId();
        if (id !== undefined) {
          evaluationContext.featureId = id;
        } else {
          evaluationContext.featureId = null;
        }
      }
      if (parsingContext.geometryType) {
        evaluationContext.geometryType = computeGeometryType(
          feature.getGeometry(),
        );
      }
      return evaluator(evaluationContext);
    };
  }

  /**
   * This function adapts a style evaluator to the existing style function interface.
   * After we have deprecated the style function, we can use the compiled rules directly
   * and pass a more complete evaluation context (variables, zoom, time, etc.).
   *
   * @param {Array<import('../../style/flat.js').FlatStyle>} flatStyles The flat styles.
   * @return {import('../../style/Style.js').StyleFunction} A style function.
   */
  function flatStylesToStyleFunction(flatStyles) {
    const parsingContext = newParsingContext();
    const length = flatStyles.length;

    /**
     * @type {Array<StyleEvaluator>}
     */
    const evaluators = new Array(length);
    for (let i = 0; i < length; ++i) {
      evaluators[i] = buildStyle(flatStyles[i], parsingContext);
    }
    const evaluationContext = newEvaluationContext();

    /**
     * @type {Array<Style>}
     */
    const styles = new Array(length);

    return function (feature, resolution) {
      evaluationContext.properties = feature.getPropertiesInternal();
      evaluationContext.resolution = resolution;
      if (parsingContext.featureId) {
        const id = feature.getId();
        if (id !== undefined) {
          evaluationContext.featureId = id;
        } else {
          evaluationContext.featureId = null;
        }
      }
      let nonNullCount = 0;
      for (let i = 0; i < length; ++i) {
        const style = evaluators[i](evaluationContext);
        if (style) {
          styles[nonNullCount] = style;
          nonNullCount += 1;
        }
      }
      styles.length = nonNullCount;
      return styles;
    };
  }

  /**
   * @typedef {function(EvaluationContext):Array<Style>} RuleSetEvaluator
   */

  /**
   * @typedef {Object} CompiledRule
   * @property {ExpressionEvaluator} filter The compiled filter evaluator.
   * @property {Array<StyleEvaluator>} styles The list of compiled style evaluators.
   */

  /**
   * @param {Array<import('../../style/flat.js').Rule>} rules The rules.
   * @param {ParsingContext} context The parsing context.
   * @return {RuleSetEvaluator} The evaluator function.
   */
  function buildRuleSet(rules, context) {
    const length = rules.length;

    /**
     * @type {Array<CompiledRule>}
     */
    const compiledRules = new Array(length);

    for (let i = 0; i < length; ++i) {
      const rule = rules[i];
      const filter =
        'filter' in rule
          ? buildExpression$1(rule.filter, BooleanType$1, context)
          : always$1;

      /**
       * @type {Array<StyleEvaluator>}
       */
      let styles;
      if (Array.isArray(rule.style)) {
        const styleLength = rule.style.length;
        styles = new Array(styleLength);
        for (let j = 0; j < styleLength; ++j) {
          styles[j] = buildStyle(rule.style[j], context);
        }
      } else {
        styles = [buildStyle(rule.style, context)];
      }

      compiledRules[i] = {filter, styles};
    }

    return function (context) {
      /**
       * @type {Array<Style>}
       */
      const styles = [];

      let someMatched = false;
      for (let i = 0; i < length; ++i) {
        const filterEvaluator = compiledRules[i].filter;
        if (!filterEvaluator(context)) {
          continue;
        }
        if (rules[i].else && someMatched) {
          continue;
        }
        someMatched = true;
        for (const styleEvaluator of compiledRules[i].styles) {
          const style = styleEvaluator(context);
          if (!style) {
            continue;
          }
          styles.push(style);
        }
      }

      return styles;
    };
  }

  /**
   * @typedef {function(EvaluationContext):Style|null} StyleEvaluator
   */

  /**
   * @param {FlatStyle} flatStyle A flat style literal.
   * @param {ParsingContext} context The parsing context.
   * @return {StyleEvaluator} A function that evaluates to a style.  The style returned by
   * this function will be reused between invocations.
   */
  function buildStyle(flatStyle, context) {
    const evaluateFill = buildFill(flatStyle, '', context);
    const evaluateStroke = buildStroke(flatStyle, '', context);
    const evaluateText = buildText(flatStyle, context);
    const evaluateImage = buildImage(flatStyle, context);
    const evaluateZIndex = numberEvaluator(flatStyle, 'z-index', context);

    if (
      !evaluateFill &&
      !evaluateStroke &&
      !evaluateText &&
      !evaluateImage &&
      !isEmpty$1(flatStyle)
    ) {
      // assume this is a user error
      // would be nice to check the properties and suggest "did you mean..."
      throw new Error(
        'No fill, stroke, point, or text symbolizer properties in style: ' +
          JSON.stringify(flatStyle),
      );
    }

    const style = new Style();
    return function (context) {
      let empty = true;
      if (evaluateFill) {
        const fill = evaluateFill(context);
        if (fill) {
          empty = false;
        }
        style.setFill(fill);
      }
      if (evaluateStroke) {
        const stroke = evaluateStroke(context);
        if (stroke) {
          empty = false;
        }
        style.setStroke(stroke);
      }
      if (evaluateText) {
        const text = evaluateText(context);
        if (text) {
          empty = false;
        }
        style.setText(text);
      }
      if (evaluateImage) {
        const image = evaluateImage(context);
        if (image) {
          empty = false;
        }
        style.setImage(image);
      }
      if (evaluateZIndex) {
        style.setZIndex(evaluateZIndex(context));
      }
      if (empty) {
        return null;
      }
      return style;
    };
  }

  /**
   * @typedef {function(EvaluationContext):Fill|null} FillEvaluator
   */

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} prefix The property prefix.
   * @param {ParsingContext} context The parsing context.
   * @return {FillEvaluator?} A function that evaluates to a fill.
   */
  function buildFill(flatStyle, prefix, context) {
    let evaluateColor;
    if (prefix + 'fill-pattern-src' in flatStyle) {
      evaluateColor = patternEvaluator(flatStyle, prefix + 'fill-', context);
    } else {
      if (flatStyle[prefix + 'fill-color'] === 'none') {
        // avoids hit detection
        return (context) => null;
      }

      evaluateColor = colorLikeEvaluator(
        flatStyle,
        prefix + 'fill-color',
        context,
      );
    }
    if (!evaluateColor) {
      return null;
    }

    const fill = new Fill();
    return function (context) {
      const color = evaluateColor(context);
      if (color === NO_COLOR) {
        return null;
      }
      fill.setColor(color);
      return fill;
    };
  }

  /**
   * @typedef {function(EvaluationContext):Stroke|null} StrokeEvaluator
   */

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} prefix The property prefix.
   * @param {ParsingContext} context The parsing context.
   * @return {StrokeEvaluator?} A function the evaluates to a stroke.
   */
  function buildStroke(flatStyle, prefix, context) {
    const evaluateWidth = numberEvaluator(
      flatStyle,
      prefix + 'stroke-width',
      context,
    );

    const evaluateColor = colorLikeEvaluator(
      flatStyle,
      prefix + 'stroke-color',
      context,
    );

    if (!evaluateWidth && !evaluateColor) {
      return null;
    }

    const evaluateLineCap = stringEvaluator(
      flatStyle,
      prefix + 'stroke-line-cap',
      context,
    );

    const evaluateLineJoin = stringEvaluator(
      flatStyle,
      prefix + 'stroke-line-join',
      context,
    );

    const evaluateLineDash = numberArrayEvaluator(
      flatStyle,
      prefix + 'stroke-line-dash',
      context,
    );

    const evaluateLineDashOffset = numberEvaluator(
      flatStyle,
      prefix + 'stroke-line-dash-offset',
      context,
    );

    const evaluateMiterLimit = numberEvaluator(
      flatStyle,
      prefix + 'stroke-miter-limit',
      context,
    );

    const stroke = new Stroke();
    return function (context) {
      if (evaluateColor) {
        const color = evaluateColor(context);
        if (color === NO_COLOR) {
          return null;
        }
        stroke.setColor(color);
      }

      if (evaluateWidth) {
        stroke.setWidth(evaluateWidth(context));
      }

      if (evaluateLineCap) {
        const lineCap = evaluateLineCap(context);
        if (lineCap !== 'butt' && lineCap !== 'round' && lineCap !== 'square') {
          throw new Error('Expected butt, round, or square line cap');
        }
        stroke.setLineCap(lineCap);
      }

      if (evaluateLineJoin) {
        const lineJoin = evaluateLineJoin(context);
        if (
          lineJoin !== 'bevel' &&
          lineJoin !== 'round' &&
          lineJoin !== 'miter'
        ) {
          throw new Error('Expected bevel, round, or miter line join');
        }
        stroke.setLineJoin(lineJoin);
      }

      if (evaluateLineDash) {
        stroke.setLineDash(evaluateLineDash(context));
      }

      if (evaluateLineDashOffset) {
        stroke.setLineDashOffset(evaluateLineDashOffset(context));
      }

      if (evaluateMiterLimit) {
        stroke.setMiterLimit(evaluateMiterLimit(context));
      }

      return stroke;
    };
  }

  /**
   * @typedef {function(EvaluationContext):Text} TextEvaluator
   */

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {ParsingContext} context The parsing context.
   * @return {TextEvaluator?} A function that evaluates to a text symbolizer.
   */
  function buildText(flatStyle, context) {
    const prefix = 'text-';

    // Currently, an Array<string> may be used for rich text support.  This doesn't
    // work with our expression syntax where arrays of strings are interpreted as
    // call expressions.  To support rich text, we could add a 'strings' operator
    // where all the following arguments would be string values.
    const evaluateValue = stringEvaluator(flatStyle, prefix + 'value', context);
    if (!evaluateValue) {
      return null;
    }

    const evaluateFill = buildFill(flatStyle, prefix, context);

    const evaluateBackgroundFill = buildFill(
      flatStyle,
      prefix + 'background-',
      context,
    );

    const evaluateStroke = buildStroke(flatStyle, prefix, context);

    const evaluateBackgroundStroke = buildStroke(
      flatStyle,
      prefix + 'background-',
      context,
    );

    const evaluateFont = stringEvaluator(flatStyle, prefix + 'font', context);

    const evaluateMaxAngle = numberEvaluator(
      flatStyle,
      prefix + 'max-angle',
      context,
    );

    const evaluateOffsetX = numberEvaluator(
      flatStyle,
      prefix + 'offset-x',
      context,
    );

    const evaluateOffsetY = numberEvaluator(
      flatStyle,
      prefix + 'offset-y',
      context,
    );

    const evaluateOverflow = booleanEvaluator(
      flatStyle,
      prefix + 'overflow',
      context,
    );

    const evaluatePlacement = stringEvaluator(
      flatStyle,
      prefix + 'placement',
      context,
    );

    const evaluateRepeat = numberEvaluator(flatStyle, prefix + 'repeat', context);

    const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);

    const evaluateRotateWithView = booleanEvaluator(
      flatStyle,
      prefix + 'rotate-with-view',
      context,
    );

    const evaluateRotation = numberEvaluator(
      flatStyle,
      prefix + 'rotation',
      context,
    );

    const evaluateAlign = stringEvaluator(flatStyle, prefix + 'align', context);

    const evaluateJustify = stringEvaluator(
      flatStyle,
      prefix + 'justify',
      context,
    );

    const evaluateBaseline = stringEvaluator(
      flatStyle,
      prefix + 'baseline',
      context,
    );

    const evaluateKeepUpright = booleanEvaluator(
      flatStyle,
      prefix + 'keep-upright',
      context,
    );

    const evaluatePadding = numberArrayEvaluator(
      flatStyle,
      prefix + 'padding',
      context,
    );

    // The following properties are not currently settable
    const declutterMode = optionalDeclutterMode(
      flatStyle,
      prefix + 'declutter-mode',
    );

    const text = new Text({declutterMode});

    return function (context) {
      text.setText(evaluateValue(context));

      if (evaluateFill) {
        text.setFill(evaluateFill(context));
      }

      if (evaluateBackgroundFill) {
        text.setBackgroundFill(evaluateBackgroundFill(context));
      }

      if (evaluateStroke) {
        text.setStroke(evaluateStroke(context));
      }

      if (evaluateBackgroundStroke) {
        text.setBackgroundStroke(evaluateBackgroundStroke(context));
      }

      if (evaluateFont) {
        text.setFont(evaluateFont(context));
      }

      if (evaluateMaxAngle) {
        text.setMaxAngle(evaluateMaxAngle(context));
      }

      if (evaluateOffsetX) {
        text.setOffsetX(evaluateOffsetX(context));
      }

      if (evaluateOffsetY) {
        text.setOffsetY(evaluateOffsetY(context));
      }

      if (evaluateOverflow) {
        text.setOverflow(evaluateOverflow(context));
      }

      if (evaluatePlacement) {
        const placement = evaluatePlacement(context);
        if (placement !== 'point' && placement !== 'line') {
          throw new Error('Expected point or line for text-placement');
        }
        text.setPlacement(placement);
      }

      if (evaluateRepeat) {
        text.setRepeat(evaluateRepeat(context));
      }

      if (evaluateScale) {
        text.setScale(evaluateScale(context));
      }

      if (evaluateRotateWithView) {
        text.setRotateWithView(evaluateRotateWithView(context));
      }

      if (evaluateRotation) {
        text.setRotation(evaluateRotation(context));
      }

      if (evaluateAlign) {
        const textAlign = evaluateAlign(context);
        if (
          textAlign !== 'left' &&
          textAlign !== 'center' &&
          textAlign !== 'right' &&
          textAlign !== 'end' &&
          textAlign !== 'start'
        ) {
          throw new Error(
            'Expected left, right, center, start, or end for text-align',
          );
        }
        text.setTextAlign(textAlign);
      }

      if (evaluateJustify) {
        const justify = evaluateJustify(context);
        if (justify !== 'left' && justify !== 'right' && justify !== 'center') {
          throw new Error('Expected left, right, or center for text-justify');
        }
        text.setJustify(justify);
      }

      if (evaluateBaseline) {
        const textBaseline = evaluateBaseline(context);
        if (
          textBaseline !== 'bottom' &&
          textBaseline !== 'top' &&
          textBaseline !== 'middle' &&
          textBaseline !== 'alphabetic' &&
          textBaseline !== 'hanging'
        ) {
          throw new Error(
            'Expected bottom, top, middle, alphabetic, or hanging for text-baseline',
          );
        }
        text.setTextBaseline(textBaseline);
      }

      if (evaluatePadding) {
        text.setPadding(evaluatePadding(context));
      }

      if (evaluateKeepUpright) {
        text.setKeepUpright(evaluateKeepUpright(context));
      }

      return text;
    };
  }

  /**
   * @typedef {function(EvaluationContext):import("../../style/Image.js").default} ImageEvaluator
   */

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {ParsingContext} context The parsing context.
   * @return {ImageEvaluator?} A function that evaluates to an image symbolizer.
   */
  function buildImage(flatStyle, context) {
    if ('icon-src' in flatStyle) {
      return buildIcon(flatStyle, context);
    }

    if ('shape-points' in flatStyle) {
      return buildShape(flatStyle, context);
    }

    if ('circle-radius' in flatStyle) {
      return buildCircle(flatStyle, context);
    }

    return null;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {ParsingContext} context The parsing context.
   * @return {ImageEvaluator} A function that evaluates to an image symbolizer.
   */
  function buildIcon(flatStyle, context) {
    const prefix = 'icon-';

    // required property
    const srcName = prefix + 'src';
    const src = requireString(flatStyle[srcName], srcName);

    // settable properties
    const evaluateAnchor = coordinateEvaluator(
      flatStyle,
      prefix + 'anchor',
      context,
    );

    const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);

    const evaluateOpacity = numberEvaluator(
      flatStyle,
      prefix + 'opacity',
      context,
    );

    const evaluateDisplacement = coordinateEvaluator(
      flatStyle,
      prefix + 'displacement',
      context,
    );

    const evaluateRotation = numberEvaluator(
      flatStyle,
      prefix + 'rotation',
      context,
    );

    const evaluateRotateWithView = booleanEvaluator(
      flatStyle,
      prefix + 'rotate-with-view',
      context,
    );

    // the remaining symbolizer properties are not currently settable
    const anchorOrigin = optionalIconOrigin(flatStyle, prefix + 'anchor-origin');
    const anchorXUnits = optionalIconAnchorUnits(
      flatStyle,
      prefix + 'anchor-x-units',
    );
    const anchorYUnits = optionalIconAnchorUnits(
      flatStyle,
      prefix + 'anchor-y-units',
    );
    const color = optionalColorLike(flatStyle, prefix + 'color');
    const crossOrigin = optionalString(flatStyle, prefix + 'cross-origin');
    const offset = optionalNumberArray(flatStyle, prefix + 'offset');
    const offsetOrigin = optionalIconOrigin(flatStyle, prefix + 'offset-origin');
    const width = optionalNumber(flatStyle, prefix + 'width');
    const height = optionalNumber(flatStyle, prefix + 'height');
    const size = optionalSize(flatStyle, prefix + 'size');
    const declutterMode = optionalDeclutterMode(
      flatStyle,
      prefix + 'declutter-mode',
    );

    const icon = new Icon({
      src,
      anchorOrigin,
      anchorXUnits,
      anchorYUnits,
      color,
      crossOrigin,
      offset,
      offsetOrigin,
      height,
      width,
      size,
      declutterMode,
    });

    return function (context) {
      if (evaluateOpacity) {
        icon.setOpacity(evaluateOpacity(context));
      }

      if (evaluateDisplacement) {
        icon.setDisplacement(evaluateDisplacement(context));
      }

      if (evaluateRotation) {
        icon.setRotation(evaluateRotation(context));
      }

      if (evaluateRotateWithView) {
        icon.setRotateWithView(evaluateRotateWithView(context));
      }

      if (evaluateScale) {
        icon.setScale(evaluateScale(context));
      }

      if (evaluateAnchor) {
        icon.setAnchor(evaluateAnchor(context));
      }
      return icon;
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {ParsingContext} context The parsing context.
   * @return {ImageEvaluator} A function that evaluates to an icon symbolizer.
   */
  function buildShape(flatStyle, context) {
    const prefix = 'shape-';

    // required property
    const pointsName = prefix + 'points';
    const radiusName = prefix + 'radius';
    const points = requireNumber(flatStyle[pointsName], pointsName);
    const radius = requireNumber(flatStyle[radiusName], radiusName);

    // settable properties
    const evaluateFill = buildFill(flatStyle, prefix, context);
    const evaluateStroke = buildStroke(flatStyle, prefix, context);
    const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);
    const evaluateDisplacement = coordinateEvaluator(
      flatStyle,
      prefix + 'displacement',
      context,
    );
    const evaluateRotation = numberEvaluator(
      flatStyle,
      prefix + 'rotation',
      context,
    );
    const evaluateRotateWithView = booleanEvaluator(
      flatStyle,
      prefix + 'rotate-with-view',
      context,
    );

    // the remaining properties are not currently settable
    const radius2 = optionalNumber(flatStyle, prefix + 'radius2');
    const angle = optionalNumber(flatStyle, prefix + 'angle');
    const declutterMode = optionalDeclutterMode(
      flatStyle,
      prefix + 'declutter-mode',
    );

    const shape = new RegularShape({
      points,
      radius,
      radius2,
      angle,
      declutterMode,
    });

    return function (context) {
      if (evaluateFill) {
        shape.setFill(evaluateFill(context));
      }
      if (evaluateStroke) {
        shape.setStroke(evaluateStroke(context));
      }
      if (evaluateDisplacement) {
        shape.setDisplacement(evaluateDisplacement(context));
      }
      if (evaluateRotation) {
        shape.setRotation(evaluateRotation(context));
      }
      if (evaluateRotateWithView) {
        shape.setRotateWithView(evaluateRotateWithView(context));
      }
      if (evaluateScale) {
        shape.setScale(evaluateScale(context));
      }

      return shape;
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {ParsingContext} context The parsing context.
   * @return {ImageEvaluator} A function that evaluates to a circle symbolizer.
   */
  function buildCircle(flatStyle, context) {
    const prefix = 'circle-';

    // settable properties
    const evaluateFill = buildFill(flatStyle, prefix, context);
    const evaluateStroke = buildStroke(flatStyle, prefix, context);
    const evaluateRadius = numberEvaluator(flatStyle, prefix + 'radius', context);
    const evaluateScale = sizeLikeEvaluator(flatStyle, prefix + 'scale', context);
    const evaluateDisplacement = coordinateEvaluator(
      flatStyle,
      prefix + 'displacement',
      context,
    );
    const evaluateRotation = numberEvaluator(
      flatStyle,
      prefix + 'rotation',
      context,
    );
    const evaluateRotateWithView = booleanEvaluator(
      flatStyle,
      prefix + 'rotate-with-view',
      context,
    );

    // the remaining properties are not currently settable
    const declutterMode = optionalDeclutterMode(
      flatStyle,
      prefix + 'declutter-mode',
    );

    const circle = new CircleStyle({
      radius: 5, // this is arbitrary, but required - the evaluated radius is used below
      declutterMode,
    });

    return function (context) {
      if (evaluateRadius) {
        circle.setRadius(evaluateRadius(context));
      }
      if (evaluateFill) {
        circle.setFill(evaluateFill(context));
      }
      if (evaluateStroke) {
        circle.setStroke(evaluateStroke(context));
      }
      if (evaluateDisplacement) {
        circle.setDisplacement(evaluateDisplacement(context));
      }
      if (evaluateRotation) {
        circle.setRotation(evaluateRotation(context));
      }
      if (evaluateRotateWithView) {
        circle.setRotateWithView(evaluateRotateWithView(context));
      }
      if (evaluateScale) {
        circle.setScale(evaluateScale(context));
      }

      return circle;
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').NumberEvaluator|undefined} The expression evaluator or undefined.
   */
  function numberEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return undefined;
    }
    const evaluator = buildExpression$1(flatStyle[name], NumberType$1, context);
    return function (context) {
      return requireNumber(evaluator(context), name);
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').StringEvaluator?} The expression evaluator.
   */
  function stringEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], StringType$1, context);
    return function (context) {
      return requireString(evaluator(context), name);
    };
  }

  function patternEvaluator(flatStyle, prefix, context) {
    const srcEvaluator = stringEvaluator(
      flatStyle,
      prefix + 'pattern-src',
      context,
    );
    const offsetEvaluator = sizeEvaluator(
      flatStyle,
      prefix + 'pattern-offset',
      context,
    );
    const patternSizeEvaluator = sizeEvaluator(
      flatStyle,
      prefix + 'pattern-size',
      context,
    );
    const colorEvaluator = colorLikeEvaluator(
      flatStyle,
      prefix + 'color',
      context,
    );
    return function (context) {
      return {
        src: srcEvaluator(context),
        offset: offsetEvaluator && offsetEvaluator(context),
        size: patternSizeEvaluator && patternSizeEvaluator(context),
        color: colorEvaluator && colorEvaluator(context),
      };
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').BooleanEvaluator?} The expression evaluator.
   */
  function booleanEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], BooleanType$1, context);
    return function (context) {
      const value = evaluator(context);
      if (typeof value !== 'boolean') {
        throw new Error(`Expected a boolean for ${name}`);
      }
      return value;
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').ColorLikeEvaluator?} The expression evaluator.
   */
  function colorLikeEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], ColorType$1, context);
    return function (context) {
      return requireColorLike(evaluator(context), name);
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').NumberArrayEvaluator?} The expression evaluator.
   */
  function numberArrayEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], NumberArrayType$1, context);
    return function (context) {
      return requireNumberArray(evaluator(context), name);
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').CoordinateEvaluator?} The expression evaluator.
   */
  function coordinateEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], NumberArrayType$1, context);
    return function (context) {
      const array = requireNumberArray(evaluator(context), name);
      if (array.length !== 2) {
        throw new Error(`Expected two numbers for ${name}`);
      }
      return array;
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').SizeEvaluator?} The expression evaluator.
   */
  function sizeEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(flatStyle[name], NumberArrayType$1, context);
    return function (context) {
      return requireSize(evaluator(context), name);
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} name The property name.
   * @param {ParsingContext} context The parsing context.
   * @return {import('../../expr/cpu.js').SizeLikeEvaluator?} The expression evaluator.
   */
  function sizeLikeEvaluator(flatStyle, name, context) {
    if (!(name in flatStyle)) {
      return null;
    }
    const evaluator = buildExpression$1(
      flatStyle[name],
      NumberArrayType$1 | NumberType$1,
      context,
    );
    return function (context) {
      return requireSizeLike(evaluator(context), name);
    };
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {number|undefined} A number or undefined.
   */
  function optionalNumber(flatStyle, property) {
    const value = flatStyle[property];
    if (value === undefined) {
      return undefined;
    }
    if (typeof value !== 'number') {
      throw new Error(`Expected a number for ${property}`);
    }
    return value;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {import("../../size.js").Size|undefined} A size or undefined.
   */
  function optionalSize(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    if (typeof encoded === 'number') {
      return toSize(encoded);
    }
    if (!Array.isArray(encoded)) {
      throw new Error(`Expected a number or size array for ${property}`);
    }
    if (
      encoded.length !== 2 ||
      typeof encoded[0] !== 'number' ||
      typeof encoded[1] !== 'number'
    ) {
      throw new Error(`Expected a number or size array for ${property}`);
    }
    return encoded;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {string|undefined} A string or undefined.
   */
  function optionalString(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    if (typeof encoded !== 'string') {
      throw new Error(`Expected a string for ${property}`);
    }
    return encoded;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {import("../../style/Icon.js").IconOrigin|undefined} An icon origin or undefined.
   */
  function optionalIconOrigin(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    if (
      encoded !== 'bottom-left' &&
      encoded !== 'bottom-right' &&
      encoded !== 'top-left' &&
      encoded !== 'top-right'
    ) {
      throw new Error(
        `Expected bottom-left, bottom-right, top-left, or top-right for ${property}`,
      );
    }
    return encoded;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {import("../../style/Icon.js").IconAnchorUnits|undefined} Icon anchor units or undefined.
   */
  function optionalIconAnchorUnits(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    if (encoded !== 'pixels' && encoded !== 'fraction') {
      throw new Error(`Expected pixels or fraction for ${property}`);
    }
    return encoded;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {Array<number>|undefined} An array of numbers or undefined.
   */
  function optionalNumberArray(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    return requireNumberArray(encoded, property);
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {import('../../style/Style.js').DeclutterMode} Icon declutter mode.
   */
  function optionalDeclutterMode(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    if (typeof encoded !== 'string') {
      throw new Error(`Expected a string for ${property}`);
    }
    if (encoded !== 'declutter' && encoded !== 'obstacle' && encoded !== 'none') {
      throw new Error(`Expected declutter, obstacle, or none for ${property}`);
    }
    return encoded;
  }

  /**
   * @param {FlatStyle} flatStyle The flat style.
   * @param {string} property The symbolizer property.
   * @return {string|Array<number>|undefined} A string or an array of color values or undefined.
   */
  function optionalColorLike(flatStyle, property) {
    const encoded = flatStyle[property];
    if (encoded === undefined) {
      return undefined;
    }
    return requireColorLike(encoded, property);
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {Array<number>} An array of numbers.
   */
  function requireNumberArray(value, property) {
    if (!Array.isArray(value)) {
      throw new Error(`Expected an array for ${property}`);
    }
    const length = value.length;
    for (let i = 0; i < length; ++i) {
      if (typeof value[i] !== 'number') {
        throw new Error(`Expected an array of numbers for ${property}`);
      }
    }
    return value;
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {string} A string.
   */
  function requireString(value, property) {
    if (typeof value !== 'string') {
      throw new Error(`Expected a string for ${property}`);
    }
    return value;
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {number} A number.
   */
  function requireNumber(value, property) {
    if (typeof value !== 'number') {
      throw new Error(`Expected a number for ${property}`);
    }
    return value;
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {Array<number>|string} A color.
   */
  function requireColorLike(value, property) {
    if (typeof value === 'string') {
      return value;
    }
    const array = requireNumberArray(value, property);
    const length = array.length;
    if (length < 3 || length > 4) {
      throw new Error(`Expected a color with 3 or 4 values for ${property}`);
    }
    return array;
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {Array<number>} A number or an array of two numbers.
   */
  function requireSize(value, property) {
    const size = requireNumberArray(value, property);
    if (size.length !== 2) {
      throw new Error(`Expected an array of two numbers for ${property}`);
    }
    return size;
  }

  /**
   * @param {any} value The value.
   * @param {string} property The property.
   * @return {number|Array<number>} A number or an array of two numbers.
   */
  function requireSizeLike(value, property) {
    if (typeof value === 'number') {
      return value;
    }
    return requireSize(value, property);
  }

  /**
   * @module ol/ViewProperty
   */

  /**
   * @enum {string}
   */
  var ViewProperty = {
    CENTER: 'center',
    RESOLUTION: 'resolution',
    ROTATION: 'rotation',
  };

  /**
   * @module ol/centerconstraint
   */

  /**
   * @typedef {function((import("./coordinate.js").Coordinate|undefined), number, import("./size.js").Size, boolean=, Array<number>=): (import("./coordinate.js").Coordinate|undefined)} Type
   */

  /**
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {boolean} onlyCenter If true, the constraint will only apply to the view center.
   * @param {boolean} smooth If true, the view will be able to go slightly out of the given extent
   * (only during interaction and animation).
   * @return {Type} The constraint.
   */
  function createExtent(extent, onlyCenter, smooth) {
    return (
      /**
       * @param {import("./coordinate.js").Coordinate|undefined} center Center.
       * @param {number|undefined} resolution Resolution.
       * @param {import("./size.js").Size} size Viewport size; unused if `onlyCenter` was specified.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @param {Array<number>} [centerShift] Shift between map center and viewport center.
       * @return {import("./coordinate.js").Coordinate|undefined} Center.
       */
      function (center, resolution, size, isMoving, centerShift) {
        if (!center) {
          return undefined;
        }
        if (!resolution && !onlyCenter) {
          return center;
        }
        const viewWidth = onlyCenter ? 0 : size[0] * resolution;
        const viewHeight = onlyCenter ? 0 : size[1] * resolution;
        const shiftX = centerShift ? centerShift[0] : 0;
        const shiftY = centerShift ? centerShift[1] : 0;
        let minX = extent[0] + viewWidth / 2 + shiftX;
        let maxX = extent[2] - viewWidth / 2 + shiftX;
        let minY = extent[1] + viewHeight / 2 + shiftY;
        let maxY = extent[3] - viewHeight / 2 + shiftY;

        // note: when zooming out of bounds, min and max values for x and y may
        // end up inverted (min > max); this has to be accounted for
        if (minX > maxX) {
          minX = (maxX + minX) / 2;
          maxX = minX;
        }
        if (minY > maxY) {
          minY = (maxY + minY) / 2;
          maxY = minY;
        }

        let x = clamp$1(center[0], minX, maxX);
        let y = clamp$1(center[1], minY, maxY);

        // during an interaction, allow some overscroll
        if (isMoving && smooth && resolution) {
          const ratio = 30 * resolution;
          x +=
            -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) +
            ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio);
          y +=
            -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) +
            ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio);
        }

        return [x, y];
      }
    );
  }

  /**
   * @param {import("./coordinate.js").Coordinate} [center] Center.
   * @return {import("./coordinate.js").Coordinate|undefined} Center.
   */
  function none$1(center) {
    return center;
  }

  /**
   * @module ol/easing
   */

  /**
   * Start slow and speed up.
   * @param {number} t Input between 0 and 1.
   * @return {number} Output between 0 and 1.
   * @api
   */
  function easeIn(t) {
    return Math.pow(t, 3);
  }

  /**
   * Start fast and slow down.
   * @param {number} t Input between 0 and 1.
   * @return {number} Output between 0 and 1.
   * @api
   */
  function easeOut(t) {
    return 1 - easeIn(1 - t);
  }

  /**
   * Start slow, speed up, and then slow down again.
   * @param {number} t Input between 0 and 1.
   * @return {number} Output between 0 and 1.
   * @api
   */
  function inAndOut(t) {
    return 3 * t * t - 2 * t * t * t;
  }

  /**
   * Maintain a constant speed over time.
   * @param {number} t Input between 0 and 1.
   * @return {number} Output between 0 and 1.
   * @api
   */
  function linear(t) {
    return t;
  }

  /**
   * @module ol/resolutionconstraint
   */

  /**
   * @typedef {function((number|undefined), number, import("./size.js").Size, boolean=): (number|undefined)} Type
   */

  /**
   * Returns a modified resolution taking into account the viewport size and maximum
   * allowed extent.
   * @param {number} resolution Resolution
   * @param {import("./extent.js").Extent} maxExtent Maximum allowed extent.
   * @param {import("./size.js").Size} viewportSize Viewport size.
   * @param {boolean} showFullExtent Whether to show the full extent.
   * @return {number} Capped resolution.
   */
  function getViewportClampedResolution(
    resolution,
    maxExtent,
    viewportSize,
    showFullExtent,
  ) {
    const xResolution = getWidth(maxExtent) / viewportSize[0];
    const yResolution = getHeight(maxExtent) / viewportSize[1];

    if (showFullExtent) {
      return Math.min(resolution, Math.max(xResolution, yResolution));
    }
    return Math.min(resolution, Math.min(xResolution, yResolution));
  }

  /**
   * Returns a modified resolution to be between maxResolution and minResolution while
   * still allowing the value to be slightly out of bounds.
   * Note: the computation is based on the logarithm function (ln):
   *  - at 1, ln(x) is 0
   *  - above 1, ln(x) keeps increasing but at a much slower pace than x
   * The final result is clamped to prevent getting too far away from bounds.
   * @param {number} resolution Resolution.
   * @param {number} maxResolution Max resolution.
   * @param {number} minResolution Min resolution.
   * @return {number} Smoothed resolution.
   */
  function getSmoothClampedResolution(resolution, maxResolution, minResolution) {
    let result = Math.min(resolution, maxResolution);
    const ratio = 50;

    result *=
      Math.log(1 + ratio * Math.max(0, resolution / maxResolution - 1)) / ratio +
      1;
    if (minResolution) {
      result = Math.max(result, minResolution);
      result /=
        Math.log(1 + ratio * Math.max(0, minResolution / resolution - 1)) /
          ratio +
        1;
    }
    return clamp$1(result, minResolution / 2, maxResolution * 2);
  }

  /**
   * @param {Array<number>} resolutions Resolutions.
   * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.
   * @param {import("./extent.js").Extent} [maxExtent] Maximum allowed extent.
   * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.
   * @return {Type} Zoom function.
   */
  function createSnapToResolutions(
    resolutions,
    smooth,
    maxExtent,
    showFullExtent,
  ) {
    smooth = smooth !== undefined ? smooth : true;
    return (
      /**
       * @param {number|undefined} resolution Resolution.
       * @param {number} direction Direction.
       * @param {import("./size.js").Size} size Viewport size.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @return {number|undefined} Resolution.
       */
      function (resolution, direction, size, isMoving) {
        if (resolution !== undefined) {
          const maxResolution = resolutions[0];
          const minResolution = resolutions[resolutions.length - 1];
          const cappedMaxRes = maxExtent
            ? getViewportClampedResolution(
                maxResolution,
                maxExtent,
                size,
                showFullExtent,
              )
            : maxResolution;

          // during interacting or animating, allow intermediary values
          if (isMoving) {
            if (!smooth) {
              return clamp$1(resolution, minResolution, cappedMaxRes);
            }
            return getSmoothClampedResolution(
              resolution,
              cappedMaxRes,
              minResolution,
            );
          }

          const capped = Math.min(cappedMaxRes, resolution);
          const z = Math.floor(linearFindNearest(resolutions, capped, direction));
          if (resolutions[z] > cappedMaxRes && z < resolutions.length - 1) {
            return resolutions[z + 1];
          }
          return resolutions[z];
        }
        return undefined;
      }
    );
  }

  /**
   * @param {number} power Power.
   * @param {number} maxResolution Maximum resolution.
   * @param {number} [minResolution] Minimum resolution.
   * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.
   * @param {import("./extent.js").Extent} [maxExtent] Maximum allowed extent.
   * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.
   * @return {Type} Zoom function.
   */
  function createSnapToPower(
    power,
    maxResolution,
    minResolution,
    smooth,
    maxExtent,
    showFullExtent,
  ) {
    smooth = smooth !== undefined ? smooth : true;
    minResolution = minResolution !== undefined ? minResolution : 0;

    return (
      /**
       * @param {number|undefined} resolution Resolution.
       * @param {number} direction Direction.
       * @param {import("./size.js").Size} size Viewport size.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @return {number|undefined} Resolution.
       */
      function (resolution, direction, size, isMoving) {
        if (resolution !== undefined) {
          const cappedMaxRes = maxExtent
            ? getViewportClampedResolution(
                maxResolution,
                maxExtent,
                size,
                showFullExtent,
              )
            : maxResolution;

          // during interacting or animating, allow intermediary values
          if (isMoving) {
            if (!smooth) {
              return clamp$1(resolution, minResolution, cappedMaxRes);
            }
            return getSmoothClampedResolution(
              resolution,
              cappedMaxRes,
              minResolution,
            );
          }

          const tolerance = 1e-9;
          const minZoomLevel = Math.ceil(
            Math.log(maxResolution / cappedMaxRes) / Math.log(power) - tolerance,
          );
          const offset = -direction * (0.5 - tolerance) + 0.5;
          const capped = Math.min(cappedMaxRes, resolution);
          const cappedZoomLevel = Math.floor(
            Math.log(maxResolution / capped) / Math.log(power) + offset,
          );
          const zoomLevel = Math.max(minZoomLevel, cappedZoomLevel);
          const newResolution = maxResolution / Math.pow(power, zoomLevel);
          return clamp$1(newResolution, minResolution, cappedMaxRes);
        }
        return undefined;
      }
    );
  }

  /**
   * @param {number} maxResolution Max resolution.
   * @param {number} minResolution Min resolution.
   * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.
   * @param {import("./extent.js").Extent} [maxExtent] Maximum allowed extent.
   * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.
   * @return {Type} Zoom function.
   */
  function createMinMaxResolution(
    maxResolution,
    minResolution,
    smooth,
    maxExtent,
    showFullExtent,
  ) {
    smooth = smooth !== undefined ? smooth : true;

    return (
      /**
       * @param {number|undefined} resolution Resolution.
       * @param {number} direction Direction.
       * @param {import("./size.js").Size} size Viewport size.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @return {number|undefined} Resolution.
       */
      function (resolution, direction, size, isMoving) {
        if (resolution !== undefined) {
          const cappedMaxRes = maxExtent
            ? getViewportClampedResolution(
                maxResolution,
                maxExtent,
                size,
                showFullExtent,
              )
            : maxResolution;

          if (!smooth || !isMoving) {
            return clamp$1(resolution, minResolution, cappedMaxRes);
          }
          return getSmoothClampedResolution(
            resolution,
            cappedMaxRes,
            minResolution,
          );
        }
        return undefined;
      }
    );
  }

  /**
   * @module ol/rotationconstraint
   */

  /**
   * @typedef {function((number|undefined), boolean=): (number|undefined)} Type
   */

  /**
   * @param {number|undefined} rotation Rotation.
   * @return {number|undefined} Rotation.
   */
  function disable(rotation) {
    if (rotation !== undefined) {
      return 0;
    }
    return undefined;
  }

  /**
   * @param {number|undefined} rotation Rotation.
   * @return {number|undefined} Rotation.
   */
  function none(rotation) {
    if (rotation !== undefined) {
      return rotation;
    }
    return undefined;
  }

  /**
   * @param {number} n N.
   * @return {Type} Rotation constraint.
   */
  function createSnapToN(n) {
    const theta = (2 * Math.PI) / n;
    return (
      /**
       * @param {number|undefined} rotation Rotation.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @return {number|undefined} Rotation.
       */
      function (rotation, isMoving) {
        if (isMoving) {
          return rotation;
        }

        if (rotation !== undefined) {
          rotation = Math.floor(rotation / theta + 0.5) * theta;
          return rotation;
        }
        return undefined;
      }
    );
  }

  /**
   * @param {number} [tolerance] Tolerance.
   * @return {Type} Rotation constraint.
   */
  function createSnapToZero(tolerance) {
    const t = toRadians(5) ;
    return (
      /**
       * @param {number|undefined} rotation Rotation.
       * @param {boolean} [isMoving] True if an interaction or animation is in progress.
       * @return {number|undefined} Rotation.
       */
      function (rotation, isMoving) {
        if (isMoving || rotation === undefined) {
          return rotation;
        }

        if (Math.abs(rotation) <= t) {
          return 0;
        }
        return rotation;
      }
    );
  }

  /**
   * @module ol/tilegrid/common
   */

  /**
   * Default maximum zoom for default tile grids.
   * @type {number}
   */
  const DEFAULT_MAX_ZOOM = 42;

  /**
   * Default tile size.
   * @type {number}
   */
  const DEFAULT_TILE_SIZE = 256;

  /**
   * @module ol/View
   */

  /**
   * An animation configuration
   *
   * @typedef {Object} Animation
   * @property {import("./coordinate.js").Coordinate} [sourceCenter] Source center.
   * @property {import("./coordinate.js").Coordinate} [targetCenter] Target center.
   * @property {number} [sourceResolution] Source resolution.
   * @property {number} [targetResolution] Target resolution.
   * @property {number} [sourceRotation] Source rotation.
   * @property {number} [targetRotation] Target rotation.
   * @property {import("./coordinate.js").Coordinate} [anchor] Anchor.
   * @property {number} start Start.
   * @property {number} duration Duration.
   * @property {boolean} complete Complete.
   * @property {function(number):number} easing Easing.
   * @property {function(boolean):void} callback Callback.
   */

  /**
   * @typedef {Object} Constraints
   * @property {import("./centerconstraint.js").Type} center Center.
   * @property {import("./resolutionconstraint.js").Type} resolution Resolution.
   * @property {import("./rotationconstraint.js").Type} rotation Rotation.
   */

  /**
   * @typedef {Object} FitOptions
   * @property {import("./size.js").Size} [size] The size in pixels of the box to
   * fit the extent into. Defaults to the size of the map the view is associated with.
   * If no map or multiple maps are connected to the view, provide the desired box size
   * (e.g. `map.getSize()`).
   * @property {!Array<number>} [padding=[0, 0, 0, 0]] Padding (in pixels) to be
   * cleared inside the view. Values in the array are top, right, bottom and left
   * padding.
   * @property {boolean} [nearest=false] If the view `constrainResolution` option is `true`,
   * get the nearest extent instead of the closest that actually fits the view.
   * @property {number} [minResolution=0] Minimum resolution that we zoom to.
   * @property {number} [maxZoom] Maximum zoom level that we zoom to. If
   * `minResolution` is given, this property is ignored.
   * @property {number} [duration] The duration of the animation in milliseconds.
   * By default, there is no animation to the target extent.
   * @property {function(number):number} [easing] The easing function used during
   * the animation (defaults to {@link module:ol/easing.inAndOut}).
   * The function will be called for each frame with a number representing a
   * fraction of the animation's duration.  The function should return a number
   * between 0 and 1 representing the progress toward the destination state.
   * @property {function(boolean):void} [callback] Function called when the view is in
   * its final position. The callback will be called with `true` if the animation
   * series completed on its own or `false` if it was cancelled.
   */

  /**
   * @typedef {Object} ViewOptions
   * @property {import("./coordinate.js").Coordinate} [center] The initial center for
   * the view. If a user projection is not set, the coordinate system for the center is
   * specified with the `projection` option. Layer sources will not be fetched if this
   * is not set, but the center can be set later with {@link #setCenter}.
   * @property {boolean|number} [constrainRotation=true] Rotation constraint.
   * `false` means no constraint. `true` means no constraint, but snap to zero
   * near zero. A number constrains the rotation to that number of values. For
   * example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees.
   * @property {boolean} [enableRotation=true] Enable rotation.
   * If `false`, a rotation constraint that always sets the rotation to zero is
   * used. The `constrainRotation` option has no effect if `enableRotation` is
   * `false`.
   * @property {import("./extent.js").Extent} [extent] The extent that constrains the
   * view, in other words, nothing outside of this extent can be visible on the map.
   * @property {boolean} [constrainOnlyCenter=false] If true, the extent
   * constraint will only apply to the view center and not the whole extent.
   * @property {boolean} [smoothExtentConstraint=true] If true, the extent
   * constraint will be applied smoothly, i.e. allow the view to go slightly outside
   * of the given `extent`.
   * @property {number} [maxResolution] The maximum resolution used to determine
   * the resolution constraint. It is used together with `minResolution` (or
   * `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way
   * that the projection's validity extent fits in a 256x256 px tile. If the
   * projection is Spherical Mercator (the default) then `maxResolution` defaults
   * to `40075016.68557849 / 256 = 156543.03392804097`.
   * @property {number} [minResolution] The minimum resolution used to determine
   * the resolution constraint.  It is used together with `maxResolution` (or
   * `minZoom`) and `zoomFactor`.  If unspecified it is calculated assuming 29
   * zoom levels (with a factor of 2). If the projection is Spherical Mercator
   * (the default) then `minResolution` defaults to
   * `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`.
   * @property {number} [maxZoom=28] The maximum zoom level used to determine the
   * resolution constraint. It is used together with `minZoom` (or
   * `maxResolution`) and `zoomFactor`.  Note that if `minResolution` is also
   * provided, it is given precedence over `maxZoom`.
   * @property {number} [minZoom=0] The minimum zoom level used to determine the
   * resolution constraint. It is used together with `maxZoom` (or
   * `minResolution`) and `zoomFactor`.  Note that if `maxResolution` is also
   * provided, it is given precedence over `minZoom`.
   * @property {boolean} [multiWorld=false] If `false` the view is constrained so
   * only one world is visible, and you cannot pan off the edge.  If `true` the map
   * may show multiple worlds at low zoom levels.  Only used if the `projection` is
   * global.  Note that if `extent` is also provided it is given precedence.
   * @property {boolean} [constrainResolution=false] If true, the view will always
   * animate to the closest zoom level after an interaction; false means
   * intermediary zoom levels are allowed.
   * @property {boolean} [smoothResolutionConstraint=true] If true, the resolution
   * min/max values will be applied smoothly, i. e. allow the view to exceed slightly
   * the given resolution or zoom bounds.
   * @property {boolean} [showFullExtent=false] Allow the view to be zoomed out to
   * show the full configured extent. By default, when a view is configured with an
   * extent, users will not be able to zoom out so the viewport exceeds the extent in
   * either dimension. This means the full extent may not be visible if the viewport
   * is taller or wider than the aspect ratio of the configured extent. If
   * showFullExtent is true, the user will be able to zoom out so that the viewport
   * exceeds the height or width of the configured extent, but not both, allowing the
   * full extent to be shown.
   * @property {import("./proj.js").ProjectionLike} [projection='EPSG:3857'] The
   * projection. The default is Spherical Mercator.
   * @property {number} [resolution] The initial resolution for the view. The
   * units are `projection` units per pixel (e.g. meters per pixel). An
   * alternative to setting this is to set `zoom`. Layer sources will not be
   * fetched if neither this nor `zoom` are defined, but they can be set later
   * with {@link #setZoom} or {@link #setResolution}.
   * @property {Array<number>} [resolutions] Resolutions that determine the
   * zoom levels if specified. The index in the array corresponds to the zoom level,
   * therefore the resolution values have to be in descending order. It also constrains
   * the resolution by the minimum and maximum value. If set the `maxResolution`,
   * `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored.
   * @property {number} [rotation=0] The initial rotation for the view in radians
   * (positive rotation clockwise, 0 means North).
   * @property {number} [zoom] Only used if `resolution` is not defined. Zoom
   * level used to calculate the initial resolution for the view.
   * @property {number} [zoomFactor=2] The zoom factor used to compute the
   * corresponding resolution.
   * @property {!Array<number>} [padding=[0, 0, 0, 0]] Padding (in css pixels).
   * If the map viewport is partially covered with other content (overlays) along
   * its edges, this setting allows to shift the center of the viewport away from
   * that content. The order of the values is top, right, bottom, left.
   */

  /**
   * @typedef {Object} AnimationOptions
   * @property {import("./coordinate.js").Coordinate} [center] The center of the view at the end of
   * the animation.
   * @property {number} [zoom] The zoom level of the view at the end of the
   * animation. This takes precedence over `resolution`.
   * @property {number} [resolution] The resolution of the view at the end
   * of the animation.  If `zoom` is also provided, this option will be ignored.
   * @property {number} [rotation] The rotation of the view at the end of
   * the animation.
   * @property {import("./coordinate.js").Coordinate} [anchor] Optional anchor to remain fixed
   * during a rotation or resolution animation.
   * @property {number} [duration=1000] The duration of the animation in milliseconds.
   * @property {function(number):number} [easing] The easing function used
   * during the animation (defaults to {@link module:ol/easing.inAndOut}).
   * The function will be called for each frame with a number representing a
   * fraction of the animation's duration.  The function should return a number
   * between 0 and 1 representing the progress toward the destination state.
   */

  /**
   * @typedef {Object} State
   * @property {import("./coordinate.js").Coordinate} center Center (in view projection coordinates).
   * @property {import("./proj/Projection.js").default} projection Projection.
   * @property {number} resolution Resolution.
   * @property {import("./coordinate.js").Coordinate} [nextCenter] The next center during an animation series.
   * @property {number} [nextResolution] The next resolution during an animation series.
   * @property {number} [nextRotation] The next rotation during an animation series.
   * @property {number} rotation Rotation.
   * @property {number} zoom Zoom.
   */

  /**
   * Like {@link import("./Map.js").FrameState}, but just `viewState` and `extent`.
   * @typedef {Object} ViewStateLayerStateExtent
   * @property {State} viewState View state.
   * @property {import("./extent.js").Extent} extent Extent (in user projection coordinates).
   * @property {Array<import("./layer/Layer.js").State>} [layerStatesArray] Layer states.
   */

  /**
   * Default min zoom level for the map view.
   * @type {number}
   */
  const DEFAULT_MIN_ZOOM = 0;

  /**
   * @typedef {import("./ObjectEventType").Types|'change:center'|'change:resolution'|'change:rotation'} ViewObjectEventTypes
   */

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *   import("./Observable").OnSignature<ViewObjectEventTypes, import("./Object").ObjectEvent, Return> &
   *   import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|ViewObjectEventTypes, Return>} ViewOnSignature
   */

  /**
   * @classdesc
   * A View object represents a simple 2D view of the map.
   *
   * This is the object to act upon to change the center, resolution,
   * and rotation of the map.
   *
   * A View has a `projection`. The projection determines the
   * coordinate system of the center, and its units determine the units of the
   * resolution (projection units per pixel). The default projection is
   * Web Mercator (EPSG:3857).
   *
   * ### The view states
   *
   * A View is determined by three states: `center`, `resolution`,
   * and `rotation`. Each state has a corresponding getter and setter, e.g.
   * `getCenter` and `setCenter` for the `center` state.
   *
   * The `zoom` state is actually not saved on the view: all computations
   * internally use the `resolution` state. Still, the `setZoom` and `getZoom`
   * methods are available, as well as `getResolutionForZoom` and
   * `getZoomForResolution` to switch from one system to the other.
   *
   * ### The constraints
   *
   * `setCenter`, `setResolution` and `setRotation` can be used to change the
   * states of the view, but any constraint defined in the constructor will
   * be applied along the way.
   *
   * A View object can have a *resolution constraint*, a *rotation constraint*
   * and a *center constraint*.
   *
   * The *resolution constraint* typically restricts min/max values and
   * snaps to specific resolutions. It is determined by the following
   * options: `resolutions`, `maxResolution`, `maxZoom` and `zoomFactor`.
   * If `resolutions` is set, the other three options are ignored. See
   * documentation for each option for more information. By default, the view
   * only has a min/max restriction and allow intermediary zoom levels when
   * pinch-zooming for example.
   *
   * The *rotation constraint* snaps to specific angles. It is determined
   * by the following options: `enableRotation` and `constrainRotation`.
   * By default rotation is allowed and its value is snapped to zero when approaching the
   * horizontal.
   *
   * The *center constraint* is determined by the `extent` option. By
   * default the view center is not constrained at all.
   *
   * ### Changing the view state
   *
   * It is important to note that `setZoom`, `setResolution`, `setCenter` and
   * `setRotation` are subject to the above mentioned constraints. As such, it
   * may sometimes not be possible to know in advance the resulting state of the
   * View. For example, calling `setResolution(10)` does not guarantee that
   * `getResolution()` will return `10`.
   *
   * A consequence of this is that, when applying a delta on the view state, one
   * should use `adjustCenter`, `adjustRotation`, `adjustZoom` and `adjustResolution`
   * rather than the corresponding setters. This will let view do its internal
   * computations. Besides, the `adjust*` methods also take an `anchor`
   * argument which allows specifying an origin for the transformation.
   *
   * ### Interacting with the view
   *
   * View constraints are usually only applied when the view is *at rest*, meaning that
   * no interaction or animation is ongoing. As such, if the user puts the view in a
   * state that is not equivalent to a constrained one (e.g. rotating the view when
   * the snap angle is 0), an animation will be triggered at the interaction end to
   * put back the view to a stable state;
   *
   * @api
   */
  class View extends BaseObject {
    /**
     * @param {ViewOptions} [options] View options.
     */
    constructor(options) {
      super();

      /***
       * @type {ViewOnSignature<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {ViewOnSignature<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {ViewOnSignature<void>}
       */
      this.un;

      options = Object.assign({}, options);

      /**
       * @private
       * @type {Array<number>}
       */
      this.hints_ = [0, 0];

      /**
       * @private
       * @type {Array<Array<Animation>>}
       */
      this.animations_ = [];

      /**
       * @private
       * @type {number|undefined}
       */
      this.updateAnimationKey_;

      /**
       * @private
       * @const
       * @type {import("./proj/Projection.js").default}
       */
      this.projection_ = createProjection(options.projection, 'EPSG:3857');

      /**
       * @private
       * @type {import("./size.js").Size}
       */
      this.viewportSize_ = [100, 100];

      /**
       * @private
       * @type {import("./coordinate.js").Coordinate|undefined}
       */
      this.targetCenter_ = null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.targetResolution_;

      /**
       * @private
       * @type {number|undefined}
       */
      this.targetRotation_;

      /**
       * @private
       * @type {import("./coordinate.js").Coordinate}
       */
      this.nextCenter_ = null;

      /**
       * @private
       * @type {number}
       */
      this.nextResolution_;

      /**
       * @private
       * @type {number}
       */
      this.nextRotation_;

      /**
       * @private
       * @type {import("./coordinate.js").Coordinate|undefined}
       */
      this.cancelAnchor_ = undefined;

      if (options.projection) {
        disableCoordinateWarning();
      }
      if (options.center) {
        options.center = fromUserCoordinate(options.center, this.projection_);
      }
      if (options.extent) {
        options.extent = fromUserExtent(options.extent, this.projection_);
      }

      this.applyOptions_(options);
    }

    /**
     * Set up the view with the given options.
     * @param {ViewOptions} options View options.
     */
    applyOptions_(options) {
      const properties = Object.assign({}, options);
      for (const key in ViewProperty) {
        delete properties[key];
      }
      this.setProperties(properties, true);

      const resolutionConstraintInfo = createResolutionConstraint(options);

      /**
       * @private
       * @type {number}
       */
      this.maxResolution_ = resolutionConstraintInfo.maxResolution;

      /**
       * @private
       * @type {number}
       */
      this.minResolution_ = resolutionConstraintInfo.minResolution;

      /**
       * @private
       * @type {number}
       */
      this.zoomFactor_ = resolutionConstraintInfo.zoomFactor;

      /**
       * @private
       * @type {Array<number>|undefined}
       */
      this.resolutions_ = options.resolutions;

      /**
       * @type {Array<number>|undefined}
       * @private
       */
      this.padding_ = options.padding;

      /**
       * @private
       * @type {number}
       */
      this.minZoom_ = resolutionConstraintInfo.minZoom;

      const centerConstraint = createCenterConstraint(options);
      const resolutionConstraint = resolutionConstraintInfo.constraint;
      const rotationConstraint = createRotationConstraint(options);

      /**
       * @private
       * @type {Constraints}
       */
      this.constraints_ = {
        center: centerConstraint,
        resolution: resolutionConstraint,
        rotation: rotationConstraint,
      };

      this.setRotation(options.rotation !== undefined ? options.rotation : 0);
      this.setCenterInternal(
        options.center !== undefined ? options.center : null,
      );
      if (options.resolution !== undefined) {
        this.setResolution(options.resolution);
      } else if (options.zoom !== undefined) {
        this.setZoom(options.zoom);
      }
    }

    /**
     * Padding (in css pixels).
     * If the map viewport is partially covered with other content (overlays) along
     * its edges, this setting allows to shift the center of the viewport away from that
     * content. The order of the values in the array is top, right, bottom, left.
     * The default is no padding, which is equivalent to `[0, 0, 0, 0]`.
     * @type {Array<number>|undefined}
     * @api
     */
    get padding() {
      return this.padding_;
    }
    set padding(padding) {
      let oldPadding = this.padding_;
      this.padding_ = padding;
      const center = this.getCenterInternal();
      if (center) {
        const newPadding = padding || [0, 0, 0, 0];
        oldPadding = oldPadding || [0, 0, 0, 0];
        const resolution = this.getResolution();
        const offsetX =
          (resolution / 2) *
          (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]);
        const offsetY =
          (resolution / 2) *
          (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]);
        this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]);
      }
    }

    /**
     * Get an updated version of the view options used to construct the view.  The
     * current resolution (or zoom), center, and rotation are applied to any stored
     * options.  The provided options can be used to apply new min/max zoom or
     * resolution limits.
     * @param {ViewOptions} newOptions New options to be applied.
     * @return {ViewOptions} New options updated with the current view state.
     */
    getUpdatedOptions_(newOptions) {
      const options = this.getProperties();

      // preserve resolution (or zoom)
      if (options.resolution !== undefined) {
        options.resolution = this.getResolution();
      } else {
        options.zoom = this.getZoom();
      }

      // preserve center
      options.center = this.getCenterInternal();

      // preserve rotation
      options.rotation = this.getRotation();

      return Object.assign({}, options, newOptions);
    }

    /**
     * Animate the view.  The view's center, zoom (or resolution), and rotation
     * can be animated for smooth transitions between view states.  For example,
     * to animate the view to a new zoom level:
     *
     *     view.animate({zoom: view.getZoom() + 1});
     *
     * By default, the animation lasts one second and uses in-and-out easing.  You
     * can customize this behavior by including `duration` (in milliseconds) and
     * `easing` options (see {@link module:ol/easing}).
     *
     * To chain together multiple animations, call the method with multiple
     * animation objects.  For example, to first zoom and then pan:
     *
     *     view.animate({zoom: 10}, {center: [0, 0]});
     *
     * If you provide a function as the last argument to the animate method, it
     * will get called at the end of an animation series.  The callback will be
     * called with `true` if the animation series completed on its own or `false`
     * if it was cancelled.
     *
     * Animations are cancelled by user interactions (e.g. dragging the map) or by
     * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()`
     * (or another method that calls one of these).
     *
     * @param {...(AnimationOptions|function(boolean): void)} var_args Animation
     *     options.  Multiple animations can be run in series by passing multiple
     *     options objects.  To run multiple animations in parallel, call the method
     *     multiple times.  An optional callback can be provided as a final
     *     argument.  The callback will be called with a boolean indicating whether
     *     the animation completed without being cancelled.
     * @api
     */
    animate(var_args) {
      if (this.isDef() && !this.getAnimating()) {
        this.resolveConstraints(0);
      }
      const args = new Array(arguments.length);
      for (let i = 0; i < args.length; ++i) {
        let options = arguments[i];
        if (options.center) {
          options = Object.assign({}, options);
          options.center = fromUserCoordinate(
            options.center,
            this.getProjection(),
          );
        }
        if (options.anchor) {
          options = Object.assign({}, options);
          options.anchor = fromUserCoordinate(
            options.anchor,
            this.getProjection(),
          );
        }
        args[i] = options;
      }
      this.animateInternal.apply(this, args);
    }

    /**
     * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options.
     */
    animateInternal(var_args) {
      let animationCount = arguments.length;
      let callback;
      if (
        animationCount > 1 &&
        typeof arguments[animationCount - 1] === 'function'
      ) {
        callback = arguments[animationCount - 1];
        --animationCount;
      }

      let i = 0;
      for (; i < animationCount && !this.isDef(); ++i) {
        // if view properties are not yet set, shortcut to the final state
        const state = arguments[i];
        if (state.center) {
          this.setCenterInternal(state.center);
        }
        if (state.zoom !== undefined) {
          this.setZoom(state.zoom);
        } else if (state.resolution) {
          this.setResolution(state.resolution);
        }
        if (state.rotation !== undefined) {
          this.setRotation(state.rotation);
        }
      }
      if (i === animationCount) {
        if (callback) {
          animationCallback(callback, true);
        }
        return;
      }

      let start = Date.now();
      let center = this.targetCenter_.slice();
      let resolution = this.targetResolution_;
      let rotation = this.targetRotation_;
      const series = [];
      for (; i < animationCount; ++i) {
        const options = /** @type {AnimationOptions} */ (arguments[i]);

        const animation = {
          start: start,
          complete: false,
          anchor: options.anchor,
          duration: options.duration !== undefined ? options.duration : 1000,
          easing: options.easing || inAndOut,
          callback: callback,
        };

        if (options.center) {
          animation.sourceCenter = center;
          animation.targetCenter = options.center.slice();
          center = animation.targetCenter;
        }

        if (options.zoom !== undefined) {
          animation.sourceResolution = resolution;
          animation.targetResolution = this.getResolutionForZoom(options.zoom);
          resolution = animation.targetResolution;
        } else if (options.resolution) {
          animation.sourceResolution = resolution;
          animation.targetResolution = options.resolution;
          resolution = animation.targetResolution;
        }

        if (options.rotation !== undefined) {
          animation.sourceRotation = rotation;
          const delta =
            modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI;
          animation.targetRotation = rotation + delta;
          rotation = animation.targetRotation;
        }

        // check if animation is a no-op
        if (isNoopAnimation(animation)) {
          animation.complete = true;
          // we still push it onto the series for callback handling
        } else {
          start += animation.duration;
        }
        series.push(animation);
      }
      this.animations_.push(series);
      this.setHint(ViewHint.ANIMATING, 1);
      this.updateAnimations_();
    }

    /**
     * Determine if the view is being animated.
     * @return {boolean} The view is being animated.
     * @api
     */
    getAnimating() {
      return this.hints_[ViewHint.ANIMATING] > 0;
    }

    /**
     * Determine if the user is interacting with the view, such as panning or zooming.
     * @return {boolean} The view is being interacted with.
     * @api
     */
    getInteracting() {
      return this.hints_[ViewHint.INTERACTING] > 0;
    }

    /**
     * Cancel any ongoing animations.
     * @api
     */
    cancelAnimations() {
      this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]);
      let anchor;
      for (let i = 0, ii = this.animations_.length; i < ii; ++i) {
        const series = this.animations_[i];
        if (series[0].callback) {
          animationCallback(series[0].callback, false);
        }
        if (!anchor) {
          for (let j = 0, jj = series.length; j < jj; ++j) {
            const animation = series[j];
            if (!animation.complete) {
              anchor = animation.anchor;
              break;
            }
          }
        }
      }
      this.animations_.length = 0;
      this.cancelAnchor_ = anchor;
      this.nextCenter_ = null;
      this.nextResolution_ = NaN;
      this.nextRotation_ = NaN;
    }

    /**
     * Update all animations.
     */
    updateAnimations_() {
      if (this.updateAnimationKey_ !== undefined) {
        cancelAnimationFrame(this.updateAnimationKey_);
        this.updateAnimationKey_ = undefined;
      }
      if (!this.getAnimating()) {
        return;
      }
      const now = Date.now();
      let more = false;
      for (let i = this.animations_.length - 1; i >= 0; --i) {
        const series = this.animations_[i];
        let seriesComplete = true;
        for (let j = 0, jj = series.length; j < jj; ++j) {
          const animation = series[j];
          if (animation.complete) {
            continue;
          }
          const elapsed = now - animation.start;
          let fraction =
            animation.duration > 0 ? elapsed / animation.duration : 1;
          if (fraction >= 1) {
            animation.complete = true;
            fraction = 1;
          } else {
            seriesComplete = false;
          }
          const progress = animation.easing(fraction);
          if (animation.sourceCenter) {
            const x0 = animation.sourceCenter[0];
            const y0 = animation.sourceCenter[1];
            const x1 = animation.targetCenter[0];
            const y1 = animation.targetCenter[1];
            this.nextCenter_ = animation.targetCenter;
            const x = x0 + progress * (x1 - x0);
            const y = y0 + progress * (y1 - y0);
            this.targetCenter_ = [x, y];
          }
          if (animation.sourceResolution && animation.targetResolution) {
            const resolution =
              progress === 1
                ? animation.targetResolution
                : animation.sourceResolution +
                  progress *
                    (animation.targetResolution - animation.sourceResolution);
            if (animation.anchor) {
              const size = this.getViewportSize_(this.getRotation());
              const constrainedResolution = this.constraints_.resolution(
                resolution,
                0,
                size,
                true,
              );
              this.targetCenter_ = this.calculateCenterZoom(
                constrainedResolution,
                animation.anchor,
              );
            }
            this.nextResolution_ = animation.targetResolution;
            this.targetResolution_ = resolution;
            this.applyTargetState_(true);
          }
          if (
            animation.sourceRotation !== undefined &&
            animation.targetRotation !== undefined
          ) {
            const rotation =
              progress === 1
                ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) -
                  Math.PI
                : animation.sourceRotation +
                  progress *
                    (animation.targetRotation - animation.sourceRotation);
            if (animation.anchor) {
              const constrainedRotation = this.constraints_.rotation(
                rotation,
                true,
              );
              this.targetCenter_ = this.calculateCenterRotate(
                constrainedRotation,
                animation.anchor,
              );
            }
            this.nextRotation_ = animation.targetRotation;
            this.targetRotation_ = rotation;
          }
          this.applyTargetState_(true);
          more = true;
          if (!animation.complete) {
            break;
          }
        }
        if (seriesComplete) {
          this.animations_[i] = null;
          this.setHint(ViewHint.ANIMATING, -1);
          this.nextCenter_ = null;
          this.nextResolution_ = NaN;
          this.nextRotation_ = NaN;
          const callback = series[0].callback;
          if (callback) {
            animationCallback(callback, true);
          }
        }
      }
      // prune completed series
      this.animations_ = this.animations_.filter(Boolean);
      if (more && this.updateAnimationKey_ === undefined) {
        this.updateAnimationKey_ = requestAnimationFrame(
          this.updateAnimations_.bind(this),
        );
      }
    }

    /**
     * @param {number} rotation Target rotation.
     * @param {import("./coordinate.js").Coordinate} anchor Rotation anchor.
     * @return {import("./coordinate.js").Coordinate|undefined} Center for rotation and anchor.
     */
    calculateCenterRotate(rotation, anchor) {
      let center;
      const currentCenter = this.getCenterInternal();
      if (currentCenter !== undefined) {
        center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]];
        rotate$2(center, rotation - this.getRotation());
        add$2(center, anchor);
      }
      return center;
    }

    /**
     * @param {number} resolution Target resolution.
     * @param {import("./coordinate.js").Coordinate} anchor Zoom anchor.
     * @return {import("./coordinate.js").Coordinate|undefined} Center for resolution and anchor.
     */
    calculateCenterZoom(resolution, anchor) {
      let center;
      const currentCenter = this.getCenterInternal();
      const currentResolution = this.getResolution();
      if (currentCenter !== undefined && currentResolution !== undefined) {
        const x =
          anchor[0] -
          (resolution * (anchor[0] - currentCenter[0])) / currentResolution;
        const y =
          anchor[1] -
          (resolution * (anchor[1] - currentCenter[1])) / currentResolution;
        center = [x, y];
      }
      return center;
    }

    /**
     * Returns the current viewport size.
     * @private
     * @param {number} [rotation] Take into account the rotation of the viewport when giving the size
     * @return {import("./size.js").Size} Viewport size or `[100, 100]` when no viewport is found.
     */
    getViewportSize_(rotation) {
      const size = this.viewportSize_;
      if (rotation) {
        const w = size[0];
        const h = size[1];
        return [
          Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)),
          Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)),
        ];
      }
      return size;
    }

    /**
     * Stores the viewport size on the view. The viewport size is not read every time from the DOM
     * to avoid performance hit and layout reflow.
     * This should be done on map size change.
     * Note: the constraints are not resolved during an animation to avoid stopping it
     * @param {import("./size.js").Size} [size] Viewport size; if undefined, [100, 100] is assumed
     */
    setViewportSize(size) {
      this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100];
      if (!this.getAnimating()) {
        this.resolveConstraints(0);
      }
    }

    /**
     * Get the view center.
     * @return {import("./coordinate.js").Coordinate|undefined} The center of the view.
     * @observable
     * @api
     */
    getCenter() {
      const center = this.getCenterInternal();
      if (!center) {
        return center;
      }
      return toUserCoordinate(center, this.getProjection());
    }

    /**
     * Get the view center without transforming to user projection.
     * @return {import("./coordinate.js").Coordinate|undefined} The center of the view.
     */
    getCenterInternal() {
      return /** @type {import("./coordinate.js").Coordinate|undefined} */ (
        this.get(ViewProperty.CENTER)
      );
    }

    /**
     * @return {Constraints} Constraints.
     */
    getConstraints() {
      return this.constraints_;
    }

    /**
     * @return {boolean} Resolution constraint is set
     */
    getConstrainResolution() {
      return this.get('constrainResolution');
    }

    /**
     * @param {Array<number>} [hints] Destination array.
     * @return {Array<number>} Hint.
     */
    getHints(hints) {
      if (hints !== undefined) {
        hints[0] = this.hints_[0];
        hints[1] = this.hints_[1];
        return hints;
      }
      return this.hints_.slice();
    }

    /**
     * Calculate the extent for the current view state and the passed box size.
     * @param {import("./size.js").Size} [size] The pixel dimensions of the box
     * into which the calculated extent should fit. Defaults to the size of the
     * map the view is associated with.
     * If no map or multiple maps are connected to the view, provide the desired
     * box size (e.g. `map.getSize()`).
     * @return {import("./extent.js").Extent} Extent.
     * @api
     */
    calculateExtent(size) {
      const extent = this.calculateExtentInternal(size);
      return toUserExtent(extent, this.getProjection());
    }

    /**
     * @param {import("./size.js").Size} [size] Box pixel size. If not provided,
     * the map's last known viewport size will be used.
     * @return {import("./extent.js").Extent} Extent.
     */
    calculateExtentInternal(size) {
      size = size || this.getViewportSizeMinusPadding_();
      const center = /** @type {!import("./coordinate.js").Coordinate} */ (
        this.getCenterInternal()
      );
      assert(center, 'The view center is not defined');
      const resolution = /** @type {!number} */ (this.getResolution());
      assert(resolution !== undefined, 'The view resolution is not defined');
      const rotation = /** @type {!number} */ (this.getRotation());
      assert(rotation !== undefined, 'The view rotation is not defined');

      return getForViewAndSize(center, resolution, rotation, size);
    }

    /**
     * Get the maximum resolution of the view.
     * @return {number} The maximum resolution of the view.
     * @api
     */
    getMaxResolution() {
      return this.maxResolution_;
    }

    /**
     * Get the minimum resolution of the view.
     * @return {number} The minimum resolution of the view.
     * @api
     */
    getMinResolution() {
      return this.minResolution_;
    }

    /**
     * Get the maximum zoom level for the view.
     * @return {number} The maximum zoom level.
     * @api
     */
    getMaxZoom() {
      return /** @type {number} */ (
        this.getZoomForResolution(this.minResolution_)
      );
    }

    /**
     * Set a new maximum zoom level for the view.
     * @param {number} zoom The maximum zoom level.
     * @api
     */
    setMaxZoom(zoom) {
      this.applyOptions_(this.getUpdatedOptions_({maxZoom: zoom}));
    }

    /**
     * Get the minimum zoom level for the view.
     * @return {number} The minimum zoom level.
     * @api
     */
    getMinZoom() {
      return /** @type {number} */ (
        this.getZoomForResolution(this.maxResolution_)
      );
    }

    /**
     * Set a new minimum zoom level for the view.
     * @param {number} zoom The minimum zoom level.
     * @api
     */
    setMinZoom(zoom) {
      this.applyOptions_(this.getUpdatedOptions_({minZoom: zoom}));
    }

    /**
     * Set whether the view should allow intermediary zoom levels.
     * @param {boolean} enabled Whether the resolution is constrained.
     * @api
     */
    setConstrainResolution(enabled) {
      this.applyOptions_(this.getUpdatedOptions_({constrainResolution: enabled}));
    }

    /**
     * Get the view projection.
     * @return {import("./proj/Projection.js").default} The projection of the view.
     * @api
     */
    getProjection() {
      return this.projection_;
    }

    /**
     * Get the view resolution.
     * @return {number|undefined} The resolution of the view.
     * @observable
     * @api
     */
    getResolution() {
      return /** @type {number|undefined} */ (this.get(ViewProperty.RESOLUTION));
    }

    /**
     * Get the resolutions for the view. This returns the array of resolutions
     * passed to the constructor of the View, or undefined if none were given.
     * @return {Array<number>|undefined} The resolutions of the view.
     * @api
     */
    getResolutions() {
      return this.resolutions_;
    }

    /**
     * Get the resolution for a provided extent (in map units) and size (in pixels).
     * @param {import("./extent.js").Extent} extent Extent.
     * @param {import("./size.js").Size} [size] Box pixel size.
     * @return {number} The resolution at which the provided extent will render at
     *     the given size.
     * @api
     */
    getResolutionForExtent(extent, size) {
      return this.getResolutionForExtentInternal(
        fromUserExtent(extent, this.getProjection()),
        size,
      );
    }

    /**
     * Get the resolution for a provided extent (in map units) and size (in pixels).
     * @param {import("./extent.js").Extent} extent Extent.
     * @param {import("./size.js").Size} [size] Box pixel size.
     * @return {number} The resolution at which the provided extent will render at
     *     the given size.
     */
    getResolutionForExtentInternal(extent, size) {
      size = size || this.getViewportSizeMinusPadding_();
      const xResolution = getWidth(extent) / size[0];
      const yResolution = getHeight(extent) / size[1];
      return Math.max(xResolution, yResolution);
    }

    /**
     * Return a function that returns a value between 0 and 1 for a
     * resolution. Exponential scaling is assumed.
     * @param {number} [power] Power.
     * @return {function(number): number} Resolution for value function.
     */
    getResolutionForValueFunction(power) {
      power = power || 2;
      const maxResolution = this.getConstrainedResolution(this.maxResolution_);
      const minResolution = this.minResolution_;
      const max = Math.log(maxResolution / minResolution) / Math.log(power);
      return (
        /**
         * @param {number} value Value.
         * @return {number} Resolution.
         */
        function (value) {
          const resolution = maxResolution / Math.pow(power, value * max);
          return resolution;
        }
      );
    }

    /**
     * Get the view rotation.
     * @return {number} The rotation of the view in radians.
     * @observable
     * @api
     */
    getRotation() {
      return /** @type {number} */ (this.get(ViewProperty.ROTATION));
    }

    /**
     * Return a function that returns a resolution for a value between
     * 0 and 1. Exponential scaling is assumed.
     * @param {number} [power] Power.
     * @return {function(number): number} Value for resolution function.
     */
    getValueForResolutionFunction(power) {
      const logPower = Math.log(power || 2);
      const maxResolution = this.getConstrainedResolution(this.maxResolution_);
      const minResolution = this.minResolution_;
      const max = Math.log(maxResolution / minResolution) / logPower;
      return (
        /**
         * @param {number} resolution Resolution.
         * @return {number} Value.
         */
        function (resolution) {
          const value = Math.log(maxResolution / resolution) / logPower / max;
          return value;
        }
      );
    }

    /**
     * Returns the size of the viewport minus padding.
     * @private
     * @param {number} [rotation] Take into account the rotation of the viewport when giving the size
     * @return {import("./size.js").Size} Viewport size reduced by the padding.
     */
    getViewportSizeMinusPadding_(rotation) {
      let size = this.getViewportSize_(rotation);
      const padding = this.padding_;
      if (padding) {
        size = [
          size[0] - padding[1] - padding[3],
          size[1] - padding[0] - padding[2],
        ];
      }
      return size;
    }

    /**
     * @return {State} View state.
     */
    getState() {
      const projection = this.getProjection();
      const resolution = this.getResolution();
      const rotation = this.getRotation();
      let center = /** @type {import("./coordinate.js").Coordinate} */ (
        this.getCenterInternal()
      );
      const padding = this.padding_;
      if (padding) {
        const reducedSize = this.getViewportSizeMinusPadding_();
        center = calculateCenterOn(
          center,
          this.getViewportSize_(),
          [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],
          resolution,
          rotation,
        );
      }
      return {
        center: center.slice(0),
        projection: projection !== undefined ? projection : null,
        resolution: resolution,
        nextCenter: this.nextCenter_,
        nextResolution: this.nextResolution_,
        nextRotation: this.nextRotation_,
        rotation: rotation,
        zoom: this.getZoom(),
      };
    }

    /**
     * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`.
     */
    getViewStateAndExtent() {
      return {
        viewState: this.getState(),
        extent: this.calculateExtent(),
      };
    }

    /**
     * Get the current zoom level. This method may return non-integer zoom levels
     * if the view does not constrain the resolution, or if an interaction or
     * animation is underway.
     * @return {number|undefined} Zoom.
     * @api
     */
    getZoom() {
      let zoom;
      const resolution = this.getResolution();
      if (resolution !== undefined) {
        zoom = this.getZoomForResolution(resolution);
      }
      return zoom;
    }

    /**
     * Get the zoom level for a resolution.
     * @param {number} resolution The resolution.
     * @return {number|undefined} The zoom level for the provided resolution.
     * @api
     */
    getZoomForResolution(resolution) {
      let offset = this.minZoom_ || 0;
      let max, zoomFactor;
      if (this.resolutions_) {
        const nearest = linearFindNearest(this.resolutions_, resolution, 1);
        offset = nearest;
        max = this.resolutions_[nearest];
        if (nearest == this.resolutions_.length - 1) {
          zoomFactor = 2;
        } else {
          zoomFactor = max / this.resolutions_[nearest + 1];
        }
      } else {
        max = this.maxResolution_;
        zoomFactor = this.zoomFactor_;
      }
      return offset + Math.log(max / resolution) / Math.log(zoomFactor);
    }

    /**
     * Get the resolution for a zoom level.
     * @param {number} zoom Zoom level.
     * @return {number} The view resolution for the provided zoom level.
     * @api
     */
    getResolutionForZoom(zoom) {
      if (this.resolutions_?.length) {
        if (this.resolutions_.length === 1) {
          return this.resolutions_[0];
        }
        const baseLevel = clamp$1(
          Math.floor(zoom),
          0,
          this.resolutions_.length - 2,
        );
        const zoomFactor =
          this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1];
        return (
          this.resolutions_[baseLevel] /
          Math.pow(zoomFactor, clamp$1(zoom - baseLevel, 0, 1))
        );
      }
      return (
        this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_)
      );
    }

    /**
     * Fit the given geometry or extent based on the given map size and border.
     * The size is pixel dimensions of the box to fit the extent into.
     * In most cases you will want to use the map size, that is `map.getSize()`.
     * Takes care of the map angle.
     * @param {import("./geom/SimpleGeometry.js").default|import("./extent.js").Extent} geometryOrExtent The geometry or
     *     extent to fit the view to.
     * @param {FitOptions} [options] Options.
     * @api
     */
    fit(geometryOrExtent, options) {
      /** @type {import("./geom/SimpleGeometry.js").default} */
      let geometry;
      assert(
        Array.isArray(geometryOrExtent) ||
          typeof (/** @type {?} */ (geometryOrExtent).getSimplifiedGeometry) ===
            'function',
        'Invalid extent or geometry provided as `geometry`',
      );
      if (Array.isArray(geometryOrExtent)) {
        assert(
          !isEmpty(geometryOrExtent),
          'Cannot fit empty extent provided as `geometry`',
        );
        const extent = fromUserExtent(geometryOrExtent, this.getProjection());
        geometry = fromExtent(extent);
      } else if (geometryOrExtent.getType() === 'Circle') {
        const extent = fromUserExtent(
          geometryOrExtent.getExtent(),
          this.getProjection(),
        );
        geometry = fromExtent(extent);
        geometry.rotate(this.getRotation(), getCenter(extent));
      } else {
        const userProjection = getUserProjection();
        if (userProjection) {
          geometry = /** @type {import("./geom/SimpleGeometry.js").default} */ (
            geometryOrExtent
              .clone()
              .transform(userProjection, this.getProjection())
          );
        } else {
          geometry = geometryOrExtent;
        }
      }

      this.fitInternal(geometry, options);
    }

    /**
     * Calculate rotated extent
     * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry.
     * @return {import("./extent").Extent} The rotated extent for the geometry.
     */
    rotatedExtentForGeometry(geometry) {
      const rotation = this.getRotation();
      const cosAngle = Math.cos(rotation);
      const sinAngle = Math.sin(-rotation);
      const coords = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      let minRotX = +Infinity;
      let minRotY = +Infinity;
      let maxRotX = -Infinity;
      let maxRotY = -Infinity;
      for (let i = 0, ii = coords.length; i < ii; i += stride) {
        const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle;
        const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle;
        minRotX = Math.min(minRotX, rotX);
        minRotY = Math.min(minRotY, rotY);
        maxRotX = Math.max(maxRotX, rotX);
        maxRotY = Math.max(maxRotY, rotY);
      }
      return [minRotX, minRotY, maxRotX, maxRotY];
    }

    /**
     * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry.
     * @param {FitOptions} [options] Options.
     */
    fitInternal(geometry, options) {
      options = options || {};
      let size = options.size;
      if (!size) {
        size = this.getViewportSizeMinusPadding_();
      }
      const padding =
        options.padding !== undefined ? options.padding : [0, 0, 0, 0];
      const nearest = options.nearest !== undefined ? options.nearest : false;
      let minResolution;
      if (options.minResolution !== undefined) {
        minResolution = options.minResolution;
      } else if (options.maxZoom !== undefined) {
        minResolution = this.getResolutionForZoom(options.maxZoom);
      } else {
        minResolution = 0;
      }

      const rotatedExtent = this.rotatedExtentForGeometry(geometry);

      // calculate resolution
      let resolution = this.getResolutionForExtentInternal(rotatedExtent, [
        size[0] - padding[1] - padding[3],
        size[1] - padding[0] - padding[2],
      ]);
      resolution = isNaN(resolution)
        ? minResolution
        : Math.max(resolution, minResolution);
      resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1);

      // calculate center
      const rotation = this.getRotation();
      const sinAngle = Math.sin(rotation);
      const cosAngle = Math.cos(rotation);
      const centerRot = getCenter(rotatedExtent);
      centerRot[0] += ((padding[1] - padding[3]) / 2) * resolution;
      centerRot[1] += ((padding[0] - padding[2]) / 2) * resolution;
      const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle;
      const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle;
      const center = this.getConstrainedCenter([centerX, centerY], resolution);
      const callback = options.callback ? options.callback : VOID;

      if (options.duration !== undefined) {
        this.animateInternal(
          {
            resolution: resolution,
            center: center,
            duration: options.duration,
            easing: options.easing,
          },
          callback,
        );
      } else {
        this.targetResolution_ = resolution;
        this.targetCenter_ = center;
        this.applyTargetState_(false, true);
        animationCallback(callback, true);
      }
    }

    /**
     * Center on coordinate and view position.
     * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("./size.js").Size} size Box pixel size.
     * @param {import("./pixel.js").Pixel} position Position on the view to center on.
     * @api
     */
    centerOn(coordinate, size, position) {
      this.centerOnInternal(
        fromUserCoordinate(coordinate, this.getProjection()),
        size,
        position,
      );
    }

    /**
     * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("./size.js").Size} size Box pixel size.
     * @param {import("./pixel.js").Pixel} position Position on the view to center on.
     */
    centerOnInternal(coordinate, size, position) {
      this.setCenterInternal(
        calculateCenterOn(
          coordinate,
          size,
          position,
          this.getResolution(),
          this.getRotation(),
        ),
      );
    }

    /**
     * Calculates the shift between map and viewport center.
     * @param {import("./coordinate.js").Coordinate} center Center.
     * @param {number} resolution Resolution.
     * @param {number} rotation Rotation.
     * @param {import("./size.js").Size} size Size.
     * @return {Array<number>|undefined} Center shift.
     */
    calculateCenterShift(center, resolution, rotation, size) {
      let centerShift;
      const padding = this.padding_;
      if (padding && center) {
        const reducedSize = this.getViewportSizeMinusPadding_(-rotation);
        const shiftedCenter = calculateCenterOn(
          center,
          size,
          [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],
          resolution,
          rotation,
        );
        centerShift = [
          center[0] - shiftedCenter[0],
          center[1] - shiftedCenter[1],
        ];
      }
      return centerShift;
    }

    /**
     * @return {boolean} Is defined.
     */
    isDef() {
      return !!this.getCenterInternal() && this.getResolution() !== undefined;
    }

    /**
     * Adds relative coordinates to the center of the view. Any extent constraint will apply.
     * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add.
     * @api
     */
    adjustCenter(deltaCoordinates) {
      const center = toUserCoordinate(this.targetCenter_, this.getProjection());
      this.setCenter([
        center[0] + deltaCoordinates[0],
        center[1] + deltaCoordinates[1],
      ]);
    }

    /**
     * Adds relative coordinates to the center of the view. Any extent constraint will apply.
     * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add.
     */
    adjustCenterInternal(deltaCoordinates) {
      const center = this.targetCenter_;
      this.setCenterInternal([
        center[0] + deltaCoordinates[0],
        center[1] + deltaCoordinates[1],
      ]);
    }

    /**
     * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution
     * constraint will apply.
     * @param {number} ratio The ratio to apply on the view resolution.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     * @api
     */
    adjustResolution(ratio, anchor) {
      anchor = anchor && fromUserCoordinate(anchor, this.getProjection());
      this.adjustResolutionInternal(ratio, anchor);
    }

    /**
     * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution
     * constraint will apply.
     * @param {number} ratio The ratio to apply on the view resolution.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     */
    adjustResolutionInternal(ratio, anchor) {
      const isMoving = this.getAnimating() || this.getInteracting();
      const size = this.getViewportSize_(this.getRotation());
      const newResolution = this.constraints_.resolution(
        this.targetResolution_ * ratio,
        0,
        size,
        isMoving,
      );

      if (anchor) {
        this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor);
      }

      this.targetResolution_ *= ratio;
      this.applyTargetState_();
    }

    /**
     * Adds a value to the view zoom level, optionally using an anchor. Any resolution
     * constraint will apply.
     * @param {number} delta Relative value to add to the zoom level.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     * @api
     */
    adjustZoom(delta, anchor) {
      this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor);
    }

    /**
     * Adds a value to the view rotation, optionally using an anchor. Any rotation
     * constraint will apply.
     * @param {number} delta Relative value to add to the zoom rotation, in radians.
     * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center.
     * @api
     */
    adjustRotation(delta, anchor) {
      if (anchor) {
        anchor = fromUserCoordinate(anchor, this.getProjection());
      }
      this.adjustRotationInternal(delta, anchor);
    }

    /**
     * @param {number} delta Relative value to add to the zoom rotation, in radians.
     * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center.
     */
    adjustRotationInternal(delta, anchor) {
      const isMoving = this.getAnimating() || this.getInteracting();
      const newRotation = this.constraints_.rotation(
        this.targetRotation_ + delta,
        isMoving,
      );
      if (anchor) {
        this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor);
      }
      this.targetRotation_ += delta;
      this.applyTargetState_();
    }

    /**
     * Set the center of the current view. Any extent constraint will apply.
     * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view.
     * @observable
     * @api
     */
    setCenter(center) {
      this.setCenterInternal(
        center ? fromUserCoordinate(center, this.getProjection()) : center,
      );
    }

    /**
     * Set the center using the view projection (not the user projection).
     * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view.
     */
    setCenterInternal(center) {
      this.targetCenter_ = center;
      this.applyTargetState_();
    }

    /**
     * @param {import("./ViewHint.js").default} hint Hint.
     * @param {number} delta Delta.
     * @return {number} New value.
     */
    setHint(hint, delta) {
      this.hints_[hint] += delta;
      this.changed();
      return this.hints_[hint];
    }

    /**
     * Set the resolution for this view. Any resolution constraint will apply.
     * @param {number|undefined} resolution The resolution of the view.
     * @observable
     * @api
     */
    setResolution(resolution) {
      this.targetResolution_ = resolution;
      this.applyTargetState_();
    }

    /**
     * Set the rotation for this view. Any rotation constraint will apply.
     * @param {number} rotation The rotation of the view in radians.
     * @observable
     * @api
     */
    setRotation(rotation) {
      this.targetRotation_ = rotation;
      this.applyTargetState_();
    }

    /**
     * Zoom to a specific zoom level. Any resolution constrain will apply.
     * @param {number} zoom Zoom level.
     * @api
     */
    setZoom(zoom) {
      this.setResolution(this.getResolutionForZoom(zoom));
    }

    /**
     * Recompute rotation/resolution/center based on target values.
     * Note: we have to compute rotation first, then resolution and center considering that
     * parameters can influence one another in case a view extent constraint is present.
     * @param {boolean} [doNotCancelAnims] Do not cancel animations.
     * @param {boolean} [forceMoving] Apply constraints as if the view is moving.
     * @private
     */
    applyTargetState_(doNotCancelAnims, forceMoving) {
      const isMoving =
        this.getAnimating() || this.getInteracting() || forceMoving;

      // compute rotation
      const newRotation = this.constraints_.rotation(
        this.targetRotation_,
        isMoving,
      );
      const size = this.getViewportSize_(newRotation);
      const newResolution = this.constraints_.resolution(
        this.targetResolution_,
        0,
        size,
        isMoving,
      );
      const newCenter = this.constraints_.center(
        this.targetCenter_,
        newResolution,
        size,
        isMoving,
        this.calculateCenterShift(
          this.targetCenter_,
          newResolution,
          newRotation,
          size,
        ),
      );

      if (this.get(ViewProperty.ROTATION) !== newRotation) {
        this.set(ViewProperty.ROTATION, newRotation);
      }
      if (this.get(ViewProperty.RESOLUTION) !== newResolution) {
        this.set(ViewProperty.RESOLUTION, newResolution);
        this.set('zoom', this.getZoom(), true);
      }
      if (
        !newCenter ||
        !this.get(ViewProperty.CENTER) ||
        !equals(this.get(ViewProperty.CENTER), newCenter)
      ) {
        this.set(ViewProperty.CENTER, newCenter);
      }

      if (this.getAnimating() && !doNotCancelAnims) {
        this.cancelAnimations();
      }
      this.cancelAnchor_ = undefined;
    }

    /**
     * If any constraints need to be applied, an animation will be triggered.
     * This is typically done on interaction end.
     * Note: calling this with a duration of 0 will apply the constrained values straight away,
     * without animation.
     * @param {number} [duration] The animation duration in ms.
     * @param {number} [resolutionDirection] Which direction to zoom.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     */
    resolveConstraints(duration, resolutionDirection, anchor) {
      duration = duration !== undefined ? duration : 200;
      const direction = resolutionDirection || 0;

      const newRotation = this.constraints_.rotation(this.targetRotation_);
      const size = this.getViewportSize_(newRotation);
      const newResolution = this.constraints_.resolution(
        this.targetResolution_,
        direction,
        size,
      );
      const newCenter = this.constraints_.center(
        this.targetCenter_,
        newResolution,
        size,
        false,
        this.calculateCenterShift(
          this.targetCenter_,
          newResolution,
          newRotation,
          size,
        ),
      );

      if (duration === 0 && !this.cancelAnchor_) {
        this.targetResolution_ = newResolution;
        this.targetRotation_ = newRotation;
        this.targetCenter_ = newCenter;
        this.applyTargetState_();
        return;
      }

      anchor = anchor || (duration === 0 ? this.cancelAnchor_ : undefined);
      this.cancelAnchor_ = undefined;

      if (
        this.getResolution() !== newResolution ||
        this.getRotation() !== newRotation ||
        !this.getCenterInternal() ||
        !equals(this.getCenterInternal(), newCenter)
      ) {
        if (this.getAnimating()) {
          this.cancelAnimations();
        }

        this.animateInternal({
          rotation: newRotation,
          center: newCenter,
          resolution: newResolution,
          duration: duration,
          easing: easeOut,
          anchor: anchor,
        });
      }
    }

    /**
     * Notify the View that an interaction has started.
     * The view state will be resolved to a stable one if needed
     * (depending on its constraints).
     * @api
     */
    beginInteraction() {
      this.resolveConstraints(0);

      this.setHint(ViewHint.INTERACTING, 1);
    }

    /**
     * Notify the View that an interaction has ended. The view state will be resolved
     * to a stable one if needed (depending on its constraints).
     * @param {number} [duration] Animation duration in ms.
     * @param {number} [resolutionDirection] Which direction to zoom.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     * @api
     */
    endInteraction(duration, resolutionDirection, anchor) {
      anchor = anchor && fromUserCoordinate(anchor, this.getProjection());
      this.endInteractionInternal(duration, resolutionDirection, anchor);
    }

    /**
     * Notify the View that an interaction has ended. The view state will be resolved
     * to a stable one if needed (depending on its constraints).
     * @param {number} [duration] Animation duration in ms.
     * @param {number} [resolutionDirection] Which direction to zoom.
     * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation.
     */
    endInteractionInternal(duration, resolutionDirection, anchor) {
      if (!this.getInteracting()) {
        return;
      }
      this.setHint(ViewHint.INTERACTING, -1);
      this.resolveConstraints(duration, resolutionDirection, anchor);
    }

    /**
     * Get a valid position for the view center according to the current constraints.
     * @param {import("./coordinate.js").Coordinate|undefined} targetCenter Target center position.
     * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used.
     * This is useful to guess a valid center position at a different zoom level.
     * @return {import("./coordinate.js").Coordinate|undefined} Valid center position.
     */
    getConstrainedCenter(targetCenter, targetResolution) {
      const size = this.getViewportSize_(this.getRotation());
      return this.constraints_.center(
        targetCenter,
        targetResolution || this.getResolution(),
        size,
      );
    }

    /**
     * Get a valid zoom level according to the current view constraints.
     * @param {number|undefined} targetZoom Target zoom.
     * @param {number} [direction] Indicate which resolution should be used
     * by a renderer if the view resolution does not match any resolution of the tile source.
     * If 0, the nearest resolution will be used. If 1, the nearest lower resolution
     * will be used. If -1, the nearest higher resolution will be used.
     * @return {number|undefined} Valid zoom level.
     */
    getConstrainedZoom(targetZoom, direction) {
      const targetRes = this.getResolutionForZoom(targetZoom);
      return this.getZoomForResolution(
        this.getConstrainedResolution(targetRes, direction),
      );
    }

    /**
     * Get a valid resolution according to the current view constraints.
     * @param {number|undefined} targetResolution Target resolution.
     * @param {number} [direction] Indicate which resolution should be used
     * by a renderer if the view resolution does not match any resolution of the tile source.
     * If 0, the nearest resolution will be used. If 1, the nearest lower resolution
     * will be used. If -1, the nearest higher resolution will be used.
     * @return {number|undefined} Valid resolution.
     */
    getConstrainedResolution(targetResolution, direction) {
      direction = direction || 0;
      const size = this.getViewportSize_(this.getRotation());

      return this.constraints_.resolution(targetResolution, direction, size);
    }
  }

  /**
   * @param {Function} callback Callback.
   * @param {*} returnValue Return value.
   */
  function animationCallback(callback, returnValue) {
    setTimeout(function () {
      callback(returnValue);
    }, 0);
  }

  /**
   * @param {ViewOptions} options View options.
   * @return {import("./centerconstraint.js").Type} The constraint.
   */
  function createCenterConstraint(options) {
    if (options.extent !== undefined) {
      const smooth =
        options.smoothExtentConstraint !== undefined
          ? options.smoothExtentConstraint
          : true;
      return createExtent(options.extent, options.constrainOnlyCenter, smooth);
    }

    const projection = createProjection(options.projection, 'EPSG:3857');
    if (options.multiWorld !== true && projection.isGlobal()) {
      const extent = projection.getExtent().slice();
      extent[0] = -Infinity;
      extent[2] = Infinity;
      return createExtent(extent, false, false);
    }

    return none$1;
  }

  /**
   * @param {ViewOptions} options View options.
   * @return {{constraint: import("./resolutionconstraint.js").Type, maxResolution: number,
   *     minResolution: number, minZoom: number, zoomFactor: number}} The constraint.
   */
  function createResolutionConstraint(options) {
    let resolutionConstraint;
    let maxResolution;
    let minResolution;

    // TODO: move these to be ol constants
    // see https://github.com/openlayers/openlayers/issues/2076
    const defaultMaxZoom = 28;
    const defaultZoomFactor = 2;

    let minZoom =
      options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM;

    let maxZoom =
      options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom;

    const zoomFactor =
      options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor;

    const multiWorld =
      options.multiWorld !== undefined ? options.multiWorld : false;

    const smooth =
      options.smoothResolutionConstraint !== undefined
        ? options.smoothResolutionConstraint
        : true;

    const showFullExtent =
      options.showFullExtent !== undefined ? options.showFullExtent : false;

    const projection = createProjection(options.projection, 'EPSG:3857');
    const projExtent = projection.getExtent();
    let constrainOnlyCenter = options.constrainOnlyCenter;
    let extent = options.extent;
    if (!multiWorld && !extent && projection.isGlobal()) {
      constrainOnlyCenter = false;
      extent = projExtent;
    }

    if (options.resolutions !== undefined) {
      const resolutions = options.resolutions;
      maxResolution = resolutions[minZoom];
      minResolution =
        resolutions[maxZoom] !== undefined
          ? resolutions[maxZoom]
          : resolutions[resolutions.length - 1];

      if (options.constrainResolution) {
        resolutionConstraint = createSnapToResolutions(
          resolutions,
          smooth,
          !constrainOnlyCenter && extent,
          showFullExtent,
        );
      } else {
        resolutionConstraint = createMinMaxResolution(
          maxResolution,
          minResolution,
          smooth,
          !constrainOnlyCenter && extent,
          showFullExtent,
        );
      }
    } else {
      // calculate the default min and max resolution
      const size = !projExtent
        ? // use an extent that can fit the whole world if need be
          (360 * METERS_PER_UNIT$1.degrees) / projection.getMetersPerUnit()
        : Math.max(getWidth(projExtent), getHeight(projExtent));

      const defaultMaxResolution =
        size / DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM);

      const defaultMinResolution =
        defaultMaxResolution /
        Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM);

      // user provided maxResolution takes precedence
      maxResolution = options.maxResolution;
      if (maxResolution !== undefined) {
        minZoom = 0;
      } else {
        maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom);
      }

      // user provided minResolution takes precedence
      minResolution = options.minResolution;
      if (minResolution === undefined) {
        if (options.maxZoom !== undefined) {
          if (options.maxResolution !== undefined) {
            minResolution = maxResolution / Math.pow(zoomFactor, maxZoom);
          } else {
            minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom);
          }
        } else {
          minResolution = defaultMinResolution;
        }
      }

      // given discrete zoom levels, minResolution may be different than provided
      maxZoom =
        minZoom +
        Math.floor(
          Math.log(maxResolution / minResolution) / Math.log(zoomFactor),
        );
      minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom);

      if (options.constrainResolution) {
        resolutionConstraint = createSnapToPower(
          zoomFactor,
          maxResolution,
          minResolution,
          smooth,
          !constrainOnlyCenter && extent,
          showFullExtent,
        );
      } else {
        resolutionConstraint = createMinMaxResolution(
          maxResolution,
          minResolution,
          smooth,
          !constrainOnlyCenter && extent,
          showFullExtent,
        );
      }
    }
    return {
      constraint: resolutionConstraint,
      maxResolution: maxResolution,
      minResolution: minResolution,
      minZoom: minZoom,
      zoomFactor: zoomFactor,
    };
  }

  /**
   * @param {ViewOptions} options View options.
   * @return {import("./rotationconstraint.js").Type} Rotation constraint.
   */
  function createRotationConstraint(options) {
    const enableRotation =
      options.enableRotation !== undefined ? options.enableRotation : true;
    if (enableRotation) {
      const constrainRotation = options.constrainRotation;
      if (constrainRotation === undefined || constrainRotation === true) {
        return createSnapToZero();
      }
      if (constrainRotation === false) {
        return none;
      }
      if (typeof constrainRotation === 'number') {
        return createSnapToN(constrainRotation);
      }
      return none;
    }
    return disable;
  }

  /**
   * Determine if an animation involves no view change.
   * @param {Animation} animation The animation.
   * @return {boolean} The animation involves no view change.
   */
  function isNoopAnimation(animation) {
    if (animation.sourceCenter && animation.targetCenter) {
      if (!equals(animation.sourceCenter, animation.targetCenter)) {
        return false;
      }
    }
    if (animation.sourceResolution !== animation.targetResolution) {
      return false;
    }
    if (animation.sourceRotation !== animation.targetRotation) {
      return false;
    }
    return true;
  }

  /**
   * @param {import("./coordinate.js").Coordinate} coordinate Coordinate.
   * @param {import("./size.js").Size} size Box pixel size.
   * @param {import("./pixel.js").Pixel} position Position on the view to center on.
   * @param {number} resolution Resolution.
   * @param {number} rotation Rotation.
   * @return {import("./coordinate.js").Coordinate} Shifted center.
   */
  function calculateCenterOn(coordinate, size, position, resolution, rotation) {
    // calculate rotated position
    const cosAngle = Math.cos(-rotation);
    let sinAngle = Math.sin(-rotation);
    let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle;
    let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle;
    rotX += (size[0] / 2 - position[0]) * resolution;
    rotY += (position[1] - size[1] / 2) * resolution;

    // go back to original angle
    sinAngle = -sinAngle; // go back to original rotation
    const centerX = rotX * cosAngle - rotY * sinAngle;
    const centerY = rotY * cosAngle + rotX * sinAngle;

    return [centerX, centerY];
  }

  /**
   * @module ol/layer/Property
   */

  /**
   * @enum {string}
   */
  var LayerProperty = {
    OPACITY: 'opacity',
    VISIBLE: 'visible',
    EXTENT: 'extent',
    Z_INDEX: 'zIndex',
    MAX_RESOLUTION: 'maxResolution',
    MIN_RESOLUTION: 'minResolution',
    MAX_ZOOM: 'maxZoom',
    MIN_ZOOM: 'minZoom',
    SOURCE: 'source',
    MAP: 'map',
  };

  /**
   * @module ol/layer/Base
   */

  /**
   * A css color, or a function called with a view resolution returning a css color.
   *
   * @typedef {string|function(number):string} BackgroundColor
   * @api
   */

  /**
   * @typedef {import("../ObjectEventType").Types|'change:extent'|'change:maxResolution'|'change:maxZoom'|
   *    'change:minResolution'|'change:minZoom'|'change:opacity'|'change:visible'|'change:zIndex'} BaseLayerObjectEventTypes
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<BaseLayerObjectEventTypes, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|BaseLayerObjectEventTypes, Return>} BaseLayerOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number | undefined} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Note that with {@link module:ol/layer/Base~BaseLayer} and all its subclasses, any property set in
   * the options is set as a {@link module:ol/Object~BaseObject} property on the layer object, so
   * is observable, and has get/set accessors.
   *
   * @api
   */
  class BaseLayer extends BaseObject {
    /**
     * @param {Options} options Layer options.
     */
    constructor(options) {
      super();

      /***
       * @type {BaseLayerOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {BaseLayerOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {BaseLayerOnSignature<void>}
       */
      this.un;

      /**
       * @type {BackgroundColor|false}
       * @private
       */
      this.background_ = options.background;

      /**
       * @type {Object<string, *>}
       */
      const properties = Object.assign({}, options);
      if (typeof options.properties === 'object') {
        delete properties.properties;
        Object.assign(properties, options.properties);
      }

      properties[LayerProperty.OPACITY] =
        options.opacity !== undefined ? options.opacity : 1;
      assert(
        typeof properties[LayerProperty.OPACITY] === 'number',
        'Layer opacity must be a number',
      );

      properties[LayerProperty.VISIBLE] =
        options.visible !== undefined ? options.visible : true;
      properties[LayerProperty.Z_INDEX] = options.zIndex;
      properties[LayerProperty.MAX_RESOLUTION] =
        options.maxResolution !== undefined ? options.maxResolution : Infinity;
      properties[LayerProperty.MIN_RESOLUTION] =
        options.minResolution !== undefined ? options.minResolution : 0;
      properties[LayerProperty.MIN_ZOOM] =
        options.minZoom !== undefined ? options.minZoom : -Infinity;
      properties[LayerProperty.MAX_ZOOM] =
        options.maxZoom !== undefined ? options.maxZoom : Infinity;

      /**
       * @type {string}
       * @private
       */
      this.className_ =
        properties.className !== undefined ? properties.className : 'ol-layer';
      delete properties.className;

      this.setProperties(properties);

      /**
       * @type {import("./Layer.js").State}
       * @private
       */
      this.state_ = null;
    }

    /**
     * Get the background for this layer.
     * @return {BackgroundColor|false} Layer background.
     */
    getBackground() {
      return this.background_;
    }

    /**
     * @return {string} CSS class name.
     */
    getClassName() {
      return this.className_;
    }

    /**
     * This method is not meant to be called by layers or layer renderers because the state
     * is incorrect if the layer is included in a layer group.
     *
     * @param {boolean} [managed] Layer is managed.
     * @return {import("./Layer.js").State} Layer state.
     */
    getLayerState(managed) {
      /** @type {import("./Layer.js").State} */
      const state =
        this.state_ ||
        /** @type {?} */ ({
          layer: this,
          managed: managed === undefined ? true : managed,
        });
      const zIndex = this.getZIndex();
      state.opacity = clamp$1(Math.round(this.getOpacity() * 100) / 100, 0, 1);
      state.visible = this.getVisible();
      state.extent = this.getExtent();
      state.zIndex = zIndex === undefined && !state.managed ? Infinity : zIndex;
      state.maxResolution = this.getMaxResolution();
      state.minResolution = Math.max(this.getMinResolution(), 0);
      state.minZoom = this.getMinZoom();
      state.maxZoom = this.getMaxZoom();
      this.state_ = state;

      return state;
    }

    /**
     * @abstract
     * @param {Array<import("./Layer.js").default>} [array] Array of layers (to be
     *     modified in place).
     * @return {Array<import("./Layer.js").default>} Array of layers.
     */
    getLayersArray(array) {
      return abstract();
    }

    /**
     * @abstract
     * @param {Array<import("./Layer.js").State>} [states] Optional list of layer
     *     states (to be modified in place).
     * @return {Array<import("./Layer.js").State>} List of layer states.
     */
    getLayerStatesArray(states) {
      return abstract();
    }

    /**
     * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it
     * will be visible regardless of extent.
     * @return {import("../extent.js").Extent|undefined} The layer extent.
     * @observable
     * @api
     */
    getExtent() {
      return /** @type {import("../extent.js").Extent|undefined} */ (
        this.get(LayerProperty.EXTENT)
      );
    }

    /**
     * Return the maximum resolution of the layer. Returns Infinity if
     * the layer has no maximum resolution set.
     * @return {number} The maximum resolution of the layer.
     * @observable
     * @api
     */
    getMaxResolution() {
      return /** @type {number} */ (this.get(LayerProperty.MAX_RESOLUTION));
    }

    /**
     * Return the minimum resolution of the layer. Returns 0 if
     * the layer has no minimum resolution set.
     * @return {number} The minimum resolution of the layer.
     * @observable
     * @api
     */
    getMinResolution() {
      return /** @type {number} */ (this.get(LayerProperty.MIN_RESOLUTION));
    }

    /**
     * Return the minimum zoom level of the layer. Returns -Infinity if
     * the layer has no minimum zoom set.
     * @return {number} The minimum zoom level of the layer.
     * @observable
     * @api
     */
    getMinZoom() {
      return /** @type {number} */ (this.get(LayerProperty.MIN_ZOOM));
    }

    /**
     * Return the maximum zoom level of the layer. Returns Infinity if
     * the layer has no maximum zoom set.
     * @return {number} The maximum zoom level of the layer.
     * @observable
     * @api
     */
    getMaxZoom() {
      return /** @type {number} */ (this.get(LayerProperty.MAX_ZOOM));
    }

    /**
     * Return the opacity of the layer (between 0 and 1).
     * @return {number} The opacity of the layer.
     * @observable
     * @api
     */
    getOpacity() {
      return /** @type {number} */ (this.get(LayerProperty.OPACITY));
    }

    /**
     * @abstract
     * @return {import("../source/Source.js").State} Source state.
     */
    getSourceState() {
      return abstract();
    }

    /**
     * Return the value of this layer's `visible` property. To find out whether the layer
     * is visible on a map, use `isVisible()` instead.
     * @return {boolean} The value of the `visible` property of the layer.
     * @observable
     * @api
     */
    getVisible() {
      return /** @type {boolean} */ (this.get(LayerProperty.VISIBLE));
    }

    /**
     * Return the Z-index of the layer, which is used to order layers before
     * rendering. Returns undefined if the layer is unmanaged.
     * @return {number|undefined} The Z-index of the layer.
     * @observable
     * @api
     */
    getZIndex() {
      return /** @type {number|undefined} */ (this.get(LayerProperty.Z_INDEX));
    }

    /**
     * Sets the background color.
     * @param {BackgroundColor} [background] Background color.
     */
    setBackground(background) {
      this.background_ = background;
      this.changed();
    }

    /**
     * Set the extent at which the layer is visible.  If `undefined`, the layer
     * will be visible at all extents.
     * @param {import("../extent.js").Extent|undefined} extent The extent of the layer.
     * @observable
     * @api
     */
    setExtent(extent) {
      this.set(LayerProperty.EXTENT, extent);
    }

    /**
     * Set the maximum resolution at which the layer is visible.
     * @param {number} maxResolution The maximum resolution of the layer.
     * @observable
     * @api
     */
    setMaxResolution(maxResolution) {
      this.set(LayerProperty.MAX_RESOLUTION, maxResolution);
    }

    /**
     * Set the minimum resolution at which the layer is visible.
     * @param {number} minResolution The minimum resolution of the layer.
     * @observable
     * @api
     */
    setMinResolution(minResolution) {
      this.set(LayerProperty.MIN_RESOLUTION, minResolution);
    }

    /**
     * Set the maximum zoom (exclusive) at which the layer is visible.
     * Note that the zoom levels for layer visibility are based on the
     * view zoom level, which may be different from a tile source zoom level.
     * @param {number} maxZoom The maximum zoom of the layer.
     * @observable
     * @api
     */
    setMaxZoom(maxZoom) {
      this.set(LayerProperty.MAX_ZOOM, maxZoom);
    }

    /**
     * Set the minimum zoom (inclusive) at which the layer is visible.
     * Note that the zoom levels for layer visibility are based on the
     * view zoom level, which may be different from a tile source zoom level.
     * @param {number} minZoom The minimum zoom of the layer.
     * @observable
     * @api
     */
    setMinZoom(minZoom) {
      this.set(LayerProperty.MIN_ZOOM, minZoom);
    }

    /**
     * Set the opacity of the layer, allowed values range from 0 to 1.
     * @param {number} opacity The opacity of the layer.
     * @observable
     * @api
     */
    setOpacity(opacity) {
      assert(typeof opacity === 'number', 'Layer opacity must be a number');
      this.set(LayerProperty.OPACITY, opacity);
    }

    /**
     * Set the visibility of the layer (`true` or `false`).
     * @param {boolean} visible The visibility of the layer.
     * @observable
     * @api
     */
    setVisible(visible) {
      this.set(LayerProperty.VISIBLE, visible);
    }

    /**
     * Set Z-index of the layer, which is used to order layers before rendering.
     * The default Z-index is 0.
     * @param {number} zindex The z-index of the layer.
     * @observable
     * @api
     */
    setZIndex(zindex) {
      this.set(LayerProperty.Z_INDEX, zindex);
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      if (this.state_) {
        this.state_.layer = null;
        this.state_ = null;
      }
      super.disposeInternal();
    }
  }

  /**
   * @module ol/layer/Layer
   */

  /**
   * @typedef {function(import("../Map.js").FrameState):HTMLElement} RenderFunction
   */

  /**
   * @typedef {'sourceready'|'change:source'} LayerEventType
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("./Base").BaseLayerObjectEventTypes|
   *     LayerEventType, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("../render/EventType").LayerRenderEventTypes, import("../render/Event").default, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("./Base").BaseLayerObjectEventTypes|LayerEventType|
   *     import("../render/EventType").LayerRenderEventTypes, Return>} LayerOnSignature
   */

  /**
   * @template {import("../source/Source.js").default} [SourceType=import("../source/Source.js").default]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {SourceType} [source] Source for this layer.  If not provided to the constructor,
   * the source can be set by calling {@link module:ol/layer/Layer~Layer#setSource layer.setSource(source)} after
   * construction.
   * @property {import("../Map.js").default|null} [map] Map.
   * @property {RenderFunction} [render] Render function. Takes the frame state as input and is expected to return an
   * HTML element. Will overwrite the default rendering for the layer.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @typedef {Object} State
   * @property {import("./Layer.js").default} layer Layer.
   * @property {number} opacity Opacity, the value is rounded to two digits to appear after the decimal point.
   * @property {boolean} visible Visible.
   * @property {boolean} managed Managed.
   * @property {import("../extent.js").Extent} [extent] Extent.
   * @property {number} zIndex ZIndex.
   * @property {number} maxResolution Maximum resolution.
   * @property {number} minResolution Minimum resolution.
   * @property {number} minZoom Minimum zoom.
   * @property {number} maxZoom Maximum zoom.
   */

  /**
   * @classdesc
   * Base class from which all layer types are derived. This should only be instantiated
   * in the case where a custom layer is added to the map with a custom `render` function.
   * Such a function can be specified in the `options` object, and is expected to return an HTML element.
   *
   * A visual representation of raster or vector map data.
   * Layers group together those properties that pertain to how the data is to be
   * displayed, irrespective of the source of that data.
   *
   * Layers are usually added to a map with [map.addLayer()]{@link import("../Map.js").default#addLayer}.
   * Components like {@link module:ol/interaction/Draw~Draw} use unmanaged layers
   * internally. These unmanaged layers are associated with the map using
   * [layer.setMap()]{@link module:ol/layer/Layer~Layer#setMap} instead.
   *
   * A generic `change` event is fired when the state of the source changes.
   * A `sourceready` event is fired when the layer's source is ready.
   *
   * @fires import("../render/Event.js").RenderEvent#prerender
   * @fires import("../render/Event.js").RenderEvent#postrender
   * @fires import("../events/Event.js").BaseEvent#sourceready
   *
   * @template {import("../source/Source.js").default} [SourceType=import("../source/Source.js").default]
   * @template {import("../renderer/Layer.js").default} [RendererType=import("../renderer/Layer.js").default]
   * @api
   */
  class Layer extends BaseLayer {
    /**
     * @param {Options<SourceType>} options Layer options.
     */
    constructor(options) {
      const baseOptions = Object.assign({}, options);
      delete baseOptions.source;

      super(baseOptions);

      /***
       * @type {LayerOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {LayerOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {LayerOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {?import("../events.js").EventsKey}
       */
      this.mapPrecomposeKey_ = null;

      /**
       * @private
       * @type {?import("../events.js").EventsKey}
       */
      this.mapRenderKey_ = null;

      /**
       * @private
       * @type {?import("../events.js").EventsKey}
       */
      this.sourceChangeKey_ = null;

      /**
       * @private
       * @type {RendererType}
       */
      this.renderer_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.sourceReady_ = false;

      /**
       * @protected
       * @type {boolean}
       */
      this.rendered = false;

      // Overwrite default render method with a custom one
      if (options.render) {
        this.render = options.render;
      }

      if (options.map) {
        this.setMap(options.map);
      }

      this.addChangeListener(
        LayerProperty.SOURCE,
        this.handleSourcePropertyChange_,
      );

      const source = options.source
        ? /** @type {SourceType} */ (options.source)
        : null;
      this.setSource(source);
    }

    /**
     * @param {Array<import("./Layer.js").default>} [array] Array of layers (to be modified in place).
     * @return {Array<import("./Layer.js").default>} Array of layers.
     * @override
     */
    getLayersArray(array) {
      array = array ? array : [];
      array.push(this);
      return array;
    }

    /**
     * @param {Array<import("./Layer.js").State>} [states] Optional list of layer states (to be modified in place).
     * @return {Array<import("./Layer.js").State>} List of layer states.
     * @override
     */
    getLayerStatesArray(states) {
      states = states ? states : [];
      states.push(this.getLayerState());
      return states;
    }

    /**
     * Get the layer source.
     * @return {SourceType|null} The layer source (or `null` if not yet set).
     * @observable
     * @api
     */
    getSource() {
      return /** @type {SourceType} */ (this.get(LayerProperty.SOURCE)) || null;
    }

    /**
     * @return {SourceType|null} The source being rendered.
     */
    getRenderSource() {
      return this.getSource();
    }

    /**
     * @return {import("../source/Source.js").State} Source state.
     * @override
     */
    getSourceState() {
      const source = this.getSource();
      return !source ? 'undefined' : source.getState();
    }

    /**
     * @private
     */
    handleSourceChange_() {
      this.changed();
      if (this.sourceReady_ || this.getSource().getState() !== 'ready') {
        return;
      }
      this.sourceReady_ = true;
      this.dispatchEvent('sourceready');
    }

    /**
     * @private
     */
    handleSourcePropertyChange_() {
      if (this.sourceChangeKey_) {
        unlistenByKey(this.sourceChangeKey_);
        this.sourceChangeKey_ = null;
      }
      this.sourceReady_ = false;
      const source = this.getSource();
      if (source) {
        this.sourceChangeKey_ = listen(
          source,
          EventType.CHANGE,
          this.handleSourceChange_,
          this,
        );
        if (source.getState() === 'ready') {
          this.sourceReady_ = true;
          setTimeout(() => {
            this.dispatchEvent('sourceready');
          }, 0);
        }
      }
      this.changed();
    }

    /**
     * @param {import("../pixel").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../Feature").FeatureLike>>} Promise that resolves with
     * an array of features.
     */
    getFeatures(pixel) {
      if (!this.renderer_) {
        return Promise.resolve([]);
      }
      return this.renderer_.getFeatures(pixel);
    }

    /**
     * @param {import("../pixel").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.
     */
    getData(pixel) {
      if (!this.renderer_ || !this.rendered) {
        return null;
      }
      return this.renderer_.getData(pixel);
    }

    /**
     * The layer is visible on the map view, i.e. within its min/max resolution or zoom and
     * extent, not set to `visible: false`, and not inside a layer group that is set
     * to `visible: false`.
     * @param {View|import("../View.js").ViewStateLayerStateExtent} [view] View or {@link import("../Map.js").FrameState}.
     * Only required when the layer is not added to a map.
     * @return {boolean} The layer is visible in the map view.
     * @api
     */
    isVisible(view) {
      let frameState;
      const map = this.getMapInternal();
      if (!view && map) {
        view = map.getView();
      }
      if (view instanceof View) {
        frameState = {
          viewState: view.getState(),
          extent: view.calculateExtent(),
        };
      } else {
        frameState = view;
      }
      if (!frameState.layerStatesArray && map) {
        frameState.layerStatesArray = map.getLayerGroup().getLayerStatesArray();
      }
      let layerState;
      if (frameState.layerStatesArray) {
        layerState = frameState.layerStatesArray.find(
          (layerState) => layerState.layer === this,
        );
        if (!layerState) {
          return false;
        }
      } else {
        layerState = this.getLayerState();
      }

      const layerExtent = this.getExtent();

      return (
        inView(layerState, frameState.viewState) &&
        (!layerExtent || intersects$2(layerExtent, frameState.extent))
      );
    }

    /**
     * Get the attributions of the source of this layer for the given view.
     * @param {View|import("../View.js").ViewStateLayerStateExtent} [view] View or {@link import("../Map.js").FrameState}.
     * Only required when the layer is not added to a map.
     * @return {Array<string>} Attributions for this layer at the given view.
     * @api
     */
    getAttributions(view) {
      if (!this.isVisible(view)) {
        return [];
      }
      const getAttributions = this.getSource()?.getAttributions();
      if (!getAttributions) {
        return [];
      }
      const frameState =
        view instanceof View ? view.getViewStateAndExtent() : view;
      let attributions = getAttributions(frameState);
      if (!Array.isArray(attributions)) {
        attributions = [attributions];
      }
      return attributions;
    }

    /**
     * In charge to manage the rendering of the layer. One layer type is
     * bounded with one layer renderer.
     * @param {?import("../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement} target Target which the renderer may (but need not) use
     * for rendering its content.
     * @return {HTMLElement|null} The rendered element.
     */
    render(frameState, target) {
      const layerRenderer = this.getRenderer();

      if (layerRenderer.prepareFrame(frameState)) {
        this.rendered = true;
        return layerRenderer.renderFrame(frameState, target);
      }
      return null;
    }

    /**
     * Called when a layer is not visible during a map render.
     */
    unrender() {
      this.rendered = false;
    }

    /** @return {string} Declutter */
    getDeclutter() {
      return undefined;
    }

    /**
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {import("../layer/Layer.js").State} layerState Layer state.
     */
    renderDeclutter(frameState, layerState) {}

    /**
     * When the renderer follows a layout -> render approach, do the final rendering here.
     * @param {import('../Map.js').FrameState} frameState Frame state
     */
    renderDeferred(frameState) {
      const layerRenderer = this.getRenderer();
      if (!layerRenderer) {
        return;
      }
      layerRenderer.renderDeferred(frameState);
    }

    /**
     * For use inside the library only.
     * @param {import("../Map.js").default|null} map Map.
     */
    setMapInternal(map) {
      if (!map) {
        this.unrender();
      }
      this.set(LayerProperty.MAP, map);
    }

    /**
     * For use inside the library only.
     * @return {import("../Map.js").default|null} Map.
     */
    getMapInternal() {
      return this.get(LayerProperty.MAP);
    }

    /**
     * Sets the layer to be rendered on top of other layers on a map. The map will
     * not manage this layer in its layers collection. This
     * is useful for temporary layers. To remove an unmanaged layer from the map,
     * use `#setMap(null)`.
     *
     * To add the layer to a map and have it managed by the map, use
     * {@link module:ol/Map~Map#addLayer} instead.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     */
    setMap(map) {
      if (this.mapPrecomposeKey_) {
        unlistenByKey(this.mapPrecomposeKey_);
        this.mapPrecomposeKey_ = null;
      }
      if (!map) {
        this.changed();
      }
      if (this.mapRenderKey_) {
        unlistenByKey(this.mapRenderKey_);
        this.mapRenderKey_ = null;
      }
      if (map) {
        this.mapPrecomposeKey_ = listen(
          map,
          RenderEventType.PRECOMPOSE,
          this.handlePrecompose_,
          this,
        );
        this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map);
        this.changed();
      }
    }

    /**
     * @param {import("../events/Event.js").default} renderEvent Render event
     * @private
     */
    handlePrecompose_(renderEvent) {
      const layerStatesArray =
        /** @type {import("../render/Event.js").default} */ (renderEvent)
          .frameState.layerStatesArray;
      const layerState = this.getLayerState(false);
      assert(
        !layerStatesArray.some(
          (arrayLayerState) => arrayLayerState.layer === layerState.layer,
        ),
        'A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both.',
      );
      layerStatesArray.push(layerState);
    }

    /**
     * Set the layer source.
     * @param {SourceType|null} source The layer source.
     * @observable
     * @api
     */
    setSource(source) {
      this.set(LayerProperty.SOURCE, source);
    }

    /**
     * Get the renderer for this layer.
     * @return {RendererType|null} The layer renderer.
     */
    getRenderer() {
      if (!this.renderer_) {
        this.renderer_ = this.createRenderer();
      }
      return this.renderer_;
    }

    /**
     * @return {boolean} The layer has a renderer.
     */
    hasRenderer() {
      return !!this.renderer_;
    }

    /**
     * Create a renderer for this layer.
     * @return {RendererType} A layer renderer.
     * @protected
     */
    createRenderer() {
      return null;
    }

    /**
     * This will clear the renderer so that a new one can be created next time it is needed
     */
    clearRenderer() {
      if (this.renderer_) {
        this.renderer_.dispose();
        delete this.renderer_;
      }
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.clearRenderer();
      this.setSource(null);
      super.disposeInternal();
    }
  }

  /**
   * Return `true` if the layer is visible and if the provided view state
   * has resolution and zoom levels that are in range of the layer's min/max.
   * @param {State} layerState Layer state.
   * @param {import("../View.js").State} viewState View state.
   * @return {boolean} The layer is visible at the given view state.
   */
  function inView(layerState, viewState) {
    if (!layerState.visible) {
      return false;
    }
    const resolution = viewState.resolution;
    if (
      resolution < layerState.minResolution ||
      resolution >= layerState.maxResolution
    ) {
      return false;
    }
    const zoom = viewState.zoom;
    return zoom > layerState.minZoom && zoom <= layerState.maxZoom;
  }

  /**
   * @module ol/layer/BaseVector
   */

  /***
   * @template T
   * @typedef {T extends import("../source/Vector.js").default<infer U extends import("../Feature.js").FeatureLike> ? U : never} ExtractedFeatureType
   */

  /**
   * @template {import('../Feature').FeatureLike} FeatureType
   * @template {import("../source/Vector.js").default<FeatureType>|import("../source/VectorTile.js").default<FeatureType>} VectorSourceType<FeatureType>
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
   * features before rendering. By default features are drawn in the order that they are created. Use
   * `null` to avoid the sort, but get an undefined draw order.
   * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the
   * renderer when getting features from the vector source for the rendering or hit-detection.
   * Recommended value: the size of the largest symbol, line width or label.
   * @property {VectorSourceType} [source] Source.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use [map.addLayer()]{@link import("../Map.js").default#addLayer}.
   * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable
   * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the
   * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the
   * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct
   * layers or groups of layers separately, use different truthy values for `declutter`.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. When set to `null`, only
   * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style
   * which will be used if this is not set.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will
   * be recreated during animations. This means that no vectors will be shown clipped, but the
   * setting will have a performance impact for large amounts of vector data. When set to `false`,
   * batches will be recreated when no animation is active.
   * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will
   * be recreated during interactions. See also `updateWhileAnimating`.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @enum {string}
   * @private
   */
  const Property$3 = {
    RENDER_ORDER: 'renderOrder',
  };

  /**
   * @classdesc
   * Vector data that is rendered client-side.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import('../Feature').FeatureLike} FeatureType
   * @template {import("../source/Vector.js").default<FeatureType>|import("../source/VectorTile.js").default<FeatureType>} VectorSourceType<FeatureType>
   * @extends {Layer<VectorSourceType, RendererType>}
   * @template {import("../renderer/canvas/VectorLayer.js").default|import("../renderer/canvas/VectorTileLayer.js").default|import("../renderer/canvas/VectorImageLayer.js").default|import("../renderer/webgl/VectorLayer.js").default|import("../renderer/webgl/PointsLayer.js").default} RendererType
   * @api
   */
  class BaseVectorLayer extends Layer {
    /**
     * @param {Options<FeatureType, VectorSourceType>} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign({}, options);

      delete baseOptions.style;
      delete baseOptions.renderBuffer;
      delete baseOptions.updateWhileAnimating;
      delete baseOptions.updateWhileInteracting;
      super(baseOptions);

      /**
       * @private
       * @type {string}
       */
      this.declutter_ = options.declutter ? String(options.declutter) : undefined;

      /**
       * @type {number}
       * @private
       */
      this.renderBuffer_ =
        options.renderBuffer !== undefined ? options.renderBuffer : 100;

      /**
       * User provided style.
       * @type {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike}
       * @private
       */
      this.style_ = null;

      /**
       * Style function for use within the library.
       * @type {import("../style/Style.js").StyleFunction|undefined}
       * @private
       */
      this.styleFunction_ = undefined;

      this.setStyle(options.style);

      /**
       * @type {boolean}
       * @private
       */
      this.updateWhileAnimating_ =
        options.updateWhileAnimating !== undefined
          ? options.updateWhileAnimating
          : false;

      /**
       * @type {boolean}
       * @private
       */
      this.updateWhileInteracting_ =
        options.updateWhileInteracting !== undefined
          ? options.updateWhileInteracting
          : false;
    }

    /**
     * @return {string} Declutter group.
     * @override
     */
    getDeclutter() {
      return this.declutter_;
    }

    /**
     * Get the topmost feature that intersects the given pixel on the viewport. Returns a promise
     * that resolves with an array of features. The array will either contain the topmost feature
     * when a hit was detected, or it will be empty.
     *
     * The hit detection algorithm used for this method is optimized for performance, but is less
     * accurate than the one used in [map.getFeaturesAtPixel()]{@link import("../Map.js").default#getFeaturesAtPixel}.
     * Text is not considered, and icons are only represented by their bounding box instead of the exact
     * image.
     *
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../Feature").FeatureLike>>} Promise that resolves with an array of features.
     * @api
     * @override
     */
    getFeatures(pixel) {
      return super.getFeatures(pixel);
    }

    /**
     * @return {number|undefined} Render buffer.
     */
    getRenderBuffer() {
      return this.renderBuffer_;
    }

    /**
     * @return {import("../render.js").OrderFunction|null|undefined} Render order.
     */
    getRenderOrder() {
      return /** @type {import("../render.js").OrderFunction|null|undefined} */ (
        this.get(Property$3.RENDER_ORDER)
      );
    }

    /**
     * Get the style for features.  This returns whatever was passed to the `style`
     * option at construction or to the `setStyle` method.
     * @return {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null|undefined} Layer style.
     * @api
     */
    getStyle() {
      return this.style_;
    }

    /**
     * Get the style function.
     * @return {import("../style/Style.js").StyleFunction|undefined} Layer style function.
     * @api
     */
    getStyleFunction() {
      return this.styleFunction_;
    }

    /**
     * @return {boolean} Whether the rendered layer should be updated while
     *     animating.
     */
    getUpdateWhileAnimating() {
      return this.updateWhileAnimating_;
    }

    /**
     * @return {boolean} Whether the rendered layer should be updated while
     *     interacting.
     */
    getUpdateWhileInteracting() {
      return this.updateWhileInteracting_;
    }

    /**
     * Render declutter items for this layer
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {import("../layer/Layer.js").State} layerState Layer state.
     * @override
     */
    renderDeclutter(frameState, layerState) {
      const declutterGroup = this.getDeclutter();
      if (declutterGroup in frameState.declutter === false) {
        frameState.declutter[declutterGroup] = new RBush$1(9);
      }
      this.getRenderer().renderDeclutter(frameState, layerState);
    }

    /**
     * @param {import("../render.js").OrderFunction|null|undefined} renderOrder
     *     Render order.
     */
    setRenderOrder(renderOrder) {
      this.set(Property$3.RENDER_ORDER, renderOrder);
    }

    /**
     * Set the style for features.  This can be a single style object, an array
     * of styles, or a function that takes a feature and resolution and returns
     * an array of styles. If set to `null`, the layer has no style (a `null` style),
     * so only features that have their own styles will be rendered in the layer. Call
     * `setStyle()` without arguments to reset to the default style. See
     * [the ol/style/Style module]{@link module:ol/style/Style~Style} for information on the default style.
     *
     * If your layer has a static style, you can use [flat style]{@link module:ol/style/flat~FlatStyle} object
     * literals instead of using the `Style` and symbolizer constructors (`Fill`, `Stroke`, etc.):
     * ```js
     * vectorLayer.setStyle({
     *   "fill-color": "yellow",
     *   "stroke-color": "black",
     *   "stroke-width": 4
     * })
     * ```
     *
     * @param {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style.
     * @api
     */
    setStyle(style) {
      this.style_ = style === undefined ? createDefaultStyle$1 : style;
      const styleLike = toStyleLike(style);
      this.styleFunction_ =
        style === null ? undefined : toFunction(styleLike);
      this.changed();
    }

    /**
     * @param {boolean|string|number} declutter Declutter images and text.
     * @api
     */
    setDeclutter(declutter) {
      this.declutter_ = declutter ? String(declutter) : undefined;
      this.changed();
    }
  }

  /**
   * Coerce the allowed style types into a shorter list of types.  Flat styles, arrays of flat
   * styles, and arrays of rules are converted into style functions.
   *
   * @param {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style.
   * @return {import("../style/Style.js").StyleLike|null} The style.
   */
  function toStyleLike(style) {
    if (style === undefined) {
      return createDefaultStyle$1;
    }
    if (!style) {
      return null;
    }
    if (typeof style === 'function') {
      return style;
    }
    if (style instanceof Style) {
      return style;
    }
    if (!Array.isArray(style)) {
      return flatStylesToStyleFunction([style]);
    }
    if (style.length === 0) {
      return [];
    }

    const length = style.length;
    const first = style[0];

    if (first instanceof Style) {
      /**
       * @type {Array<Style>}
       */
      const styles = new Array(length);
      for (let i = 0; i < length; ++i) {
        const candidate = style[i];
        if (!(candidate instanceof Style)) {
          throw new Error('Expected a list of style instances');
        }
        styles[i] = candidate;
      }
      return styles;
    }

    if ('style' in first) {
      /**
       * @type {Array<import("../style/flat.js").Rule>}
       */
      const rules = new Array(length);
      for (let i = 0; i < length; ++i) {
        const candidate = style[i];
        if (!('style' in candidate)) {
          throw new Error('Expected a list of rules with a style property');
        }
        rules[i] = candidate;
      }
      return rulesToStyleFunction(rules);
    }

    const flatStyles =
      /** @type {Array<import("../style/flat.js").FlatStyle>} */ (style);
    return flatStylesToStyleFunction(flatStyles);
  }

  /**
   * @module ol/layer/Vector
   */

  /**
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("./BaseVector.js").ExtractedFeatureType<VectorSourceType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
   * features before rendering. By default features are drawn in the order that they are created. Use
   * `null` to avoid the sort, but get an undefined draw order.
   * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the
   * renderer when getting features from the vector source for the rendering or hit-detection.
   * Recommended value: the size of the largest symbol, line width or label.
   * @property {VectorSourceType} [source] Source.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use [map.addLayer()]{@link import("../Map.js").default#addLayer}.
   * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable
   * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the
   * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the
   * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct
   * layers or groups of layers separately, use different truthy values for `declutter`.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. When set to `null`, only
   * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style
   * which will be used if this is not set.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will
   * be recreated during animations. This means that no vectors will be shown clipped, but the
   * setting will have a performance impact for large amounts of vector data. When set to `false`,
   * batches will be recreated when no animation is active.
   * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will
   * be recreated during interactions. See also `updateWhileAnimating`.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Vector data is rendered client-side, as vectors. This layer type provides most accurate rendering
   * even during animations. Points and labels stay upright on rotated views. For very large
   * amounts of vector data, performance may suffer during pan and zoom animations. In this case,
   * try {@link module:ol/layer/VectorImage~VectorImageLayer}.
   *
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("./BaseVector.js").ExtractedFeatureType<VectorSourceType>]
   * @extends {BaseVectorLayer<FeatureType, VectorSourceType, CanvasVectorLayerRenderer>}
   * @api
   */
  class VectorLayer extends BaseVectorLayer {
    /**
     * @param {Options<VectorSourceType, FeatureType>} [options] Options.
     */
    constructor(options) {
      super(options);
    }

    /**
     * @override
     */
    createRenderer() {
      return new CanvasVectorLayerRenderer(this);
    }
  }

  /**
   * @module ol/layer/Graticule
   */

  /**
   * @type {Stroke}
   * @private
   * @const
   */
  const DEFAULT_STROKE_STYLE$1 = new Stroke({
    color: 'rgba(0,0,0,0.2)',
  });

  /**
   * @type {Array<number>}
   * @private
   */
  const INTERVALS = [
    90,
    45,
    30,
    20,
    10,
    5,
    2,
    1,
    30 / 60,
    20 / 60,
    10 / 60,
    5 / 60,
    2 / 60,
    1 / 60,
    30 / 3600,
    20 / 3600,
    10 / 3600,
    5 / 3600,
    2 / 3600,
    1 / 3600,
  ];

  /**
   * @typedef {Object} GraticuleLabelDataType
   * @property {Point} geom Geometry.
   * @property {string} text Text.
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {number} [maxLines=100] The maximum number of meridians and
   * parallels from the center of the map. The default value of 100 means that at
   * most 200 meridians and 200 parallels will be displayed. The default value is
   * appropriate for conformal projections like Spherical Mercator. If you
   * increase the value, more lines will be drawn and the drawing performance will
   * decrease.
   * @property {Stroke} [strokeStyle] The
   * stroke style to use for drawing the graticule. If not provided, the following stroke will be used:
   * ```js
   * new Stroke({
   *   color: 'rgba(0, 0, 0, 0.2)' // a not fully opaque black
   * });
   * ```
   * @property {number} [targetSize=100] The target size of the graticule cells,
   * in pixels.
   * @property {boolean} [showLabels=false] Render a label with the respective
   * latitude/longitude for each graticule line.
   * @property {function(number):string} [lonLabelFormatter] Label formatter for
   * longitudes. This function is called with the longitude as argument, and
   * should return a formatted string representing the longitude. By default,
   * labels are formatted as degrees, minutes, seconds and hemisphere.
   * @property {function(number):string} [latLabelFormatter] Label formatter for
   * latitudes. This function is called with the latitude as argument, and
   * should return a formatted string representing the latitude. By default,
   * labels are formatted as degrees, minutes, seconds and hemisphere.
   * @property {number} [lonLabelPosition=0] Longitude label position in fractions
   * (0..1) of view extent. 0 means at the bottom of the viewport, 1 means at the
   * top.
   * @property {number} [latLabelPosition=1] Latitude label position in fractions
   * (0..1) of view extent. 0 means at the left of the viewport, 1 means at the
   * right.
   * @property {Text} [lonLabelStyle] Longitude label text
   * style. If not provided, the following style will be used:
   * ```js
   * new Text({
   *   font: '12px Calibri,sans-serif',
   *   textBaseline: 'bottom',
   *   fill: new Fill({
   *     color: 'rgba(0,0,0,1)'
   *   }),
   *   stroke: new Stroke({
   *     color: 'rgba(255,255,255,1)',
   *     width: 3
   *   })
   * });
   * ```
   * Note that the default's `textBaseline` configuration will not work well for
   * `lonLabelPosition` configurations that position labels close to the top of
   * the viewport.
   * @property {Text} [latLabelStyle] Latitude label text style.
   * If not provided, the following style will be used:
   * ```js
   * new Text({
   *   font: '12px Calibri,sans-serif',
   *   textAlign: 'end',
   *   fill: new Fill({
   *     color: 'rgba(0,0,0,1)'
   *   }),
   *   stroke: Stroke({
   *     color: 'rgba(255,255,255,1)',
   *     width: 3
   *   })
   * });
   * ```
   * Note that the default's `textAlign` configuration will not work well for
   * `latLabelPosition` configurations that position labels close to the left of
   * the viewport.
   * @property {Array<number>} [intervals=[90, 45, 30, 20, 10, 5, 2, 1, 30/60, 20/60, 10/60, 5/60, 2/60, 1/60, 30/3600, 20/3600, 10/3600, 5/3600, 2/3600, 1/3600]]
   * Intervals (in degrees) for the graticule. Example to limit graticules to 30 and 10 degrees intervals:
   * ```js
   * [30, 10]
   * ```
   * @property {boolean} [wrapX=true] Whether to repeat the graticule horizontally.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Layer that renders a grid for a coordinate system (currently only EPSG:4326 is supported).
   * Note that the view projection must define both extent and worldExtent.
   *
   * @fires import("../render/Event.js").RenderEvent#prerender
   * @fires import("../render/Event.js").RenderEvent#postrender
   * @extends {VectorLayer<VectorSource<Feature>>}
   * @api
   */
  class Graticule extends VectorLayer {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign(
        {
          updateWhileAnimating: true,
          updateWhileInteracting: true,
          renderBuffer: 0,
        },
        options,
      );

      delete baseOptions.maxLines;
      delete baseOptions.strokeStyle;
      delete baseOptions.targetSize;
      delete baseOptions.showLabels;
      delete baseOptions.lonLabelFormatter;
      delete baseOptions.latLabelFormatter;
      delete baseOptions.lonLabelPosition;
      delete baseOptions.latLabelPosition;
      delete baseOptions.lonLabelStyle;
      delete baseOptions.latLabelStyle;
      delete baseOptions.intervals;
      super(baseOptions);

      /**
       * @type {import("../proj/Projection.js").default}
       * @private
       */
      this.projection_ = null;

      /**
       * @type {number}
       * @private
       */
      this.maxLat_ = Infinity;

      /**
       * @type {number}
       * @private
       */
      this.maxLon_ = Infinity;

      /**
       * @type {number}
       * @private
       */
      this.minLat_ = -Infinity;

      /**
       * @type {number}
       * @private
       */
      this.minLon_ = -Infinity;

      /**
       * @type {number}
       * @private
       */
      this.maxX_ = Infinity;

      /**
       * @type {number}
       * @private
       */
      this.maxY_ = Infinity;

      /**
       * @type {number}
       * @private
       */
      this.minX_ = -Infinity;

      /**
       * @type {number}
       * @private
       */
      this.minY_ = -Infinity;

      /**
       * @type {number}
       * @private
       */
      this.targetSize_ =
        options.targetSize !== undefined ? options.targetSize : 100;

      /**
       * @type {number}
       * @private
       */
      this.maxLines_ = options.maxLines !== undefined ? options.maxLines : 100;

      /**
       * @type {Array<LineString>}
       * @private
       */
      this.meridians_ = [];

      /**
       * @type {Array<LineString>}
       * @private
       */
      this.parallels_ = [];

      /**
       * @type {Stroke}
       * @private
       */
      this.strokeStyle_ =
        options.strokeStyle !== undefined
          ? options.strokeStyle
          : DEFAULT_STROKE_STYLE$1;

      /**
       * @type {import("../proj.js").TransformFunction|undefined}
       * @private
       */
      this.fromLonLatTransform_ = undefined;

      /**
       * @type {import("../proj.js").TransformFunction|undefined}
       * @private
       */
      this.toLonLatTransform_ = undefined;

      /**
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.projectionCenterLonLat_ = null;

      /**
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.bottomLeft_ = null;

      /**
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.bottomRight_ = null;

      /**
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.topLeft_ = null;

      /**
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.topRight_ = null;

      /**
       * @type {Array<GraticuleLabelDataType>}
       * @private
       */
      this.meridiansLabels_ = null;

      /**
       * @type {Array<GraticuleLabelDataType>}
       * @private
       */
      this.parallelsLabels_ = null;

      if (options.showLabels) {
        /**
         * @type {null|function(number):string}
         * @private
         */
        this.lonLabelFormatter_ =
          options.lonLabelFormatter == undefined
            ? degreesToStringHDMS.bind(this, 'EW')
            : options.lonLabelFormatter;

        /**
         * @type {function(number):string}
         * @private
         */
        this.latLabelFormatter_ =
          options.latLabelFormatter == undefined
            ? degreesToStringHDMS.bind(this, 'NS')
            : options.latLabelFormatter;

        /**
         * Longitude label position in fractions (0..1) of view extent. 0 means
         * bottom, 1 means top.
         * @type {number}
         * @private
         */
        this.lonLabelPosition_ =
          options.lonLabelPosition == undefined ? 0 : options.lonLabelPosition;

        /**
         * Latitude Label position in fractions (0..1) of view extent. 0 means left, 1
         * means right.
         * @type {number}
         * @private
         */
        this.latLabelPosition_ =
          options.latLabelPosition == undefined ? 1 : options.latLabelPosition;

        /**
         * @type {Style}
         * @private
         */
        this.lonLabelStyleBase_ = new Style({
          text:
            options.lonLabelStyle !== undefined
              ? options.lonLabelStyle.clone()
              : new Text({
                  font: '12px Calibri,sans-serif',
                  textBaseline: 'bottom',
                  fill: new Fill({
                    color: 'rgba(0,0,0,1)',
                  }),
                  stroke: new Stroke({
                    color: 'rgba(255,255,255,1)',
                    width: 3,
                  }),
                }),
        });

        /**
         * @private
         * @param {import("../Feature").default} feature Feature
         * @return {Style} style
         */
        this.lonLabelStyle_ = (feature) => {
          const label = feature.get('graticule_label');
          this.lonLabelStyleBase_.getText().setText(label);
          return this.lonLabelStyleBase_;
        };

        /**
         * @type {Style}
         * @private
         */
        this.latLabelStyleBase_ = new Style({
          text:
            options.latLabelStyle !== undefined
              ? options.latLabelStyle.clone()
              : new Text({
                  font: '12px Calibri,sans-serif',
                  textAlign: 'right',
                  fill: new Fill({
                    color: 'rgba(0,0,0,1)',
                  }),
                  stroke: new Stroke({
                    color: 'rgba(255,255,255,1)',
                    width: 3,
                  }),
                }),
        });

        /**
         * @private
         * @param {import("../Feature").default} feature Feature
         * @return {Style} style
         */
        this.latLabelStyle_ = (feature) => {
          const label = feature.get('graticule_label');
          this.latLabelStyleBase_.getText().setText(label);
          return this.latLabelStyleBase_;
        };

        this.meridiansLabels_ = [];
        this.parallelsLabels_ = [];

        this.addEventListener(RenderEventType.POSTRENDER, this.drawLabels_.bind(this));
      }

      /**
       * @type {Array<number>}
       * @private
       */
      this.intervals_ =
        options.intervals !== undefined ? options.intervals : INTERVALS;

      // use a source with a custom loader for lines & text
      this.setSource(
        new VectorSource({
          loader: this.loaderFunction.bind(this),
          strategy: this.strategyFunction.bind(this),
          features: new Collection(),
          overlaps: false,
          useSpatialIndex: false,
          wrapX: options.wrapX,
        }),
      );

      /**
       * feature pool to use when updating graticule
       * @type {Array<Feature>}
       * @private
       */
      this.featurePool_ = [];

      /**
       * @type {Style}
       * @private
       */
      this.lineStyle_ = new Style({
        stroke: this.strokeStyle_,
      });

      /**
       * @type {?import("../extent.js").Extent}
       * @private
       */
      this.loadedExtent_ = null;

      /**
       * @type {?import("../extent.js").Extent}
       * @private
       */
      this.renderedExtent_ = null;

      /**
       * @type {?number}
       * @private
       */
      this.renderedResolution_ = null;

      this.setRenderOrder(null);
    }

    /**
     * Strategy function for loading features based on the view's extent and
     * resolution.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @return {Array<import("../extent.js").Extent>} Extents.
     */
    strategyFunction(extent, resolution) {
      // extents may be passed in different worlds, to avoid endless loop we use only one
      let realWorldExtent = extent.slice();
      if (this.projection_ && this.getSource().getWrapX()) {
        wrapX$2(realWorldExtent, this.projection_);
      }
      if (this.loadedExtent_) {
        if (
          approximatelyEquals(this.loadedExtent_, realWorldExtent, resolution)
        ) {
          // make sure result is exactly equal to previous extent
          realWorldExtent = this.loadedExtent_.slice();
        } else {
          // we should not keep track of loaded extents
          this.getSource().removeLoadedExtent(this.loadedExtent_);
        }
      }
      return [realWorldExtent];
    }

    /**
     * Update geometries in the source based on current view
     * @param {import("../extent").Extent} extent Extent
     * @param {number} resolution Resolution
     * @param {import("../proj/Projection.js").default} projection Projection
     */
    loaderFunction(extent, resolution, projection) {
      this.loadedExtent_ = extent;
      const source = this.getSource();

      // only consider the intersection between our own extent & the requested one
      const layerExtent = this.getExtent() || [
        -Infinity,
        -Infinity,
        Infinity,
        Infinity,
      ];
      const renderExtent = getIntersection(layerExtent, extent);

      if (
        this.renderedExtent_ &&
        equals$1(this.renderedExtent_, renderExtent) &&
        this.renderedResolution_ === resolution
      ) {
        return;
      }
      this.renderedExtent_ = renderExtent;
      this.renderedResolution_ = resolution;

      // bail out if nothing to render
      if (isEmpty(renderExtent)) {
        return;
      }

      // update projection info
      const center = getCenter(renderExtent);
      const squaredTolerance = (resolution * resolution) / 4;

      const updateProjectionInfo =
        !this.projection_ || !equivalent$1(this.projection_, projection);

      if (updateProjectionInfo) {
        this.updateProjectionInfo_(projection);
      }

      this.createGraticule_(renderExtent, center, resolution, squaredTolerance);

      // first make sure we have enough features in the pool
      let featureCount = this.meridians_.length + this.parallels_.length;
      if (this.meridiansLabels_) {
        featureCount += this.meridians_.length;
      }
      if (this.parallelsLabels_) {
        featureCount += this.parallels_.length;
      }

      let feature;
      while (featureCount > this.featurePool_.length) {
        feature = new Feature();
        this.featurePool_.push(feature);
      }

      const featuresColl = source.getFeaturesCollection();
      featuresColl.clear();
      let poolIndex = 0;

      // add features for the lines & labels
      let i, l;
      for (i = 0, l = this.meridians_.length; i < l; ++i) {
        feature = this.featurePool_[poolIndex++];
        feature.setGeometry(this.meridians_[i]);
        feature.setStyle(this.lineStyle_);
        featuresColl.push(feature);
      }
      for (i = 0, l = this.parallels_.length; i < l; ++i) {
        feature = this.featurePool_[poolIndex++];
        feature.setGeometry(this.parallels_[i]);
        feature.setStyle(this.lineStyle_);
        featuresColl.push(feature);
      }
    }

    /**
     * @param {number} lon Longitude.
     * @param {number} minLat Minimal latitude.
     * @param {number} maxLat Maximal latitude.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} index Index.
     * @return {number} Index.
     * @private
     */
    addMeridian_(lon, minLat, maxLat, squaredTolerance, extent, index) {
      const lineString = this.getMeridian_(
        lon,
        minLat,
        maxLat,
        squaredTolerance,
        index,
      );
      if (intersects$2(lineString.getExtent(), extent)) {
        if (this.meridiansLabels_) {
          const text = this.lonLabelFormatter_(lon);
          if (index in this.meridiansLabels_) {
            this.meridiansLabels_[index].text = text;
          } else {
            this.meridiansLabels_[index] = {
              geom: new Point([]),
              text: text,
            };
          }
        }
        this.meridians_[index++] = lineString;
      }
      return index;
    }

    /**
     * @param {number} lat Latitude.
     * @param {number} minLon Minimal longitude.
     * @param {number} maxLon Maximal longitude.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} index Index.
     * @return {number} Index.
     * @private
     */
    addParallel_(lat, minLon, maxLon, squaredTolerance, extent, index) {
      const lineString = this.getParallel_(
        lat,
        minLon,
        maxLon,
        squaredTolerance,
        index,
      );
      if (intersects$2(lineString.getExtent(), extent)) {
        if (this.parallelsLabels_) {
          const text = this.latLabelFormatter_(lat);
          if (index in this.parallelsLabels_) {
            this.parallelsLabels_[index].text = text;
          } else {
            this.parallelsLabels_[index] = {
              geom: new Point([]),
              text: text,
            };
          }
        }
        this.parallels_[index++] = lineString;
      }
      return index;
    }

    /**
     * @param {import("../render/Event.js").default} event Render event.
     * @private
     */
    drawLabels_(event) {
      const rotation = event.frameState.viewState.rotation;
      const resolution = event.frameState.viewState.resolution;
      const size = event.frameState.size;
      const extent = event.frameState.extent;
      const rotationCenter = getCenter(extent);
      let rotationExtent = extent;
      if (rotation) {
        const unrotatedWidth = size[0] * resolution;
        const unrotatedHeight = size[1] * resolution;
        rotationExtent = [
          rotationCenter[0] - unrotatedWidth / 2,
          rotationCenter[1] - unrotatedHeight / 2,
          rotationCenter[0] + unrotatedWidth / 2,
          rotationCenter[1] + unrotatedHeight / 2,
        ];
      }

      let startWorld = 0;
      let endWorld = 0;
      let labelsAtStart = this.latLabelPosition_ < 0.5;
      const projectionExtent = this.projection_.getExtent();
      const worldWidth = getWidth(projectionExtent);
      if (
        this.getSource().getWrapX() &&
        this.projection_.canWrapX() &&
        !containsExtent(projectionExtent, extent)
      ) {
        startWorld = Math.floor((extent[0] - projectionExtent[0]) / worldWidth);
        endWorld = Math.ceil((extent[2] - projectionExtent[2]) / worldWidth);
        const inverted = Math.abs(rotation) > Math.PI / 2;
        labelsAtStart = labelsAtStart !== inverted;
      }
      const vectorContext = getVectorContext(event);

      for (let world = startWorld; world <= endWorld; ++world) {
        let poolIndex = this.meridians_.length + this.parallels_.length;
        let feature, index, l, textPoint;

        if (this.meridiansLabels_) {
          for (index = 0, l = this.meridiansLabels_.length; index < l; ++index) {
            const lineString = this.meridians_[index];
            if (!rotation && world === 0) {
              textPoint = this.getMeridianPoint_(lineString, extent, index);
            } else {
              const clone = lineString.clone();
              clone.translate(world * worldWidth, 0);
              clone.rotate(-rotation, rotationCenter);
              textPoint = this.getMeridianPoint_(clone, rotationExtent, index);
              textPoint.rotate(rotation, rotationCenter);
            }
            feature = this.featurePool_[poolIndex++];
            feature.setGeometry(textPoint);
            feature.set('graticule_label', this.meridiansLabels_[index].text);
            vectorContext.drawFeature(feature, this.lonLabelStyle_(feature));
          }
        }
        if (this.parallelsLabels_) {
          if (
            (world === startWorld && labelsAtStart) ||
            (world === endWorld && !labelsAtStart)
          ) {
            for (index = 0, l = this.parallels_.length; index < l; ++index) {
              const lineString = this.parallels_[index];
              if (!rotation && world === 0) {
                textPoint = this.getParallelPoint_(lineString, extent, index);
              } else {
                const clone = lineString.clone();
                clone.translate(world * worldWidth, 0);
                clone.rotate(-rotation, rotationCenter);
                textPoint = this.getParallelPoint_(clone, rotationExtent, index);
                textPoint.rotate(rotation, rotationCenter);
              }
              feature = this.featurePool_[poolIndex++];
              feature.setGeometry(textPoint);
              feature.set('graticule_label', this.parallelsLabels_[index].text);
              vectorContext.drawFeature(feature, this.latLabelStyle_(feature));
            }
          }
        }
      }
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {import("../coordinate.js").Coordinate} center Center.
     * @param {number} resolution Resolution.
     * @param {number} squaredTolerance Squared tolerance.
     * @private
     */
    createGraticule_(extent, center, resolution, squaredTolerance) {
      const interval = this.getInterval_(resolution);
      if (interval == -1) {
        this.meridians_.length = 0;
        this.parallels_.length = 0;
        if (this.meridiansLabels_) {
          this.meridiansLabels_.length = 0;
        }
        if (this.parallelsLabels_) {
          this.parallelsLabels_.length = 0;
        }
        return;
      }

      let wrapX = false;
      const projectionExtent = this.projection_.getExtent();
      const worldWidth = getWidth(projectionExtent);
      if (
        this.getSource().getWrapX() &&
        this.projection_.canWrapX() &&
        !containsExtent(projectionExtent, extent)
      ) {
        if (getWidth(extent) >= worldWidth) {
          extent[0] = projectionExtent[0];
          extent[2] = projectionExtent[2];
        } else {
          wrapX = true;
        }
      }

      // Constrain the center to fit into the extent available to the graticule

      const validCenterP = [
        clamp$1(center[0], this.minX_, this.maxX_),
        clamp$1(center[1], this.minY_, this.maxY_),
      ];

      // Transform the center to lon lat
      // Some projections may have a void area at the poles
      // so replace any NaN latitudes with the min or max value closest to a pole

      const centerLonLat = this.toLonLatTransform_(validCenterP);
      if (isNaN(centerLonLat[1])) {
        centerLonLat[1] =
          Math.abs(this.maxLat_) >= Math.abs(this.minLat_)
            ? this.maxLat_
            : this.minLat_;
      }
      let centerLon = clamp$1(centerLonLat[0], this.minLon_, this.maxLon_);
      let centerLat = clamp$1(centerLonLat[1], this.minLat_, this.maxLat_);
      const maxLines = this.maxLines_;
      let cnt, idx, lat, lon;

      // Limit the extent to fit into the extent available to the graticule

      let validExtentP = extent;
      if (!wrapX) {
        validExtentP = [
          clamp$1(extent[0], this.minX_, this.maxX_),
          clamp$1(extent[1], this.minY_, this.maxY_),
          clamp$1(extent[2], this.minX_, this.maxX_),
          clamp$1(extent[3], this.minY_, this.maxY_),
        ];
      }

      // Transform the extent to get the lon lat ranges for the edges of the extent

      const validExtent = applyTransform(
        validExtentP,
        this.toLonLatTransform_,
        undefined,
        8,
      );

      let maxLat = validExtent[3];
      let maxLon = validExtent[2];
      let minLat = validExtent[1];
      let minLon = validExtent[0];

      if (!wrapX) {
        // Check if extremities of the world extent lie inside the extent
        // (for example the pole in a polar projection)
        // and extend the extent as appropriate

        if (containsCoordinate(validExtentP, this.bottomLeft_)) {
          minLon = this.minLon_;
          minLat = this.minLat_;
        }
        if (containsCoordinate(validExtentP, this.bottomRight_)) {
          maxLon = this.maxLon_;
          minLat = this.minLat_;
        }
        if (containsCoordinate(validExtentP, this.topLeft_)) {
          minLon = this.minLon_;
          maxLat = this.maxLat_;
        }
        if (containsCoordinate(validExtentP, this.topRight_)) {
          maxLon = this.maxLon_;
          maxLat = this.maxLat_;
        }

        // The transformed center may also extend the lon lat ranges used for rendering

        maxLat = clamp$1(maxLat, centerLat, this.maxLat_);
        maxLon = clamp$1(maxLon, centerLon, this.maxLon_);
        minLat = clamp$1(minLat, this.minLat_, centerLat);
        minLon = clamp$1(minLon, this.minLon_, centerLon);
      }

      // Create meridians

      centerLon = Math.floor(centerLon / interval) * interval;
      lon = clamp$1(centerLon, this.minLon_, this.maxLon_);

      idx = this.addMeridian_(lon, minLat, maxLat, squaredTolerance, extent, 0);

      cnt = 0;
      if (wrapX) {
        while ((lon -= interval) >= minLon && cnt++ < maxLines) {
          idx = this.addMeridian_(
            lon,
            minLat,
            maxLat,
            squaredTolerance,
            extent,
            idx,
          );
        }
      } else {
        while (lon != this.minLon_ && cnt++ < maxLines) {
          lon = Math.max(lon - interval, this.minLon_);
          idx = this.addMeridian_(
            lon,
            minLat,
            maxLat,
            squaredTolerance,
            extent,
            idx,
          );
        }
      }

      lon = clamp$1(centerLon, this.minLon_, this.maxLon_);

      cnt = 0;
      if (wrapX) {
        while ((lon += interval) <= maxLon && cnt++ < maxLines) {
          idx = this.addMeridian_(
            lon,
            minLat,
            maxLat,
            squaredTolerance,
            extent,
            idx,
          );
        }
      } else {
        while (lon != this.maxLon_ && cnt++ < maxLines) {
          lon = Math.min(lon + interval, this.maxLon_);
          idx = this.addMeridian_(
            lon,
            minLat,
            maxLat,
            squaredTolerance,
            extent,
            idx,
          );
        }
      }

      this.meridians_.length = idx;
      if (this.meridiansLabels_) {
        this.meridiansLabels_.length = idx;
      }

      // Create parallels

      centerLat = Math.floor(centerLat / interval) * interval;
      lat = clamp$1(centerLat, this.minLat_, this.maxLat_);

      idx = this.addParallel_(lat, minLon, maxLon, squaredTolerance, extent, 0);

      cnt = 0;
      while (lat != this.minLat_ && cnt++ < maxLines) {
        lat = Math.max(lat - interval, this.minLat_);
        idx = this.addParallel_(
          lat,
          minLon,
          maxLon,
          squaredTolerance,
          extent,
          idx,
        );
      }

      lat = clamp$1(centerLat, this.minLat_, this.maxLat_);

      cnt = 0;
      while (lat != this.maxLat_ && cnt++ < maxLines) {
        lat = Math.min(lat + interval, this.maxLat_);
        idx = this.addParallel_(
          lat,
          minLon,
          maxLon,
          squaredTolerance,
          extent,
          idx,
        );
      }

      this.parallels_.length = idx;
      if (this.parallelsLabels_) {
        this.parallelsLabels_.length = idx;
      }
    }

    /**
     * @param {number} resolution Resolution.
     * @return {number} The interval in degrees.
     * @private
     */
    getInterval_(resolution) {
      const centerLon = this.projectionCenterLonLat_[0];
      const centerLat = this.projectionCenterLonLat_[1];
      let interval = -1;
      const target = Math.pow(this.targetSize_ * resolution, 2);
      /** @type {Array<number>} **/
      const p1 = [];
      /** @type {Array<number>} **/
      const p2 = [];
      for (let i = 0, ii = this.intervals_.length; i < ii; ++i) {
        const delta = clamp$1(this.intervals_[i] / 2, 0, 90);
        // Don't attempt to transform latitudes beyond the poles!
        const clampedLat = clamp$1(centerLat, -90 + delta, 90 - delta);
        p1[0] = centerLon - delta;
        p1[1] = clampedLat - delta;
        p2[0] = centerLon + delta;
        p2[1] = clampedLat + delta;
        this.fromLonLatTransform_(p1, p1);
        this.fromLonLatTransform_(p2, p2);
        const dist = Math.pow(p2[0] - p1[0], 2) + Math.pow(p2[1] - p1[1], 2);
        if (dist <= target) {
          break;
        }
        interval = this.intervals_[i];
      }
      return interval;
    }

    /**
     * @param {number} lon Longitude.
     * @param {number} minLat Minimal latitude.
     * @param {number} maxLat Maximal latitude.
     * @param {number} squaredTolerance Squared tolerance.
     * @return {LineString} The meridian line string.
     * @param {number} index Index.
     * @private
     */
    getMeridian_(lon, minLat, maxLat, squaredTolerance, index) {
      const flatCoordinates = meridian(
        lon,
        minLat,
        maxLat,
        this.projection_,
        squaredTolerance,
      );
      let lineString = this.meridians_[index];
      if (!lineString) {
        lineString = new LineString(flatCoordinates, 'XY');
        this.meridians_[index] = lineString;
      } else {
        lineString.setFlatCoordinates('XY', flatCoordinates);
        lineString.changed();
      }
      return lineString;
    }

    /**
     * @param {LineString} lineString Meridian
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} index Index.
     * @return {Point} Meridian point.
     * @private
     */
    getMeridianPoint_(lineString, extent, index) {
      const flatCoordinates = lineString.getFlatCoordinates();
      let bottom = 1;
      let top = flatCoordinates.length - 1;
      if (flatCoordinates[bottom] > flatCoordinates[top]) {
        bottom = top;
        top = 1;
      }
      const clampedBottom = Math.max(extent[1], flatCoordinates[bottom]);
      const clampedTop = Math.min(extent[3], flatCoordinates[top]);
      const lat = clamp$1(
        extent[1] + Math.abs(extent[1] - extent[3]) * this.lonLabelPosition_,
        clampedBottom,
        clampedTop,
      );
      const coordinate0 =
        flatCoordinates[bottom - 1] +
        ((flatCoordinates[top - 1] - flatCoordinates[bottom - 1]) *
          (lat - flatCoordinates[bottom])) /
          (flatCoordinates[top] - flatCoordinates[bottom]);
      const coordinate = [coordinate0, lat];
      const point = this.meridiansLabels_[index].geom;
      point.setCoordinates(coordinate);
      return point;
    }

    /**
     * Get the list of meridians.  Meridians are lines of equal longitude.
     * @return {Array<LineString>} The meridians.
     * @api
     */
    getMeridians() {
      return this.meridians_;
    }

    /**
     * @param {number} lat Latitude.
     * @param {number} minLon Minimal longitude.
     * @param {number} maxLon Maximal longitude.
     * @param {number} squaredTolerance Squared tolerance.
     * @return {LineString} The parallel line string.
     * @param {number} index Index.
     * @private
     */
    getParallel_(lat, minLon, maxLon, squaredTolerance, index) {
      const flatCoordinates = parallel(
        lat,
        minLon,
        maxLon,
        this.projection_,
        squaredTolerance,
      );
      let lineString = this.parallels_[index];
      if (!lineString) {
        lineString = new LineString(flatCoordinates, 'XY');
      } else {
        lineString.setFlatCoordinates('XY', flatCoordinates);
        lineString.changed();
      }
      return lineString;
    }

    /**
     * @param {LineString} lineString Parallels.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} index Index.
     * @return {Point} Parallel point.
     * @private
     */
    getParallelPoint_(lineString, extent, index) {
      const flatCoordinates = lineString.getFlatCoordinates();
      let left = 0;
      let right = flatCoordinates.length - 2;
      if (flatCoordinates[left] > flatCoordinates[right]) {
        left = right;
        right = 0;
      }
      const clampedLeft = Math.max(extent[0], flatCoordinates[left]);
      const clampedRight = Math.min(extent[2], flatCoordinates[right]);
      const lon = clamp$1(
        extent[0] + Math.abs(extent[0] - extent[2]) * this.latLabelPosition_,
        clampedLeft,
        clampedRight,
      );
      const coordinate1 =
        flatCoordinates[left + 1] +
        ((flatCoordinates[right + 1] - flatCoordinates[left + 1]) *
          (lon - flatCoordinates[left])) /
          (flatCoordinates[right] - flatCoordinates[left]);
      const coordinate = [lon, coordinate1];
      const point = this.parallelsLabels_[index].geom;
      point.setCoordinates(coordinate);
      return point;
    }

    /**
     * Get the list of parallels.  Parallels are lines of equal latitude.
     * @return {Array<LineString>} The parallels.
     * @api
     */
    getParallels() {
      return this.parallels_;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @private
     */
    updateProjectionInfo_(projection) {
      const epsg4326Projection = get$2('EPSG:4326');

      const worldExtent = projection.getWorldExtent();

      this.maxLat_ = worldExtent[3];
      this.maxLon_ = worldExtent[2];
      this.minLat_ = worldExtent[1];
      this.minLon_ = worldExtent[0];

      // If the world extent crosses the dateline define a custom transform to
      // return longitudes which wrap the dateline

      const toLonLatTransform = getTransform(projection, epsg4326Projection);
      if (this.minLon_ < this.maxLon_) {
        this.toLonLatTransform_ = toLonLatTransform;
      } else {
        const split = this.minLon_ + this.maxLon_ / 2;
        this.maxLon_ += 360;
        this.toLonLatTransform_ = function (coordinates, output, dimension) {
          dimension = dimension || 2;
          const lonLatCoordinates = toLonLatTransform(
            coordinates,
            output,
            dimension,
          );
          for (let i = 0, l = lonLatCoordinates.length; i < l; i += dimension) {
            if (lonLatCoordinates[i] < split) {
              lonLatCoordinates[i] += 360;
            }
          }
          return lonLatCoordinates;
        };
      }

      // Transform the extent to get the limits of the view projection extent
      // which should be available to the graticule

      this.fromLonLatTransform_ = getTransform(epsg4326Projection, projection);
      const worldExtentP = applyTransform(
        [this.minLon_, this.minLat_, this.maxLon_, this.maxLat_],
        this.fromLonLatTransform_,
        undefined,
        8,
      );

      this.minX_ = worldExtentP[0];
      this.maxX_ = worldExtentP[2];
      this.minY_ = worldExtentP[1];
      this.maxY_ = worldExtentP[3];

      // Determine the view projection coordinates of the extremities of the world extent
      // as these may lie inside a view extent (for example the pole in a polar projection)

      this.bottomLeft_ = this.fromLonLatTransform_([this.minLon_, this.minLat_]);
      this.bottomRight_ = this.fromLonLatTransform_([this.maxLon_, this.minLat_]);
      this.topLeft_ = this.fromLonLatTransform_([this.minLon_, this.maxLat_]);
      this.topRight_ = this.fromLonLatTransform_([this.maxLon_, this.maxLat_]);

      // Transform the projection center to lon lat
      // Some projections may have a void area at the poles
      // so replace any NaN latitudes with the min or max value closest to a pole

      this.projectionCenterLonLat_ = this.toLonLatTransform_(
        getCenter(projection.getExtent()),
      );
      if (isNaN(this.projectionCenterLonLat_[1])) {
        this.projectionCenterLonLat_[1] =
          Math.abs(this.maxLat_) >= Math.abs(this.minLat_)
            ? this.maxLat_
            : this.minLat_;
      }

      this.projection_ = projection;
    }
  }

  /**
   * @module ol/ImageCanvas
   */

  /**
   * A function that is called to trigger asynchronous canvas drawing.  It is
   * called with a "done" callback that should be called when drawing is done.
   * If any error occurs during drawing, the "done" callback should be called with
   * that error.
   *
   * @typedef {function(function(Error=): void): void} Loader
   */

  class ImageCanvas extends ImageWrapper {
    /**
     * @param {import("./extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {HTMLCanvasElement} canvas Canvas.
     * @param {Loader} [loader] Optional loader function to
     *     support asynchronous canvas drawing.
     */
    constructor(extent, resolution, pixelRatio, canvas, loader) {
      const state = loader !== undefined ? ImageState.IDLE : ImageState.LOADED;

      super(extent, resolution, pixelRatio, state);

      /**
       * Optional canvas loader function.
       * @type {?Loader}
       * @private
       */
      this.loader_ = loader !== undefined ? loader : null;

      /**
       * @private
       * @type {HTMLCanvasElement}
       */
      this.canvas_ = canvas;

      /**
       * @private
       * @type {?Error}
       */
      this.error_ = null;
    }

    /**
     * Get any error associated with asynchronous rendering.
     * @return {?Error} Any error that occurred during rendering.
     */
    getError() {
      return this.error_;
    }

    /**
     * Handle async drawing complete.
     * @param {Error} [err] Any error during drawing.
     * @private
     */
    handleLoad_(err) {
      if (err) {
        this.error_ = err;
        this.state = ImageState.ERROR;
      } else {
        this.state = ImageState.LOADED;
      }
      this.changed();
    }

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {
      if (this.state == ImageState.IDLE) {
        this.state = ImageState.LOADING;
        this.changed();
        this.loader_(this.handleLoad_.bind(this));
      }
    }

    /**
     * @return {HTMLCanvasElement} Canvas element.
     * @override
     */
    getImage() {
      return this.canvas_;
    }
  }

  /**
   * @module ol/TileState
   */

  /**
   * @enum {number}
   */
  var TileState = {
    IDLE: 0,
    LOADING: 1,
    LOADED: 2,
    /**
     * Indicates that tile loading failed
     * @type {number}
     */
    ERROR: 3,
    EMPTY: 4,
  };

  /**
   * @module ol/Tile
   */

  /**
   * A function that takes a {@link module:ol/Tile~Tile} for the tile and a
   * `{string}` for the url as arguments. The default is
   * ```js
   * source.setTileLoadFunction(function(tile, src) {
   *   tile.getImage().src = src;
   * });
   * ```
   * For more fine grained control, the load function can use fetch or XMLHttpRequest and involve
   * error handling:
   *
   * ```js
   * import TileState from 'ol/TileState.js';
   *
   * source.setTileLoadFunction(function(tile, src) {
   *   const xhr = new XMLHttpRequest();
   *   xhr.responseType = 'blob';
   *   xhr.addEventListener('loadend', function (evt) {
   *     const data = this.response;
   *     if (data !== undefined) {
   *       tile.getImage().src = URL.createObjectURL(data);
   *     } else {
   *       tile.setState(TileState.ERROR);
   *     }
   *   });
   *   xhr.addEventListener('error', function () {
   *     tile.setState(TileState.ERROR);
   *   });
   *   xhr.open('GET', src);
   *   xhr.send();
   * });
   * ```
   *
   * @typedef {function(Tile, string): void} LoadFunction
   * @api
   */

  /**
   * {@link module:ol/source/Tile~TileSource} sources use a function of this type to get
   * the url that provides a tile for a given tile coordinate.
   *
   * This function takes a {@link module:ol/tilecoord~TileCoord} for the tile
   * coordinate, a `{number}` representing the pixel ratio and a
   * {@link module:ol/proj/Projection~Projection} for the projection  as arguments
   * and returns a `{string}` representing the tile URL, or undefined if no tile
   * should be requested for the passed tile coordinate.
   *
   * @typedef {function(import("./tilecoord.js").TileCoord, number,
   *           import("./proj/Projection.js").default): (string|undefined)} UrlFunction
   * @api
   */

  /**
   * @typedef {Object} Options
   * @property {number} [transition=250] A duration for tile opacity
   * transitions in milliseconds. A duration of 0 disables the opacity transition.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   * @api
   */

  /**
   * @classdesc
   * Base class for tiles.
   *
   * @abstract
   */
  class Tile extends Target {
    /**
     * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("./TileState.js").default} state State.
     * @param {Options} [options] Tile options.
     */
    constructor(tileCoord, state, options) {
      super();

      options = options ? options : {};

      /**
       * @type {import("./tilecoord.js").TileCoord}
       */
      this.tileCoord = tileCoord;

      /**
       * @protected
       * @type {import("./TileState.js").default}
       */
      this.state = state;

      /**
       * A key assigned to the tile. This is used in conjunction with a source key
       * to determine if a cached version of this tile may be used by the renderer.
       * @type {string}
       */
      this.key = '';

      /**
       * The duration for the opacity transition.
       * @private
       * @type {number}
       */
      this.transition_ =
        options.transition === undefined ? 250 : options.transition;

      /**
       * Lookup of start times for rendering transitions.  If the start time is
       * equal to -1, the transition is complete.
       * @private
       * @type {Object<string, number>}
       */
      this.transitionStarts_ = {};

      /**
       * @type {boolean}
       */
      this.interpolate = !!options.interpolate;
    }

    /**
     * @protected
     */
    changed() {
      this.dispatchEvent(EventType.CHANGE);
    }

    /**
     * Called by the tile cache when the tile is removed from the cache due to expiry
     */
    release() {
      // to remove the `change` listener on this tile in `ol/TileQueue#handleTileChange`
      this.setState(TileState.EMPTY);
    }

    /**
     * @return {string} Key.
     */
    getKey() {
      return this.key + '/' + this.tileCoord;
    }

    /**
     * Get the tile coordinate for this tile.
     * @return {import("./tilecoord.js").TileCoord} The tile coordinate.
     * @api
     */
    getTileCoord() {
      return this.tileCoord;
    }

    /**
     * @return {import("./TileState.js").default} State.
     */
    getState() {
      return this.state;
    }

    /**
     * Sets the state of this tile. If you write your own {@link module:ol/Tile~LoadFunction tileLoadFunction} ,
     * it is important to set the state correctly to {@link module:ol/TileState~ERROR}
     * when the tile cannot be loaded. Otherwise the tile cannot be removed from
     * the tile queue and will block other requests.
     * @param {import("./TileState.js").default} state State.
     * @api
     */
    setState(state) {
      if (this.state === TileState.EMPTY) {
        // no more state changes
        return;
      }
      if (this.state !== TileState.ERROR && this.state > state) {
        throw new Error('Tile load sequence violation');
      }
      this.state = state;
      this.changed();
    }

    /**
     * Load the image or retry if loading previously failed.
     * Loading is taken care of by the tile queue, and calling this method is
     * only needed for preloading or for reloading in case of an error.
     * @abstract
     * @api
     */
    load() {
      abstract();
    }

    /**
     * Get the alpha value for rendering.
     * @param {string} id An id for the renderer.
     * @param {number} time The render frame time.
     * @return {number} A number between 0 and 1.
     */
    getAlpha(id, time) {
      if (!this.transition_) {
        return 1;
      }

      let start = this.transitionStarts_[id];
      if (!start) {
        start = time;
        this.transitionStarts_[id] = start;
      } else if (start === -1) {
        return 1;
      }

      const delta = time - start + 1000 / 60; // avoid rendering at 0
      if (delta >= this.transition_) {
        return 1;
      }
      return easeIn(delta / this.transition_);
    }

    /**
     * Determine if a tile is in an alpha transition.  A tile is considered in
     * transition if tile.getAlpha() has not yet been called or has been called
     * and returned 1.
     * @param {string} id An id for the renderer.
     * @return {boolean} The tile is in transition.
     */
    inTransition(id) {
      if (!this.transition_) {
        return false;
      }
      return this.transitionStarts_[id] !== -1;
    }

    /**
     * Mark a transition as complete.
     * @param {string} id An id for the renderer.
     */
    endTransition(id) {
      if (this.transition_) {
        this.transitionStarts_[id] = -1;
      }
    }

    /**
     * @override
     */
    disposeInternal() {
      this.release();
      super.disposeInternal();
    }
  }

  /**
   * @module ol/ImageTile
   */

  class ImageTile extends Tile {
    /**
     * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("./TileState.js").default} state State.
     * @param {string} src Image source URI.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function.
     * @param {import("./Tile.js").Options} [options] Tile options.
     */
    constructor(tileCoord, state, src, crossOrigin, tileLoadFunction, options) {
      super(tileCoord, state, options);

      /**
       * @private
       * @type {?string}
       */
      this.crossOrigin_ = crossOrigin;

      /**
       * Image URI
       *
       * @private
       * @type {string}
       */
      this.src_ = src;

      this.key = src;

      /**
       * @private
       * @type {HTMLImageElement|HTMLCanvasElement}
       */
      this.image_ = new Image();
      if (crossOrigin !== null) {
        this.image_.crossOrigin = crossOrigin;
      }

      /**
       * @private
       * @type {?function():void}
       */
      this.unlisten_ = null;

      /**
       * @private
       * @type {import("./Tile.js").LoadFunction}
       */
      this.tileLoadFunction_ = tileLoadFunction;
    }

    /**
     * Get the HTML image element for this tile (may be a Canvas, Image, or Video).
     * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
     * @api
     */
    getImage() {
      return this.image_;
    }

    /**
     * Sets an HTML image element for this tile (may be a Canvas or preloaded Image).
     * @param {HTMLCanvasElement|HTMLImageElement} element Element.
     */
    setImage(element) {
      this.image_ = element;
      this.state = TileState.LOADED;
      this.unlistenImage_();
      this.changed();
    }

    /**
     * Tracks loading or read errors.
     *
     * @private
     */
    handleImageError_() {
      this.state = TileState.ERROR;
      this.unlistenImage_();
      this.image_ = getBlankImage();
      this.changed();
    }

    /**
     * Tracks successful image load.
     *
     * @private
     */
    handleImageLoad_() {
      const image = /** @type {HTMLImageElement} */ (this.image_);
      if (image.naturalWidth && image.naturalHeight) {
        this.state = TileState.LOADED;
      } else {
        this.state = TileState.EMPTY;
      }
      this.unlistenImage_();
      this.changed();
    }

    /**
     * Load the image or retry if loading previously failed.
     * Loading is taken care of by the tile queue, and calling this method is
     * only needed for preloading or for reloading in case of an error.
     *
     * To retry loading tiles on failed requests, use a custom `tileLoadFunction`
     * that checks for error status codes and reloads only when the status code is
     * 408, 429, 500, 502, 503 and 504, and only when not too many retries have been
     * made already:
     *
     * ```js
     * const retryCodes = [408, 429, 500, 502, 503, 504];
     * const retries = {};
     * source.setTileLoadFunction((tile, src) => {
     *   const image = tile.getImage();
     *   fetch(src)
     *     .then((response) => {
     *       if (retryCodes.includes(response.status)) {
     *         retries[src] = (retries[src] || 0) + 1;
     *         if (retries[src] <= 3) {
     *           setTimeout(() => tile.load(), retries[src] * 1000);
     *         }
     *         return Promise.reject();
     *       }
     *       return response.blob();
     *     })
     *     .then((blob) => {
     *       const imageUrl = URL.createObjectURL(blob);
     *       image.src = imageUrl;
     *       setTimeout(() => URL.revokeObjectURL(imageUrl), 5000);
     *     })
     *     .catch(() => tile.setState(3)); // error
     * });
     * ```
     * @api
     * @override
     */
    load() {
      if (this.state == TileState.ERROR) {
        this.state = TileState.IDLE;
        this.image_ = new Image();
        if (this.crossOrigin_ !== null) {
          this.image_.crossOrigin = this.crossOrigin_;
        }
      }
      if (this.state == TileState.IDLE) {
        this.state = TileState.LOADING;
        this.changed();
        this.tileLoadFunction_(this, this.src_);
        this.unlisten_ = listenImage(
          this.image_,
          this.handleImageLoad_.bind(this),
          this.handleImageError_.bind(this),
        );
      }
    }

    /**
     * Discards event handlers which listen for load completion or errors.
     *
     * @private
     */
    unlistenImage_() {
      if (this.unlisten_) {
        this.unlisten_();
        this.unlisten_ = null;
      }
    }

    /**
     * @override
     */
    disposeInternal() {
      this.unlistenImage_();
      this.image_ = null;
      super.disposeInternal();
    }
  }

  /**
   * Get a 1-pixel blank image.
   * @return {HTMLCanvasElement} Blank image.
   */
  function getBlankImage() {
    const ctx = createCanvasContext2D(1, 1);
    ctx.fillStyle = 'rgba(0,0,0,0)';
    ctx.fillRect(0, 0, 1, 1);
    return ctx.canvas;
  }

  /**
   * @module ol/Kinetic
   */

  /**
   * @classdesc
   * Implementation of inertial deceleration for map movement.
   *
   * @api
   */
  class Kinetic {
    /**
     * @param {number} decay Rate of decay (must be negative).
     * @param {number} minVelocity Minimum velocity (pixels/millisecond).
     * @param {number} delay Delay to consider to calculate the kinetic
     *     initial values (milliseconds).
     */
    constructor(decay, minVelocity, delay) {
      /**
       * @private
       * @type {number}
       */
      this.decay_ = decay;

      /**
       * @private
       * @type {number}
       */
      this.minVelocity_ = minVelocity;

      /**
       * @private
       * @type {number}
       */
      this.delay_ = delay;

      /**
       * @private
       * @type {Array<number>}
       */
      this.points_ = [];

      /**
       * @private
       * @type {number}
       */
      this.angle_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.initialVelocity_ = 0;
    }

    /**
     * FIXME empty description for jsdoc
     */
    begin() {
      this.points_.length = 0;
      this.angle_ = 0;
      this.initialVelocity_ = 0;
    }

    /**
     * @param {number} x X.
     * @param {number} y Y.
     */
    update(x, y) {
      this.points_.push(x, y, Date.now());
    }

    /**
     * @return {boolean} Whether we should do kinetic animation.
     */
    end() {
      if (this.points_.length < 6) {
        // at least 2 points are required (i.e. there must be at least 6 elements
        // in the array)
        return false;
      }
      const delay = Date.now() - this.delay_;
      const lastIndex = this.points_.length - 3;
      if (this.points_[lastIndex + 2] < delay) {
        // the last tracked point is too old, which means that the user stopped
        // panning before releasing the map
        return false;
      }

      // get the first point which still falls into the delay time
      let firstIndex = lastIndex - 3;
      while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) {
        firstIndex -= 3;
      }

      const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2];
      // we don't want a duration of 0 (divide by zero)
      // we also make sure the user panned for a duration of at least one frame
      // (1/60s) to compute sane displacement values
      if (duration < 1000 / 60) {
        return false;
      }

      const dx = this.points_[lastIndex] - this.points_[firstIndex];
      const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1];
      this.angle_ = Math.atan2(dy, dx);
      this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration;
      return this.initialVelocity_ > this.minVelocity_;
    }

    /**
     * @return {number} Total distance travelled (pixels).
     */
    getDistance() {
      return (this.minVelocity_ - this.initialVelocity_) / this.decay_;
    }

    /**
     * @return {number} Angle of the kinetic panning animation (radians).
     */
    getAngle() {
      return this.angle_;
    }
  }

  /**
   * @module ol/MapEvent
   */

  /**
   * @classdesc
   * Events emitted as map events are instances of this type.
   * See {@link module:ol/Map~Map} for which events trigger a map event.
   */
  class MapEvent extends BaseEvent {
    /**
     * @param {string} type Event type.
     * @param {import("./Map.js").default} map Map.
     * @param {?import("./Map.js").FrameState} [frameState] Frame state.
     */
    constructor(type, map, frameState) {
      super(type);

      /**
       * The map where the event occurred.
       * @type {import("./Map.js").default}
       * @api
       */
      this.map = map;

      /**
       * The frame state at the time of the event.
       * @type {?import("./Map.js").FrameState}
       * @api
       */
      this.frameState = frameState !== undefined ? frameState : null;
    }
  }

  /**
   * @module ol/MapBrowserEvent
   */

  /**
   * @classdesc
   * Events emitted as map browser events are instances of this type.
   * See {@link module:ol/Map~Map} for which events trigger a map browser event.
   * @template {PointerEvent|KeyboardEvent|WheelEvent} [EVENT=PointerEvent|KeyboardEvent|WheelEvent]
   */
  class MapBrowserEvent extends MapEvent {
    /**
     * @param {string} type Event type.
     * @param {import("./Map.js").default} map Map.
     * @param {EVENT} originalEvent Original event.
     * @param {boolean} [dragging] Is the map currently being dragged?
     * @param {import("./Map.js").FrameState} [frameState] Frame state.
     * @param {Array<PointerEvent>} [activePointers] Active pointers.
     */
    constructor(type, map, originalEvent, dragging, frameState, activePointers) {
      super(type, map, frameState);

      /**
       * The original browser event.
       * @const
       * @type {EVENT}
       * @api
       */
      this.originalEvent = originalEvent;

      /**
       * The map pixel relative to the viewport corresponding to the original browser event.
       * @type {?import("./pixel.js").Pixel}
       * @private
       */
      this.pixel_ = null;

      /**
       * The coordinate in the user projection corresponding to the original browser event.
       * @type {?import("./coordinate.js").Coordinate}
       * @private
       */
      this.coordinate_ = null;

      /**
       * Indicates if the map is currently being dragged. Only set for
       * `POINTERDRAG` and `POINTERMOVE` events. Default is `false`.
       *
       * @type {boolean}
       * @api
       */
      this.dragging = dragging !== undefined ? dragging : false;

      /**
       * @type {Array<PointerEvent>|undefined}
       */
      this.activePointers = activePointers;
    }

    /**
     * The map pixel relative to the viewport corresponding to the original event.
     * @type {import("./pixel.js").Pixel}
     * @api
     */
    get pixel() {
      if (!this.pixel_) {
        this.pixel_ = this.map.getEventPixel(this.originalEvent);
      }
      return this.pixel_;
    }
    set pixel(pixel) {
      this.pixel_ = pixel;
    }

    /**
     * The coordinate corresponding to the original browser event.  This will be in the user
     * projection if one is set.  Otherwise it will be in the view projection.
     * @type {import("./coordinate.js").Coordinate}
     * @api
     */
    get coordinate() {
      if (!this.coordinate_) {
        this.coordinate_ = this.map.getCoordinateFromPixel(this.pixel);
      }
      return this.coordinate_;
    }
    set coordinate(coordinate) {
      this.coordinate_ = coordinate;
    }

    /**
     * Prevents the default browser action.
     * See https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault.
     * @api
     * @override
     */
    preventDefault() {
      super.preventDefault();
      if ('preventDefault' in this.originalEvent) {
        /** @type {UIEvent} */ (this.originalEvent).preventDefault();
      }
    }

    /**
     * Prevents further propagation of the current event.
     * See https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation.
     * @api
     * @override
     */
    stopPropagation() {
      super.stopPropagation();
      if ('stopPropagation' in this.originalEvent) {
        /** @type {UIEvent} */ (this.originalEvent).stopPropagation();
      }
    }
  }

  /**
   * @module ol/MapBrowserEventType
   */

  /**
   * Constants for event names.
   * @enum {string}
   */
  var MapBrowserEventType = {
    /**
     * A true single click with no dragging and no double click. Note that this
     * event is delayed by 250 ms to ensure that it is not a double click.
     * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick
     * @api
     */
    SINGLECLICK: 'singleclick',

    /**
     * A click with no dragging. A double click will fire two of this.
     * @event module:ol/MapBrowserEvent~MapBrowserEvent#click
     * @api
     */
    CLICK: EventType.CLICK,

    /**
     * A true double click, with no dragging.
     * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick
     * @api
     */
    DBLCLICK: EventType.DBLCLICK,

    /**
     * Triggered when a pointer is dragged.
     * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag
     * @api
     */
    POINTERDRAG: 'pointerdrag',

    /**
     * Triggered when a pointer is moved. Note that on touch devices this is
     * triggered when the map is panned, so is not the same as mousemove.
     * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove
     * @api
     */
    POINTERMOVE: 'pointermove',

    POINTERDOWN: 'pointerdown',
    POINTERUP: 'pointerup',
    POINTEROVER: 'pointerover',
    POINTEROUT: 'pointerout',
    POINTERENTER: 'pointerenter',
    POINTERLEAVE: 'pointerleave',
    POINTERCANCEL: 'pointercancel',
  };

  /***
   * @typedef {'singleclick'|'click'|'dblclick'|'pointerdrag'|'pointermove'} Types
   */

  /**
   * @module ol/pointer/EventType
   */

  /**
   * Constants for event names.
   * @enum {string}
   */
  var PointerEventType = {
    POINTERMOVE: 'pointermove',
    POINTERDOWN: 'pointerdown',
    POINTERUP: 'pointerup',
    POINTEROUT: 'pointerout'};

  /**
   * @module ol/MapBrowserEventHandler
   */


  class MapBrowserEventHandler extends Target {
    /**
     * @param {import("./Map.js").default} map The map with the viewport to listen to events on.
     * @param {number} [moveTolerance] The minimal distance the pointer must travel to trigger a move.
     */
    constructor(map, moveTolerance) {
      super(map);

      /**
       * This is the element that we will listen to the real events on.
       * @type {import("./Map.js").default}
       * @private
       */
      this.map_ = map;

      /**
       * @type {ReturnType<typeof setTimeout>}
       * @private
       */
      this.clickTimeoutId_;

      /**
       * Emulate dblclick and singleclick. Will be true when only one pointer is active.
       * @type {boolean}
       */
      this.emulateClicks_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.dragging_ = false;

      /**
       * @type {!Array<import("./events.js").EventsKey>}
       * @private
       */
      this.dragListenerKeys_ = [];

      /**
       * @type {number}
       * @private
       */
      this.moveTolerance_ = moveTolerance === undefined ? 1 : moveTolerance;

      /**
       * The most recent "down" type event (or null if none have occurred).
       * Set on pointerdown.
       * @type {PointerEvent|null}
       * @private
       */
      this.down_ = null;

      const element = this.map_.getViewport();

      /**
       * @type {Array<PointerEvent>}
       * @private
       */
      this.activePointers_ = [];

      /**
       * @type {!Object<number, Event>}
       * @private
       */
      this.trackedTouches_ = {};

      /**
       * @private
       */
      this.element_ = element;

      /**
       * @type {?import("./events.js").EventsKey}
       * @private
       */
      this.pointerdownListenerKey_ = listen(
        element,
        PointerEventType.POINTERDOWN,
        this.handlePointerDown_,
        this,
      );

      /**
       * @type {PointerEvent}
       * @private
       */
      this.originalPointerMoveEvent_;

      /**
       * @type {?import("./events.js").EventsKey}
       * @private
       */
      this.relayedListenerKey_ = listen(
        element,
        PointerEventType.POINTERMOVE,
        this.relayMoveEvent_,
        this,
      );

      /**
       * @private
       */
      this.boundHandleTouchMove_ = this.handleTouchMove_.bind(this);

      this.element_.addEventListener(
        EventType.TOUCHMOVE,
        this.boundHandleTouchMove_,
        PASSIVE_EVENT_LISTENERS ? {passive: false} : false,
      );
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    emulateClick_(pointerEvent) {
      let newEvent = new MapBrowserEvent(
        MapBrowserEventType.CLICK,
        this.map_,
        pointerEvent,
      );
      this.dispatchEvent(newEvent);
      if (this.clickTimeoutId_ !== undefined) {
        // double-click
        clearTimeout(this.clickTimeoutId_);
        this.clickTimeoutId_ = undefined;
        newEvent = new MapBrowserEvent(
          MapBrowserEventType.DBLCLICK,
          this.map_,
          pointerEvent,
        );
        this.dispatchEvent(newEvent);
      } else {
        // click
        this.clickTimeoutId_ = setTimeout(() => {
          this.clickTimeoutId_ = undefined;
          const newEvent = new MapBrowserEvent(
            MapBrowserEventType.SINGLECLICK,
            this.map_,
            pointerEvent,
          );
          this.dispatchEvent(newEvent);
        }, 250);
      }
    }

    /**
     * Keeps track on how many pointers are currently active.
     *
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    updateActivePointers_(pointerEvent) {
      const event = pointerEvent;
      const id = event.pointerId;

      if (
        event.type == MapBrowserEventType.POINTERUP ||
        event.type == MapBrowserEventType.POINTERCANCEL
      ) {
        delete this.trackedTouches_[id];
        for (const pointerId in this.trackedTouches_) {
          if (this.trackedTouches_[pointerId].target !== event.target) {
            // Some platforms assign a new pointerId when the target changes.
            // If this happens, delete one tracked pointer. If there is more
            // than one tracked pointer for the old target, it will be cleared
            // by subsequent POINTERUP events from other pointers.
            delete this.trackedTouches_[pointerId];
            break;
          }
        }
      } else if (
        event.type == MapBrowserEventType.POINTERDOWN ||
        event.type == MapBrowserEventType.POINTERMOVE
      ) {
        this.trackedTouches_[id] = event;
      }
      this.activePointers_ = Object.values(this.trackedTouches_);
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    handlePointerUp_(pointerEvent) {
      this.updateActivePointers_(pointerEvent);
      const newEvent = new MapBrowserEvent(
        MapBrowserEventType.POINTERUP,
        this.map_,
        pointerEvent,
        undefined,
        undefined,
        this.activePointers_,
      );
      this.dispatchEvent(newEvent);

      // We emulate click events on left mouse button click, touch contact, and pen
      // contact. isMouseActionButton returns true in these cases (evt.button is set
      // to 0).
      // See http://www.w3.org/TR/pointerevents/#button-states
      // We only fire click, singleclick, and doubleclick if nobody has called
      // event.preventDefault().
      if (
        this.emulateClicks_ &&
        !newEvent.defaultPrevented &&
        !this.dragging_ &&
        this.isMouseActionButton_(pointerEvent)
      ) {
        this.emulateClick_(this.down_);
      }

      if (this.activePointers_.length === 0) {
        this.dragListenerKeys_.forEach(unlistenByKey);
        this.dragListenerKeys_.length = 0;
        this.dragging_ = false;
        this.down_ = null;
      }
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @return {boolean} If the left mouse button was pressed.
     * @private
     */
    isMouseActionButton_(pointerEvent) {
      return pointerEvent.button === 0;
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    handlePointerDown_(pointerEvent) {
      this.emulateClicks_ = this.activePointers_.length === 0;
      this.updateActivePointers_(pointerEvent);
      const newEvent = new MapBrowserEvent(
        MapBrowserEventType.POINTERDOWN,
        this.map_,
        pointerEvent,
        undefined,
        undefined,
        this.activePointers_,
      );
      this.dispatchEvent(newEvent);

      this.down_ = new PointerEvent(pointerEvent.type, pointerEvent);
      Object.defineProperty(this.down_, 'target', {
        writable: false,
        value: pointerEvent.target,
      });

      if (this.dragListenerKeys_.length === 0) {
        const doc = this.map_.getOwnerDocument();
        this.dragListenerKeys_.push(
          listen(
            doc,
            MapBrowserEventType.POINTERMOVE,
            this.handlePointerMove_,
            this,
          ),
          listen(doc, MapBrowserEventType.POINTERUP, this.handlePointerUp_, this),
          /* Note that the listener for `pointercancel is set up on
           * `pointerEventHandler_` and not `documentPointerEventHandler_` like
           * the `pointerup` and `pointermove` listeners.
           *
           * The reason for this is the following: `TouchSource.vacuumTouches_()`
           * issues `pointercancel` events, when there was no `touchend` for a
           * `touchstart`. Now, let's say a first `touchstart` is registered on
           * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up.
           * But `documentPointerEventHandler_` doesn't know about the first
           * `touchstart`. If there is no `touchend` for the `touchstart`, we can
           * only receive a `touchcancel` from `pointerEventHandler_`, because it is
           * only registered there.
           */
          listen(
            this.element_,
            MapBrowserEventType.POINTERCANCEL,
            this.handlePointerUp_,
            this,
          ),
        );
        if (this.element_.getRootNode && this.element_.getRootNode() !== doc) {
          this.dragListenerKeys_.push(
            listen(
              this.element_.getRootNode(),
              MapBrowserEventType.POINTERUP,
              this.handlePointerUp_,
              this,
            ),
          );
        }
      }
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    handlePointerMove_(pointerEvent) {
      // Between pointerdown and pointerup, pointermove events are triggered.
      // To avoid a 'false' touchmove event to be dispatched, we test if the pointer
      // moved a significant distance.
      if (this.isMoving_(pointerEvent)) {
        this.updateActivePointers_(pointerEvent);
        this.dragging_ = true;
        const newEvent = new MapBrowserEvent(
          MapBrowserEventType.POINTERDRAG,
          this.map_,
          pointerEvent,
          this.dragging_,
          undefined,
          this.activePointers_,
        );
        this.dispatchEvent(newEvent);
      }
    }

    /**
     * Wrap and relay a pointermove event.
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @private
     */
    relayMoveEvent_(pointerEvent) {
      this.originalPointerMoveEvent_ = pointerEvent;
      const dragging = !!(this.down_ && this.isMoving_(pointerEvent));
      this.dispatchEvent(
        new MapBrowserEvent(
          MapBrowserEventType.POINTERMOVE,
          this.map_,
          pointerEvent,
          dragging,
        ),
      );
    }

    /**
     * Flexible handling of a `touch-action: none` css equivalent: because calling
     * `preventDefault()` on a `pointermove` event does not stop native page scrolling
     * and zooming, we also listen for `touchmove` and call `preventDefault()` on it
     * when an interaction (currently `DragPan` handles the event.
     * @param {TouchEvent} event Event.
     * @private
     */
    handleTouchMove_(event) {
      // Due to https://github.com/mpizenberg/elm-pep/issues/2, `this.originalPointerMoveEvent_`
      // may not be initialized yet when we get here on a platform without native pointer events,
      // when elm-pep is used as pointer events polyfill.
      const originalEvent = this.originalPointerMoveEvent_;
      if (
        (!originalEvent || originalEvent.defaultPrevented) &&
        (typeof event.cancelable !== 'boolean' || event.cancelable === true)
      ) {
        event.preventDefault();
      }
    }

    /**
     * @param {PointerEvent} pointerEvent Pointer
     * event.
     * @return {boolean} Is moving.
     * @private
     */
    isMoving_(pointerEvent) {
      return (
        this.dragging_ ||
        Math.abs(pointerEvent.clientX - this.down_.clientX) >
          this.moveTolerance_ ||
        Math.abs(pointerEvent.clientY - this.down_.clientY) > this.moveTolerance_
      );
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      if (this.relayedListenerKey_) {
        unlistenByKey(this.relayedListenerKey_);
        this.relayedListenerKey_ = null;
      }
      this.element_.removeEventListener(
        EventType.TOUCHMOVE,
        this.boundHandleTouchMove_,
      );

      if (this.pointerdownListenerKey_) {
        unlistenByKey(this.pointerdownListenerKey_);
        this.pointerdownListenerKey_ = null;
      }

      this.dragListenerKeys_.forEach(unlistenByKey);
      this.dragListenerKeys_.length = 0;

      this.element_ = null;
      super.disposeInternal();
    }
  }

  /**
   * @module ol/MapEventType
   */

  /**
   * @enum {string}
   */
  var MapEventType = {
    /**
     * Triggered after a map frame is rendered.
     * @event module:ol/MapEvent~MapEvent#postrender
     * @api
     */
    POSTRENDER: 'postrender',

    /**
     * Triggered when the map starts moving.
     * @event module:ol/MapEvent~MapEvent#movestart
     * @api
     */
    MOVESTART: 'movestart',

    /**
     * Triggered after the map is moved.
     * @event module:ol/MapEvent~MapEvent#moveend
     * @api
     */
    MOVEEND: 'moveend',

    /**
     * Triggered when loading of additional map data (tiles, images, features) starts.
     * @event module:ol/MapEvent~MapEvent#loadstart
     * @api
     */
    LOADSTART: 'loadstart',

    /**
     * Triggered when loading of additional map data has completed.
     * @event module:ol/MapEvent~MapEvent#loadend
     * @api
     */
    LOADEND: 'loadend',
  };

  /***
   * @typedef {'postrender'|'movestart'|'moveend'|'loadstart'|'loadend'} Types
   */

  /**
   * @module ol/MapProperty
   */

  /**
   * @enum {string}
   */
  var MapProperty = {
    LAYERGROUP: 'layergroup',
    SIZE: 'size',
    TARGET: 'target',
    VIEW: 'view',
  };

  /**
   * @module ol/structs/PriorityQueue
   */

  /**
   * @type {number}
   */
  const DROP = Infinity;

  /**
   * @classdesc
   * Priority queue.
   *
   * The implementation is inspired from the Closure Library's Heap class and
   * Python's heapq module.
   *
   * See https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js
   * and https://hg.python.org/cpython/file/2.7/Lib/heapq.py.
   *
   * @template T
   */
  class PriorityQueue {
    /**
     * @param {function(T): number} priorityFunction Priority function.
     * @param {function(T): string} keyFunction Key function.
     */
    constructor(priorityFunction, keyFunction) {
      /**
       * @type {function(T): number}
       * @private
       */
      this.priorityFunction_ = priorityFunction;

      /**
       * @type {function(T): string}
       * @private
       */
      this.keyFunction_ = keyFunction;

      /**
       * @type {Array<T>}
       * @private
       */
      this.elements_ = [];

      /**
       * @type {Array<number>}
       * @private
       */
      this.priorities_ = [];

      /**
       * @type {!Object<string, boolean>}
       * @private
       */
      this.queuedElements_ = {};
    }

    /**
     * FIXME empty description for jsdoc
     */
    clear() {
      this.elements_.length = 0;
      this.priorities_.length = 0;
      clear$2(this.queuedElements_);
    }

    /**
     * Remove and return the highest-priority element. O(log N).
     * @return {T} Element.
     */
    dequeue() {
      const elements = this.elements_;
      const priorities = this.priorities_;
      const element = elements[0];
      if (elements.length == 1) {
        elements.length = 0;
        priorities.length = 0;
      } else {
        elements[0] = /** @type {T} */ (elements.pop());
        priorities[0] = /** @type {number} */ (priorities.pop());
        this.siftUp_(0);
      }
      const elementKey = this.keyFunction_(element);
      delete this.queuedElements_[elementKey];
      return element;
    }

    /**
     * Enqueue an element. O(log N).
     * @param {T} element Element.
     * @return {boolean} The element was added to the queue.
     */
    enqueue(element) {
      assert(
        !(this.keyFunction_(element) in this.queuedElements_),
        'Tried to enqueue an `element` that was already added to the queue',
      );
      const priority = this.priorityFunction_(element);
      if (priority != DROP) {
        this.elements_.push(element);
        this.priorities_.push(priority);
        this.queuedElements_[this.keyFunction_(element)] = true;
        this.siftDown_(0, this.elements_.length - 1);
        return true;
      }
      return false;
    }

    /**
     * @return {number} Count.
     */
    getCount() {
      return this.elements_.length;
    }

    /**
     * Gets the index of the left child of the node at the given index.
     * @param {number} index The index of the node to get the left child for.
     * @return {number} The index of the left child.
     * @private
     */
    getLeftChildIndex_(index) {
      return index * 2 + 1;
    }

    /**
     * Gets the index of the right child of the node at the given index.
     * @param {number} index The index of the node to get the right child for.
     * @return {number} The index of the right child.
     * @private
     */
    getRightChildIndex_(index) {
      return index * 2 + 2;
    }

    /**
     * Gets the index of the parent of the node at the given index.
     * @param {number} index The index of the node to get the parent for.
     * @return {number} The index of the parent.
     * @private
     */
    getParentIndex_(index) {
      return (index - 1) >> 1;
    }

    /**
     * Make this a heap. O(N).
     * @private
     */
    heapify_() {
      let i;
      for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) {
        this.siftUp_(i);
      }
    }

    /**
     * @return {boolean} Is empty.
     */
    isEmpty() {
      return this.elements_.length === 0;
    }

    /**
     * @param {string} key Key.
     * @return {boolean} Is key queued.
     */
    isKeyQueued(key) {
      return key in this.queuedElements_;
    }

    /**
     * @param {T} element Element.
     * @return {boolean} Is queued.
     */
    isQueued(element) {
      return this.isKeyQueued(this.keyFunction_(element));
    }

    /**
     * @param {number} index The index of the node to move down.
     * @private
     */
    siftUp_(index) {
      const elements = this.elements_;
      const priorities = this.priorities_;
      const count = elements.length;
      const element = elements[index];
      const priority = priorities[index];
      const startIndex = index;

      while (index < count >> 1) {
        const lIndex = this.getLeftChildIndex_(index);
        const rIndex = this.getRightChildIndex_(index);

        const smallerChildIndex =
          rIndex < count && priorities[rIndex] < priorities[lIndex]
            ? rIndex
            : lIndex;

        elements[index] = elements[smallerChildIndex];
        priorities[index] = priorities[smallerChildIndex];
        index = smallerChildIndex;
      }

      elements[index] = element;
      priorities[index] = priority;
      this.siftDown_(startIndex, index);
    }

    /**
     * @param {number} startIndex The index of the root.
     * @param {number} index The index of the node to move up.
     * @private
     */
    siftDown_(startIndex, index) {
      const elements = this.elements_;
      const priorities = this.priorities_;
      const element = elements[index];
      const priority = priorities[index];

      while (index > startIndex) {
        const parentIndex = this.getParentIndex_(index);
        if (priorities[parentIndex] > priority) {
          elements[index] = elements[parentIndex];
          priorities[index] = priorities[parentIndex];
          index = parentIndex;
        } else {
          break;
        }
      }
      elements[index] = element;
      priorities[index] = priority;
    }

    /**
     * FIXME empty description for jsdoc
     */
    reprioritize() {
      const priorityFunction = this.priorityFunction_;
      const elements = this.elements_;
      const priorities = this.priorities_;
      let index = 0;
      const n = elements.length;
      let element, i, priority;
      for (i = 0; i < n; ++i) {
        element = elements[i];
        priority = priorityFunction(element);
        if (priority == DROP) {
          delete this.queuedElements_[this.keyFunction_(element)];
        } else {
          priorities[index] = priority;
          elements[index++] = element;
        }
      }
      elements.length = index;
      priorities.length = index;
      this.heapify_();
    }
  }

  /**
   * @module ol/TileQueue
   */

  /**
   * @typedef {function(import("./Tile.js").default, string, import('./tilecoord.js').TileCoord, number): number} PriorityFunction
   */

  /**
   * @typedef {[import('./Tile.js').default, string, import('./tilecoord.js').TileCoord, number]} TileQueueElement
   */

  /**
   * @extends PriorityQueue<TileQueueElement>}
   */
  class TileQueue extends PriorityQueue {
    /**
     * @param {PriorityFunction} tilePriorityFunction Tile priority function.
     * @param {function(): ?} tileChangeCallback Function called on each tile change event.
     */
    constructor(tilePriorityFunction, tileChangeCallback) {
      super(
        (element) => tilePriorityFunction.apply(null, element),
        (element) => element[0].getKey(),
      );

      /** @private */
      this.boundHandleTileChange_ = this.handleTileChange.bind(this);

      /**
       * @private
       * @type {function(): ?}
       */
      this.tileChangeCallback_ = tileChangeCallback;

      /**
       * @private
       * @type {number}
       */
      this.tilesLoading_ = 0;

      /**
       * @private
       * @type {!Object<string,boolean>}
       */
      this.tilesLoadingKeys_ = {};
    }

    /**
     * @param {TileQueueElement} element Element.
     * @return {boolean} The element was added to the queue.
     * @override
     */
    enqueue(element) {
      const added = super.enqueue(element);
      if (added) {
        const tile = element[0];
        tile.addEventListener(EventType.CHANGE, this.boundHandleTileChange_);
      }
      return added;
    }

    /**
     * @return {number} Number of tiles loading.
     */
    getTilesLoading() {
      return this.tilesLoading_;
    }

    /**
     * @param {import("./events/Event.js").default} event Event.
     * @protected
     */
    handleTileChange(event) {
      const tile = /** @type {import("./Tile.js").default} */ (event.target);
      const state = tile.getState();
      if (
        state === TileState.LOADED ||
        state === TileState.ERROR ||
        state === TileState.EMPTY
      ) {
        if (state !== TileState.ERROR) {
          tile.removeEventListener(EventType.CHANGE, this.boundHandleTileChange_);
        }
        const tileKey = tile.getKey();
        if (tileKey in this.tilesLoadingKeys_) {
          delete this.tilesLoadingKeys_[tileKey];
          --this.tilesLoading_;
        }
        this.tileChangeCallback_();
      }
    }

    /**
     * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.
     * @param {number} maxNewLoads Maximum number of new tiles to load.
     */
    loadMoreTiles(maxTotalLoading, maxNewLoads) {
      let newLoads = 0;
      while (
        this.tilesLoading_ < maxTotalLoading &&
        newLoads < maxNewLoads &&
        this.getCount() > 0
      ) {
        const tile = this.dequeue()[0];
        const tileKey = tile.getKey();
        const state = tile.getState();
        if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) {
          this.tilesLoadingKeys_[tileKey] = true;
          ++this.tilesLoading_;
          ++newLoads;
          tile.load();
        }
      }
    }
  }

  /**
   * @param {import('./Map.js').FrameState} frameState Frame state.
   * @param {import("./Tile.js").default} tile Tile.
   * @param {string} tileSourceKey Tile source key.
   * @param {import("./coordinate.js").Coordinate} tileCenter Tile center.
   * @param {number} tileResolution Tile resolution.
   * @return {number} Tile priority.
   */
  function getTilePriority(
    frameState,
    tile,
    tileSourceKey,
    tileCenter,
    tileResolution,
  ) {
    // Filter out tiles at higher zoom levels than the current zoom level, or that
    // are outside the visible extent.
    if (!frameState || !(tileSourceKey in frameState.wantedTiles)) {
      return DROP;
    }
    if (!frameState.wantedTiles[tileSourceKey][tile.getKey()]) {
      return DROP;
    }
    // Prioritize the highest zoom level tiles closest to the focus.
    // Tiles at higher zoom levels are prioritized using Math.log(tileResolution).
    // Within a zoom level, tiles are prioritized by the distance in pixels between
    // the center of the tile and the center of the viewport.  The factor of 65536
    // means that the prioritization should behave as desired for tiles up to
    // 65536 * Math.log(2) = 45426 pixels from the focus.
    const center = frameState.viewState.center;
    const deltaX = tileCenter[0] - center[0];
    const deltaY = tileCenter[1] - center[1];
    return (
      65536 * Math.log(tileResolution) +
      Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution
    );
  }

  /**
   * @module ol/control/Control
   */

  /**
   * @typedef {Object} Options
   * @property {HTMLElement} [element] The element is the control's
   * container element. This only needs to be specified if you're developing
   * a custom control.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when
   * the control should be re-rendered. This is called in a `requestAnimationFrame`
   * callback.
   * @property {HTMLElement|string} [target] Specify a target if you want
   * the control to be rendered outside of the map's viewport.
   */

  /**
   * @classdesc
   * A control is a visible widget with a DOM element in a fixed position on the
   * screen. They can involve user input (buttons), or be informational only;
   * the position is determined using CSS. By default these are placed in the
   * container with CSS class name `ol-overlaycontainer-stopevent`, but can use
   * any outside DOM element.
   *
   * This is the base class for controls. You can use it for simple custom
   * controls by creating the element with listeners, creating an instance:
   * ```js
   * const myControl = new Control({element: myElement});
   * ```
   * and then adding this to the map.
   *
   * The main advantage of having this as a control rather than a simple separate
   * DOM element is that preventing propagation is handled for you. Controls
   * will also be objects in a {@link module:ol/Collection~Collection}, so you can use their methods.
   *
   * You can also extend this base for your own control class. See
   * examples/custom-controls for an example of how to do this.
   *
   * @api
   */
  class Control extends BaseObject {
    /**
     * @param {Options} options Control options.
     */
    constructor(options) {
      super();

      const element = options.element;
      if (element && !options.target && !element.style.pointerEvents) {
        element.style.pointerEvents = 'auto';
      }

      /**
       * @protected
       * @type {HTMLElement}
       */
      this.element = element ? element : null;

      /**
       * @private
       * @type {HTMLElement}
       */
      this.target_ = null;

      /**
       * @private
       * @type {import("../Map.js").default|null}
       */
      this.map_ = null;

      /**
       * @protected
       * @type {!Array<import("../events.js").EventsKey>}
       */
      this.listenerKeys = [];

      if (options.render) {
        this.render = options.render;
      }

      if (options.target) {
        this.setTarget(options.target);
      }
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.element?.remove();
      super.disposeInternal();
    }

    /**
     * Get the map associated with this control.
     * @return {import("../Map.js").default|null} Map.
     * @api
     */
    getMap() {
      return this.map_;
    }

    /**
     * Remove the control from its current map and attach it to the new map.
     * Pass `null` to just remove the control from the current map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     */
    setMap(map) {
      if (this.map_) {
        this.element?.remove();
      }
      for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) {
        unlistenByKey(this.listenerKeys[i]);
      }
      this.listenerKeys.length = 0;
      this.map_ = map;
      if (map) {
        const target = this.target_ ?? map.getOverlayContainerStopEvent();
        if (this.element) {
          target.appendChild(this.element);
        }
        if (this.render !== VOID) {
          this.listenerKeys.push(
            listen(map, MapEventType.POSTRENDER, this.render, this),
          );
        }
        map.render();
      }
    }

    /**
     * Renders the control.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @api
     */
    render(mapEvent) {}

    /**
     * This function is used to set a target element for the control. It has no
     * effect if it is called after the control has been added to the map (i.e.
     * after `setMap` is called on the control). If no `target` is set in the
     * options passed to the control constructor and if `setTarget` is not called
     * then the control is added to the map's overlay container.
     * @param {HTMLElement|string} target Target.
     * @api
     */
    setTarget(target) {
      this.target_ =
        typeof target === 'string' ? document.getElementById(target) : target;
    }
  }

  /**
   * @module ol/control/Attribution
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-attribution'] CSS class name.
   * @property {HTMLElement|string} [target] Specify a target if you
   * want the control to be rendered outside of the map's
   * viewport.
   * @property {boolean} [collapsible] Specify if attributions can
   * be collapsed. If not specified, sources control this behavior with their
   * `attributionsCollapsible` setting.
   * @property {boolean} [collapsed=true] Specify if attributions should
   * be collapsed at startup.
   * @property {string} [tipLabel='Attributions'] Text label to use for the button tip.
   * @property {string|HTMLElement} [label='i'] Text label to use for the
   * collapsed attributions button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [expandClassName=className + '-expand'] CSS class name for the
   * collapsed attributions button.
   * @property {string|HTMLElement} [collapseLabel='›'] Text label to use
   * for the expanded attributions button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [collapseClassName=className + '-collapse'] CSS class name for the
   * expanded attributions button.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when
   * the control should be re-rendered. This is called in a `requestAnimationFrame`
   * callback.
   * @property {string|Array<string>|undefined} [attributions] Optional attribution(s) that will always be
   * displayed regardless of the layers rendered.
   * **Caution:** Attributions are rendered dynamically using `innerHTML`, which can lead to potential
   * [**XSS (Cross-Site Scripting)**](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerabilities.
   * Use this feature only for trusted content
   * or ensure that the content is properly sanitized before inserting it.
   */

  /**
   * @classdesc
   * Control to show all the attributions associated with the layer sources
   * in the map. This control is one of the default controls included in maps.
   * By default it will show in the bottom right portion of the map, but this can
   * be changed by using a css selector for `.ol-attribution`.
   *
   * @api
   */
  class Attribution extends Control {
    /**
     * @param {Options} [options] Attribution options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        render: options.render,
        target: options.target,
      });

      /**
       * @private
       * @type {HTMLElement}
       */
      this.ulElement_ = document.createElement('ul');

      /**
       * @private
       * @type {boolean}
       */
      this.collapsed_ =
        options.collapsed !== undefined ? options.collapsed : true;

      /**
       * @private
       * @type {boolean}
       */
      this.userCollapsed_ = this.collapsed_;

      /**
       * @private
       * @type {boolean}
       */
      this.overrideCollapsible_ = options.collapsible !== undefined;

      /**
       * @private
       * @type {boolean}
       */
      this.collapsible_ =
        options.collapsible !== undefined ? options.collapsible : true;

      if (!this.collapsible_) {
        this.collapsed_ = false;
      }

      /**
       * @private
       * @type {string | Array<string> | undefined}
       */
      this.attributions_ = options.attributions;

      const className =
        options.className !== undefined ? options.className : 'ol-attribution';

      const tipLabel =
        options.tipLabel !== undefined ? options.tipLabel : 'Attributions';

      const expandClassName =
        options.expandClassName !== undefined
          ? options.expandClassName
          : className + '-expand';

      const collapseLabel =
        options.collapseLabel !== undefined ? options.collapseLabel : '\u203A';

      const collapseClassName =
        options.collapseClassName !== undefined
          ? options.collapseClassName
          : className + '-collapse';

      if (typeof collapseLabel === 'string') {
        /**
         * @private
         * @type {HTMLElement}
         */
        this.collapseLabel_ = document.createElement('span');
        this.collapseLabel_.textContent = collapseLabel;
        this.collapseLabel_.className = collapseClassName;
      } else {
        this.collapseLabel_ = collapseLabel;
      }

      const label = options.label !== undefined ? options.label : 'i';

      if (typeof label === 'string') {
        /**
         * @private
         * @type {HTMLElement}
         */
        this.label_ = document.createElement('span');
        this.label_.textContent = label;
        this.label_.className = expandClassName;
      } else {
        this.label_ = label;
      }

      const activeLabel =
        this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_;

      /**
       * @private
       * @type {HTMLElement}
       */
      this.toggleButton_ = document.createElement('button');
      this.toggleButton_.setAttribute('type', 'button');
      this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));
      this.toggleButton_.title = tipLabel;
      this.toggleButton_.appendChild(activeLabel);

      this.toggleButton_.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this),
        false,
      );

      const cssClasses =
        className +
        ' ' +
        CLASS_UNSELECTABLE +
        ' ' +
        CLASS_CONTROL +
        (this.collapsed_ && this.collapsible_ ? ' ' + CLASS_COLLAPSED : '') +
        (this.collapsible_ ? '' : ' ol-uncollapsible');
      const element = this.element;
      element.className = cssClasses;
      element.appendChild(this.toggleButton_);
      element.appendChild(this.ulElement_);

      /**
       * A list of currently rendered resolutions.
       * @type {Array<string>}
       * @private
       */
      this.renderedAttributions_ = [];

      /**
       * @private
       * @type {boolean}
       */
      this.renderedVisible_ = true;
    }

    /**
     * Collect a list of visible attributions and set the collapsible state.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @return {Array<string>} Attributions.
     * @private
     */
    collectSourceAttributions_(frameState) {
      const layers = this.getMap().getAllLayers();
      const visibleAttributions = new Set(
        layers.flatMap((layer) => layer.getAttributions(frameState)),
      );
      if (this.attributions_ !== undefined) {
        Array.isArray(this.attributions_)
          ? this.attributions_.forEach((item) => visibleAttributions.add(item))
          : visibleAttributions.add(this.attributions_);
      }

      if (!this.overrideCollapsible_) {
        const collapsible = !layers.some(
          (layer) => layer.getSource()?.getAttributionsCollapsible() === false,
        );
        this.setCollapsible(collapsible);
      }
      return Array.from(visibleAttributions);
    }

    /**
     * @private
     * @param {?import("../Map.js").FrameState} frameState Frame state.
     */
    async updateElement_(frameState) {
      if (!frameState) {
        if (this.renderedVisible_) {
          this.element.style.display = 'none';
          this.renderedVisible_ = false;
        }
        return;
      }

      const attributions = await Promise.all(
        this.collectSourceAttributions_(frameState).map((attribution) =>
          toPromise(() => attribution),
        ),
      );

      const visible = attributions.length > 0;
      if (this.renderedVisible_ != visible) {
        this.element.style.display = visible ? '' : 'none';
        this.renderedVisible_ = visible;
      }

      if (equals$2(attributions, this.renderedAttributions_)) {
        return;
      }

      removeChildren(this.ulElement_);

      // append the attributions
      for (let i = 0, ii = attributions.length; i < ii; ++i) {
        const element = document.createElement('li');
        element.innerHTML = attributions[i];
        this.ulElement_.appendChild(element);
      }

      this.renderedAttributions_ = attributions;
    }

    /**
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(event) {
      event.preventDefault();
      this.handleToggle_();
      this.userCollapsed_ = this.collapsed_;
    }

    /**
     * @private
     */
    handleToggle_() {
      this.element.classList.toggle(CLASS_COLLAPSED);
      if (this.collapsed_) {
        replaceNode(this.collapseLabel_, this.label_);
      } else {
        replaceNode(this.label_, this.collapseLabel_);
      }
      this.collapsed_ = !this.collapsed_;
      this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));
    }

    /**
     * Return `true` if the attribution is collapsible, `false` otherwise.
     * @return {boolean} True if the widget is collapsible.
     * @api
     */
    getCollapsible() {
      return this.collapsible_;
    }

    /**
     * Set whether the attribution should be collapsible.
     * @param {boolean} collapsible True if the widget is collapsible.
     * @api
     */
    setCollapsible(collapsible) {
      if (this.collapsible_ === collapsible) {
        return;
      }
      this.collapsible_ = collapsible;
      this.element.classList.toggle('ol-uncollapsible');
      if (this.userCollapsed_) {
        this.handleToggle_();
      }
    }

    /**
     * Collapse or expand the attribution according to the passed parameter. Will
     * not do anything if the attribution isn't collapsible or if the current
     * collapsed state is already the one requested.
     * @param {boolean} collapsed True if the widget is collapsed.
     * @api
     */
    setCollapsed(collapsed) {
      this.userCollapsed_ = collapsed;
      if (!this.collapsible_ || this.collapsed_ === collapsed) {
        return;
      }
      this.handleToggle_();
    }

    /**
     * Return `true` when the attribution is currently collapsed or `false`
     * otherwise.
     * @return {boolean} True if the widget is collapsed.
     * @api
     */
    getCollapsed() {
      return this.collapsed_;
    }

    /**
     * Update the attribution element.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      this.updateElement_(mapEvent.frameState);
    }
  }

  /**
   * @module ol/control/Rotate
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-rotate'] CSS class name.
   * @property {string|HTMLElement} [label='⇧'] Text label to use for the rotate button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [tipLabel='Reset rotation'] Text label to use for the rotate tip.
   * @property {string} [compassClassName='ol-compass'] CSS class name for the compass.
   * @property {number} [duration=250] Animation duration in milliseconds.
   * @property {boolean} [autoHide=true] Hide the control when rotation is 0.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when the control should
   * be re-rendered. This is called in a `requestAnimationFrame` callback.
   * @property {function():void} [resetNorth] Function called when the control is clicked.
   * This will override the default `resetNorth`.
   * @property {HTMLElement|string} [target] Specify a target if you want the control to be
   * rendered outside of the map's viewport.
   */

  /**
   * @classdesc
   * A button control to reset rotation to 0.
   * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css
   * selector is added to the button when the rotation is 0.
   *
   * @api
   */
  class Rotate extends Control {
    /**
     * @param {Options} [options] Rotate options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        render: options.render,
        target: options.target,
      });

      const className =
        options.className !== undefined ? options.className : 'ol-rotate';

      const label = options.label !== undefined ? options.label : '\u21E7';

      const compassClassName =
        options.compassClassName !== undefined
          ? options.compassClassName
          : 'ol-compass';

      /**
       * @type {HTMLElement}
       * @private
       */
      this.label_ = null;

      if (typeof label === 'string') {
        this.label_ = document.createElement('span');
        this.label_.className = compassClassName;
        this.label_.textContent = label;
      } else {
        this.label_ = label;
        this.label_.classList.add(compassClassName);
      }

      const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';

      const button = document.createElement('button');
      button.className = className + '-reset';
      button.setAttribute('type', 'button');
      button.title = tipLabel;
      button.appendChild(this.label_);

      button.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this),
        false,
      );

      const cssClasses =
        className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
      const element = this.element;
      element.className = cssClasses;
      element.appendChild(button);

      /**
       * @private
       */
      this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;

      /**
       * @type {number}
       * @private
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;

      /**
       * @type {boolean}
       * @private
       */
      this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;

      /**
       * @private
       * @type {number|undefined}
       */
      this.rotation_ = undefined;

      if (this.autoHide_) {
        this.element.classList.add(CLASS_HIDDEN);
      }
    }

    /**
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(event) {
      event.preventDefault();
      if (this.callResetNorth_ !== undefined) {
        this.callResetNorth_();
      } else {
        this.resetNorth_();
      }
    }

    /**
     * @private
     */
    resetNorth_() {
      const map = this.getMap();
      const view = map.getView();
      if (!view) {
        // the map does not have a view, so we can't act
        // upon it
        return;
      }
      const rotation = view.getRotation();
      if (rotation !== undefined) {
        if (this.duration_ > 0 && rotation % (2 * Math.PI) !== 0) {
          view.animate({
            rotation: 0,
            duration: this.duration_,
            easing: easeOut,
          });
        } else {
          view.setRotation(0);
        }
      }
    }

    /**
     * Update the rotate control element.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      const frameState = mapEvent.frameState;
      if (!frameState) {
        return;
      }
      const rotation = frameState.viewState.rotation;
      if (rotation != this.rotation_) {
        const transform = 'rotate(' + rotation + 'rad)';
        if (this.autoHide_) {
          const contains = this.element.classList.contains(CLASS_HIDDEN);
          if (!contains && rotation === 0) {
            this.element.classList.add(CLASS_HIDDEN);
          } else if (contains && rotation !== 0) {
            this.element.classList.remove(CLASS_HIDDEN);
          }
        }
        this.label_.style.transform = transform;
      }
      this.rotation_ = rotation;
    }
  }

  /**
   * @module ol/control/Zoom
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=250] Animation duration in milliseconds.
   * @property {string} [className='ol-zoom'] CSS class name.
   * @property {string} [zoomInClassName=className + '-in'] CSS class name for the zoom-in button.
   * @property {string} [zoomOutClassName=className + '-out'] CSS class name for the zoom-out button.
   * @property {string|HTMLElement} [zoomInLabel='+'] Text label to use for the zoom-in
   * button. Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string|HTMLElement} [zoomOutLabel='–'] Text label to use for the zoom-out button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.
   * @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.
   * @property {number} [delta=1] The zoom delta applied on each click.
   * @property {HTMLElement|string} [target] Specify a target if you want the control to be
   * rendered outside of the map's viewport.
   */

  /**
   * @classdesc
   * A control with 2 buttons, one for zoom in and one for zoom out.
   * This control is one of the default controls of a map. To style this control
   * use css selectors `.ol-zoom-in` and `.ol-zoom-out`.
   *
   * @api
   */
  class Zoom extends Control {
    /**
     * @param {Options} [options] Zoom options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        target: options.target,
      });

      const className =
        options.className !== undefined ? options.className : 'ol-zoom';

      const delta = options.delta !== undefined ? options.delta : 1;

      const zoomInClassName =
        options.zoomInClassName !== undefined
          ? options.zoomInClassName
          : className + '-in';

      const zoomOutClassName =
        options.zoomOutClassName !== undefined
          ? options.zoomOutClassName
          : className + '-out';

      const zoomInLabel =
        options.zoomInLabel !== undefined ? options.zoomInLabel : '+';
      const zoomOutLabel =
        options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\u2013';

      const zoomInTipLabel =
        options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in';
      const zoomOutTipLabel =
        options.zoomOutTipLabel !== undefined
          ? options.zoomOutTipLabel
          : 'Zoom out';

      const inElement = document.createElement('button');
      inElement.className = zoomInClassName;
      inElement.setAttribute('type', 'button');
      inElement.title = zoomInTipLabel;
      inElement.appendChild(
        typeof zoomInLabel === 'string'
          ? document.createTextNode(zoomInLabel)
          : zoomInLabel,
      );

      inElement.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this, delta),
        false,
      );

      const outElement = document.createElement('button');
      outElement.className = zoomOutClassName;
      outElement.setAttribute('type', 'button');
      outElement.title = zoomOutTipLabel;
      outElement.appendChild(
        typeof zoomOutLabel === 'string'
          ? document.createTextNode(zoomOutLabel)
          : zoomOutLabel,
      );

      outElement.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this, -delta),
        false,
      );

      const cssClasses =
        className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
      const element = this.element;
      element.className = cssClasses;
      element.appendChild(inElement);
      element.appendChild(outElement);

      /**
       * @type {number}
       * @private
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;
    }

    /**
     * @param {number} delta Zoom delta.
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(delta, event) {
      event.preventDefault();
      this.zoomByDelta_(delta);
    }

    /**
     * @param {number} delta Zoom delta.
     * @private
     */
    zoomByDelta_(delta) {
      const map = this.getMap();
      const view = map.getView();
      if (!view) {
        // the map does not have a view, so we can't act
        // upon it
        return;
      }
      const currentZoom = view.getZoom();
      if (currentZoom !== undefined) {
        const newZoom = view.getConstrainedZoom(currentZoom + delta);
        if (this.duration_ > 0) {
          if (view.getAnimating()) {
            view.cancelAnimations();
          }
          view.animate({
            zoom: newZoom,
            duration: this.duration_,
            easing: easeOut,
          });
        } else {
          view.setZoom(newZoom);
        }
      }
    }
  }

  /**
   * @module ol/control/defaults
   */

  /**
   * @typedef {Object} DefaultsOptions
   * @property {boolean} [attribution=true] Include
   * {@link module:ol/control/Attribution~Attribution}.
   * @property {import("./Attribution.js").Options} [attributionOptions]
   * Options for {@link module:ol/control/Attribution~Attribution}.
   * @property {boolean} [rotate=true] Include
   * {@link module:ol/control/Rotate~Rotate}.
   * @property {import("./Rotate.js").Options} [rotateOptions] Options
   * for {@link module:ol/control/Rotate~Rotate}.
   * @property {boolean} [zoom] Include {@link module:ol/control/Zoom~Zoom}.
   * @property {import("./Zoom.js").Options} [zoomOptions] Options for
   * {@link module:ol/control/Zoom~Zoom}.
   */

  /**
   * Set of controls included in maps by default. Unless configured otherwise,
   * this returns a collection containing an instance of each of the following
   * controls:
   * {@link module:ol/control/Zoom~Zoom}
   * {@link module:ol/control/Rotate~Rotate}
   * {@link module:ol/control/Attribution~Attribution}
   *
   * @param {DefaultsOptions} [options] Options for the default controls.
   * @return {Collection<import("./Control.js").default>} A collection of controls
   * to be used with the {@link module:ol/Map~Map} constructor's `controls` option.
   * @api
   */
  function defaults$1(options) {
    options = options ? options : {};

    /** @type {Collection<import("./Control.js").default>} */
    const controls = new Collection();

    const zoomControl = options.zoom !== undefined ? options.zoom : true;
    if (zoomControl) {
      controls.push(new Zoom(options.zoomOptions));
    }

    const rotateControl = options.rotate !== undefined ? options.rotate : true;
    if (rotateControl) {
      controls.push(new Rotate(options.rotateOptions));
    }

    const attributionControl =
      options.attribution !== undefined ? options.attribution : true;
    if (attributionControl) {
      controls.push(new Attribution(options.attributionOptions));
    }

    return controls;
  }

  /**
   * @module ol/interaction/Property
   */

  /**
   * @enum {string}
   */
  var InteractionProperty = {
    ACTIVE: 'active',
  };

  /**
   * @module ol/interaction/Interaction
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active', Return>} InteractionOnSignature
   */

  /**
   * Object literal with config options for interactions.
   * @typedef {Object} InteractionOptions
   * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleEvent]
   * Method called by the map to notify the interaction that a browser event was
   * dispatched to the map. If the function returns a falsy value, propagation of
   * the event to other interactions in the map's interactions chain will be
   * prevented (this includes functions with no explicit return). The interactions
   * are traversed in reverse order of the interactions collection of the map.
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * User actions that change the state of the map. Some are similar to controls,
   * but are not associated with a DOM element.
   * For example, {@link module:ol/interaction/KeyboardZoom~KeyboardZoom} is
   * functionally the same as {@link module:ol/control/Zoom~Zoom}, but triggered
   * by a keyboard event not a button element event.
   * Although interactions do not have a DOM element, some of them do render
   * vectors and so are visible on the screen.
   * @api
   */
  class Interaction extends BaseObject {
    /**
     * @param {InteractionOptions} [options] Options.
     */
    constructor(options) {
      super();

      /***
       * @type {InteractionOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {InteractionOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {InteractionOnSignature<void>}
       */
      this.un;

      if (options && options.handleEvent) {
        this.handleEvent = options.handleEvent;
      }

      /**
       * @private
       * @type {import("../Map.js").default|null}
       */
      this.map_ = null;

      this.setActive(true);
    }

    /**
     * Return whether the interaction is currently active.
     * @return {boolean} `true` if the interaction is active, `false` otherwise.
     * @observable
     * @api
     */
    getActive() {
      return /** @type {boolean} */ (this.get(InteractionProperty.ACTIVE));
    }

    /**
     * Get the map associated with this interaction.
     * @return {import("../Map.js").default|null} Map.
     * @api
     */
    getMap() {
      return this.map_;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     */
    handleEvent(mapBrowserEvent) {
      return true;
    }

    /**
     * Activate or deactivate the interaction.
     * @param {boolean} active Active.
     * @observable
     * @api
     */
    setActive(active) {
      this.set(InteractionProperty.ACTIVE, active);
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     */
    setMap(map) {
      this.map_ = map;
    }
  }

  /**
   * @param {import("../View.js").default} view View.
   * @param {import("../coordinate.js").Coordinate} delta Delta.
   * @param {number} [duration] Duration.
   */
  function pan(view, delta, duration) {
    const currentCenter = view.getCenterInternal();
    if (currentCenter) {
      const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]];
      view.animateInternal({
        duration: duration !== undefined ? duration : 250,
        easing: linear,
        center: view.getConstrainedCenter(center),
      });
    }
  }

  /**
   * @param {import("../View.js").default} view View.
   * @param {number} delta Delta from previous zoom level.
   * @param {import("../coordinate.js").Coordinate} [anchor] Anchor coordinate in the user projection.
   * @param {number} [duration] Duration.
   */
  function zoomByDelta(view, delta, anchor, duration) {
    const currentZoom = view.getZoom();

    if (currentZoom === undefined) {
      return;
    }

    const newZoom = view.getConstrainedZoom(currentZoom + delta);
    const newResolution = view.getResolutionForZoom(newZoom);

    if (view.getAnimating()) {
      view.cancelAnimations();
    }
    view.animate({
      resolution: newResolution,
      anchor: anchor,
      duration: duration !== undefined ? duration : 250,
      easing: easeOut,
    });
  }

  /**
   * @module ol/interaction/DoubleClickZoom
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=250] Animation duration in milliseconds.
   * @property {number} [delta=1] The zoom delta applied on each double click.
   */

  /**
   * @classdesc
   * Allows the user to zoom by double-clicking on the map.
   * @api
   */
  class DoubleClickZoom extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @private
       * @type {number}
       */
      this.delta_ = options.delta ? options.delta : 1;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a
     * doubleclick) and eventually zooms the map.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      let stopEvent = false;
      if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) {
        const browserEvent = /** @type {MouseEvent} */ (
          mapBrowserEvent.originalEvent
        );
        const map = mapBrowserEvent.map;
        const anchor = mapBrowserEvent.coordinate;
        const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;
        const view = map.getView();
        zoomByDelta(view, delta, anchor, this.duration_);
        browserEvent.preventDefault();
        stopEvent = true;
      }
      return !stopEvent;
    }
  }

  /**
   * @module ol/events/condition
   */

  /**
   * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * `{boolean}`. If the condition is met, true should be returned.
   *
   * @typedef {function(this: ?, import("../MapBrowserEvent.js").default): boolean} Condition
   */

  /**
   * Creates a condition function that passes when all provided conditions pass.
   * @param {...Condition} var_args Conditions to check.
   * @return {Condition} Condition function.
   */
  function all(var_args) {
    const conditions = arguments;
    /**
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @return {boolean} All conditions passed.
     */
    return function (event) {
      let pass = true;
      for (let i = 0, ii = conditions.length; i < ii; ++i) {
        pass = pass && conditions[i](event);
        if (!pass) {
          break;
        }
      }
      return pass;
    };
  }

  /**
   * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when
   * additionally the shift-key is pressed).
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if only the alt key is pressed.
   * @api
   */
  const altKeyOnly = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return (
      originalEvent.altKey &&
      !(originalEvent.metaKey || originalEvent.ctrlKey) &&
      !originalEvent.shiftKey
    );
  };

  /**
   * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise
   * (e.g. when additionally the platform-modifier-key is pressed).
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if only the alt and shift keys are pressed.
   * @api
   */
  const altShiftKeysOnly = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return (
      originalEvent.altKey &&
      !(originalEvent.metaKey || originalEvent.ctrlKey) &&
      originalEvent.shiftKey
    );
  };

  /**
   * Return `true` if the map has the focus. This condition requires a map target
   * element with a `tabindex` attribute, e.g. `<div id="map" tabindex="1">`.
   *
   * @param {import("../MapBrowserEvent.js").default} event Map browser event.
   * @return {boolean} The map has the focus.
   * @api
   */
  const focus = function (event) {
    const targetElement = event.map.getTargetElement();
    const rootNode = targetElement.getRootNode();
    const activeElement = event.map.getOwnerDocument().activeElement;

    return rootNode instanceof ShadowRoot
      ? rootNode.host.contains(activeElement)
      : targetElement.contains(activeElement);
  };

  /**
   * Return `true` if the map has the focus or no 'tabindex' attribute set.
   *
   * @param {import("../MapBrowserEvent.js").default} event Map browser event.
   * @return {boolean} The map container has the focus or no 'tabindex' attribute.
   */
  const focusWithTabindex = function (event) {
    const targetElement = event.map.getTargetElement();
    const rootNode = targetElement.getRootNode();
    const tabIndexCandidate =
      rootNode instanceof ShadowRoot ? rootNode.host : targetElement;

    return tabIndexCandidate.hasAttribute('tabindex') ? focus(event) : true;
  };

  /**
   * Return always true.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True.
   * @api
   */
  const always = TRUE;

  /**
   * Return `true` if the event is a `click` event, `false` otherwise.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event is a map `click` event.
   * @api
   */
  const click = function (mapBrowserEvent) {
    return mapBrowserEvent.type == MapBrowserEventType.CLICK;
  };

  /**
   * Return `true` if the event has an "action"-producing mouse button.
   *
   * By definition, this includes left-click on windows/linux, and left-click
   * without the ctrl key on Macs.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} The result.
   */
  const mouseActionButton = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return (
      'pointerId' in originalEvent &&
      originalEvent.button == 0 &&
      !(WEBKIT && MAC && originalEvent.ctrlKey)
    );
  };

  /**
   * Return always false.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} False.
   * @api
   */
  const never = FALSE;

  /**
   * Return `true` if the browser event is a `pointermove` event, `false`
   * otherwise.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the browser event is a `pointermove` event.
   * @api
   */
  const pointerMove = function (mapBrowserEvent) {
    return mapBrowserEvent.type == 'pointermove';
  };

  /**
   * Return `true` if the event is a map `singleclick` event, `false` otherwise.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event is a map `singleclick` event.
   * @api
   */
  const singleClick = function (mapBrowserEvent) {
    return mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK;
  };

  /**
   * Return `true` if the event is a map `dblclick` event, `false` otherwise.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event is a map `dblclick` event.
   * @api
   */
  const doubleClick = function (mapBrowserEvent) {
    return mapBrowserEvent.type == MapBrowserEventType.DBLCLICK;
  };

  /**
   * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is
   * pressed.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True only if there no modifier keys are pressed.
   * @api
   */
  const noModifierKeys = function (mapBrowserEvent) {
    const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (
      mapBrowserEvent.originalEvent
    );
    return (
      !originalEvent.altKey &&
      !(originalEvent.metaKey || originalEvent.ctrlKey) &&
      !originalEvent.shiftKey
    );
  };

  /**
   * Return `true` if only the platform-modifier-key (the meta-key on Mac,
   * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally
   * the shift-key is pressed).
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if only the platform modifier key is pressed.
   * @api
   */
  const platformModifierKeyOnly = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return (
      !originalEvent.altKey &&
      (MAC ? originalEvent.metaKey : originalEvent.ctrlKey) &&
      !originalEvent.shiftKey
    );
  };

  /**
   * Return `true` if the platform-modifier-key (the meta-key on Mac,
   * ctrl-key otherwise) is pressed.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the platform modifier key is pressed.
   * @api
   */
  const platformModifierKey = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return MAC ? originalEvent.metaKey : originalEvent.ctrlKey;
  };

  /**
   * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when
   * additionally the alt-key is pressed).
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if only the shift key is pressed.
   * @api
   */
  const shiftKeyOnly = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    return (
      !originalEvent.altKey &&
      !(originalEvent.metaKey || originalEvent.ctrlKey) &&
      originalEvent.shiftKey
    );
  };

  /**
   * Return `true` if the target element is not editable, i.e. not an `input`,
   * `select`, or `textarea` element and no `contenteditable` attribute is
   * set or inherited, `false` otherwise.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True only if the target element is not editable.
   * @api
   */
  const targetNotEditable = function (mapBrowserEvent) {
    const originalEvent = mapBrowserEvent.originalEvent;
    const tagName = /** @type {Element} */ (originalEvent.target).tagName;
    return (
      tagName !== 'INPUT' &&
      tagName !== 'SELECT' &&
      tagName !== 'TEXTAREA' &&
      // `isContentEditable` is only available on `HTMLElement`, but it may also be a
      // different type like `SVGElement`.
      // @ts-ignore
      !originalEvent.target.isContentEditable
    );
  };

  /**
   * Return `true` if the event originates from a mouse device.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event originates from a mouse device.
   * @api
   */
  const mouseOnly = function (mapBrowserEvent) {
    const pointerEvent = mapBrowserEvent.originalEvent;
    // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType
    return 'pointerId' in pointerEvent && pointerEvent.pointerType == 'mouse';
  };

  /**
   * Return `true` if the event originates from a touchable device.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event originates from a touchable device.
   * @api
   */
  const touchOnly = function (mapBrowserEvent) {
    const pointerEvt = mapBrowserEvent.originalEvent;
    // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType
    return 'pointerId' in pointerEvt && pointerEvt.pointerType === 'touch';
  };

  /**
   * Return `true` if the event originates from a digital pen.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event originates from a digital pen.
   * @api
   */
  const penOnly = function (mapBrowserEvent) {
    const pointerEvt = mapBrowserEvent.originalEvent;
    // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType
    return 'pointerId' in pointerEvt && pointerEvt.pointerType === 'pen';
  };

  /**
   * Return `true` if the event originates from a primary pointer in
   * contact with the surface or if the left mouse button is pressed.
   * See https://www.w3.org/TR/pointerevents/#button-states.
   *
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
   * @return {boolean} True if the event originates from a primary pointer.
   * @api
   */
  const primaryAction = function (mapBrowserEvent) {
    const pointerEvent = mapBrowserEvent.originalEvent;
    return (
      'pointerId' in pointerEvent &&
      pointerEvent.isPrimary &&
      pointerEvent.button === 0
    );
  };

  var nsEvents_condition = {
    __proto__: null,
    all: all,
    altKeyOnly: altKeyOnly,
    altShiftKeysOnly: altShiftKeysOnly,
    always: always,
    click: click,
    doubleClick: doubleClick,
    focus: focus,
    focusWithTabindex: focusWithTabindex,
    mouseActionButton: mouseActionButton,
    mouseOnly: mouseOnly,
    never: never,
    noModifierKeys: noModifierKeys,
    penOnly: penOnly,
    platformModifierKey: platformModifierKey,
    platformModifierKeyOnly: platformModifierKeyOnly,
    pointerMove: pointerMove,
    primaryAction: primaryAction,
    shiftKeyOnly: shiftKeyOnly,
    singleClick: singleClick,
    targetNotEditable: targetNotEditable,
    touchOnly: touchOnly
  };

  /**
   * @module ol/interaction/Pointer
   */

  /**
   * @typedef {Object} Options
   * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleDownEvent]
   * Function handling "down" events. If the function returns `true` then a drag
   * sequence is started.
   * @property {function(import("../MapBrowserEvent.js").default):void} [handleDragEvent]
   * Function handling "drag" events. This function is called on "move" events
   * during a drag sequence.
   * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleEvent]
   * Method called by the map to notify the interaction that a browser event was
   * dispatched to the map. The function may return `false` to prevent the
   * propagation of the event to other interactions in the map's interactions
   * chain.
   * @property {function(import("../MapBrowserEvent.js").default):void} [handleMoveEvent]
   * Function handling "move" events. This function is called on "move" events.
   * This functions is also called during a drag sequence, so during a drag
   * sequence both the `handleDragEvent` function and this function are called.
   * If `handleDownEvent` is defined and it returns true this function will not
   * be called during a drag sequence.
   * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleUpEvent]
   *  Function handling "up" events. If the function returns `false` then the
   * current drag sequence is stopped.
   * @property {function(boolean):boolean} [stopDown]
   * Should the down event be propagated to other interactions, or should be
   * stopped?
   */

  /**
   * @classdesc
   * Base class that calls user-defined functions on `down`, `move` and `up`
   * events. This class also manages "drag sequences".
   *
   * When the `handleDownEvent` user function returns `true` a drag sequence is
   * started. During a drag sequence the `handleDragEvent` user function is
   * called on `move` events. The drag sequence ends when the `handleUpEvent`
   * user function is called and returns `false`.
   * @api
   */
  class PointerInteraction extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super(
        /** @type {import("./Interaction.js").InteractionOptions} */ (options),
      );

      if (options.handleDownEvent) {
        this.handleDownEvent = options.handleDownEvent;
      }

      if (options.handleDragEvent) {
        this.handleDragEvent = options.handleDragEvent;
      }

      if (options.handleMoveEvent) {
        this.handleMoveEvent = options.handleMoveEvent;
      }

      if (options.handleUpEvent) {
        this.handleUpEvent = options.handleUpEvent;
      }

      if (options.stopDown) {
        this.stopDown = options.stopDown;
      }

      /**
       * @type {boolean}
       * @protected
       */
      this.handlingDownUpSequence = false;

      /**
       * @type {Array<PointerEvent>}
       * @protected
       */
      this.targetPointers = [];
    }

    /**
     * Returns the current number of pointers involved in the interaction,
     * e.g. `2` when two fingers are used.
     * @return {number} The number of pointers.
     * @api
     */
    getPointerCount() {
      return this.targetPointers.length;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @protected
     */
    handleDownEvent(mapBrowserEvent) {
      return false;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @protected
     */
    handleDragEvent(mapBrowserEvent) {}

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into
     * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are
     * detected.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!mapBrowserEvent.originalEvent) {
        return true;
      }

      let stopEvent = false;
      this.updateTrackedPointers_(mapBrowserEvent);
      if (this.handlingDownUpSequence) {
        if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) {
          this.handleDragEvent(mapBrowserEvent);
          // prevent page scrolling during dragging
          mapBrowserEvent.originalEvent.preventDefault();
        } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {
          const handledUp = this.handleUpEvent(mapBrowserEvent);
          this.handlingDownUpSequence =
            handledUp && this.targetPointers.length > 0;
        }
      } else {
        if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {
          const handled = this.handleDownEvent(mapBrowserEvent);
          this.handlingDownUpSequence = handled;
          stopEvent = this.stopDown(handled);
        } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) {
          this.handleMoveEvent(mapBrowserEvent);
        }
      }
      return !stopEvent;
    }

    /**
     * Handle pointer move events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @protected
     */
    handleMoveEvent(mapBrowserEvent) {}

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @protected
     */
    handleUpEvent(mapBrowserEvent) {
      return false;
    }

    /**
     * This function is used to determine if "down" events should be propagated
     * to other interactions or should be stopped.
     * @param {boolean} handled Was the event handled by the interaction?
     * @return {boolean} Should the `down` event be stopped?
     */
    stopDown(handled) {
      return handled;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @private
     */
    updateTrackedPointers_(mapBrowserEvent) {
      if (mapBrowserEvent.activePointers) {
        this.targetPointers = mapBrowserEvent.activePointers;
      }
    }
  }

  /**
   * @param {Array<PointerEvent>} pointerEvents List of events.
   * @return {{clientX: number, clientY: number}} Centroid pixel.
   */
  function centroid(pointerEvents) {
    const length = pointerEvents.length;
    let clientX = 0;
    let clientY = 0;
    for (let i = 0; i < length; i++) {
      clientX += pointerEvents[i].clientX;
      clientY += pointerEvents[i].clientY;
    }
    return {clientX: clientX / length, clientY: clientY / length};
  }

  /**
   * @module ol/interaction/DragPan
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean
   * to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.noModifierKeys} and {@link module:ol/events/condition.primaryAction}.
   * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,
   * the interaction will only handle events when the map has the focus.
   * @property {import("../Kinetic.js").default} [kinetic] Kinetic inertia to apply to the pan.
   */

  /**
   * @classdesc
   * Allows the user to pan the map by dragging the map.
   * @api
   */
  class DragPan extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super({
        stopDown: FALSE,
      });

      options = options ? options : {};

      /**
       * @private
       * @type {import("../Kinetic.js").default|undefined}
       */
      this.kinetic_ = options.kinetic;

      /**
       * @type {import("../pixel.js").Pixel}
       */
      this.lastCentroid = null;

      /**
       * @type {number}
       * @private
       */
      this.lastPointersCount_;

      /**
       * @type {boolean}
       * @private
       */
      this.panning_ = false;

      const condition = options.condition
        ? options.condition
        : all(noModifierKeys, primaryAction);

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.onFocusOnly
        ? all(focusWithTabindex, condition)
        : condition;

      /**
       * @private
       * @type {boolean}
       */
      this.noKinetic_ = false;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      const map = mapBrowserEvent.map;
      if (!this.panning_) {
        this.panning_ = true;
        map.getView().beginInteraction();
      }
      const targetPointers = this.targetPointers;
      const centroid$1 = map.getEventPixel(centroid(targetPointers));
      if (targetPointers.length == this.lastPointersCount_) {
        if (this.kinetic_) {
          this.kinetic_.update(centroid$1[0], centroid$1[1]);
        }
        if (this.lastCentroid) {
          const delta = [
            this.lastCentroid[0] - centroid$1[0],
            centroid$1[1] - this.lastCentroid[1],
          ];
          const map = mapBrowserEvent.map;
          const view = map.getView();
          scale$4(delta, view.getResolution());
          rotate$2(delta, view.getRotation());
          view.adjustCenterInternal(delta);
        }
      } else if (this.kinetic_) {
        // reset so we don't overestimate the kinetic energy after
        // after one finger down, tiny drag, second finger down
        this.kinetic_.begin();
      }
      this.lastCentroid = centroid$1;
      this.lastPointersCount_ = targetPointers.length;
      mapBrowserEvent.originalEvent.preventDefault();
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      const map = mapBrowserEvent.map;
      const view = map.getView();
      if (this.targetPointers.length === 0) {
        if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) {
          const distance = this.kinetic_.getDistance();
          const angle = this.kinetic_.getAngle();
          const center = view.getCenterInternal();
          const centerpx = map.getPixelFromCoordinateInternal(center);
          const dest = map.getCoordinateFromPixelInternal([
            centerpx[0] - distance * Math.cos(angle),
            centerpx[1] - distance * Math.sin(angle),
          ]);
          view.animateInternal({
            center: view.getConstrainedCenter(dest),
            duration: 500,
            easing: easeOut,
          });
        }
        if (this.panning_) {
          this.panning_ = false;
          view.endInteraction();
        }
        return false;
      }
      if (this.kinetic_) {
        // reset so we don't overestimate the kinetic energy after
        // after one finger up, tiny drag, second finger up
        this.kinetic_.begin();
      }
      this.lastCentroid = null;
      return true;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) {
        const map = mapBrowserEvent.map;
        const view = map.getView();
        this.lastCentroid = null;
        // stop any current animation
        if (view.getAnimating()) {
          view.cancelAnimations();
        }
        if (this.kinetic_) {
          this.kinetic_.begin();
        }
        // No kinetic as soon as more than one pointer on the screen is
        // detected. This is to prevent nasty pans after pinch.
        this.noKinetic_ = this.targetPointers.length > 1;
        return true;
      }
      return false;
    }
  }

  /**
   * @module ol/interaction/DragRotate
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that takes a
   * {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean
   * to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.altShiftKeysOnly}.
   * @property {number} [duration=250] Animation duration in milliseconds.
   */

  /**
   * @classdesc
   * Allows the user to rotate the map by clicking and dragging on the map,
   * normally combined with a {@link module:ol/events/condition} that limits
   * it to when the alt and shift keys are held down.
   *
   * This interaction is only supported for mouse devices.
   * @api
   */
  class DragRotate extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        stopDown: FALSE,
      });

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : altShiftKeysOnly;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lastAngle_ = undefined;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return;
      }

      const map = mapBrowserEvent.map;
      const view = map.getView();
      if (view.getConstraints().rotation === disable) {
        return;
      }
      const size = map.getSize();
      const offset = mapBrowserEvent.pixel;
      const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2);
      if (this.lastAngle_ !== undefined) {
        const delta = theta - this.lastAngle_;
        view.adjustRotationInternal(-delta);
      }
      this.lastAngle_ = theta;
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return true;
      }

      const map = mapBrowserEvent.map;
      const view = map.getView();
      view.endInteraction(this.duration_);
      return false;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return false;
      }

      if (
        mouseActionButton(mapBrowserEvent) &&
        this.condition_(mapBrowserEvent)
      ) {
        const map = mapBrowserEvent.map;
        map.getView().beginInteraction();
        this.lastAngle_ = undefined;
        return true;
      }
      return false;
    }
  }

  /**
   * @module ol/render/Box
   */


  class RenderBox extends Disposable {
    /**
     * @param {string} className CSS class name.
     */
    constructor(className) {
      super();

      /**
       * @type {import("../geom/Polygon.js").default}
       * @private
       */
      this.geometry_ = null;

      /**
       * @type {HTMLDivElement}
       * @private
       */
      this.element_ = document.createElement('div');
      this.element_.style.position = 'absolute';
      this.element_.style.pointerEvents = 'auto';
      this.element_.className = 'ol-box ' + className;

      /**
       * @private
       * @type {import("../Map.js").default|null}
       */
      this.map_ = null;

      /**
       * @private
       * @type {import("../pixel.js").Pixel}
       */
      this.startPixel_ = null;

      /**
       * @private
       * @type {import("../pixel.js").Pixel}
       */
      this.endPixel_ = null;
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.setMap(null);
    }

    /**
     * @private
     */
    render_() {
      const startPixel = this.startPixel_;
      const endPixel = this.endPixel_;
      const px = 'px';
      const style = this.element_.style;
      style.left = Math.min(startPixel[0], endPixel[0]) + px;
      style.top = Math.min(startPixel[1], endPixel[1]) + px;
      style.width = Math.abs(endPixel[0] - startPixel[0]) + px;
      style.height = Math.abs(endPixel[1] - startPixel[1]) + px;
    }

    /**
     * @param {import("../Map.js").default|null} map Map.
     */
    setMap(map) {
      if (this.map_) {
        this.map_.getOverlayContainer().removeChild(this.element_);
        const style = this.element_.style;
        style.left = 'inherit';
        style.top = 'inherit';
        style.width = 'inherit';
        style.height = 'inherit';
      }
      this.map_ = map;
      if (this.map_) {
        this.map_.getOverlayContainer().appendChild(this.element_);
      }
    }

    /**
     * @param {import("../pixel.js").Pixel} startPixel Start pixel.
     * @param {import("../pixel.js").Pixel} endPixel End pixel.
     */
    setPixels(startPixel, endPixel) {
      this.startPixel_ = startPixel;
      this.endPixel_ = endPixel;
      this.createOrUpdateGeometry();
      this.render_();
    }

    /**
     * Creates or updates the cached geometry.
     */
    createOrUpdateGeometry() {
      if (!this.map_) {
        return;
      }

      const startPixel = this.startPixel_;
      const endPixel = this.endPixel_;
      const pixels = [
        startPixel,
        [startPixel[0], endPixel[1]],
        endPixel,
        [endPixel[0], startPixel[1]],
      ];
      const coordinates = pixels.map(
        this.map_.getCoordinateFromPixelInternal,
        this.map_,
      );
      // close the polygon
      coordinates[4] = coordinates[0].slice();
      if (!this.geometry_) {
        this.geometry_ = new Polygon([coordinates]);
      } else {
        this.geometry_.setCoordinates([coordinates]);
      }
    }

    /**
     * @return {import("../geom/Polygon.js").default} Geometry.
     */
    getGeometry() {
      return this.geometry_;
    }
  }

  /**
   * @module ol/interaction/DragBox
   */
  // FIXME draw drag box

  /**
   * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two
   * {@link module:ol/pixel~Pixel}s and returns a `{boolean}`. If the condition is met,
   * true should be returned.
   * @typedef {function(this: ?, import("../MapBrowserEvent.js").default, import("../pixel.js").Pixel, import("../pixel.js").Pixel):boolean} EndCondition
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-dragbox'] CSS class name for styling the box.
   * @property {import("../events/condition.js").Condition} [condition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean
   * to indicate whether that event should be handled.
   * Default is {@link ol/events/condition~mouseActionButton}.
   * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the default
   * `boxEndCondition` function.
   * @property {EndCondition} [boxEndCondition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two
   * {@link module:ol/pixel~Pixel}s to indicate whether a `boxend` event should be fired.
   * Default is `true` if the area of the box is bigger than the `minArea` option.
   * @property {function(this:DragBox, import("../MapBrowserEvent.js").default):void} [onBoxEnd] Code to execute just
   * before `boxend` is fired.
   */

  /**
   * @enum {string}
   */
  const DragBoxEventType = {
    /**
     * Triggered upon drag box start.
     * @event DragBoxEvent#boxstart
     * @api
     */
    BOXSTART: 'boxstart',

    /**
     * Triggered on drag when box is active.
     * @event DragBoxEvent#boxdrag
     * @api
     */
    BOXDRAG: 'boxdrag',

    /**
     * Triggered upon drag box end.
     * @event DragBoxEvent#boxend
     * @api
     */
    BOXEND: 'boxend',

    /**
     * Triggered upon drag box canceled.
     * @event DragBoxEvent#boxcancel
     * @api
     */
    BOXCANCEL: 'boxcancel',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/DragBox~DragBox} instances are instances of
   * this type.
   */
  class DragBoxEvent extends BaseEvent {
    /**
     * @param {string} type The event type.
     * @param {import("../coordinate.js").Coordinate} coordinate The event coordinate.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Originating event.
     */
    constructor(type, coordinate, mapBrowserEvent) {
      super(type);

      /**
       * The coordinate of the drag event.
       * @const
       * @type {import("../coordinate.js").Coordinate}
       * @api
       */
      this.coordinate = coordinate;

      /**
       * @const
       * @type {import("../MapBrowserEvent.js").default}
       * @api
       */
      this.mapBrowserEvent = mapBrowserEvent;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'boxcancel'|'boxdrag'|'boxend'|'boxstart', DragBoxEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'boxcancel'|'boxdrag'|'boxend', Return>} DragBoxOnSignature
   */

  /**
   * @classdesc
   * Allows the user to draw a vector box by clicking and dragging on the map,
   * normally combined with a {@link module:ol/events/condition} that limits
   * it to when the shift or other key is held down. This is used, for example,
   * for zooming to a specific area of the map
   * (see {@link module:ol/interaction/DragZoom~DragZoom} and
   * {@link module:ol/interaction/DragRotateAndZoom~DragRotateAndZoom}).
   *
   * @fires DragBoxEvent
   * @api
   */
  class DragBox extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      /***
       * @type {DragBoxOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {DragBoxOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {DragBoxOnSignature<void>}
       */
      this.un;

      options = options ?? {};

      /**
       * @type {import("../render/Box.js").default}
       * @private
       */
      this.box_ = new RenderBox(options.className || 'ol-dragbox');

      /**
       * @type {number}
       * @private
       */
      this.minArea_ = options.minArea ?? 64;

      if (options.onBoxEnd) {
        this.onBoxEnd = options.onBoxEnd;
      }

      /**
       * @type {import("../pixel.js").Pixel}
       * @private
       */
      this.startPixel_ = null;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ?? mouseActionButton;

      /**
       * @private
       * @type {EndCondition}
       */
      this.boxEndCondition_ =
        options.boxEndCondition ?? this.defaultBoxEndCondition;
    }

    /**
     * The default condition for determining whether the boxend event
     * should fire.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent The originating MapBrowserEvent
     *     leading to the box end.
     * @param {import("../pixel.js").Pixel} startPixel The starting pixel of the box.
     * @param {import("../pixel.js").Pixel} endPixel The end pixel of the box.
     * @return {boolean} Whether or not the boxend condition should be fired.
     */
    defaultBoxEndCondition(mapBrowserEvent, startPixel, endPixel) {
      const width = endPixel[0] - startPixel[0];
      const height = endPixel[1] - startPixel[1];
      return width * width + height * height >= this.minArea_;
    }

    /**
     * Returns geometry of last drawn box.
     * @return {import("../geom/Polygon.js").default} Geometry.
     * @api
     */
    getGeometry() {
      return this.box_.getGeometry();
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      if (!this.startPixel_) {
        return;
      }

      this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);

      this.dispatchEvent(
        new DragBoxEvent(
          DragBoxEventType.BOXDRAG,
          mapBrowserEvent.coordinate,
          mapBrowserEvent,
        ),
      );
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      if (!this.startPixel_) {
        return false;
      }

      const completeBox = this.boxEndCondition_(
        mapBrowserEvent,
        this.startPixel_,
        mapBrowserEvent.pixel,
      );
      if (completeBox) {
        this.onBoxEnd(mapBrowserEvent);
      }
      this.dispatchEvent(
        new DragBoxEvent(
          completeBox ? DragBoxEventType.BOXEND : DragBoxEventType.BOXCANCEL,
          mapBrowserEvent.coordinate,
          mapBrowserEvent,
        ),
      );

      this.box_.setMap(null);
      this.startPixel_ = null;

      return false;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (this.condition_(mapBrowserEvent)) {
        this.startPixel_ = mapBrowserEvent.pixel;
        this.box_.setMap(mapBrowserEvent.map);
        this.box_.setPixels(this.startPixel_, this.startPixel_);
        this.dispatchEvent(
          new DragBoxEvent(
            DragBoxEventType.BOXSTART,
            mapBrowserEvent.coordinate,
            mapBrowserEvent,
          ),
        );
        return true;
      }
      return false;
    }

    /**
     * Function to execute just before `onboxend` is fired
     * @param {import("../MapBrowserEvent.js").default} event Event.
     */
    onBoxEnd(event) {}

    /**
     * Activate or deactivate the interaction.
     * @param {boolean} active Active.
     * @observable
     * @api
     * @override
     */
    setActive(active) {
      if (!active) {
        this.box_.setMap(null);
        if (this.startPixel_) {
          this.dispatchEvent(
            new DragBoxEvent(DragBoxEventType.BOXCANCEL, this.startPixel_, null),
          );
          this.startPixel_ = null;
        }
      }

      super.setActive(active);
    }

    /**
     * @param {import("../Map.js").default|null} map Map.
     * @override
     */
    setMap(map) {
      const oldMap = this.getMap();

      if (oldMap) {
        this.box_.setMap(null);

        if (this.startPixel_) {
          this.dispatchEvent(
            new DragBoxEvent(DragBoxEventType.BOXCANCEL, this.startPixel_, null),
          );
          this.startPixel_ = null;
        }
      }

      super.setMap(map);
    }
  }

  /**
   * @module ol/interaction/DragZoom
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-dragzoom'] CSS class name for styling the
   * box.
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.shiftKeyOnly}.
   * @property {number} [duration=200] Animation duration in milliseconds.
   * @property {boolean} [out=false] Use interaction for zooming out.
   * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the parent default
   * `boxEndCondition` function.
   */

  /**
   * @classdesc
   * Allows the user to zoom the map by clicking and dragging on the map,
   * normally combined with a {@link module:ol/events/condition} that limits
   * it to when a key, shift by default, is held down.
   *
   * To change the style of the box, use CSS and the `.ol-dragzoom` selector, or
   * your custom one configured with `className`.
   * @api
   */
  class DragZoom extends DragBox {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const condition = options.condition ? options.condition : shiftKeyOnly;

      super({
        condition: condition,
        className: options.className || 'ol-dragzoom',
        minArea: options.minArea,
      });

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 200;

      /**
       * @private
       * @type {boolean}
       */
      this.out_ = options.out !== undefined ? options.out : false;
    }

    /**
     * Function to execute just before `onboxend` is fired
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @override
     */
    onBoxEnd(event) {
      const map = this.getMap();
      const view = /** @type {!import("../View.js").default} */ (map.getView());
      let geometry = this.getGeometry();

      if (this.out_) {
        const rotatedExtent = view.rotatedExtentForGeometry(geometry);
        const resolution = view.getResolutionForExtentInternal(rotatedExtent);
        const factor = view.getResolution() / resolution;
        geometry = geometry.clone();
        geometry.scale(factor * factor);
      }

      view.fitInternal(geometry, {
        duration: this.duration_,
        easing: easeOut,
      });
    }
  }

  /**
   * @module ol/events/Key
   */

  /**
   * @enum {string}
   * @const
   */
  var Key = {
    LEFT: 'ArrowLeft',
    UP: 'ArrowUp',
    RIGHT: 'ArrowRight',
    DOWN: 'ArrowDown',
  };

  /**
   * @module ol/interaction/KeyboardPan
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. Default is
   * {@link module:ol/events/condition.noModifierKeys} and
   * {@link module:ol/events/condition.targetNotEditable}.
   * @property {number} [duration=100] Animation duration in milliseconds.
   * @property {number} [pixelDelta=128] The amount of pixels to pan on each key
   * press.
   */

  /**
   * @classdesc
   * Allows the user to pan the map using keyboard arrows.
   * Note that, although this interaction is by default included in maps,
   * the keys can only be used when browser focus is on the element to which
   * the keyboard events are attached. By default, this is the map div,
   * though you can change this with the `keyboardEventTarget` in
   * {@link module:ol/Map~Map}. `document` never loses focus but, for any other
   * element, focus will have to be on, and returned to, this element if the keys
   * are to function.
   * See also {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}.
   * @api
   */
  class KeyboardPan extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options || {};

      /**
       * @private
       * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Browser event.
       * @return {boolean} Combined condition result.
       */
      this.defaultCondition_ = function (mapBrowserEvent) {
        return (
          noModifierKeys(mapBrowserEvent) && targetNotEditable(mapBrowserEvent)
        );
      };

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ =
        options.condition !== undefined
          ? options.condition
          : this.defaultCondition_;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 100;

      /**
       * @private
       * @type {number}
       */
      this.pixelDelta_ =
        options.pixelDelta !== undefined ? options.pixelDelta : 128;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a
     * `KeyEvent`, and decides the direction to pan to (if an arrow key was
     * pressed).
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      let stopEvent = false;
      if (mapBrowserEvent.type == EventType.KEYDOWN) {
        const keyEvent = /** @type {KeyboardEvent} */ (
          mapBrowserEvent.originalEvent
        );
        const key = keyEvent.key;
        if (
          this.condition_(mapBrowserEvent) &&
          (key == Key.DOWN ||
            key == Key.LEFT ||
            key == Key.RIGHT ||
            key == Key.UP)
        ) {
          const map = mapBrowserEvent.map;
          const view = map.getView();
          const mapUnitsDelta = view.getResolution() * this.pixelDelta_;
          let deltaX = 0,
            deltaY = 0;
          if (key == Key.DOWN) {
            deltaY = -mapUnitsDelta;
          } else if (key == Key.LEFT) {
            deltaX = -mapUnitsDelta;
          } else if (key == Key.RIGHT) {
            deltaX = mapUnitsDelta;
          } else {
            deltaY = mapUnitsDelta;
          }
          const delta = [deltaX, deltaY];
          rotate$2(delta, view.getRotation());
          pan(view, delta, this.duration_);
          keyEvent.preventDefault();
          stopEvent = true;
        }
      }
      return !stopEvent;
    }
  }

  /**
   * @module ol/interaction/KeyboardZoom
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=100] Animation duration in milliseconds.
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. The default condition is
   * that {@link module:ol/events/condition.targetNotEditable} is fulfilled and that
   * the platform modifier key isn't pressed
   * (!{@link module:ol/events/condition.platformModifierKey}).
   * @property {number} [delta=1] The zoom level delta on each key press.
   */

  /**
   * @classdesc
   * Allows the user to zoom the map using keyboard + and -.
   * Note that, although this interaction is by default included in maps,
   * the keys can only be used when browser focus is on the element to which
   * the keyboard events are attached. By default, this is the map div,
   * though you can change this with the `keyboardEventTarget` in
   * {@link module:ol/Map~Map}. `document` never loses focus but, for any other
   * element, focus will have to be on, and returned to, this element if the keys
   * are to function.
   * See also {@link module:ol/interaction/KeyboardPan~KeyboardPan}.
   * @api
   */
  class KeyboardZoom extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition
        ? options.condition
        : function (mapBrowserEvent) {
            return (
              !platformModifierKey(mapBrowserEvent) &&
              targetNotEditable(mapBrowserEvent)
            );
          };

      /**
       * @private
       * @type {number}
       */
      this.delta_ = options.delta ? options.delta : 1;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 100;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a
     * `KeyEvent`, and decides whether to zoom in or out (depending on whether the
     * key pressed was '+' or '-').
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      let stopEvent = false;
      if (
        mapBrowserEvent.type == EventType.KEYDOWN ||
        mapBrowserEvent.type == EventType.KEYPRESS
      ) {
        const keyEvent = /** @type {KeyboardEvent} */ (
          mapBrowserEvent.originalEvent
        );
        const key = keyEvent.key;
        if (this.condition_(mapBrowserEvent) && (key === '+' || key === '-')) {
          const map = mapBrowserEvent.map;
          const delta = key === '+' ? this.delta_ : -this.delta_;
          const view = map.getView();
          zoomByDelta(view, delta, undefined, this.duration_);
          keyEvent.preventDefault();
          stopEvent = true;
        }
      }
      return !stopEvent;
    }
  }

  /**
   * @module ol/interaction/MouseWheelZoom
   */

  /**
   * @typedef {'trackpad' | 'wheel'} Mode
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. Default is
   * {@link module:ol/events/condition.always}.
   * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,
   * the interaction will only handle events when the map has the focus.
   * @property {number} [maxDelta=1] Maximum mouse wheel delta.
   * @property {number} [duration=250] Animation duration in milliseconds.
   * @property {number} [timeout=80] Mouse wheel timeout duration in milliseconds.
   * @property {boolean} [useAnchor=true] Enable zooming using the mouse's
   * location as the anchor. When set to `false`, zooming in and out will zoom to
   * the center of the screen instead of zooming on the mouse's location.
   * @property {boolean} [constrainResolution=false] If true, the mouse wheel zoom
   * event will always animate to the closest zoom level after an interaction;
   * false means intermediary zoom levels are allowed.
   */

  /**
   * Mutliplier for the DOM_DELTA_LINE delta value.
   * @type {number}
   */
  const DELTA_LINE_MULTIPLIER = 40;

  /**
   * Mutliplier for the DOM_DELTA_PAGE delta value.
   * @type {number}
   */
  const DELTA_PAGE_MULTIPLIER = 300;

  /**
   * @classdesc
   * Allows the user to zoom the map by scrolling the mouse wheel.
   * @api
   */
  class MouseWheelZoom extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super(
        /** @type {import("./Interaction.js").InteractionOptions} */ (options),
      );

      /**
       * @private
       * @type {number}
       */
      this.totalDelta_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.lastDelta_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.maxDelta_ = options.maxDelta !== undefined ? options.maxDelta : 1;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;

      /**
       * @private
       * @type {number}
       */
      this.timeout_ = options.timeout !== undefined ? options.timeout : 80;

      /**
       * @private
       * @type {boolean}
       */
      this.useAnchor_ =
        options.useAnchor !== undefined ? options.useAnchor : true;

      /**
       * @private
       * @type {boolean}
       */
      this.constrainResolution_ =
        options.constrainResolution !== undefined
          ? options.constrainResolution
          : false;

      const condition = options.condition ? options.condition : always;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.onFocusOnly
        ? all(focusWithTabindex, condition)
        : condition;

      /**
       * @private
       * @type {?import("../pixel.js").Pixel}
       */
      this.lastAnchor_ = null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.startTime_ = undefined;

      /**
       * @private
       * @type {ReturnType<typeof setTimeout>}
       */
      this.timeoutId_;

      /**
       * @private
       * @type {Mode|undefined}
       */
      this.mode_ = undefined;

      /**
       * Trackpad events separated by this delay will be considered separate
       * interactions.
       * @private
       * @type {number}
       */
      this.trackpadEventGap_ = 400;

      /**
       * @private
       * @type {ReturnType<typeof setTimeout>}
       */
      this.trackpadTimeoutId_;

      /**
       * The number of delta values per zoom level
       * @private
       * @type {number}
       */
      this.deltaPerZoom_ = 300;
    }

    /**
     * @private
     */
    endInteraction_() {
      this.trackpadTimeoutId_ = undefined;
      const map = this.getMap();
      if (!map) {
        return;
      }
      const view = map.getView();
      view.endInteraction(
        undefined,
        this.lastDelta_ ? (this.lastDelta_ > 0 ? 1 : -1) : 0,
        this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,
      );
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a mousewheel-event) and eventually
     * zooms the map.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!this.condition_(mapBrowserEvent)) {
        return true;
      }
      const type = mapBrowserEvent.type;
      if (type !== EventType.WHEEL) {
        return true;
      }

      const map = mapBrowserEvent.map;
      const wheelEvent = /** @type {WheelEvent} */ (
        mapBrowserEvent.originalEvent
      );
      wheelEvent.preventDefault();

      if (this.useAnchor_) {
        this.lastAnchor_ = mapBrowserEvent.pixel;
      }

      // Delta normalisation inspired by
      // https://github.com/mapbox/mapbox-gl-js/blob/001c7b9/js/ui/handler/scroll_zoom.js
      let delta = wheelEvent.deltaY;

      switch (wheelEvent.deltaMode) {
        case WheelEvent.DOM_DELTA_LINE:
          delta *= DELTA_LINE_MULTIPLIER;
          break;
        case WheelEvent.DOM_DELTA_PAGE:
          delta *= DELTA_PAGE_MULTIPLIER;
          break;
        // pass
      }

      if (delta === 0) {
        return false;
      }
      this.lastDelta_ = delta;

      const now = Date.now();

      if (this.startTime_ === undefined) {
        this.startTime_ = now;
      }

      if (!this.mode_ || now - this.startTime_ > this.trackpadEventGap_) {
        this.mode_ = Math.abs(delta) < 4 ? 'trackpad' : 'wheel';
      }

      const view = map.getView();
      if (
        this.mode_ === 'trackpad' &&
        !(view.getConstrainResolution() || this.constrainResolution_)
      ) {
        if (this.trackpadTimeoutId_) {
          clearTimeout(this.trackpadTimeoutId_);
        } else {
          if (view.getAnimating()) {
            view.cancelAnimations();
          }
          view.beginInteraction();
        }
        this.trackpadTimeoutId_ = setTimeout(
          this.endInteraction_.bind(this),
          this.timeout_,
        );
        view.adjustZoom(
          -delta / this.deltaPerZoom_,
          this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,
        );
        this.startTime_ = now;
        return false;
      }

      this.totalDelta_ += delta;

      const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0);

      clearTimeout(this.timeoutId_);
      this.timeoutId_ = setTimeout(
        this.handleWheelZoom_.bind(this, map),
        timeLeft,
      );

      return false;
    }

    /**
     * @private
     * @param {import("../Map.js").default} map Map.
     */
    handleWheelZoom_(map) {
      const view = map.getView();
      if (view.getAnimating()) {
        view.cancelAnimations();
      }
      let delta =
        -clamp$1(
          this.totalDelta_,
          -this.maxDelta_ * this.deltaPerZoom_,
          this.maxDelta_ * this.deltaPerZoom_,
        ) / this.deltaPerZoom_;
      if (view.getConstrainResolution() || this.constrainResolution_) {
        // view has a zoom constraint, zoom by 1
        delta = delta ? (delta > 0 ? 1 : -1) : 0;
      }
      zoomByDelta(
        view,
        delta,
        this.lastAnchor_ ? map.getCoordinateFromPixel(this.lastAnchor_) : null,
        this.duration_,
      );

      this.mode_ = undefined;
      this.totalDelta_ = 0;
      this.lastAnchor_ = null;
      this.startTime_ = undefined;
      this.timeoutId_ = undefined;
    }

    /**
     * Enable or disable using the mouse's location as an anchor when zooming
     * @param {boolean} useAnchor true to zoom to the mouse's location, false
     * to zoom to the center of the map
     * @api
     */
    setMouseAnchor(useAnchor) {
      this.useAnchor_ = useAnchor;
      if (!useAnchor) {
        this.lastAnchor_ = null;
      }
    }
  }

  /**
   * @module ol/interaction/PinchRotate
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=250] The duration of the animation in
   * milliseconds.
   * @property {number} [threshold=0.3] Minimal angle in radians to start a rotation.
   */

  /**
   * @classdesc
   * Allows the user to rotate the map by twisting with two fingers
   * on a touch screen.
   * @api
   */
  class PinchRotate extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const pointerOptions = /** @type {import("./Pointer.js").Options} */ (
        options
      );

      if (!pointerOptions.stopDown) {
        pointerOptions.stopDown = FALSE;
      }

      super(pointerOptions);

      /**
       * @private
       * @type {import("../coordinate.js").Coordinate}
       */
      this.anchor_ = null;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lastAngle_ = undefined;

      /**
       * @private
       * @type {boolean}
       */
      this.rotating_ = false;

      /**
       * @private
       * @type {number}
       */
      this.rotationDelta_ = 0.0;

      /**
       * @private
       * @type {number}
       */
      this.threshold_ = options.threshold !== undefined ? options.threshold : 0.3;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      let rotationDelta = 0.0;

      const touch0 = this.targetPointers[0];
      const touch1 = this.targetPointers[1];

      // angle between touches
      const angle = Math.atan2(
        touch1.clientY - touch0.clientY,
        touch1.clientX - touch0.clientX,
      );

      if (this.lastAngle_ !== undefined) {
        const delta = angle - this.lastAngle_;
        this.rotationDelta_ += delta;
        if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) {
          this.rotating_ = true;
        }
        rotationDelta = delta;
      }
      this.lastAngle_ = angle;

      const map = mapBrowserEvent.map;
      const view = map.getView();
      if (view.getConstraints().rotation === disable) {
        return;
      }

      // rotate anchor point.
      // FIXME: should be the intersection point between the lines:
      //     touch0,touch1 and previousTouch0,previousTouch1
      this.anchor_ = map.getCoordinateFromPixelInternal(
        map.getEventPixel(centroid(this.targetPointers)),
      );

      // rotate
      if (this.rotating_) {
        map.render();
        view.adjustRotationInternal(rotationDelta, this.anchor_);
      }
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      if (this.targetPointers.length < 2) {
        const map = mapBrowserEvent.map;
        const view = map.getView();
        view.endInteraction(this.duration_);
        return false;
      }
      return true;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (this.targetPointers.length >= 2) {
        const map = mapBrowserEvent.map;
        this.anchor_ = null;
        this.lastAngle_ = undefined;
        this.rotating_ = false;
        this.rotationDelta_ = 0.0;
        if (!this.handlingDownUpSequence) {
          map.getView().beginInteraction();
        }
        return true;
      }
      return false;
    }
  }

  /**
   * @module ol/interaction/PinchZoom
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=400] Animation duration in milliseconds.
   */

  /**
   * @classdesc
   * Allows the user to zoom the map by pinching with two fingers
   * on a touch screen.
   * @api
   */
  class PinchZoom extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const pointerOptions = /** @type {import("./Pointer.js").Options} */ (
        options
      );

      if (!pointerOptions.stopDown) {
        pointerOptions.stopDown = FALSE;
      }

      super(pointerOptions);

      /**
       * @private
       * @type {import("../coordinate.js").Coordinate}
       */
      this.anchor_ = null;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 400;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lastDistance_ = undefined;

      /**
       * @private
       * @type {number}
       */
      this.lastScaleDelta_ = 1;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      let scaleDelta = 1.0;

      const touch0 = this.targetPointers[0];
      const touch1 = this.targetPointers[1];
      const dx = touch0.clientX - touch1.clientX;
      const dy = touch0.clientY - touch1.clientY;

      // distance between touches
      const distance = Math.sqrt(dx * dx + dy * dy);

      if (this.lastDistance_ !== undefined) {
        scaleDelta = this.lastDistance_ / distance;
      }
      this.lastDistance_ = distance;

      const map = mapBrowserEvent.map;
      const view = map.getView();

      if (scaleDelta != 1.0) {
        this.lastScaleDelta_ = scaleDelta;
      }

      // scale anchor point.
      this.anchor_ = map.getCoordinateFromPixelInternal(
        map.getEventPixel(centroid(this.targetPointers)),
      );

      // scale, bypass the resolution constraint
      map.render();
      view.adjustResolutionInternal(scaleDelta, this.anchor_);
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      if (this.targetPointers.length < 2) {
        const map = mapBrowserEvent.map;
        const view = map.getView();
        const direction = this.lastScaleDelta_ > 1 ? 1 : -1;
        view.endInteraction(this.duration_, direction);
        return false;
      }
      return true;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (this.targetPointers.length >= 2) {
        const map = mapBrowserEvent.map;
        this.anchor_ = null;
        this.lastDistance_ = undefined;
        this.lastScaleDelta_ = 1;
        if (!this.handlingDownUpSequence) {
          map.getView().beginInteraction();
        }
        return true;
      }
      return false;
    }
  }

  /**
   * @module ol/interaction/defaults
   */

  /**
   * @typedef {Object} DefaultsOptions
   * @property {boolean} [altShiftDragRotate=true] Whether Alt-Shift-drag rotate is
   * desired.
   * @property {boolean} [onFocusOnly=false] Interact only when the map has the
   * focus. This affects the `MouseWheelZoom` and `DragPan` interactions and is
   * useful when page scroll is desired for maps that do not have the browser's
   * focus.
   * @property {boolean} [doubleClickZoom=true] Whether double click zoom is
   * desired.
   * @property {boolean} [keyboard=true] Whether keyboard interaction is desired.
   * @property {boolean} [mouseWheelZoom=true] Whether mousewheel zoom is desired.
   * @property {boolean} [shiftDragZoom=true] Whether Shift-drag zoom is desired.
   * @property {boolean} [dragPan=true] Whether drag pan is desired.
   * @property {boolean} [pinchRotate=true] Whether pinch rotate is desired.
   * @property {boolean} [pinchZoom=true] Whether pinch zoom is desired.
   * @property {number} [zoomDelta] Zoom level delta when using keyboard or double click zoom.
   * @property {number} [zoomDuration] Duration of the zoom animation in
   * milliseconds.
   */

  /**
   * Set of interactions included in maps by default. Specific interactions can be
   * excluded by setting the appropriate option to false in the constructor
   * options, but the order of the interactions is fixed.  If you want to specify
   * a different order for interactions, you will need to create your own
   * {@link module:ol/interaction/Interaction~Interaction} instances and insert
   * them into a {@link module:ol/Collection~Collection} in the order you want
   * before creating your {@link module:ol/Map~Map} instance. Changing the order can
   * be of interest if the event propagation needs to be stopped at a point.
   * The default set of interactions, in sequence, is:
   * {@link module:ol/interaction/DragRotate~DragRotate}
   * {@link module:ol/interaction/DoubleClickZoom~DoubleClickZoom}
   * {@link module:ol/interaction/DragPan~DragPan}
   * {@link module:ol/interaction/PinchRotate~PinchRotate}
   * {@link module:ol/interaction/PinchZoom~PinchZoom}
   * {@link module:ol/interaction/KeyboardPan~KeyboardPan}
   * {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}
   * {@link module:ol/interaction/MouseWheelZoom~MouseWheelZoom}
   * {@link module:ol/interaction/DragZoom~DragZoom}
   *
   * @param {DefaultsOptions} [options] Defaults options.
   * @return {Collection<import("./Interaction.js").default>}
   * A collection of interactions to be used with the {@link module:ol/Map~Map}
   * constructor's `interactions` option.
   * @api
   */
  function defaults(options) {
    options = options ? options : {};

    /** @type {Collection<import("./Interaction.js").default>} */
    const interactions = new Collection();

    const kinetic = new Kinetic(-5e-3, 0.05, 100);

    const altShiftDragRotate =
      options.altShiftDragRotate !== undefined
        ? options.altShiftDragRotate
        : true;
    if (altShiftDragRotate) {
      interactions.push(new DragRotate());
    }

    const doubleClickZoom =
      options.doubleClickZoom !== undefined ? options.doubleClickZoom : true;
    if (doubleClickZoom) {
      interactions.push(
        new DoubleClickZoom({
          delta: options.zoomDelta,
          duration: options.zoomDuration,
        }),
      );
    }

    const dragPan = options.dragPan !== undefined ? options.dragPan : true;
    if (dragPan) {
      interactions.push(
        new DragPan({
          onFocusOnly: options.onFocusOnly,
          kinetic: kinetic,
        }),
      );
    }

    const pinchRotate =
      options.pinchRotate !== undefined ? options.pinchRotate : true;
    if (pinchRotate) {
      interactions.push(new PinchRotate());
    }

    const pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true;
    if (pinchZoom) {
      interactions.push(
        new PinchZoom({
          duration: options.zoomDuration,
        }),
      );
    }

    const keyboard = options.keyboard !== undefined ? options.keyboard : true;
    if (keyboard) {
      interactions.push(new KeyboardPan());
      interactions.push(
        new KeyboardZoom({
          delta: options.zoomDelta,
          duration: options.zoomDuration,
        }),
      );
    }

    const mouseWheelZoom =
      options.mouseWheelZoom !== undefined ? options.mouseWheelZoom : true;
    if (mouseWheelZoom) {
      interactions.push(
        new MouseWheelZoom({
          onFocusOnly: options.onFocusOnly,
          duration: options.zoomDuration,
        }),
      );
    }

    const shiftDragZoom =
      options.shiftDragZoom !== undefined ? options.shiftDragZoom : true;
    if (shiftDragZoom) {
      interactions.push(
        new DragZoom({
          duration: options.zoomDuration,
        }),
      );
    }

    return interactions;
  }

  /**
   * @module ol/layer/Group
   */

  /**
   * @typedef {'addlayer'|'removelayer'} GroupEventType
   */

  /**
   * @classdesc
   * A layer group triggers 'addlayer' and 'removelayer' events when layers are added to or removed from
   * the group or one of its child groups.  When a layer group is added to or removed from another layer group,
   * a single event will be triggered (instead of one per layer in the group added or removed).
   */
  class GroupEvent extends BaseEvent {
    /**
     * @param {GroupEventType} type The event type.
     * @param {BaseLayer} layer The layer.
     */
    constructor(type, layer) {
      super(type);

      /**
       * The added or removed layer.
       * @type {BaseLayer}
       * @api
       */
      this.layer = layer;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("./Base").BaseLayerObjectEventTypes|
   *     'change:layers', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("./Base").BaseLayerObjectEventTypes|'change:layers', Return>} GroupOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {Array<import("./Base.js").default>|Collection<import("./Base.js").default>} [layers] Child layers.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @enum {string}
   * @private
   */
  const Property$2 = {
    LAYERS: 'layers',
  };

  /**
   * @classdesc
   * A {@link module:ol/Collection~Collection} of layers that are handled together.
   *
   * A generic `change` event is triggered when the group/Collection changes.
   *
   * @api
   */
  class LayerGroup extends BaseLayer {
    /**
     * @param {Options} [options] Layer options.
     */
    constructor(options) {
      options = options || {};
      const baseOptions = /** @type {Options} */ (Object.assign({}, options));
      delete baseOptions.layers;

      let layers = options.layers;

      super(baseOptions);

      /***
       * @type {GroupOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {GroupOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {GroupOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {Array<import("../events.js").EventsKey>}
       */
      this.layersListenerKeys_ = [];

      /**
       * @private
       * @type {Object<string, Array<import("../events.js").EventsKey>>}
       */
      this.listenerKeys_ = {};

      this.addChangeListener(Property$2.LAYERS, this.handleLayersChanged_);

      if (layers) {
        if (Array.isArray(layers)) {
          layers = new Collection(layers.slice(), {unique: true});
        } else {
          assert(
            typeof (/** @type {?} */ (layers).getArray) === 'function',
            'Expected `layers` to be an array or a `Collection`',
          );
        }
      } else {
        layers = new Collection(undefined, {unique: true});
      }

      this.setLayers(layers);
    }

    /**
     * @private
     */
    handleLayerChange_() {
      this.changed();
    }

    /**
     * @private
     */
    handleLayersChanged_() {
      this.layersListenerKeys_.forEach(unlistenByKey);
      this.layersListenerKeys_.length = 0;

      const layers = this.getLayers();
      this.layersListenerKeys_.push(
        listen(layers, CollectionEventType.ADD, this.handleLayersAdd_, this),
        listen(
          layers,
          CollectionEventType.REMOVE,
          this.handleLayersRemove_,
          this,
        ),
      );

      for (const id in this.listenerKeys_) {
        this.listenerKeys_[id].forEach(unlistenByKey);
      }
      clear$2(this.listenerKeys_);

      const layersArray = layers.getArray();
      for (let i = 0, ii = layersArray.length; i < ii; i++) {
        const layer = layersArray[i];
        this.registerLayerListeners_(layer);
        this.dispatchEvent(new GroupEvent('addlayer', layer));
      }
      this.changed();
    }

    /**
     * @param {BaseLayer} layer The layer.
     */
    registerLayerListeners_(layer) {
      const listenerKeys = [
        listen(
          layer,
          ObjectEventType.PROPERTYCHANGE,
          this.handleLayerChange_,
          this,
        ),
        listen(layer, EventType.CHANGE, this.handleLayerChange_, this),
      ];

      if (layer instanceof LayerGroup) {
        listenerKeys.push(
          listen(layer, 'addlayer', this.handleLayerGroupAdd_, this),
          listen(layer, 'removelayer', this.handleLayerGroupRemove_, this),
        );
      }

      this.listenerKeys_[getUid(layer)] = listenerKeys;
    }

    /**
     * @param {GroupEvent} event The layer group event.
     */
    handleLayerGroupAdd_(event) {
      this.dispatchEvent(new GroupEvent('addlayer', event.layer));
    }

    /**
     * @param {GroupEvent} event The layer group event.
     */
    handleLayerGroupRemove_(event) {
      this.dispatchEvent(new GroupEvent('removelayer', event.layer));
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<import("./Base.js").default>} collectionEvent CollectionEvent.
     * @private
     */
    handleLayersAdd_(collectionEvent) {
      const layer = collectionEvent.element;
      this.registerLayerListeners_(layer);
      this.dispatchEvent(new GroupEvent('addlayer', layer));
      this.changed();
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<import("./Base.js").default>} collectionEvent CollectionEvent.
     * @private
     */
    handleLayersRemove_(collectionEvent) {
      const layer = collectionEvent.element;
      const key = getUid(layer);
      this.listenerKeys_[key].forEach(unlistenByKey);
      delete this.listenerKeys_[key];
      this.dispatchEvent(new GroupEvent('removelayer', layer));
      this.changed();
    }

    /**
     * Returns the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}
     * in this group.
     * @return {!Collection<import("./Base.js").default>} Collection of
     *   {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.
     * @observable
     * @api
     */
    getLayers() {
      return /** @type {!Collection<import("./Base.js").default>} */ (
        this.get(Property$2.LAYERS)
      );
    }

    /**
     * Set the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}
     * in this group.
     * @param {!Collection<import("./Base.js").default>} layers Collection of
     *   {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.
     * @observable
     * @api
     */
    setLayers(layers) {
      const collection = this.getLayers();
      if (collection) {
        const currentLayers = collection.getArray();
        for (let i = 0, ii = currentLayers.length; i < ii; ++i) {
          this.dispatchEvent(new GroupEvent('removelayer', currentLayers[i]));
        }
      }

      this.set(Property$2.LAYERS, layers);
    }

    /**
     * @param {Array<import("./Layer.js").default>} [array] Array of layers (to be modified in place).
     * @return {Array<import("./Layer.js").default>} Array of layers.
     * @override
     */
    getLayersArray(array) {
      array = array !== undefined ? array : [];
      this.getLayers().forEach(function (layer) {
        layer.getLayersArray(array);
      });
      return array;
    }

    /**
     * Get the layer states list and use this groups z-index as the default
     * for all layers in this and nested groups, if it is unset at this point.
     * If dest is not provided and this group's z-index is undefined
     * 0 is used a the default z-index.
     * @param {Array<import("./Layer.js").State>} [dest] Optional list
     * of layer states (to be modified in place).
     * @return {Array<import("./Layer.js").State>} List of layer states.
     * @override
     */
    getLayerStatesArray(dest) {
      const states = dest !== undefined ? dest : [];
      const pos = states.length;

      this.getLayers().forEach(function (layer) {
        layer.getLayerStatesArray(states);
      });

      const ownLayerState = this.getLayerState();
      let defaultZIndex = ownLayerState.zIndex;
      if (!dest && ownLayerState.zIndex === undefined) {
        defaultZIndex = 0;
      }
      for (let i = pos, ii = states.length; i < ii; i++) {
        const layerState = states[i];
        layerState.opacity *= ownLayerState.opacity;
        layerState.visible = layerState.visible && ownLayerState.visible;
        layerState.maxResolution = Math.min(
          layerState.maxResolution,
          ownLayerState.maxResolution,
        );
        layerState.minResolution = Math.max(
          layerState.minResolution,
          ownLayerState.minResolution,
        );
        layerState.minZoom = Math.max(layerState.minZoom, ownLayerState.minZoom);
        layerState.maxZoom = Math.min(layerState.maxZoom, ownLayerState.maxZoom);
        if (ownLayerState.extent !== undefined) {
          if (layerState.extent !== undefined) {
            layerState.extent = getIntersection(
              layerState.extent,
              ownLayerState.extent,
            );
          } else {
            layerState.extent = ownLayerState.extent;
          }
        }
        if (layerState.zIndex === undefined) {
          layerState.zIndex = defaultZIndex;
        }
      }

      return states;
    }

    /**
     * @return {import("../source/Source.js").State} Source state.
     * @override
     */
    getSourceState() {
      return 'ready';
    }
  }

  /**
   * @module ol/renderer/Map
   */

  /**
   * @template T
   * @typedef HitMatch
   * @property {import("../Feature.js").FeatureLike} feature Feature.
   * @property {import("../layer/Layer.js").default} layer Layer.
   * @property {import("../geom/SimpleGeometry.js").default} geometry Geometry.
   * @property {number} distanceSq Squared distance.
   * @property {import("./vector.js").FeatureCallback<T>} callback Callback.
   */

  /**
   * @abstract
   */
  class MapRenderer extends Disposable {
    /**
     * @param {import("../Map.js").default} map Map.
     */
    constructor(map) {
      super();

      /**
       * @private
       * @type {import("../Map.js").default}
       */
      this.map_ = map;
    }

    /**
     * @abstract
     * @param {import("../render/EventType.js").default} type Event type.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     */
    dispatchRenderEvent(type, frameState) {
      abstract();
    }

    /**
     * @param {import("../Map.js").FrameState} frameState FrameState.
     * @protected
     */
    calculateMatrices2D(frameState) {
      const viewState = frameState.viewState;
      const coordinateToPixelTransform = frameState.coordinateToPixelTransform;
      const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform;

      compose(
        coordinateToPixelTransform,
        frameState.size[0] / 2,
        frameState.size[1] / 2,
        1 / viewState.resolution,
        -1 / viewState.resolution,
        -viewState.rotation,
        -viewState.center[0],
        -viewState.center[1],
      );

      makeInverse(pixelToCoordinateTransform, coordinateToPixelTransform);
    }

    /**
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../Map.js").FrameState} frameState FrameState.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {boolean} checkWrapped Check for wrapped geometries.
     * @param {import("./vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {S} thisArg Value to use as `this` when executing `callback`.
     * @param {function(this: U, import("../layer/Layer.js").default): boolean} layerFilter Layer filter
     *     function, only layers which are visible and for which this function
     *     returns `true` will be tested for features.  By default, all visible
     *     layers will be tested.
     * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.
     * @return {T|undefined} Callback result.
     * @template S,T,U
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      checkWrapped,
      callback,
      thisArg,
      layerFilter,
      thisArg2,
    ) {
      let result;
      const viewState = frameState.viewState;

      /**
       * @param {boolean} managed Managed layer.
       * @param {import("../Feature.js").FeatureLike} feature Feature.
       * @param {import("../layer/Layer.js").default} layer Layer.
       * @param {import("../geom/Geometry.js").default} geometry Geometry.
       * @return {T|undefined} Callback result.
       */
      function forEachFeatureAtCoordinate(managed, feature, layer, geometry) {
        return callback.call(thisArg, feature, managed ? layer : null, geometry);
      }

      const projection = viewState.projection;

      const translatedCoordinate = wrapX$1(coordinate.slice(), projection);
      const offsets = [[0, 0]];
      if (projection.canWrapX() && checkWrapped) {
        const projectionExtent = projection.getExtent();
        const worldWidth = getWidth(projectionExtent);
        offsets.push([-worldWidth, 0], [worldWidth, 0]);
      }

      const layerStates = frameState.layerStatesArray;
      const numLayers = layerStates.length;

      const matches = /** @type {Array<HitMatch<T>>} */ ([]);
      const tmpCoord = [];
      for (let i = 0; i < offsets.length; i++) {
        for (let j = numLayers - 1; j >= 0; --j) {
          const layerState = layerStates[j];
          const layer = layerState.layer;
          if (
            layer.hasRenderer() &&
            inView(layerState, viewState) &&
            layerFilter.call(thisArg2, layer)
          ) {
            const layerRenderer = layer.getRenderer();
            const source = layer.getSource();
            if (layerRenderer && source) {
              const coordinates = source.getWrapX()
                ? translatedCoordinate
                : coordinate;
              const callback = forEachFeatureAtCoordinate.bind(
                null,
                layerState.managed,
              );
              tmpCoord[0] = coordinates[0] + offsets[i][0];
              tmpCoord[1] = coordinates[1] + offsets[i][1];
              result = layerRenderer.forEachFeatureAtCoordinate(
                tmpCoord,
                frameState,
                hitTolerance,
                callback,
                matches,
              );
            }
            if (result) {
              return result;
            }
          }
        }
      }
      if (matches.length === 0) {
        return undefined;
      }
      const order = 1 / matches.length;
      matches.forEach((m, i) => (m.distanceSq += i * order));
      matches.sort((a, b) => a.distanceSq - b.distanceSq);
      matches.some((m) => {
        return (result = m.callback(m.feature, m.layer, m.geometry));
      });
      return result;
    }

    /**
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../Map.js").FrameState} frameState FrameState.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {boolean} checkWrapped Check for wrapped geometries.
     * @param {function(this: U, import("../layer/Layer.js").default): boolean} layerFilter Layer filter
     *     function, only layers which are visible and for which this function
     *     returns `true` will be tested for features.  By default, all visible
     *     layers will be tested.
     * @param {U} thisArg Value to use as `this` when executing `layerFilter`.
     * @return {boolean} Is there a feature at the given coordinate?
     * @template U
     */
    hasFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      checkWrapped,
      layerFilter,
      thisArg,
    ) {
      const hasFeature = this.forEachFeatureAtCoordinate(
        coordinate,
        frameState,
        hitTolerance,
        checkWrapped,
        TRUE,
        this,
        layerFilter,
        thisArg,
      );

      return hasFeature !== undefined;
    }

    /**
     * @return {import("../Map.js").default} Map.
     */
    getMap() {
      return this.map_;
    }

    /**
     * Render.
     * @abstract
     * @param {?import("../Map.js").FrameState} frameState Frame state.
     */
    renderFrame(frameState) {
      abstract();
    }

    /**
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    scheduleExpireIconCache(frameState) {
      if (shared.canExpireCache()) {
        frameState.postRenderFunctions.push(expireIconCache);
      }
    }
  }

  /**
   * @param {import("../Map.js").default} map Map.
   * @param {import("../Map.js").FrameState} frameState Frame state.
   */
  function expireIconCache(map, frameState) {
    shared.expire();
  }

  /**
   * @module ol/renderer/Composite
   */

  /**
   * @classdesc
   * Canvas map renderer.
   * @api
   */
  class CompositeMapRenderer extends MapRenderer {
    /**
     * @param {import("../Map.js").default} map Map.
     */
    constructor(map) {
      super(map);

      /**
       * @private
       * @type {import("../events.js").EventsKey}
       */
      this.fontChangeListenerKey_ = listen(
        checkedFonts,
        ObjectEventType.PROPERTYCHANGE,
        map.redrawText,
        map,
      );

      /**
       * @private
       * @type {HTMLDivElement}
       */
      this.element_ = document.createElement('div');
      const style = this.element_.style;
      style.position = 'absolute';
      style.width = '100%';
      style.height = '100%';
      style.zIndex = '0';

      this.element_.className = CLASS_UNSELECTABLE + ' ol-layers';

      const container = map.getViewport();
      container.insertBefore(this.element_, container.firstChild || null);

      /**
       * @private
       * @type {Array<HTMLElement>}
       */
      this.children_ = [];

      /**
       * @private
       * @type {boolean}
       */
      this.renderedVisible_ = true;
    }

    /**
     * @param {import("../render/EventType.js").default} type Event type.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @override
     */
    dispatchRenderEvent(type, frameState) {
      const map = this.getMap();
      if (map.hasListener(type)) {
        const event = new RenderEvent(type, undefined, frameState);
        map.dispatchEvent(event);
      }
    }

    /**
     * @override
     */
    disposeInternal() {
      unlistenByKey(this.fontChangeListenerKey_);
      this.element_.remove();
      super.disposeInternal();
    }

    /**
     * Render.
     * @param {?import("../Map.js").FrameState} frameState Frame state.
     * @override
     */
    renderFrame(frameState) {
      if (!frameState) {
        if (this.renderedVisible_) {
          this.element_.style.display = 'none';
          this.renderedVisible_ = false;
        }
        return;
      }

      this.calculateMatrices2D(frameState);
      this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState);

      const layerStatesArray = frameState.layerStatesArray.sort(
        (a, b) => a.zIndex - b.zIndex,
      );
      const declutter = layerStatesArray.some(
        (layerState) =>
          layerState.layer instanceof BaseVectorLayer &&
          layerState.layer.getDeclutter(),
      );
      if (declutter) {
        // Some layers need decluttering, turn on deferred rendering hint
        frameState.declutter = {};
      }
      const viewState = frameState.viewState;

      this.children_.length = 0;

      const renderedLayerStates = [];
      let previousElement = null;
      for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {
        const layerState = layerStatesArray[i];
        frameState.layerIndex = i;

        const layer = layerState.layer;
        const sourceState = layer.getSourceState();
        if (
          !inView(layerState, viewState) ||
          (sourceState != 'ready' && sourceState != 'undefined')
        ) {
          layer.unrender();
          continue;
        }

        const element = layer.render(frameState, previousElement);
        if (!element) {
          continue;
        }
        if (element !== previousElement) {
          this.children_.push(element);
          previousElement = element;
        }

        renderedLayerStates.push(layerState);
      }

      this.declutter(frameState, renderedLayerStates);

      replaceChildren(this.element_, this.children_);

      this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState);

      if (!this.renderedVisible_) {
        this.element_.style.display = '';
        this.renderedVisible_ = true;
      }

      this.scheduleExpireIconCache(frameState);
    }

    /**
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {Array<import('../layer/Layer.js').State>} layerStates Layers.
     */
    declutter(frameState, layerStates) {
      if (!frameState.declutter) {
        return;
      }
      for (let i = layerStates.length - 1; i >= 0; --i) {
        const layerState = layerStates[i];
        const layer = layerState.layer;
        if (layer.getDeclutter()) {
          layer.renderDeclutter(frameState, layerState);
        }
      }
      layerStates.forEach((layerState) =>
        layerState.layer.renderDeferred(frameState),
      );
    }
  }

  /**
   * @module ol/Map
   */

  /**
   * State of the current frame. Only `pixelRatio`, `time` and `viewState` should
   * be used in applications.
   * @typedef {Object} FrameState
   * @property {number} pixelRatio The pixel ratio of the frame.
   * @property {number} time The time when rendering of the frame was requested.
   * @property {import("./View.js").State} viewState The state of the current view.
   * @property {boolean} animate Animate.
   * @property {import("./transform.js").Transform} coordinateToPixelTransform CoordinateToPixelTransform.
   * @property {Object<string, import("rbush").default<import('./render/canvas/Executor.js').DeclutterEntry>>|null} declutter
   * Declutter trees by declutter group.
   * When null, no decluttering is needed because no layers have decluttering enabled.
   * @property {null|import("./extent.js").Extent} extent Extent (in view projection coordinates).
   * @property {import("./extent.js").Extent} [nextExtent] Next extent during an animation series.
   * @property {number} index Index.
   * @property {Array<import("./layer/Layer.js").State>} layerStatesArray LayerStatesArray.
   * @property {number} layerIndex LayerIndex.
   * @property {import("./transform.js").Transform} pixelToCoordinateTransform PixelToCoordinateTransform.
   * @property {Array<PostRenderFunction>} postRenderFunctions PostRenderFunctions.
   * @property {import("./size.js").Size} size Size.
   * @property {TileQueue} tileQueue TileQueue.
   * @property {!Object<string, Object<string, boolean>>} usedTiles UsedTiles.
   * @property {Array<number>} viewHints ViewHints.
   * @property {!Object<string, Object<string, boolean>>} wantedTiles WantedTiles.
   * @property {string} mapId The id of the map.
   * @property {Object<string, boolean>} renderTargets Identifiers of previously rendered elements.
   */

  /**
   * @typedef {function(Map, FrameState): any} PostRenderFunction
   */

  /**
   * @typedef {Object} AtPixelOptions
   * @property {undefined|function(import("./layer/Layer.js").default<import("./source/Source").default>): boolean} [layerFilter] Layer filter
   * function. The filter function will receive one argument, the
   * {@link module:ol/layer/Layer~Layer layer-candidate} and it should return a boolean value.
   * Only layers which are visible and for which this function returns `true`
   * will be tested for features. By default, all visible layers will be tested.
   * @property {number} [hitTolerance=0] Hit-detection tolerance in css pixels. Pixels
   * inside the radius around the given position will be checked for features.
   * @property {boolean} [checkWrapped=true] Check-Wrapped Will check for wrapped geometries inside the range of
   *   +/- 1 world width. Works only if a projection is used that can be wrapped.
   */

  /**
   * @typedef {Object} MapOptionsInternal
   * @property {Collection<import("./control/Control.js").default>} [controls] Controls.
   * @property {Collection<import("./interaction/Interaction.js").default>} [interactions] Interactions.
   * @property {HTMLElement|Document} keyboardEventTarget KeyboardEventTarget.
   * @property {Collection<import("./Overlay.js").default>} overlays Overlays.
   * @property {Object<string, *>} values Values.
   */

  /**
   * @typedef {import("./ObjectEventType").Types|'change:layergroup'|'change:size'|'change:target'|'change:view'} MapObjectEventTypes
   */

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *    import("./Observable").OnSignature<MapObjectEventTypes, import("./Object").ObjectEvent, Return> &
   *    import("./Observable").OnSignature<import("./MapBrowserEventType").Types, import("./MapBrowserEvent").default, Return> &
   *    import("./Observable").OnSignature<import("./MapEventType").Types, import("./MapEvent").default, Return> &
   *    import("./Observable").OnSignature<import("./render/EventType").MapRenderEventTypes, import("./render/Event").default, Return> &
   *    import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|MapObjectEventTypes|
   *      import("./MapBrowserEventType").Types|import("./MapEventType").Types|
   *      import("./render/EventType").MapRenderEventTypes, Return>} MapEventHandler
   */

  /**
   * Object literal with config options for the map.
   * @typedef {Object} MapOptions
   * @property {Collection<import("./control/Control.js").default>|Array<import("./control/Control.js").default>} [controls]
   * Controls initially added to the map. If not specified,
   * {@link module:ol/control/defaults.defaults} is used.
   * @property {number} [pixelRatio=window.devicePixelRatio] The ratio between
   * physical pixels and device-independent pixels (dips) on the device.
   * @property {Collection<import("./interaction/Interaction.js").default>|Array<import("./interaction/Interaction.js").default>} [interactions]
   * Interactions that are initially added to the map. If not specified,
   * {@link module:ol/interaction/defaults.defaults} is used.
   * @property {HTMLElement|Document|string} [keyboardEventTarget] The element to
   * listen to keyboard events on. This determines when the `KeyboardPan` and
   * `KeyboardZoom` interactions trigger. For example, if this option is set to
   * `document` the keyboard interactions will always trigger. If this option is
   * not specified, the element the library listens to keyboard events on is the
   * map target (i.e. the user-provided div for the map). If this is not
   * `document`, the target element needs to be focused for key events to be
   * emitted, requiring that the target element has a `tabindex` attribute.
   * @property {Array<import("./layer/Base.js").default>|Collection<import("./layer/Base.js").default>|LayerGroup} [layers]
   * Layers. If this is not defined, a map with no layers will be rendered. Note
   * that layers are rendered in the order supplied, so if you want, for example,
   * a vector layer to appear on top of a tile layer, it must come after the tile
   * layer.
   * @property {number} [maxTilesLoading=16] Maximum number tiles to load
   * simultaneously.
   * @property {number} [moveTolerance=1] The minimum distance in pixels the
   * cursor must move to be detected as a map move event instead of a click.
   * Increasing this value can make it easier to click on the map.
   * @property {Collection<import("./Overlay.js").default>|Array<import("./Overlay.js").default>} [overlays]
   * Overlays initially added to the map. By default, no overlays are added.
   * @property {HTMLElement|string} [target] The container for the map, either the
   * element itself or the `id` of the element. If not specified at construction
   * time, {@link module:ol/Map~Map#setTarget} must be called for the map to be
   * rendered. If passed by element, the container can be in a secondary document.
   * For accessibility (focus and keyboard events for map navigation), the `target` element must have a
   *  properly configured `tabindex` attribute. If the `target` element is inside a Shadow DOM, the
   *  `tabindex` atribute must be set on the custom element's host element.
   * **Note:** CSS `transform` support for the target element is limited to `scale`.
   * @property {View|Promise<import("./View.js").ViewOptions>} [view] The map's view.  No layer sources will be
   * fetched unless this is specified at construction time or through
   * {@link module:ol/Map~Map#setView}.
   */

  /**
   * @param {import("./layer/Base.js").default} layer Layer.
   */
  function removeLayerMapProperty(layer) {
    if (layer instanceof Layer) {
      layer.setMapInternal(null);
      return;
    }
    if (layer instanceof LayerGroup) {
      layer.getLayers().forEach(removeLayerMapProperty);
    }
  }

  /**
   * @param {import("./layer/Base.js").default} layer Layer.
   * @param {Map} map Map.
   */
  function setLayerMapProperty(layer, map) {
    if (layer instanceof Layer) {
      layer.setMapInternal(map);
      return;
    }
    if (layer instanceof LayerGroup) {
      const layers = layer.getLayers().getArray();
      for (let i = 0, ii = layers.length; i < ii; ++i) {
        setLayerMapProperty(layers[i], map);
      }
    }
  }

  /**
   * @classdesc
   * The map is the core component of OpenLayers. For a map to render, a view,
   * one or more layers, and a target container are needed:
   *
   *     import Map from 'ol/Map.js';
   *     import View from 'ol/View.js';
   *     import TileLayer from 'ol/layer/Tile.js';
   *     import OSM from 'ol/source/OSM.js';
   *
   *     const map = new Map({
   *       view: new View({
   *         center: [0, 0],
   *         zoom: 1,
   *       }),
   *       layers: [
   *         new TileLayer({
   *           source: new OSM(),
   *         }),
   *       ],
   *       target: 'map',
   *     });
   *
   * The above snippet creates a map using a {@link module:ol/layer/Tile~TileLayer} to
   * display {@link module:ol/source/OSM~OSM} OSM data and render it to a DOM
   * element with the id `map`.
   *
   * The constructor places a viewport container (with CSS class name
   * `ol-viewport`) in the target element (see `getViewport()`), and then two
   * further elements within the viewport: one with CSS class name
   * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with
   * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent`
   * option of {@link module:ol/Overlay~Overlay} for the difference). The map
   * itself is placed in a further element within the viewport.
   *
   * Layers are stored as a {@link module:ol/Collection~Collection} in
   * layerGroups. A top-level group is provided by the library. This is what is
   * accessed by `getLayerGroup` and `setLayerGroup`. Layers entered in the
   * options are added to this group, and `addLayer` and `removeLayer` change the
   * layer collection in the group. `getLayers` is a convenience function for
   * `getLayerGroup().getLayers()`. Note that {@link module:ol/layer/Group~LayerGroup}
   * is a subclass of {@link module:ol/layer/Base~BaseLayer}, so layers entered in the
   * options or added with `addLayer` can be groups, which can contain further
   * groups, and so on.
   *
   * @fires import("./MapBrowserEvent.js").MapBrowserEvent
   * @fires import("./MapEvent.js").MapEvent
   * @fires import("./render/Event.js").default#precompose
   * @fires import("./render/Event.js").default#postcompose
   * @fires import("./render/Event.js").default#rendercomplete
   * @api
   */
  let Map$1 = class Map extends BaseObject {
    /**
     * @param {MapOptions} [options] Map options.
     */
    constructor(options) {
      super();

      options = options || {};

      /***
       * @type {MapEventHandler<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {MapEventHandler<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {MapEventHandler<void>}
       */
      this.un;

      const optionsInternal = createOptionsInternal(options);

      /**
       * @private
       * @type {boolean}
       */
      this.renderComplete_ = false;

      /**
       * @private
       * @type {boolean}
       */
      this.loaded_ = true;

      /** @private */
      this.boundHandleBrowserEvent_ = this.handleBrowserEvent.bind(this);

      /**
       * @type {number}
       * @private
       */
      this.maxTilesLoading_ =
        options.maxTilesLoading !== undefined ? options.maxTilesLoading : 16;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ =
        options.pixelRatio !== undefined
          ? options.pixelRatio
          : DEVICE_PIXEL_RATIO;

      /**
       * @private
       * @type {ReturnType<typeof setTimeout>}
       */
      this.postRenderTimeoutHandle_;

      /**
       * @private
       * @type {number|undefined}
       */
      this.animationDelayKey_;

      /**
       * @private
       */
      this.animationDelay_ = this.animationDelay_.bind(this);

      /**
       * @private
       * @type {import("./transform.js").Transform}
       */
      this.coordinateToPixelTransform_ = create$3();

      /**
       * @private
       * @type {import("./transform.js").Transform}
       */
      this.pixelToCoordinateTransform_ = create$3();

      /**
       * @private
       * @type {number}
       */
      this.frameIndex_ = 0;

      /**
       * @private
       * @type {?FrameState}
       */
      this.frameState_ = null;

      /**
       * The extent at the previous 'moveend' event.
       * @private
       * @type {import("./extent.js").Extent}
       */
      this.previousExtent_ = null;

      /**
       * @private
       * @type {?import("./events.js").EventsKey}
       */
      this.viewPropertyListenerKey_ = null;

      /**
       * @private
       * @type {?import("./events.js").EventsKey}
       */
      this.viewChangeListenerKey_ = null;

      /**
       * @private
       * @type {?Array<import("./events.js").EventsKey>}
       */
      this.layerGroupPropertyListenerKeys_ = null;

      /**
       * @private
       * @type {!HTMLElement}
       */
      this.viewport_ = document.createElement('div');
      this.viewport_.className =
        'ol-viewport' + ('ontouchstart' in window ? ' ol-touch' : '');
      this.viewport_.style.position = 'relative';
      this.viewport_.style.overflow = 'hidden';
      this.viewport_.style.width = '100%';
      this.viewport_.style.height = '100%';

      /**
       * @private
       * @type {!HTMLElement}
       */
      this.overlayContainer_ = document.createElement('div');
      this.overlayContainer_.style.position = 'absolute';
      this.overlayContainer_.style.zIndex = '0';
      this.overlayContainer_.style.width = '100%';
      this.overlayContainer_.style.height = '100%';
      this.overlayContainer_.style.pointerEvents = 'none';
      this.overlayContainer_.className = 'ol-overlaycontainer';
      this.viewport_.appendChild(this.overlayContainer_);

      /**
       * @private
       * @type {!HTMLElement}
       */
      this.overlayContainerStopEvent_ = document.createElement('div');
      this.overlayContainerStopEvent_.style.position = 'absolute';
      this.overlayContainerStopEvent_.style.zIndex = '0';
      this.overlayContainerStopEvent_.style.width = '100%';
      this.overlayContainerStopEvent_.style.height = '100%';
      this.overlayContainerStopEvent_.style.pointerEvents = 'none';
      this.overlayContainerStopEvent_.className = 'ol-overlaycontainer-stopevent';
      this.viewport_.appendChild(this.overlayContainerStopEvent_);

      /**
       * @private
       * @type {MapBrowserEventHandler}
       */
      this.mapBrowserEventHandler_ = null;

      /**
       * @private
       * @type {number}
       */
      this.moveTolerance_ = options.moveTolerance;

      /**
       * @private
       * @type {HTMLElement|Document}
       */
      this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget;

      /**
       * @private
       * @type {?Array<import("./events.js").EventsKey>}
       */
      this.targetChangeHandlerKeys_ = null;

      /**
       * @private
       * @type {HTMLElement|null}
       */
      this.targetElement_ = null;

      /**
       * @private
       * @type {ResizeObserver}
       */
      this.resizeObserver_ = new ResizeObserver(() => this.updateSize());

      /**
       * @type {Collection<import("./control/Control.js").default>}
       * @protected
       */
      this.controls = optionsInternal.controls || defaults$1();

      /**
       * @type {Collection<import("./interaction/Interaction.js").default>}
       * @protected
       */
      this.interactions =
        optionsInternal.interactions ||
        defaults({
          onFocusOnly: true,
        });

      /**
       * @type {Collection<import("./Overlay.js").default>}
       * @private
       */
      this.overlays_ = optionsInternal.overlays;

      /**
       * A lookup of overlays by id.
       * @private
       * @type {Object<string, import("./Overlay.js").default>}
       */
      this.overlayIdIndex_ = {};

      /**
       * @type {import("./renderer/Map.js").default|null}
       * @private
       */
      this.renderer_ = null;

      /**
       * @private
       * @type {!Array<PostRenderFunction>}
       */
      this.postRenderFunctions_ = [];

      /**
       * @private
       * @type {TileQueue}
       */
      this.tileQueue_ = new TileQueue(
        this.getTilePriority.bind(this),
        this.handleTileChange_.bind(this),
      );

      this.addChangeListener(
        MapProperty.LAYERGROUP,
        this.handleLayerGroupChanged_,
      );
      this.addChangeListener(MapProperty.VIEW, this.handleViewChanged_);
      this.addChangeListener(MapProperty.SIZE, this.handleSizeChanged_);
      this.addChangeListener(MapProperty.TARGET, this.handleTargetChanged_);

      // setProperties will trigger the rendering of the map if the map
      // is "defined" already.
      this.setProperties(optionsInternal.values);

      const map = this;
      if (options.view && !(options.view instanceof View)) {
        options.view.then(function (viewOptions) {
          map.setView(new View(viewOptions));
        });
      }

      this.controls.addEventListener(
        CollectionEventType.ADD,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./control/Control.js").default>} event CollectionEvent
         */
        (event) => {
          event.element.setMap(this);
        },
      );

      this.controls.addEventListener(
        CollectionEventType.REMOVE,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./control/Control.js").default>} event CollectionEvent.
         */
        (event) => {
          event.element.setMap(null);
        },
      );

      this.interactions.addEventListener(
        CollectionEventType.ADD,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./interaction/Interaction.js").default>} event CollectionEvent.
         */
        (event) => {
          event.element.setMap(this);
        },
      );

      this.interactions.addEventListener(
        CollectionEventType.REMOVE,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./interaction/Interaction.js").default>} event CollectionEvent.
         */
        (event) => {
          event.element.setMap(null);
        },
      );

      this.overlays_.addEventListener(
        CollectionEventType.ADD,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./Overlay.js").default>} event CollectionEvent.
         */
        (event) => {
          this.addOverlayInternal_(event.element);
        },
      );

      this.overlays_.addEventListener(
        CollectionEventType.REMOVE,
        /**
         * @param {import("./Collection.js").CollectionEvent<import("./Overlay.js").default>} event CollectionEvent.
         */
        (event) => {
          const id = event.element.getId();
          if (id !== undefined) {
            delete this.overlayIdIndex_[id.toString()];
          }
          event.element.setMap(null);
        },
      );

      this.controls.forEach(
        /**
         * @param {import("./control/Control.js").default} control Control.
         */
        (control) => {
          control.setMap(this);
        },
      );

      this.interactions.forEach(
        /**
         * @param {import("./interaction/Interaction.js").default} interaction Interaction.
         */
        (interaction) => {
          interaction.setMap(this);
        },
      );

      this.overlays_.forEach(this.addOverlayInternal_.bind(this));
    }

    /**
     * Add the given control to the map.
     * @param {import("./control/Control.js").default} control Control.
     * @api
     */
    addControl(control) {
      this.getControls().push(control);
    }

    /**
     * Add the given interaction to the map. If you want to add an interaction
     * at another point of the collection use `getInteractions()` and the methods
     * available on {@link module:ol/Collection~Collection}. This can be used to
     * stop the event propagation from the handleEvent function. The interactions
     * get to handle the events in the reverse order of this collection.
     * @param {import("./interaction/Interaction.js").default} interaction Interaction to add.
     * @api
     */
    addInteraction(interaction) {
      this.getInteractions().push(interaction);
    }

    /**
     * Adds the given layer to the top of this map. If you want to add a layer
     * elsewhere in the stack, use `getLayers()` and the methods available on
     * {@link module:ol/Collection~Collection}.
     * @param {import("./layer/Base.js").default} layer Layer.
     * @api
     */
    addLayer(layer) {
      const layers = this.getLayerGroup().getLayers();
      layers.push(layer);
    }

    /**
     * @param {import("./layer/Group.js").GroupEvent} event The layer add event.
     * @private
     */
    handleLayerAdd_(event) {
      setLayerMapProperty(event.layer, this);
    }

    /**
     * Add the given overlay to the map.
     * @param {import("./Overlay.js").default} overlay Overlay.
     * @api
     */
    addOverlay(overlay) {
      this.getOverlays().push(overlay);
    }

    /**
     * This deals with map's overlay collection changes.
     * @param {import("./Overlay.js").default} overlay Overlay.
     * @private
     */
    addOverlayInternal_(overlay) {
      const id = overlay.getId();
      if (id !== undefined) {
        this.overlayIdIndex_[id.toString()] = overlay;
      }
      overlay.setMap(this);
    }

    /**
     *
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.controls.clear();
      this.interactions.clear();
      this.overlays_.clear();
      this.resizeObserver_.disconnect();
      this.setTarget(null);
      super.disposeInternal();
    }

    /**
     * Detect features that intersect a pixel on the viewport, and execute a
     * callback with each intersecting feature. Layers included in the detection can
     * be configured through the `layerFilter` option in `options`.
     * For polygons without a fill, only the stroke will be used for hit detection.
     * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.
     * The fill can be transparent.
     * @param {import("./pixel.js").Pixel} pixel Pixel.
     * @param {function(import("./Feature.js").FeatureLike, import("./layer/Layer.js").default<import("./source/Source").default>, import("./geom/SimpleGeometry.js").default): T} callback Feature callback. The callback will be
     *     called with two arguments. The first argument is one
     *     {@link module:ol/Feature~Feature feature} or
     *     {@link module:ol/render/Feature~RenderFeature render feature} at the pixel, the second is
     *     the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for
     *     unmanaged layers. To stop detection, callback functions can return a
     *     truthy value.
     * @param {AtPixelOptions} [options] Optional options.
     * @return {T|undefined} Callback result, i.e. the return value of last
     * callback execution, or the first truthy callback return value.
     * @template T
     * @api
     */
    forEachFeatureAtPixel(pixel, callback, options) {
      if (!this.frameState_ || !this.renderer_) {
        return;
      }
      const coordinate = this.getCoordinateFromPixelInternal(pixel);
      options = options !== undefined ? options : {};
      const hitTolerance =
        options.hitTolerance !== undefined ? options.hitTolerance : 0;
      const layerFilter =
        options.layerFilter !== undefined ? options.layerFilter : TRUE;
      const checkWrapped = options.checkWrapped !== false;
      return this.renderer_.forEachFeatureAtCoordinate(
        coordinate,
        this.frameState_,
        hitTolerance,
        checkWrapped,
        callback,
        null,
        layerFilter,
        null,
      );
    }

    /**
     * Get all features that intersect a pixel on the viewport.
     * For polygons without a fill, only the stroke will be used for hit detection.
     * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.
     * The fill can be transparent.
     * @param {import("./pixel.js").Pixel} pixel Pixel.
     * @param {AtPixelOptions} [options] Optional options.
     * @return {Array<import("./Feature.js").FeatureLike>} The detected features or
     * an empty array if none were found.
     * @api
     */
    getFeaturesAtPixel(pixel, options) {
      const features = [];
      this.forEachFeatureAtPixel(
        pixel,
        function (feature) {
          features.push(feature);
        },
        options,
      );
      return features;
    }

    /**
     * Get all layers from all layer groups.
     * @return {Array<import("./layer/Layer.js").default>} Layers.
     * @api
     */
    getAllLayers() {
      const layers = [];
      function addLayersFrom(layerGroup) {
        layerGroup.forEach(function (layer) {
          if (layer instanceof LayerGroup) {
            addLayersFrom(layer.getLayers());
          } else {
            layers.push(layer);
          }
        });
      }
      addLayersFrom(this.getLayers());
      return layers;
    }

    /**
     * Detect if features intersect a pixel on the viewport. Layers included in the
     * detection can be configured through the `layerFilter` option.
     * For polygons without a fill, only the stroke will be used for hit detection.
     * Polygons must have a fill style applied to ensure that pixels inside a polygon are detected.
     * The fill can be transparent.
     * @param {import("./pixel.js").Pixel} pixel Pixel.
     * @param {AtPixelOptions} [options] Optional options.
     * @return {boolean} Is there a feature at the given pixel?
     * @api
     */
    hasFeatureAtPixel(pixel, options) {
      if (!this.frameState_ || !this.renderer_) {
        return false;
      }
      const coordinate = this.getCoordinateFromPixelInternal(pixel);
      options = options !== undefined ? options : {};
      const layerFilter =
        options.layerFilter !== undefined ? options.layerFilter : TRUE;
      const hitTolerance =
        options.hitTolerance !== undefined ? options.hitTolerance : 0;
      const checkWrapped = options.checkWrapped !== false;
      return this.renderer_.hasFeatureAtCoordinate(
        coordinate,
        this.frameState_,
        hitTolerance,
        checkWrapped,
        layerFilter,
        null,
      );
    }

    /**
     * Returns the coordinate in user projection for a browser event.
     * @param {MouseEvent} event Event.
     * @return {import("./coordinate.js").Coordinate} Coordinate.
     * @api
     */
    getEventCoordinate(event) {
      return this.getCoordinateFromPixel(this.getEventPixel(event));
    }

    /**
     * Returns the coordinate in view projection for a browser event.
     * @param {MouseEvent} event Event.
     * @return {import("./coordinate.js").Coordinate} Coordinate.
     */
    getEventCoordinateInternal(event) {
      return this.getCoordinateFromPixelInternal(this.getEventPixel(event));
    }

    /**
     * Returns the map pixel position for a browser event relative to the viewport.
     * @param {UIEvent|{clientX: number, clientY: number}} event Event.
     * @return {import("./pixel.js").Pixel} Pixel.
     * @api
     */
    getEventPixel(event) {
      const viewport = this.viewport_;
      const viewportPosition = viewport.getBoundingClientRect();
      const viewportSize = this.getSize();
      const scaleX = viewportPosition.width / viewportSize[0];
      const scaleY = viewportPosition.height / viewportSize[1];
      const eventPosition =
        //FIXME Are we really calling this with a TouchEvent anywhere?
        'changedTouches' in event
          ? /** @type {TouchEvent} */ (event).changedTouches[0]
          : /** @type {MouseEvent} */ (event);

      return [
        (eventPosition.clientX - viewportPosition.left) / scaleX,
        (eventPosition.clientY - viewportPosition.top) / scaleY,
      ];
    }

    /**
     * Get the target in which this map is rendered.
     * Note that this returns what is entered as an option or in setTarget:
     * if that was an element, it returns an element; if a string, it returns that.
     * @return {HTMLElement|string|undefined} The Element or id of the Element that the
     *     map is rendered in.
     * @observable
     * @api
     */
    getTarget() {
      return /** @type {HTMLElement|string|undefined} */ (
        this.get(MapProperty.TARGET)
      );
    }

    /**
     * Get the DOM element into which this map is rendered. In contrast to
     * `getTarget` this method always return an `Element`, or `null` if the
     * map has no target.
     * @return {HTMLElement} The element that the map is rendered in.
     * @api
     */
    getTargetElement() {
      return this.targetElement_;
    }

    /**
     * Get the coordinate for a given pixel.  This returns a coordinate in the
     * user projection.
     * @param {import("./pixel.js").Pixel} pixel Pixel position in the map viewport.
     * @return {import("./coordinate.js").Coordinate} The coordinate for the pixel position.
     * @api
     */
    getCoordinateFromPixel(pixel) {
      return toUserCoordinate(
        this.getCoordinateFromPixelInternal(pixel),
        this.getView().getProjection(),
      );
    }

    /**
     * Get the coordinate for a given pixel.  This returns a coordinate in the
     * map view projection.
     * @param {import("./pixel.js").Pixel} pixel Pixel position in the map viewport.
     * @return {import("./coordinate.js").Coordinate} The coordinate for the pixel position.
     */
    getCoordinateFromPixelInternal(pixel) {
      const frameState = this.frameState_;
      if (!frameState) {
        return null;
      }
      return apply(frameState.pixelToCoordinateTransform, pixel.slice());
    }

    /**
     * Get the map controls. Modifying this collection changes the controls
     * associated with the map.
     * @return {Collection<import("./control/Control.js").default>} Controls.
     * @api
     */
    getControls() {
      return this.controls;
    }

    /**
     * Get the map overlays. Modifying this collection changes the overlays
     * associated with the map.
     * @return {Collection<import("./Overlay.js").default>} Overlays.
     * @api
     */
    getOverlays() {
      return this.overlays_;
    }

    /**
     * Get an overlay by its identifier (the value returned by overlay.getId()).
     * Note that the index treats string and numeric identifiers as the same. So
     * `map.getOverlayById(2)` will return an overlay with id `'2'` or `2`.
     * @param {string|number} id Overlay identifier.
     * @return {import("./Overlay.js").default|null} Overlay.
     * @api
     */
    getOverlayById(id) {
      const overlay = this.overlayIdIndex_[id.toString()];
      return overlay !== undefined ? overlay : null;
    }

    /**
     * Get the map interactions. Modifying this collection changes the interactions
     * associated with the map.
     *
     * Interactions are used for e.g. pan, zoom and rotate.
     * @return {Collection<import("./interaction/Interaction.js").default>} Interactions.
     * @api
     */
    getInteractions() {
      return this.interactions;
    }

    /**
     * Get the layergroup associated with this map.
     * @return {LayerGroup} A layer group containing the layers in this map.
     * @observable
     * @api
     */
    getLayerGroup() {
      return /** @type {LayerGroup} */ (this.get(MapProperty.LAYERGROUP));
    }

    /**
     * Clear any existing layers and add layers to the map.
     * @param {Array<import("./layer/Base.js").default>|Collection<import("./layer/Base.js").default>} layers The layers to be added to the map.
     * @api
     */
    setLayers(layers) {
      const group = this.getLayerGroup();
      if (layers instanceof Collection) {
        group.setLayers(layers);
        return;
      }

      const collection = group.getLayers();
      collection.clear();
      collection.extend(layers);
    }

    /**
     * Get the collection of layers associated with this map.
     * @return {!Collection<import("./layer/Base.js").default>} Layers.
     * @api
     */
    getLayers() {
      const layers = this.getLayerGroup().getLayers();
      return layers;
    }

    /**
     * @return {boolean} Layers have sources that are still loading.
     */
    getLoadingOrNotReady() {
      const layerStatesArray = this.getLayerGroup().getLayerStatesArray();
      for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {
        const state = layerStatesArray[i];
        if (!state.visible) {
          continue;
        }
        const renderer = state.layer.getRenderer();
        if (renderer && !renderer.ready) {
          return true;
        }
        const source = state.layer.getSource();
        if (source && source.loading) {
          return true;
        }
      }
      return false;
    }

    /**
     * Get the pixel for a coordinate.  This takes a coordinate in the user
     * projection and returns the corresponding pixel.
     * @param {import("./coordinate.js").Coordinate} coordinate A map coordinate.
     * @return {import("./pixel.js").Pixel} A pixel position in the map viewport.
     * @api
     */
    getPixelFromCoordinate(coordinate) {
      const viewCoordinate = fromUserCoordinate(
        coordinate,
        this.getView().getProjection(),
      );
      return this.getPixelFromCoordinateInternal(viewCoordinate);
    }

    /**
     * Get the pixel for a coordinate.  This takes a coordinate in the map view
     * projection and returns the corresponding pixel.
     * @param {import("./coordinate.js").Coordinate} coordinate A map coordinate.
     * @return {import("./pixel.js").Pixel} A pixel position in the map viewport.
     */
    getPixelFromCoordinateInternal(coordinate) {
      const frameState = this.frameState_;
      if (!frameState) {
        return null;
      }
      return apply(
        frameState.coordinateToPixelTransform,
        coordinate.slice(0, 2),
      );
    }

    /**
     * Get the map renderer.
     * @return {import("./renderer/Map.js").default|null} Renderer
     */
    getRenderer() {
      return this.renderer_;
    }

    /**
     * Get the size of this map.
     * @return {import("./size.js").Size|undefined} The size in pixels of the map in the DOM.
     * @observable
     * @api
     */
    getSize() {
      return /** @type {import("./size.js").Size|undefined} */ (
        this.get(MapProperty.SIZE)
      );
    }

    /**
     * Get the view associated with this map. A view manages properties such as
     * center and resolution.
     * @return {View} The view that controls this map.
     * @observable
     * @api
     */
    getView() {
      return /** @type {View} */ (this.get(MapProperty.VIEW));
    }

    /**
     * Get the element that serves as the map viewport.
     * @return {HTMLElement} Viewport.
     * @api
     */
    getViewport() {
      return this.viewport_;
    }

    /**
     * Get the element that serves as the container for overlays.  Elements added to
     * this container will let mousedown and touchstart events through to the map,
     * so clicks and gestures on an overlay will trigger {@link module:ol/MapBrowserEvent~MapBrowserEvent}
     * events.
     * @return {!HTMLElement} The map's overlay container.
     */
    getOverlayContainer() {
      return this.overlayContainer_;
    }

    /**
     * Get the element that serves as a container for overlays that don't allow
     * event propagation. Elements added to this container won't let mousedown and
     * touchstart events through to the map, so clicks and gestures on an overlay
     * don't trigger any {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
     * @return {!HTMLElement} The map's overlay container that stops events.
     */
    getOverlayContainerStopEvent() {
      return this.overlayContainerStopEvent_;
    }

    /**
     * @return {!Document} The document where the map is displayed.
     */
    getOwnerDocument() {
      const targetElement = this.getTargetElement();
      return targetElement ? targetElement.ownerDocument : document;
    }

    /**
     * @param {import("./Tile.js").default} tile Tile.
     * @param {string} tileSourceKey Tile source key.
     * @param {import("./coordinate.js").Coordinate} tileCenter Tile center.
     * @param {number} tileResolution Tile resolution.
     * @return {number} Tile priority.
     */
    getTilePriority(tile, tileSourceKey, tileCenter, tileResolution) {
      return getTilePriority(
        this.frameState_,
        tile,
        tileSourceKey,
        tileCenter,
        tileResolution,
      );
    }

    /**
     * @param {PointerEvent|KeyboardEvent|WheelEvent} browserEvent Browser event.
     * @param {string} [type] Type.
     */
    handleBrowserEvent(browserEvent, type) {
      type = type || browserEvent.type;
      const mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent);
      this.handleMapBrowserEvent(mapBrowserEvent);
    }

    /**
     * @param {MapBrowserEvent} mapBrowserEvent The event to handle.
     */
    handleMapBrowserEvent(mapBrowserEvent) {
      if (!this.frameState_) {
        // With no view defined, we cannot translate pixels into geographical
        // coordinates so interactions cannot be used.
        return;
      }
      const originalEvent = mapBrowserEvent.originalEvent;
      const eventType = originalEvent.type;
      if (
        eventType === PointerEventType.POINTERDOWN ||
        eventType === EventType.WHEEL ||
        eventType === EventType.KEYDOWN
      ) {
        const doc = this.getOwnerDocument();
        const rootNode = this.viewport_.getRootNode
          ? this.viewport_.getRootNode()
          : doc;
        const target = /** @type {Node} */ (originalEvent.target);

        const currentDoc =
          rootNode instanceof ShadowRoot
            ? rootNode.host === target
              ? rootNode.host.ownerDocument
              : rootNode
            : rootNode === doc
              ? doc.documentElement
              : rootNode;
        if (
          // Abort if the target is a child of the container for elements whose events are not meant
          // to be handled by map interactions.
          this.overlayContainerStopEvent_.contains(target) ||
          // Abort if the event target is a child of the container that is no longer in the page.
          // It's possible for the target to no longer be in the page if it has been removed in an
          // event listener, this might happen in a Control that recreates it's content based on
          // user interaction either manually or via a render in something like https://reactjs.org/
          !currentDoc.contains(target)
        ) {
          return;
        }
      }
      mapBrowserEvent.frameState = this.frameState_;
      if (this.dispatchEvent(mapBrowserEvent) !== false) {
        const interactionsArray = this.getInteractions().getArray().slice();
        for (let i = interactionsArray.length - 1; i >= 0; i--) {
          const interaction = interactionsArray[i];
          if (
            interaction.getMap() !== this ||
            !interaction.getActive() ||
            !this.getTargetElement()
          ) {
            continue;
          }
          const cont = interaction.handleEvent(mapBrowserEvent);
          if (!cont || mapBrowserEvent.propagationStopped) {
            break;
          }
        }
      }
    }

    /**
     * @protected
     */
    handlePostRender() {
      const frameState = this.frameState_;

      // Manage the tile queue
      // Image loads are expensive and a limited resource, so try to use them
      // efficiently:
      // * When the view is static we allow a large number of parallel tile loads
      //   to complete the frame as quickly as possible.
      // * When animating or interacting, image loads can cause janks, so we reduce
      //   the maximum number of loads per frame and limit the number of parallel
      //   tile loads to remain reactive to view changes and to reduce the chance of
      //   loading tiles that will quickly disappear from view.
      const tileQueue = this.tileQueue_;
      if (!tileQueue.isEmpty()) {
        let maxTotalLoading = this.maxTilesLoading_;
        let maxNewLoads = maxTotalLoading;
        if (frameState) {
          const hints = frameState.viewHints;
          if (hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]) {
            const lowOnFrameBudget = Date.now() - frameState.time > 8;
            maxTotalLoading = lowOnFrameBudget ? 0 : 8;
            maxNewLoads = lowOnFrameBudget ? 0 : 2;
          }
        }
        if (tileQueue.getTilesLoading() < maxTotalLoading) {
          tileQueue.reprioritize(); // FIXME only call if view has changed
          tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads);
        }
      }

      if (frameState && this.renderer_ && !frameState.animate) {
        if (this.renderComplete_) {
          if (this.hasListener(RenderEventType.RENDERCOMPLETE)) {
            this.renderer_.dispatchRenderEvent(
              RenderEventType.RENDERCOMPLETE,
              frameState,
            );
          }
          if (this.loaded_ === false) {
            this.loaded_ = true;
            this.dispatchEvent(
              new MapEvent(MapEventType.LOADEND, this, frameState),
            );
          }
        } else if (this.loaded_ === true) {
          this.loaded_ = false;
          this.dispatchEvent(
            new MapEvent(MapEventType.LOADSTART, this, frameState),
          );
        }
      }

      const postRenderFunctions = this.postRenderFunctions_;
      if (frameState) {
        for (let i = 0, ii = postRenderFunctions.length; i < ii; ++i) {
          postRenderFunctions[i](this, frameState);
        }
      }
      postRenderFunctions.length = 0;
    }

    /**
     * @private
     */
    handleSizeChanged_() {
      if (this.getView() && !this.getView().getAnimating()) {
        this.getView().resolveConstraints(0);
      }

      this.render();
    }

    /**
     * @private
     */
    handleTargetChanged_() {
      if (this.mapBrowserEventHandler_) {
        for (let i = 0, ii = this.targetChangeHandlerKeys_.length; i < ii; ++i) {
          unlistenByKey(this.targetChangeHandlerKeys_[i]);
        }
        this.targetChangeHandlerKeys_ = null;
        this.viewport_.removeEventListener(
          EventType.CONTEXTMENU,
          this.boundHandleBrowserEvent_,
        );
        this.viewport_.removeEventListener(
          EventType.WHEEL,
          this.boundHandleBrowserEvent_,
        );
        this.mapBrowserEventHandler_.dispose();
        this.mapBrowserEventHandler_ = null;
        this.viewport_.remove();
      }

      if (this.targetElement_) {
        this.resizeObserver_.unobserve(this.targetElement_);
        const rootNode = this.targetElement_.getRootNode();
        if (rootNode instanceof ShadowRoot) {
          this.resizeObserver_.unobserve(rootNode.host);
        }
        this.setSize(undefined);
      }

      // target may be undefined, null, a string or an Element.
      // If it's a string we convert it to an Element before proceeding.
      // If it's not now an Element we remove the viewport from the DOM.
      // If it's an Element we append the viewport element to it.

      const target = this.getTarget();
      const targetElement =
        typeof target === 'string' ? document.getElementById(target) : target;
      this.targetElement_ = targetElement;
      if (!targetElement) {
        if (this.renderer_) {
          clearTimeout(this.postRenderTimeoutHandle_);
          this.postRenderTimeoutHandle_ = undefined;
          this.postRenderFunctions_.length = 0;
          this.renderer_.dispose();
          this.renderer_ = null;
        }
        if (this.animationDelayKey_) {
          cancelAnimationFrame(this.animationDelayKey_);
          this.animationDelayKey_ = undefined;
        }
      } else {
        targetElement.appendChild(this.viewport_);
        if (!this.renderer_) {
          this.renderer_ = new CompositeMapRenderer(this);
        }

        this.mapBrowserEventHandler_ = new MapBrowserEventHandler(
          this,
          this.moveTolerance_,
        );
        for (const key in MapBrowserEventType) {
          this.mapBrowserEventHandler_.addEventListener(
            MapBrowserEventType[key],
            this.handleMapBrowserEvent.bind(this),
          );
        }
        this.viewport_.addEventListener(
          EventType.CONTEXTMENU,
          this.boundHandleBrowserEvent_,
          false,
        );
        this.viewport_.addEventListener(
          EventType.WHEEL,
          this.boundHandleBrowserEvent_,
          PASSIVE_EVENT_LISTENERS ? {passive: false} : false,
        );

        let keyboardEventTarget;
        if (!this.keyboardEventTarget_) {
          // check if map target is in shadowDOM, if yes use host element as target
          const targetRoot = targetElement.getRootNode();
          const targetCandidate =
            targetRoot instanceof ShadowRoot ? targetRoot.host : targetElement;
          keyboardEventTarget = targetCandidate;
        } else {
          keyboardEventTarget = this.keyboardEventTarget_;
        }

        this.targetChangeHandlerKeys_ = [
          listen(
            keyboardEventTarget,
            EventType.KEYDOWN,
            this.handleBrowserEvent,
            this,
          ),
          listen(
            keyboardEventTarget,
            EventType.KEYPRESS,
            this.handleBrowserEvent,
            this,
          ),
        ];
        const rootNode = targetElement.getRootNode();
        if (rootNode instanceof ShadowRoot) {
          this.resizeObserver_.observe(rootNode.host);
        }
        this.resizeObserver_.observe(targetElement);
      }

      this.updateSize();
      // updateSize calls setSize, so no need to call this.render
      // ourselves here.
    }

    /**
     * @private
     */
    handleTileChange_() {
      this.render();
    }

    /**
     * @private
     */
    handleViewPropertyChanged_() {
      this.render();
    }

    /**
     * @private
     */
    handleViewChanged_() {
      if (this.viewPropertyListenerKey_) {
        unlistenByKey(this.viewPropertyListenerKey_);
        this.viewPropertyListenerKey_ = null;
      }
      if (this.viewChangeListenerKey_) {
        unlistenByKey(this.viewChangeListenerKey_);
        this.viewChangeListenerKey_ = null;
      }
      const view = this.getView();
      if (view) {
        this.updateViewportSize_(this.getSize());

        this.viewPropertyListenerKey_ = listen(
          view,
          ObjectEventType.PROPERTYCHANGE,
          this.handleViewPropertyChanged_,
          this,
        );
        this.viewChangeListenerKey_ = listen(
          view,
          EventType.CHANGE,
          this.handleViewPropertyChanged_,
          this,
        );

        view.resolveConstraints(0);
      }
      this.render();
    }

    /**
     * @private
     */
    handleLayerGroupChanged_() {
      if (this.layerGroupPropertyListenerKeys_) {
        this.layerGroupPropertyListenerKeys_.forEach(unlistenByKey);
        this.layerGroupPropertyListenerKeys_ = null;
      }
      const layerGroup = this.getLayerGroup();
      if (layerGroup) {
        this.handleLayerAdd_(new GroupEvent('addlayer', layerGroup));
        this.layerGroupPropertyListenerKeys_ = [
          listen(layerGroup, ObjectEventType.PROPERTYCHANGE, this.render, this),
          listen(layerGroup, EventType.CHANGE, this.render, this),
          listen(layerGroup, 'addlayer', this.handleLayerAdd_, this),
          listen(layerGroup, 'removelayer', this.handleLayerRemove_, this),
        ];
      }
      this.render();
    }

    /**
     * @return {boolean} Is rendered.
     */
    isRendered() {
      return !!this.frameState_;
    }

    /**
     * @private
     */
    animationDelay_() {
      this.animationDelayKey_ = undefined;
      this.renderFrame_(Date.now());
    }

    /**
     * Requests an immediate render in a synchronous manner.
     * @api
     */
    renderSync() {
      if (this.animationDelayKey_) {
        cancelAnimationFrame(this.animationDelayKey_);
      }
      this.animationDelay_();
    }

    /**
     * Redraws all text after new fonts have loaded
     */
    redrawText() {
      if (!this.frameState_) {
        return;
      }
      const layerStates = this.frameState_.layerStatesArray;
      for (let i = 0, ii = layerStates.length; i < ii; ++i) {
        const layer = layerStates[i].layer;
        if (layer.hasRenderer()) {
          layer.getRenderer().handleFontsChanged();
        }
      }
    }

    /**
     * Request a map rendering (at the next animation frame).
     * @api
     */
    render() {
      if (this.renderer_ && this.animationDelayKey_ === undefined) {
        this.animationDelayKey_ = requestAnimationFrame(this.animationDelay_);
      }
    }

    /**
     * Remove the given control from the map.
     * @param {import("./control/Control.js").default} control Control.
     * @return {import("./control/Control.js").default|undefined} The removed control (or undefined
     *     if the control was not found).
     * @api
     */
    removeControl(control) {
      return this.getControls().remove(control);
    }

    /**
     * Remove the given interaction from the map.
     * @param {import("./interaction/Interaction.js").default} interaction Interaction to remove.
     * @return {import("./interaction/Interaction.js").default|undefined} The removed interaction (or
     *     undefined if the interaction was not found).
     * @api
     */
    removeInteraction(interaction) {
      return this.getInteractions().remove(interaction);
    }

    /**
     * Removes the given layer from the map.
     * @param {import("./layer/Base.js").default} layer Layer.
     * @return {import("./layer/Base.js").default|undefined} The removed layer (or undefined if the
     *     layer was not found).
     * @api
     */
    removeLayer(layer) {
      const layers = this.getLayerGroup().getLayers();
      return layers.remove(layer);
    }

    /**
     * @param {import("./layer/Group.js").GroupEvent} event The layer remove event.
     * @private
     */
    handleLayerRemove_(event) {
      removeLayerMapProperty(event.layer);
    }

    /**
     * Remove the given overlay from the map.
     * @param {import("./Overlay.js").default} overlay Overlay.
     * @return {import("./Overlay.js").default|undefined} The removed overlay (or undefined
     *     if the overlay was not found).
     * @api
     */
    removeOverlay(overlay) {
      return this.getOverlays().remove(overlay);
    }

    /**
     * @param {number} time Time.
     * @private
     */
    renderFrame_(time) {
      const size = this.getSize();
      const view = this.getView();
      const previousFrameState = this.frameState_;
      /** @type {?FrameState} */
      let frameState = null;
      if (size !== undefined && hasArea(size) && view && view.isDef()) {
        const viewHints = view.getHints(
          this.frameState_ ? this.frameState_.viewHints : undefined,
        );
        const viewState = view.getState();
        frameState = {
          animate: false,
          coordinateToPixelTransform: this.coordinateToPixelTransform_,
          declutter: null,
          extent: getForViewAndSize(
            viewState.center,
            viewState.resolution,
            viewState.rotation,
            size,
          ),
          index: this.frameIndex_++,
          layerIndex: 0,
          layerStatesArray: this.getLayerGroup().getLayerStatesArray(),
          pixelRatio: this.pixelRatio_,
          pixelToCoordinateTransform: this.pixelToCoordinateTransform_,
          postRenderFunctions: [],
          size: size,
          tileQueue: this.tileQueue_,
          time: time,
          usedTiles: {},
          viewState: viewState,
          viewHints: viewHints,
          wantedTiles: {},
          mapId: getUid(this),
          renderTargets: {},
        };
        if (viewState.nextCenter && viewState.nextResolution) {
          const rotation = isNaN(viewState.nextRotation)
            ? viewState.rotation
            : viewState.nextRotation;

          frameState.nextExtent = getForViewAndSize(
            viewState.nextCenter,
            viewState.nextResolution,
            rotation,
            size,
          );
        }
      }

      this.frameState_ = frameState;
      this.renderer_.renderFrame(frameState);

      if (frameState) {
        if (frameState.animate) {
          this.render();
        }
        Array.prototype.push.apply(
          this.postRenderFunctions_,
          frameState.postRenderFunctions,
        );

        if (previousFrameState) {
          const moveStart =
            !this.previousExtent_ ||
            (!isEmpty(this.previousExtent_) &&
              !equals$1(frameState.extent, this.previousExtent_));
          if (moveStart) {
            this.dispatchEvent(
              new MapEvent(MapEventType.MOVESTART, this, previousFrameState),
            );
            this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_);
          }
        }

        const idle =
          this.previousExtent_ &&
          !frameState.viewHints[ViewHint.ANIMATING] &&
          !frameState.viewHints[ViewHint.INTERACTING] &&
          !equals$1(frameState.extent, this.previousExtent_);

        if (idle) {
          this.dispatchEvent(
            new MapEvent(MapEventType.MOVEEND, this, frameState),
          );
          clone(frameState.extent, this.previousExtent_);
        }
      }

      this.dispatchEvent(new MapEvent(MapEventType.POSTRENDER, this, frameState));

      this.renderComplete_ =
        (this.hasListener(MapEventType.LOADSTART) ||
          this.hasListener(MapEventType.LOADEND) ||
          this.hasListener(RenderEventType.RENDERCOMPLETE)) &&
        !this.tileQueue_.getTilesLoading() &&
        !this.tileQueue_.getCount() &&
        !this.getLoadingOrNotReady();

      if (!this.postRenderTimeoutHandle_) {
        this.postRenderTimeoutHandle_ = setTimeout(() => {
          this.postRenderTimeoutHandle_ = undefined;
          this.handlePostRender();
        }, 0);
      }
    }

    /**
     * Sets the layergroup of this map.
     * @param {LayerGroup} layerGroup A layer group containing the layers in this map.
     * @observable
     * @api
     */
    setLayerGroup(layerGroup) {
      const oldLayerGroup = this.getLayerGroup();
      if (oldLayerGroup) {
        this.handleLayerRemove_(new GroupEvent('removelayer', oldLayerGroup));
      }
      this.set(MapProperty.LAYERGROUP, layerGroup);
    }

    /**
     * Set the size of this map.
     * @param {import("./size.js").Size|undefined} size The size in pixels of the map in the DOM.
     * @observable
     * @api
     */
    setSize(size) {
      this.set(MapProperty.SIZE, size);
    }

    /**
     * Set the target element to render this map into.
     * For accessibility (focus and keyboard events for map navigation), the `target` element must have a
     *  properly configured `tabindex` attribute. If the `target` element is inside a Shadow DOM, the
     *  `tabindex` atribute must be set on the custom element's host element.
     * @param {HTMLElement|string} [target] The Element or id of the Element
     *     that the map is rendered in.
     * @observable
     * @api
     */
    setTarget(target) {
      this.set(MapProperty.TARGET, target);
    }

    /**
     * Set the view for this map.
     * @param {View|Promise<import("./View.js").ViewOptions>|null} view The view that controls this map.
     * It is also possible to pass a promise that resolves to options for constructing a view.  This
     * alternative allows view properties to be resolved by sources or other components that load
     * view-related metadata.
     * @observable
     * @api
     */
    setView(view) {
      if (!view || view instanceof View) {
        this.set(MapProperty.VIEW, view);
        return;
      }
      this.set(MapProperty.VIEW, new View());

      const map = this;
      view.then(function (viewOptions) {
        map.setView(new View(viewOptions));
      });
    }

    /**
     * Force a recalculation of the map viewport size.  This should be called when
     * third-party code changes the size of the map viewport.
     * @api
     */
    updateSize() {
      const targetElement = this.getTargetElement();

      let size = undefined;
      if (targetElement) {
        const computedStyle = getComputedStyle(targetElement);
        const width =
          targetElement.offsetWidth -
          parseFloat(computedStyle['borderLeftWidth']) -
          parseFloat(computedStyle['paddingLeft']) -
          parseFloat(computedStyle['paddingRight']) -
          parseFloat(computedStyle['borderRightWidth']);
        const height =
          targetElement.offsetHeight -
          parseFloat(computedStyle['borderTopWidth']) -
          parseFloat(computedStyle['paddingTop']) -
          parseFloat(computedStyle['paddingBottom']) -
          parseFloat(computedStyle['borderBottomWidth']);
        if (!isNaN(width) && !isNaN(height)) {
          size = [Math.max(0, width), Math.max(0, height)];
          if (
            !hasArea(size) &&
            !!(
              targetElement.offsetWidth ||
              targetElement.offsetHeight ||
              targetElement.getClientRects().length
            )
          ) {
            warn(
              "No map visible because the map container's width or height are 0.",
            );
          }
        }
      }

      const oldSize = this.getSize();
      if (size && (!oldSize || !equals$2(size, oldSize))) {
        this.setSize(size);
        this.updateViewportSize_(size);
      }
    }

    /**
     * Recomputes the viewport size and save it on the view object (if any)
     * @param {import("./size.js").Size|undefined} size The size.
     * @private
     */
    updateViewportSize_(size) {
      const view = this.getView();
      if (view) {
        view.setViewportSize(size);
      }
    }
  };

  /**
   * @param {MapOptions} options Map options.
   * @return {MapOptionsInternal} Internal map options.
   */
  function createOptionsInternal(options) {
    /**
     * @type {HTMLElement|Document}
     */
    let keyboardEventTarget = null;
    if (options.keyboardEventTarget !== undefined) {
      keyboardEventTarget =
        typeof options.keyboardEventTarget === 'string'
          ? document.getElementById(options.keyboardEventTarget)
          : options.keyboardEventTarget;
    }

    /**
     * @type {Object<string, *>}
     */
    const values = {};

    const layerGroup =
      options.layers &&
      typeof (/** @type {?} */ (options.layers).getLayers) === 'function'
        ? /** @type {LayerGroup} */ (options.layers)
        : new LayerGroup({
            layers:
              /** @type {Collection<import("./layer/Base.js").default>|Array<import("./layer/Base.js").default>} */ (
                options.layers
              ),
          });
    values[MapProperty.LAYERGROUP] = layerGroup;

    values[MapProperty.TARGET] = options.target;

    values[MapProperty.VIEW] =
      options.view instanceof View ? options.view : new View();

    /** @type {Collection<import("./control/Control.js").default>} */
    let controls;
    if (options.controls !== undefined) {
      if (Array.isArray(options.controls)) {
        controls = new Collection(options.controls.slice());
      } else {
        assert(
          typeof (/** @type {?} */ (options.controls).getArray) === 'function',
          'Expected `controls` to be an array or an `ol/Collection.js`',
        );
        controls = options.controls;
      }
    }

    /** @type {Collection<import("./interaction/Interaction").default>} */
    let interactions;
    if (options.interactions !== undefined) {
      if (Array.isArray(options.interactions)) {
        interactions = new Collection(options.interactions.slice());
      } else {
        assert(
          typeof (/** @type {?} */ (options.interactions).getArray) ===
            'function',
          'Expected `interactions` to be an array or an `ol/Collection.js`',
        );
        interactions = options.interactions;
      }
    }

    /** @type {Collection<import("./Overlay.js").default>} */
    let overlays;
    if (options.overlays !== undefined) {
      if (Array.isArray(options.overlays)) {
        overlays = new Collection(options.overlays.slice());
      } else {
        assert(
          typeof (/** @type {?} */ (options.overlays).getArray) === 'function',
          'Expected `overlays` to be an array or an `ol/Collection.js`',
        );
        overlays = options.overlays;
      }
    } else {
      overlays = new Collection();
    }

    return {
      controls: controls,
      interactions: interactions,
      keyboardEventTarget: keyboardEventTarget,
      overlays: overlays,
      values: values,
    };
  }

  /**
   * @module ol/Overlay
   */

  /**
   * @typedef {'bottom-left' | 'bottom-center' | 'bottom-right' | 'center-left' | 'center-center' | 'center-right' | 'top-left' | 'top-center' | 'top-right'} Positioning
   * The overlay position: `'bottom-left'`, `'bottom-center'`,  `'bottom-right'`,
   * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,
   * `'top-center'`, or `'top-right'`.
   */

  /**
   * @typedef {Object} Options
   * @property {number|string} [id] Set the overlay id. The overlay id can be used
   * with the {@link module:ol/Map~Map#getOverlayById} method.
   * @property {HTMLElement} [element] The overlay element.
   * @property {Array<number>} [offset=[0, 0]] Offsets in pixels used when positioning
   * the overlay. The first element in the
   * array is the horizontal offset. A positive value shifts the overlay right.
   * The second element in the array is the vertical offset. A positive value
   * shifts the overlay down.
   * @property {import("./coordinate.js").Coordinate} [position] The overlay position
   * in map projection.
   * @property {Positioning} [positioning='top-left'] Defines how
   * the overlay is actually positioned with respect to its `position` property.
   * Possible values are `'bottom-left'`, `'bottom-center'`, `'bottom-right'`,
   * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,
   * `'top-center'`, and `'top-right'`.
   * @property {boolean} [stopEvent=true] Whether event propagation to the map
   * viewport should be stopped. If `true` the overlay is placed in the same
   * container as that of the controls (CSS class name
   * `ol-overlaycontainer-stopevent`); if `false` it is placed in the container
   * with CSS class name specified by the `className` property.
   * @property {boolean} [insertFirst=true] Whether the overlay is inserted first
   * in the overlay container, or appended. If the overlay is placed in the same
   * container as that of the controls (see the `stopEvent` option) you will
   * probably set `insertFirst` to `true` so the overlay is displayed below the
   * controls.
   * @property {PanIntoViewOptions|boolean} [autoPan=false] Pan the map when calling
   * `setPosition`, so that the overlay is entirely visible in the current viewport.
   * @property {string} [className='ol-overlay-container ol-selectable'] CSS class
   * name.
   */

  /**
   * @typedef {Object} PanOptions
   * @property {number} [duration=1000] The duration of the animation in
   * milliseconds.
   * @property {function(number):number} [easing] The easing function to use. Can
   * be one from {@link module:ol/easing} or a custom function.
   * Default is {@link module:ol/easing.inAndOut}.
   */

  /**
   * @typedef {Object} PanIntoViewOptions
   * @property {PanOptions} [animation={}] The animation parameters for the pan
   * @property {number} [margin=20] The margin (in pixels) between the
   * overlay and the borders of the map when panning into view.
   */

  /**
   * @enum {string}
   * @protected
   */
  const Property$1 = {
    ELEMENT: 'element',
    MAP: 'map',
    OFFSET: 'offset',
    POSITION: 'position',
    POSITIONING: 'positioning',
  };

  /**
   * @typedef {import("./ObjectEventType").Types|'change:element'|'change:map'|'change:offset'|'change:position'|
   *   'change:positioning'} OverlayObjectEventTypes
   */

  /***
   * @template Return
   * @typedef {import("./Observable").OnSignature<import("./Observable").EventTypes, import("./events/Event.js").default, Return> &
   *   import("./Observable").OnSignature<OverlayObjectEventTypes, import("./Object").ObjectEvent, Return> &
   *   import("./Observable").CombinedOnSignature<import("./Observable").EventTypes|OverlayObjectEventTypes, Return>} OverlayOnSignature
   */

  /**
   * @classdesc
   * An element to be displayed over the map and attached to a single map
   * location.  Like {@link module:ol/control/Control~Control}, Overlays are
   * visible widgets. Unlike Controls, they are not in a fixed position on the
   * screen, but are tied to a geographical coordinate, so panning the map will
   * move an Overlay but not a Control.
   *
   * Example:
   *
   *     import Overlay from 'ol/Overlay.js';
   *
   *     // ...
   *     const popup = new Overlay({
   *       element: document.getElementById('popup'),
   *     });
   *     popup.setPosition(coordinate);
   *     map.addOverlay(popup);
   *
   * @api
   */
  class Overlay extends BaseObject {
    /**
     * @param {Options} options Overlay options.
     */
    constructor(options) {
      super();

      /***
       * @type {OverlayOnSignature<import("./events").EventsKey>}
       */
      this.on;

      /***
       * @type {OverlayOnSignature<import("./events").EventsKey>}
       */
      this.once;

      /***
       * @type {OverlayOnSignature<void>}
       */
      this.un;

      /**
       * @protected
       * @type {Options}
       */
      this.options = options;

      /**
       * @protected
       * @type {number|string|undefined}
       */
      this.id = options.id;

      /**
       * @protected
       * @type {boolean}
       */
      this.insertFirst =
        options.insertFirst !== undefined ? options.insertFirst : true;

      /**
       * @protected
       * @type {boolean}
       */
      this.stopEvent = options.stopEvent !== undefined ? options.stopEvent : true;

      /**
       * @protected
       * @type {HTMLElement}
       */
      this.element = document.createElement('div');
      this.element.className =
        options.className !== undefined
          ? options.className
          : 'ol-overlay-container ' + CLASS_SELECTABLE;
      this.element.style.position = 'absolute';
      this.element.style.pointerEvents = 'auto';

      /**
       * @protected
       * @type {PanIntoViewOptions|undefined}
       */
      this.autoPan = options.autoPan === true ? {} : options.autoPan || undefined;

      /**
       * @protected
       * @type {{transform_: string,
       *         visible: boolean}}
       */
      this.rendered = {
        transform_: '',
        visible: true,
      };

      /**
       * @protected
       * @type {?import("./events.js").EventsKey}
       */
      this.mapPostrenderListenerKey = null;

      this.addChangeListener(Property$1.ELEMENT, this.handleElementChanged);
      this.addChangeListener(Property$1.MAP, this.handleMapChanged);
      this.addChangeListener(Property$1.OFFSET, this.handleOffsetChanged);
      this.addChangeListener(Property$1.POSITION, this.handlePositionChanged);
      this.addChangeListener(Property$1.POSITIONING, this.handlePositioningChanged);

      if (options.element !== undefined) {
        this.setElement(options.element);
      }

      this.setOffset(options.offset !== undefined ? options.offset : [0, 0]);

      this.setPositioning(options.positioning || 'top-left');

      if (options.position !== undefined) {
        this.setPosition(options.position);
      }
    }

    /**
     * Get the DOM element of this overlay.
     * @return {HTMLElement|undefined} The Element containing the overlay.
     * @observable
     * @api
     */
    getElement() {
      return /** @type {HTMLElement|undefined} */ (this.get(Property$1.ELEMENT));
    }

    /**
     * Get the overlay identifier which is set on constructor.
     * @return {number|string|undefined} Id.
     * @api
     */
    getId() {
      return this.id;
    }

    /**
     * Get the map associated with this overlay.
     * @return {import("./Map.js").default|null} The map that the
     * overlay is part of.
     * @observable
     * @api
     */
    getMap() {
      return /** @type {import("./Map.js").default|null} */ (
        this.get(Property$1.MAP) || null
      );
    }

    /**
     * Get the offset of this overlay.
     * @return {Array<number>} The offset.
     * @observable
     * @api
     */
    getOffset() {
      return /** @type {Array<number>} */ (this.get(Property$1.OFFSET));
    }

    /**
     * Get the current position of this overlay.
     * @return {import("./coordinate.js").Coordinate|undefined} The spatial point that the overlay is
     *     anchored at.
     * @observable
     * @api
     */
    getPosition() {
      return /** @type {import("./coordinate.js").Coordinate|undefined} */ (
        this.get(Property$1.POSITION)
      );
    }

    /**
     * Get the current positioning of this overlay.
     * @return {Positioning} How the overlay is positioned
     *     relative to its point on the map.
     * @observable
     * @api
     */
    getPositioning() {
      return /** @type {Positioning} */ (this.get(Property$1.POSITIONING));
    }

    /**
     * @protected
     */
    handleElementChanged() {
      removeChildren(this.element);
      const element = this.getElement();
      if (element) {
        this.element.appendChild(element);
      }
    }

    /**
     * @protected
     */
    handleMapChanged() {
      if (this.mapPostrenderListenerKey) {
        this.element?.remove();
        unlistenByKey(this.mapPostrenderListenerKey);
        this.mapPostrenderListenerKey = null;
      }
      const map = this.getMap();
      if (map) {
        this.mapPostrenderListenerKey = listen(
          map,
          MapEventType.POSTRENDER,
          this.render,
          this,
        );
        this.updatePixelPosition();
        const container = this.stopEvent
          ? map.getOverlayContainerStopEvent()
          : map.getOverlayContainer();
        if (this.insertFirst) {
          container.insertBefore(this.element, container.childNodes[0] || null);
        } else {
          container.appendChild(this.element);
        }
        this.performAutoPan();
      }
    }

    /**
     * @protected
     */
    render() {
      this.updatePixelPosition();
    }

    /**
     * @protected
     */
    handleOffsetChanged() {
      this.updatePixelPosition();
    }

    /**
     * @protected
     */
    handlePositionChanged() {
      this.updatePixelPosition();
      this.performAutoPan();
    }

    /**
     * @protected
     */
    handlePositioningChanged() {
      this.updatePixelPosition();
    }

    /**
     * Set the DOM element to be associated with this overlay.
     * @param {HTMLElement|undefined} element The Element containing the overlay.
     * @observable
     * @api
     */
    setElement(element) {
      this.set(Property$1.ELEMENT, element);
    }

    /**
     * Set the map to be associated with this overlay.
     * @param {import("./Map.js").default|null} map The map that the
     * overlay is part of. Pass `null` to just remove the overlay from the current map.
     * @observable
     * @api
     */
    setMap(map) {
      this.set(Property$1.MAP, map);
    }

    /**
     * Set the offset for this overlay.
     * @param {Array<number>} offset Offset.
     * @observable
     * @api
     */
    setOffset(offset) {
      this.set(Property$1.OFFSET, offset);
    }

    /**
     * Set the position for this overlay. If the position is `undefined` the
     * overlay is hidden.
     * @param {import("./coordinate.js").Coordinate|undefined} position The spatial point that the overlay
     *     is anchored at.
     * @observable
     * @api
     */
    setPosition(position) {
      this.set(Property$1.POSITION, position);
    }

    /**
     * Pan the map so that the overlay is entirely visible in the current viewport
     * (if necessary) using the configured autoPan parameters
     * @protected
     */
    performAutoPan() {
      if (this.autoPan) {
        this.panIntoView(this.autoPan);
      }
    }

    /**
     * Pan the map so that the overlay is entirely visible in the current viewport
     * (if necessary).
     * @param {PanIntoViewOptions} [panIntoViewOptions] Options for the pan action
     * @api
     */
    panIntoView(panIntoViewOptions) {
      const map = this.getMap();

      if (!map || !map.getTargetElement() || !this.get(Property$1.POSITION)) {
        return;
      }

      const mapRect = this.getRect(map.getTargetElement(), map.getSize());
      const element = this.getElement();
      const overlayRect = this.getRect(element, [
        outerWidth(element),
        outerHeight(element),
      ]);

      panIntoViewOptions = panIntoViewOptions || {};

      const myMargin =
        panIntoViewOptions.margin === undefined ? 20 : panIntoViewOptions.margin;
      if (!containsExtent(mapRect, overlayRect)) {
        // the overlay is not completely inside the viewport, so pan the map
        const offsetLeft = overlayRect[0] - mapRect[0];
        const offsetRight = mapRect[2] - overlayRect[2];
        const offsetTop = overlayRect[1] - mapRect[1];
        const offsetBottom = mapRect[3] - overlayRect[3];

        const delta = [0, 0];
        if (offsetLeft < 0) {
          // move map to the left
          delta[0] = offsetLeft - myMargin;
        } else if (offsetRight < 0) {
          // move map to the right
          delta[0] = Math.abs(offsetRight) + myMargin;
        }
        if (offsetTop < 0) {
          // move map up
          delta[1] = offsetTop - myMargin;
        } else if (offsetBottom < 0) {
          // move map down
          delta[1] = Math.abs(offsetBottom) + myMargin;
        }

        if (delta[0] !== 0 || delta[1] !== 0) {
          const center = /** @type {import("./coordinate.js").Coordinate} */ (
            map.getView().getCenterInternal()
          );
          const centerPx = map.getPixelFromCoordinateInternal(center);
          if (!centerPx) {
            return;
          }
          const newCenterPx = [centerPx[0] + delta[0], centerPx[1] + delta[1]];

          const panOptions = panIntoViewOptions.animation || {};
          map.getView().animateInternal({
            center: map.getCoordinateFromPixelInternal(newCenterPx),
            duration: panOptions.duration,
            easing: panOptions.easing,
          });
        }
      }
    }

    /**
     * Get the extent of an element relative to the document
     * @param {HTMLElement} element The element.
     * @param {import("./size.js").Size} size The size of the element.
     * @return {import("./extent.js").Extent} The extent.
     * @protected
     */
    getRect(element, size) {
      const box = element.getBoundingClientRect();
      const offsetX = box.left + window.pageXOffset;
      const offsetY = box.top + window.pageYOffset;
      return [offsetX, offsetY, offsetX + size[0], offsetY + size[1]];
    }

    /**
     * Set the positioning for this overlay.
     * @param {Positioning} positioning how the overlay is
     *     positioned relative to its point on the map.
     * @observable
     * @api
     */
    setPositioning(positioning) {
      this.set(Property$1.POSITIONING, positioning);
    }

    /**
     * Modify the visibility of the element.
     * @param {boolean} visible Element visibility.
     * @protected
     */
    setVisible(visible) {
      if (this.rendered.visible !== visible) {
        this.element.style.display = visible ? '' : 'none';
        this.rendered.visible = visible;
      }
    }

    /**
     * Update pixel position.
     * @protected
     */
    updatePixelPosition() {
      const map = this.getMap();
      const position = this.getPosition();
      if (!map || !map.isRendered() || !position) {
        this.setVisible(false);
        return;
      }

      const pixel = map.getPixelFromCoordinate(position);
      const mapSize = map.getSize();
      this.updateRenderedPosition(pixel, mapSize);
    }

    /**
     * @param {import("./pixel.js").Pixel} pixel The pixel location.
     * @param {import("./size.js").Size|undefined} mapSize The map size.
     * @protected
     */
    updateRenderedPosition(pixel, mapSize) {
      const style = this.element.style;
      const offset = this.getOffset();

      const positioning = this.getPositioning();

      this.setVisible(true);

      const x = `${pixel[0] + offset[0]}px`;
      const y = `${pixel[1] + offset[1]}px`;
      let posX = '0%';
      let posY = '0%';
      if (
        positioning == 'bottom-right' ||
        positioning == 'center-right' ||
        positioning == 'top-right'
      ) {
        posX = '-100%';
      } else if (
        positioning == 'bottom-center' ||
        positioning == 'center-center' ||
        positioning == 'top-center'
      ) {
        posX = '-50%';
      }
      if (
        positioning == 'bottom-left' ||
        positioning == 'bottom-center' ||
        positioning == 'bottom-right'
      ) {
        posY = '-100%';
      } else if (
        positioning == 'center-left' ||
        positioning == 'center-center' ||
        positioning == 'center-right'
      ) {
        posY = '-50%';
      }
      const transform = `translate(${posX}, ${posY}) translate(${x}, ${y})`;
      if (this.rendered.transform_ != transform) {
        this.rendered.transform_ = transform;
        style.transform = transform;
      }
    }

    /**
     * returns the options this Overlay has been created with
     * @return {Options} overlay options
     */
    getOptions() {
      return this.options;
    }
  }

  /**
   * @module ol/vec/mat4
   */

  /** @typedef {Array<number>} Mat4 */

  /**
   * @return {Mat4} "4x4 matrix representing a 3D identity transform."
   */
  function create$2() {
    return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  }

  /**
   * @param {Mat4} mat4 Flattened 4x4 matrix receiving the result.
   * @param {import("../transform.js").Transform} transform Transformation matrix.
   * @return {Mat4} "2D transformation matrix as flattened 4x4 matrix."
   */
  function fromTransform(mat4, transform) {
    mat4[0] = transform[0];
    mat4[1] = transform[1];
    mat4[4] = transform[2];
    mat4[5] = transform[3];
    mat4[12] = transform[4];
    mat4[13] = transform[5];
    return mat4;
  }

  /**
   * Generates a orthogonal projection matrix with the given bounds
   *
   * @param {number} left Left bound of the frustum
   * @param {number} right Right bound of the frustum
   * @param {number} bottom Bottom bound of the frustum
   * @param {number} top Top bound of the frustum
   * @param {number} near Near bound of the frustum
   * @param {number} far Far bound of the frustum
   * @param {Mat4} [out] mat4 frustum matrix will be written into
   * @return {Mat4} out
   */
  function orthographic(left, right, bottom, top, near, far, out) {
    out = out ?? create$2();
    const lr = 1 / (left - right),
      bt = 1 / (bottom - top),
      nf = 1 / (near - far);
    out[0] = -2 * lr;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = -2 * bt;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 2 * nf;
    out[11] = 0;
    out[12] = (left + right) * lr;
    out[13] = (top + bottom) * bt;
    out[14] = (far + near) * nf;
    out[15] = 1;
    return out;
  }

  /**
   * Scales the mat4 by the dimensions in the given vec3
   *
   * @param {Mat4} m The matrix to scale.
   * @param {number} x How much to scale in the x direction.
   * @param {number} y How much to scale in the y direction.
   * @param {number} z How much to scale in the z direction.
   * @param {Mat4} [out] The matrix to write to.
   * @return {Mat4} out
   */
  function scale(m, x, y, z, out) {
    out = out ?? create$2();
    out[0] = m[0] * x;
    out[1] = m[1] * x;
    out[2] = m[2] * x;
    out[3] = m[3] * x;
    out[4] = m[4] * y;
    out[5] = m[5] * y;
    out[6] = m[6] * y;
    out[7] = m[7] * y;
    out[8] = m[8] * z;
    out[9] = m[9] * z;
    out[10] = m[10] * z;
    out[11] = m[11] * z;
    out[12] = m[12];
    out[13] = m[13];
    out[14] = m[14];
    out[15] = m[15];
    return out;
  }

  /**
   * Translate a matrix.
   *
   * @param {Mat4} m the matrix to translate
   * @param {number} x How much to translate in the x direction.
   * @param {number} y How much to translate in the y direction.
   * @param {number} z How much to translate in the z direction.
   * @param {Mat4} [out] the receiving matrix
   * @return {Mat4} out
   */
  function translate(m, x, y, z, out) {
    out = out ?? create$2();
    let a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23;

    if (m === out) {
      out[12] = m[0] * x + m[4] * y + m[8] * z + m[12];
      out[13] = m[1] * x + m[5] * y + m[9] * z + m[13];
      out[14] = m[2] * x + m[6] * y + m[10] * z + m[14];
      out[15] = m[3] * x + m[7] * y + m[11] * z + m[15];
    } else {
      a00 = m[0];
      a01 = m[1];
      a02 = m[2];
      a03 = m[3];
      a10 = m[4];
      a11 = m[5];
      a12 = m[6];
      a13 = m[7];
      a20 = m[8];
      a21 = m[9];
      a22 = m[10];
      a23 = m[11];

      out[0] = a00;
      out[1] = a01;
      out[2] = a02;
      out[3] = a03;
      out[4] = a10;
      out[5] = a11;
      out[6] = a12;
      out[7] = a13;
      out[8] = a20;
      out[9] = a21;
      out[10] = a22;
      out[11] = a23;

      out[12] = a00 * x + a10 * y + a20 * z + m[12];
      out[13] = a01 * x + a11 * y + a21 * z + m[13];
      out[14] = a02 * x + a12 * y + a22 * z + m[14];
      out[15] = a03 * x + a13 * y + a23 * z + m[15];
    }

    return out;
  }

  /**
   * @param {number} x x translation.
   * @param {number} y y translation.
   * @param {number} z z translation.
   * @param {Mat4} [out] optional matrix to store result
   * @return {Mat4} out
   */
  function translation(x, y, z, out) {
    out = out ?? create$2();

    out[0] = 1;
    out[1] = 0;
    out[2] = 0;
    out[3] = 0;
    out[4] = 0;
    out[5] = 1;
    out[6] = 0;
    out[7] = 0;
    out[8] = 0;
    out[9] = 0;
    out[10] = 1;
    out[11] = 0;
    out[12] = x;
    out[13] = y;
    out[14] = z;
    out[15] = 1;

    return out;
  }

  /**
   * @module ol/webgl
   */


  /**
   * Constants taken from goog.webgl
   */

  /**
   * Used by {@link module:ol/webgl/Helper~WebGLHelper} for buffers containing vertices data, such as
   * position, color, texture coordinate, etc. These vertices are then referenced by an index buffer
   * to be drawn on screen (see {@link module:ol/webgl.ELEMENT_ARRAY_BUFFER}).
   * @const
   * @type {number}
   * @api
   */
  const ARRAY_BUFFER = 0x8892;

  /**
   * Used by {@link module:ol/webgl/Helper~WebGLHelper} for buffers containing indices data.
   * Index buffers are essentially lists of references to vertices defined in a vertex buffer
   * (see {@link module:ol/webgl.ARRAY_BUFFER}), and define the primitives (triangles) to be drawn.
   * @const
   * @type {number}
   * @api
   */
  const ELEMENT_ARRAY_BUFFER = 0x8893;

  /**
   * Used by {link module:ol/webgl/Buffer~WebGLArrayBuffer}.
   * @const
   * @type {number}
   * @api
   */
  const STATIC_DRAW = 0x88e4;

  /**
   * Used by {link module:ol/webgl/Buffer~WebGLArrayBuffer}.
   * @const
   * @type {number}
   * @api
   */
  const DYNAMIC_DRAW = 0x88e8;

  /**
   * @const
   * @type {number}
   */
  const UNSIGNED_BYTE = 0x1401;

  /**
   * @const
   * @type {number}
   */
  const UNSIGNED_SHORT = 0x1403;

  /**
   * @const
   * @type {number}
   */
  const UNSIGNED_INT = 0x1405;

  /**
   * @const
   * @type {number}
   */
  const FLOAT = 0x1406;

  /**
    end of goog.webgl constants
   */

  /**
   * @const
   * @type {Array<string>}
   */
  const CONTEXT_IDS = ['experimental-webgl', 'webgl', 'webkit-3d', 'moz-webgl'];

  /**
   * @param {HTMLCanvasElement} canvas Canvas.
   * @param {Object} [attributes] Attributes.
   * @return {WebGLRenderingContext|null} WebGL rendering context.
   */
  function getContext(canvas, attributes) {
    attributes = Object.assign(
      {
        preserveDrawingBuffer: true,
        antialias: SAFARI_BUG_237906 ? false : true, // https://bugs.webkit.org/show_bug.cgi?id=237906
      },
      attributes,
    );
    const ii = CONTEXT_IDS.length;
    for (let i = 0; i < ii; ++i) {
      try {
        const context = canvas.getContext(CONTEXT_IDS[i], attributes);
        if (context) {
          return /** @type {!WebGLRenderingContext} */ (context);
        }
      } catch {
        // pass
      }
    }
    return null;
  }

  /**
   * @module ol/webgl/Buffer
   */

  /**
   * Used to describe the intended usage for the data: `STATIC_DRAW`, `STREAM_DRAW`
   * or `DYNAMIC_DRAW`.
   * @enum {number}
   */
  const BufferUsage = {
    STATIC_DRAW: STATIC_DRAW};

  /**
   * @classdesc
   * Object used to store an array of data as well as usage information for that data.
   * Stores typed arrays internally, either Float32Array or Uint16/32Array depending on
   * the buffer type (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER) and available extensions.
   *
   * To populate the array, you can either use:
   * A size using `#ofSize(buffer)`
   * An `ArrayBuffer` object using `#fromArrayBuffer(buffer)`
   * A plain array using `#fromArray(array)`
   *
   * Note:
   * See the documentation of [WebGLRenderingContext.bufferData](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData)
   * for more info on buffer usage.
   */
  class WebGLArrayBuffer {
    /**
     * @param {number} type Buffer type, either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER.
     * @param {number} [usage] Intended usage, either `STATIC_DRAW`, `STREAM_DRAW` or `DYNAMIC_DRAW`.
     * Default is `STATIC_DRAW`.
     */
    constructor(type, usage) {
      /**
       * @private
       * @type {Float32Array|Uint32Array|null}
       */
      this.array_ = null;

      /**
       * @private
       * @type {number}
       */
      this.type_ = type;

      assert(
        type === ARRAY_BUFFER || type === ELEMENT_ARRAY_BUFFER,
        'A `WebGLArrayBuffer` must either be of type `ELEMENT_ARRAY_BUFFER` or `ARRAY_BUFFER`',
      );

      /**
       * @private
       * @type {number}
       */
      this.usage_ = usage !== undefined ? usage : BufferUsage.STATIC_DRAW;
    }

    /**
     * Populates the buffer with an array of the given size (all values will be zeroes).
     * @param {number} size Array size
     * @return {WebGLArrayBuffer} This
     */
    ofSize(size) {
      this.array_ = new (getArrayClassForType(this.type_))(size);
      return this;
    }

    /**
     * Populates the buffer with an array of the given size.
     * @param {Array<number>} array Numerical array
     * @return {WebGLArrayBuffer} This
     */
    fromArray(array) {
      this.array_ = getArrayClassForType(this.type_).from(array);
      return this;
    }

    /**
     * Populates the buffer with a raw binary array buffer.
     * @param {ArrayBuffer} buffer Raw binary buffer to populate the array with. Note that this buffer must have been
     * initialized for the same typed array class.
     * @return {WebGLArrayBuffer} This
     */
    fromArrayBuffer(buffer) {
      this.array_ = new (getArrayClassForType(this.type_))(buffer);
      return this;
    }

    /**
     * @return {number} Buffer type.
     */
    getType() {
      return this.type_;
    }

    /**
     * Will return null if the buffer was not initialized
     * @return {Float32Array|Uint32Array|null} Array.
     */
    getArray() {
      return this.array_;
    }

    /**
     * @param {Float32Array|Uint32Array} array Array.
     */
    setArray(array) {
      const ArrayType = getArrayClassForType(this.type_);
      if (!(array instanceof ArrayType)) {
        throw new Error(`Expected ${ArrayType}`);
      }
      this.array_ = array;
    }

    /**
     * @return {number} Usage.
     */
    getUsage() {
      return this.usage_;
    }

    /**
     * Will return 0 if the buffer is not initialized
     * @return {number} Array size
     */
    getSize() {
      return this.array_ ? this.array_.length : 0;
    }
  }

  /**
   * Returns a typed array constructor based on the given buffer type
   * @param {number} type Buffer type, either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER.
   * @return {Float32ArrayConstructor|Uint32ArrayConstructor} The typed array class to use for this buffer.
   */
  function getArrayClassForType(type) {
    switch (type) {
      case ARRAY_BUFFER:
        return Float32Array;
      case ELEMENT_ARRAY_BUFFER:
        return Uint32Array;
      default:
        return Float32Array;
    }
  }

  /**
   * @module ol/webgl/ContextEventType
   */

  /**
   * @enum {string}
   */
  var ContextEventType = {
    LOST: 'webglcontextlost',
    RESTORED: 'webglcontextrestored',
  };

  /**
   * @module ol/webgl/PostProcessingPass
   */


  const DEFAULT_VERTEX_SHADER = `
  precision mediump float;

  attribute vec2 a_position;
  varying vec2 v_texCoord;
  varying vec2 v_screenCoord;

  uniform vec2 u_screenSize;

  void main() {
    v_texCoord = a_position * 0.5 + 0.5;
    v_screenCoord = v_texCoord * u_screenSize;
    gl_Position = vec4(a_position, 0.0, 1.0);
  }
`;

  const DEFAULT_FRAGMENT_SHADER = `
  precision mediump float;

  uniform sampler2D u_image;
  uniform float u_opacity;

  varying vec2 v_texCoord;

  void main() {
    gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;
  }
`;

  /**
   * @typedef {Object} Options
   * @property {WebGLRenderingContext} webGlContext WebGL context; mandatory.
   * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than
   * the main canvas that will then be sampled up (useful for saving resource on blur steps).
   * @property {string} [vertexShader] Vertex shader source
   * @property {string} [fragmentShader] Fragment shader source
   * @property {Object<string,import("./Helper").UniformValue>} [uniforms] Uniform definitions for the post process step
   */

  /**
   * @typedef {Object} UniformInternalDescription
   * @property {import("./Helper").UniformValue} value Value
   * @property {WebGLUniformLocation} location Location
   * @property {WebGLTexture} [texture] Texture
   * @private
   */

  /**
   * @classdesc
   * This class is used to define Post Processing passes with custom shaders and uniforms.
   * This is used internally by {@link module:ol/webgl/Helper~WebGLHelper}.
   *
   * Please note that the final output on the DOM canvas is expected to have premultiplied alpha, which means that
   * a pixel which is 100% red with an opacity of 50% must have a color of (r=0.5, g=0, b=0, a=0.5).
   * Failing to provide pixel colors with premultiplied alpha will result in render anomalies.
   *
   * The default post-processing pass does *not* multiply color values with alpha value, it expects color values to be
   * premultiplied.
   *
   * Default shaders are shown hereafter:
   *
   * Vertex shader:
   *
   *   ```
   *   precision mediump float;
   *
   *   attribute vec2 a_position;
   *   varying vec2 v_texCoord;
   *   varying vec2 v_screenCoord;
   *
   *   uniform vec2 u_screenSize;
   *
   *   void main() {
   *     v_texCoord = a_position * 0.5 + 0.5;
   *     v_screenCoord = v_texCoord * u_screenSize;
   *     gl_Position = vec4(a_position, 0.0, 1.0);
   *   }
   *   ```
   *
   * Fragment shader:
   *
   *   ```
   *   precision mediump float;
   *
   *   uniform sampler2D u_image;
   *   uniform float u_opacity;
   *
   *   varying vec2 v_texCoord;
   *
   *   void main() {
   *     gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;
   *   }
   *   ```
   */
  class WebGLPostProcessingPass {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      /**
       * @private
       */
      this.gl_ = options.webGlContext;
      const gl = this.gl_;

      /**
       * @private
       */
      this.scaleRatio_ = options.scaleRatio || 1;

      /**
       * @type {WebGLTexture}
       * @private
       */
      this.renderTargetTexture_ = gl.createTexture();

      /**
       * @type {import('../size.js').Size|null}
       * @private
       */
      this.renderTargetTextureSize_ = null;

      /**
       * @private
       */
      this.frameBuffer_ = gl.createFramebuffer();
      /**
       * @private
       */
      this.depthBuffer_ = gl.createRenderbuffer();

      // compile the program for the frame buffer
      // TODO: make compilation errors show up
      const vertexShader = gl.createShader(gl.VERTEX_SHADER);
      gl.shaderSource(
        vertexShader,
        options.vertexShader || DEFAULT_VERTEX_SHADER,
      );
      gl.compileShader(vertexShader);
      const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      gl.shaderSource(
        fragmentShader,
        options.fragmentShader || DEFAULT_FRAGMENT_SHADER,
      );
      gl.compileShader(fragmentShader);
      /**
       * @private
       */
      this.renderTargetProgram_ = gl.createProgram();
      gl.attachShader(this.renderTargetProgram_, vertexShader);
      gl.attachShader(this.renderTargetProgram_, fragmentShader);
      gl.linkProgram(this.renderTargetProgram_);

      // bind the vertices buffer for the frame buffer
      /**
       * @private
       */
      this.renderTargetVerticesBuffer_ = gl.createBuffer();
      const verticesArray = [-1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1];
      gl.bindBuffer(gl.ARRAY_BUFFER, this.renderTargetVerticesBuffer_);
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(verticesArray),
        gl.STATIC_DRAW,
      );

      /**
       * @private
       */
      this.renderTargetAttribLocation_ = gl.getAttribLocation(
        this.renderTargetProgram_,
        'a_position',
      );
      /**
       * @private
       */
      this.renderTargetUniformLocation_ = gl.getUniformLocation(
        this.renderTargetProgram_,
        'u_screenSize',
      );
      /**
       * @private
       */
      this.renderTargetOpacityLocation_ = gl.getUniformLocation(
        this.renderTargetProgram_,
        'u_opacity',
      );
      /**
       * @private
       */
      this.renderTargetTextureLocation_ = gl.getUniformLocation(
        this.renderTargetProgram_,
        'u_image',
      );

      /**
       * Holds info about custom uniforms used in the post processing pass
       * @type {Array<UniformInternalDescription>}
       * @private
       */
      this.uniforms_ = [];
      options.uniforms &&
        Object.keys(options.uniforms).forEach((name) => {
          this.uniforms_.push({
            value: options.uniforms[name],
            location: gl.getUniformLocation(this.renderTargetProgram_, name),
          });
        });
    }

    getRenderTargetTexture() {
      return this.renderTargetTexture_;
    }

    /**
     * Get the WebGL rendering context
     * @return {WebGLRenderingContext} The rendering context.
     */
    getGL() {
      return this.gl_;
    }

    /**
     * Initialize the render target texture of the post process, make sure it is at the
     * right size and bind it as a render target for the next draw calls.
     * The last step to be initialized will be the one where the primitives are rendered.
     * @param {import("../Map.js").FrameState} frameState current frame state
     */
    init(frameState) {
      const gl = this.getGL();
      const textureSize = [
        gl.drawingBufferWidth * this.scaleRatio_,
        gl.drawingBufferHeight * this.scaleRatio_,
      ];

      // rendering goes to my buffer
      gl.bindFramebuffer(gl.FRAMEBUFFER, this.getFrameBuffer());
      gl.bindRenderbuffer(gl.RENDERBUFFER, this.getDepthBuffer());
      gl.viewport(0, 0, textureSize[0], textureSize[1]);

      // if size has changed: adjust canvas & render target texture
      if (
        !this.renderTargetTextureSize_ ||
        this.renderTargetTextureSize_[0] !== textureSize[0] ||
        this.renderTargetTextureSize_[1] !== textureSize[1]
      ) {
        this.renderTargetTextureSize_ = textureSize;

        // create a new texture
        const level = 0;
        const internalFormat = gl.RGBA;
        const border = 0;
        const format = gl.RGBA;
        const type = gl.UNSIGNED_BYTE;
        const data = null;
        gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);
        gl.texImage2D(
          gl.TEXTURE_2D,
          level,
          internalFormat,
          textureSize[0],
          textureSize[1],
          border,
          format,
          type,
          data,
        );

        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

        // bind the texture to the framebuffer
        gl.framebufferTexture2D(
          gl.FRAMEBUFFER,
          gl.COLOR_ATTACHMENT0,
          gl.TEXTURE_2D,
          this.renderTargetTexture_,
          0,
        );

        gl.renderbufferStorage(
          gl.RENDERBUFFER,
          gl.DEPTH_COMPONENT16,
          textureSize[0],
          textureSize[1],
        );
        gl.framebufferRenderbuffer(
          gl.FRAMEBUFFER,
          gl.DEPTH_ATTACHMENT,
          gl.RENDERBUFFER,
          this.depthBuffer_,
        );
      }
    }

    /**
     * Render to the next postprocessing pass (or to the canvas if final pass).
     * @param {import("../Map.js").FrameState} frameState current frame state
     * @param {WebGLPostProcessingPass} [nextPass] Next pass, optional
     * @param {function(WebGLRenderingContext, import("../Map.js").FrameState):void} [preCompose] Called before composing.
     * @param {function(WebGLRenderingContext, import("../Map.js").FrameState):void} [postCompose] Called before composing.
     */
    apply(frameState, nextPass, preCompose, postCompose) {
      const gl = this.getGL();
      const size = frameState.size;

      gl.bindFramebuffer(
        gl.FRAMEBUFFER,
        nextPass ? nextPass.getFrameBuffer() : null,
      );
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);

      if (!nextPass) {
        // clear the canvas if we are the first to render to it
        // and preserveDrawingBuffer is true
        const canvasId = getUid(gl.canvas);
        if (!frameState.renderTargets[canvasId]) {
          const attributes = gl.getContextAttributes();
          if (attributes && attributes.preserveDrawingBuffer) {
            gl.clearColor(0.0, 0.0, 0.0, 0.0);
            gl.clearDepth(1.0);
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
          }

          frameState.renderTargets[canvasId] = true;
        }
      }

      gl.disable(gl.DEPTH_TEST);
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
      gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);

      gl.bindBuffer(gl.ARRAY_BUFFER, this.renderTargetVerticesBuffer_);

      gl.useProgram(this.renderTargetProgram_);
      gl.enableVertexAttribArray(this.renderTargetAttribLocation_);
      gl.vertexAttribPointer(
        this.renderTargetAttribLocation_,
        2,
        gl.FLOAT,
        false,
        0,
        0,
      );
      gl.uniform2f(this.renderTargetUniformLocation_, size[0], size[1]);
      gl.uniform1i(this.renderTargetTextureLocation_, 0);

      const opacity = frameState.layerStatesArray[frameState.layerIndex].opacity;
      gl.uniform1f(this.renderTargetOpacityLocation_, opacity);

      this.applyUniforms(frameState);

      if (preCompose) {
        preCompose(gl, frameState);
      }
      gl.drawArrays(gl.TRIANGLES, 0, 6);
      if (postCompose) {
        postCompose(gl, frameState);
      }
    }

    /**
     * @return {WebGLFramebuffer} Frame buffer
     */
    getFrameBuffer() {
      return this.frameBuffer_;
    }

    /**
     * @return {WebGLRenderbuffer} Depth buffer
     */
    getDepthBuffer() {
      return this.depthBuffer_;
    }

    /**
     * Sets the custom uniforms based on what was given in the constructor.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @private
     */
    applyUniforms(frameState) {
      const gl = this.getGL();

      let value;
      let textureSlot = 1;
      this.uniforms_.forEach(function (uniform) {
        value =
          typeof uniform.value === 'function'
            ? uniform.value(frameState)
            : uniform.value;

        // apply value based on type
        if (value instanceof HTMLCanvasElement || value instanceof ImageData) {
          // create a texture & put data
          if (!uniform.texture) {
            uniform.texture = gl.createTexture();
          }
          gl.activeTexture(gl[`TEXTURE${textureSlot}`]);
          gl.bindTexture(gl.TEXTURE_2D, uniform.texture);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

          if (value instanceof ImageData) {
            gl.texImage2D(
              gl.TEXTURE_2D,
              0,
              gl.RGBA,
              gl.RGBA,
              value.width,
              value.height,
              0,
              gl.UNSIGNED_BYTE,
              new Uint8Array(value.data),
            );
          } else {
            gl.texImage2D(
              gl.TEXTURE_2D,
              0,
              gl.RGBA,
              gl.RGBA,
              gl.UNSIGNED_BYTE,
              value,
            );
          }

          // fill texture slots
          gl.uniform1i(uniform.location, textureSlot++);
        } else if (Array.isArray(value)) {
          switch (value.length) {
            case 2:
              gl.uniform2f(uniform.location, value[0], value[1]);
              return;
            case 3:
              gl.uniform3f(uniform.location, value[0], value[1], value[2]);
              return;
            case 4:
              gl.uniform4f(
                uniform.location,
                value[0],
                value[1],
                value[2],
                value[3],
              );
              return;
            default:
              return;
          }
        } else if (typeof value === 'number') {
          gl.uniform1f(uniform.location, value);
        }
      });
    }
  }

  /**
   * @module ol/webgl/Helper
   */

  /**
   * Names of uniforms made available to all shaders.
   * Please note: changing these *will* break custom shaders!
   * @enum {string}
   */
  const DefaultUniform = {
    PROJECTION_MATRIX: 'u_projectionMatrix',
    SCREEN_TO_WORLD_MATRIX: 'u_screenToWorldMatrix',
    TIME: 'u_time',
    ZOOM: 'u_zoom',
    RESOLUTION: 'u_resolution',
    ROTATION: 'u_rotation',
    VIEWPORT_SIZE_PX: 'u_viewportSizePx',
    PIXEL_RATIO: 'u_pixelRatio',
    HIT_DETECTION: 'u_hitDetection',
  };

  /**
   * Attribute types, either `UNSIGNED_BYTE`, `UNSIGNED_SHORT`, `UNSIGNED_INT` or `FLOAT`
   * Note: an attribute stored in a `Float32Array` should be of type `FLOAT`.
   * @enum {number}
   */
  const AttributeType = {
    UNSIGNED_BYTE: UNSIGNED_BYTE,
    UNSIGNED_SHORT: UNSIGNED_SHORT,
    UNSIGNED_INT: UNSIGNED_INT,
    FLOAT: FLOAT,
  };

  /**
   * Description of an attribute in a buffer
   * @typedef {Object} AttributeDescription
   * @property {string} name Attribute name to use in shaders
   * @property {number} size Number of components per attributes
   * @property {AttributeType} [type] Attribute type, i.e. number of bytes used to store the value. This is
   * determined by the class of typed array which the buffer uses (eg. `Float32Array` for a `FLOAT` attribute).
   * Default is `FLOAT`.
   */

  /**
   * @typedef {number|Array<number>|HTMLCanvasElement|HTMLImageElement|ImageData|WebGLTexture|import("../transform").Transform} UniformLiteralValue
   */

  /**
   * Uniform value can be a number, array of numbers (2 to 4), canvas element or a callback returning
   * one of the previous types.
   * @typedef {UniformLiteralValue|function(import("../Map.js").FrameState):UniformLiteralValue} UniformValue
   */

  /**
   * @typedef {Object} PostProcessesOptions
   * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than
   * the main canvas which will then be sampled up (useful for saving resource on blur steps).
   * @property {string} [vertexShader] Vertex shader source
   * @property {string} [fragmentShader] Fragment shader source
   * @property {Object<string,UniformValue>} [uniforms] Uniform definitions for the post process step
   */

  /**
   * @typedef {Object} Options
   * @property {Object<string,UniformValue>} [uniforms] Uniform definitions; property names must match the uniform
   * names in the provided or default shaders.
   * @property {Array<PostProcessesOptions>} [postProcesses] Post-processes definitions
   * @property {string} [canvasCacheKey] The cache key for the canvas.
   */

  /**
   * @typedef {Object} UniformInternalDescription
   * @property {string} name Name
   * @property {UniformValue} [value] Value
   * @property {UniformValue} [prevValue] The previous value.
   * @property {WebGLTexture} [texture] Texture
   * @private
   */

  /**
   * @typedef {Object} CanvasCacheItem
   * @property {WebGLRenderingContext} context The context of this canvas.
   * @property {number} users The count of users of this canvas.
   */

  /**
   * @type {Object<string,CanvasCacheItem>}
   */
  const canvasCache = {};

  /**
   * @param {string} key The cache key for the canvas.
   * @return {string} The shared cache key.
   */
  function getSharedCanvasCacheKey(key) {
    return 'shared/' + key;
  }

  let uniqueCanvasCacheKeyCount = 0;

  /**
   * @return {string} The unique cache key.
   */
  function getUniqueCanvasCacheKey() {
    const key = 'unique/' + uniqueCanvasCacheKeyCount;
    uniqueCanvasCacheKeyCount += 1;
    return key;
  }

  /**
   * @param {string} key The cache key for the canvas.
   * @return {WebGLRenderingContext} The canvas.
   */
  function getOrCreateContext(key) {
    let cacheItem = canvasCache[key];
    if (!cacheItem) {
      const canvas = document.createElement('canvas');
      canvas.width = 1;
      canvas.height = 1;
      canvas.style.position = 'absolute';
      canvas.style.left = '0';
      const context = getContext(canvas);
      cacheItem = {users: 0, context};
      canvasCache[key] = cacheItem;
    }

    cacheItem.users += 1;
    return cacheItem.context;
  }

  /**
   * @param {string} key The cache key for the canvas.
   */
  function releaseCanvas(key) {
    const cacheItem = canvasCache[key];
    if (!cacheItem) {
      return;
    }

    cacheItem.users -= 1;
    if (cacheItem.users > 0) {
      return;
    }

    const gl = cacheItem.context;
    const extension = gl.getExtension('WEBGL_lose_context');
    if (extension) {
      extension.loseContext();
    }
    const canvas = gl.canvas;
    canvas.width = 1;
    canvas.height = 1;

    delete canvasCache[key];
  }

  /**
   * @classdesc
   * This class is intended to provide low-level functions related to WebGL rendering, so that accessing
   * directly the WebGL API should not be required anymore.
   *
   * Several operations are handled by the `WebGLHelper` class:
   *
   * ### Define custom shaders and uniforms
   *
   *   Shaders* are low-level programs executed on the GPU and written in GLSL. There are two types of shaders:
   *
   *   Vertex shaders are used to manipulate the position and attribute of *vertices* of rendered primitives (ie. corners of a square).
   *   Outputs are:
   *
   *   `gl_Position`: position of the vertex in screen space
   *
   *   Varyings usually prefixed with `v_` are passed on to the fragment shader
   *
   *   Fragment shaders are used to control the actual color of the pixels drawn on screen. Their only output is `gl_FragColor`.
   *
   *   Both shaders can take *uniforms* or *attributes* as input. Attributes are explained later. Uniforms are common, read-only values that
   *   can be changed at every frame and can be of type float, arrays of float or images.
   *
   *   Shaders must be compiled and assembled into a program like so:
   *   ```js
   *   // here we simply create two shaders and assemble them in a program which is then used
   *   // for subsequent rendering calls; note how a frameState is required to set up a program,
   *   // as several default uniforms are computed from it (projection matrix, zoom level, etc.)
   *   const vertexShader = new WebGLVertex(VERTEX_SHADER);
   *   const fragmentShader = new WebGLFragment(FRAGMENT_SHADER);
   *   const program = this.context.getProgram(fragmentShader, vertexShader);
   *   helper.useProgram(this.program, frameState);
   *   ```
   *
   *   Uniforms are defined using the `uniforms` option and can either be explicit values or callbacks taking the frame state as argument.
   *   You can also change their value along the way like so:
   *   ```js
   *   helper.setUniformFloatValue('u_value', valueAsNumber);
   *   ```
   *
   * ### Defining post processing passes
   *
   *   Post processing* describes the act of rendering primitives to a texture, and then rendering this texture to the final canvas
   *   while applying special effects in screen space.
   *   Typical uses are: blurring, color manipulation, depth of field, filtering...
   *
   *   The `WebGLHelper` class offers the possibility to define post processes at creation time using the `postProcesses` option.
   *   A post process step accepts the following options:
   *
   *   `fragmentShader` and `vertexShader`: text literals in GLSL language that will be compiled and used in the post processing step.
   *   `uniforms`: uniforms can be defined for the post processing steps just like for the main render.
   *   `scaleRatio`: allows using an intermediate texture smaller or higher than the final canvas in the post processing step.
   *     This is typically used in blur steps to reduce the performance overhead by using an already downsampled texture as input.
   *
   *   The {@link module:ol/webgl/PostProcessingPass~WebGLPostProcessingPass} class is used internally, refer to its documentation for more info.
   *
   * ### Binding WebGL buffers and flushing data into them
   *
   *   Data that must be passed to the GPU has to be transferred using {@link module:ol/webgl/Buffer~WebGLArrayBuffer} objects.
   *   A buffer has to be created only once, but must be bound every time the buffer content will be used for rendering.
   *   This is done using {@link bindBuffer}.
   *   When the buffer's array content has changed, the new data has to be flushed to the GPU memory; this is done using
   *   {@link flushBufferData}. Note: this operation is expensive and should be done as infrequently as possible.
   *
   *   When binding an array buffer, a `target` parameter must be given: it should be either {@link module:ol/webgl.ARRAY_BUFFER}
   *   (if the buffer contains vertices data) or {@link module:ol/webgl.ELEMENT_ARRAY_BUFFER} (if the buffer contains indices data).
   *
   *   Examples below:
   *   ```js
   *   // at initialization phase
   *   const verticesBuffer = new WebGLArrayBuffer([], DYNAMIC_DRAW);
   *   const indicesBuffer = new WebGLArrayBuffer([], DYNAMIC_DRAW);
   *
   *   // when array values have changed
   *   helper.flushBufferData(ARRAY_BUFFER, this.verticesBuffer);
   *   helper.flushBufferData(ELEMENT_ARRAY_BUFFER, this.indicesBuffer);
   *
   *   // at rendering phase
   *   helper.bindBuffer(ARRAY_BUFFER, this.verticesBuffer);
   *   helper.bindBuffer(ELEMENT_ARRAY_BUFFER, this.indicesBuffer);
   *   ```
   *
   * ### Specifying attributes
   *
   *   The GPU only receives the data as arrays of numbers. These numbers must be handled differently depending on what it describes (position, texture coordinate...).
   *   Attributes are used to specify these uses. Specify the attribute names with
   *   {@link module:ol/webgl/Helper~WebGLHelper#enableAttributes} (see code snippet below).
   *
   *   Please note that you will have to specify the type and offset of the attributes in the data array. You can refer to the documentation of [WebGLRenderingContext.vertexAttribPointer](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer) for more explanation.
   *   ```js
   *   // here we indicate that the data array has the following structure:
   *   // [posX, posY, offsetX, offsetY, texCoordU, texCoordV, posX, posY, ...]
   *   helper.enableAttributes([
   *     {
   *        name: 'a_position',
   *        size: 2
   *     },
   *     {
   *       name: 'a_offset',
   *       size: 2
   *     },
   *     {
   *       name: 'a_texCoord',
   *       size: 2
   *     }
   *   ])
   *   ```
   *
   * ### Rendering primitives
   *
   *   Once all the steps above have been achieved, rendering primitives to the screen is done using {@link prepareDraw}, {@link drawElements} and {@link finalizeDraw}.
   *   ```js
   *   // frame preparation step
   *   helper.prepareDraw(frameState);
   *
   *   // call this for every data array that has to be rendered on screen
   *   helper.drawElements(0, this.indicesBuffer.getArray().length);
   *
   *   // finalize the rendering by applying post processes
   *   helper.finalizeDraw(frameState);
   *   ```
   *
   * For an example usage of this class, refer to {@link module:ol/renderer/webgl/PointsLayer~WebGLPointsLayerRenderer}.
   */
  class WebGLHelper extends Disposable {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();
      options = options || {};

      /** @private */
      this.boundHandleWebGLContextLost_ = this.handleWebGLContextLost.bind(this);

      /** @private */
      this.boundHandleWebGLContextRestored_ =
        this.handleWebGLContextRestored.bind(this);

      /**
       * @private
       * @type {string}
       */
      this.canvasCacheKey_ = options.canvasCacheKey
        ? getSharedCanvasCacheKey(options.canvasCacheKey)
        : getUniqueCanvasCacheKey();

      /**
       * @private
       * @type {WebGLRenderingContext}
       */
      this.gl_ = getOrCreateContext(this.canvasCacheKey_);

      /**
       * @private
       * @type {!Object<string, BufferCacheEntry>}
       */
      this.bufferCache_ = {};

      /**
       * @private
       * @type {Object<string, Object>}
       */
      this.extensionCache_ = {};

      /**
       * @private
       * @type {WebGLProgram}
       */
      this.currentProgram_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.needsToBeRecreated_ = false;

      const canvas = this.gl_.canvas;

      canvas.addEventListener(
        ContextEventType.LOST,
        this.boundHandleWebGLContextLost_,
      );
      canvas.addEventListener(
        ContextEventType.RESTORED,
        this.boundHandleWebGLContextRestored_,
      );

      /**
       * @private
       * @type {import("../transform.js").Transform}
       */
      this.offsetRotateMatrix_ = create$3();

      /**
       * @private
       * @type {import("../transform.js").Transform}
       */
      this.offsetScaleMatrix_ = create$3();

      /**
       * @private
       * @type {Array<number>}
       */
      this.tmpMat4_ = create$2();

      /**
       * @private
       * @type {Object<string, Object<string, WebGLUniformLocation>>}
       */
      this.uniformLocationsByProgram_ = {};

      /**
       * @private
       * @type {Object<string, Object<string, number>>}
       */
      this.attribLocationsByProgram_ = {};

      /**
       * Holds info about custom uniforms used in the post processing pass.
       * If the uniform is a texture, the WebGL Texture object will be stored here.
       * @type {Array<UniformInternalDescription>}
       * @private
       */
      this.uniforms_ = [];
      if (options.uniforms) {
        this.setUniforms(options.uniforms);
      }

      /**
       * An array of PostProcessingPass objects is kept in this variable, built from the steps provided in the
       * options. If no post process was given, a default one is used (so as not to have to make an exception to
       * the frame buffer logic).
       * @type {Array<WebGLPostProcessingPass>}
       * @private
       */
      this.postProcessPasses_ = options.postProcesses
        ? options.postProcesses.map(
            (options) =>
              new WebGLPostProcessingPass({
                webGlContext: this.gl_,
                scaleRatio: options.scaleRatio,
                vertexShader: options.vertexShader,
                fragmentShader: options.fragmentShader,
                uniforms: options.uniforms,
              }),
          )
        : [new WebGLPostProcessingPass({webGlContext: this.gl_})];

      /**
       * @type {string|null}
       * @private
       */
      this.shaderCompileErrors_ = null;

      /**
       * @type {number}
       * @private
       */
      this.startTime_ = Date.now();

      /**
       * @type {number}
       * @private
       */
      this.maxAttributeCount_ = this.gl_.getParameter(
        this.gl_.MAX_VERTEX_ATTRIBS,
      );
    }

    /**
     * @param {Object<string, UniformValue>} uniforms Uniform definitions.
     */
    setUniforms(uniforms) {
      this.uniforms_ = [];
      this.addUniforms(uniforms);
    }

    /**
     * @param {Object<string, UniformValue>} uniforms Uniform definitions.
     */
    addUniforms(uniforms) {
      for (const name in uniforms) {
        this.uniforms_.push({
          name: name,
          value: uniforms[name],
        });
      }
    }

    /**
     * @param {string} canvasCacheKey The canvas cache key.
     * @return {boolean} The provided key matches the one this helper was constructed with.
     */
    canvasCacheKeyMatches(canvasCacheKey) {
      return this.canvasCacheKey_ === getSharedCanvasCacheKey(canvasCacheKey);
    }

    /**
     * Get a WebGL extension.  If the extension is not supported, null is returned.
     * Extensions are cached after they are enabled for the first time.
     * @param {string} name The extension name.
     * @return {Object|null} The extension or null if not supported.
     */
    getExtension(name) {
      if (name in this.extensionCache_) {
        return this.extensionCache_[name];
      }
      const extension = this.gl_.getExtension(name);
      this.extensionCache_[name] = extension;
      return extension;
    }

    /**
     * Just bind the buffer if it's in the cache. Otherwise create
     * the WebGL buffer, bind it, populate it, and add an entry to
     * the cache.
     * @param {import("./Buffer").default} buffer Buffer.
     */
    bindBuffer(buffer) {
      const gl = this.gl_;
      const bufferKey = getUid(buffer);
      let bufferCache = this.bufferCache_[bufferKey];
      if (!bufferCache) {
        const webGlBuffer = gl.createBuffer();
        bufferCache = {
          buffer: buffer,
          webGlBuffer: webGlBuffer,
        };
        this.bufferCache_[bufferKey] = bufferCache;
      }
      gl.bindBuffer(buffer.getType(), bufferCache.webGlBuffer);
    }

    /**
     * Update the data contained in the buffer array; this is required for the
     * new data to be rendered
     * @param {import("./Buffer").default} buffer Buffer.
     */
    flushBufferData(buffer) {
      const gl = this.gl_;
      this.bindBuffer(buffer);
      gl.bufferData(buffer.getType(), buffer.getArray(), buffer.getUsage());
    }

    /**
     * @param {import("./Buffer.js").default} buf Buffer.
     */
    deleteBuffer(buf) {
      const bufferKey = getUid(buf);
      // Note: gl.deleteBuffer is not called here since we let WebGL garbage collect it automatically
      delete this.bufferCache_[bufferKey];
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      const canvas = this.gl_.canvas;
      canvas.removeEventListener(
        ContextEventType.LOST,
        this.boundHandleWebGLContextLost_,
      );
      canvas.removeEventListener(
        ContextEventType.RESTORED,
        this.boundHandleWebGLContextRestored_,
      );

      releaseCanvas(this.canvasCacheKey_);

      delete this.gl_;
    }

    /**
     * Clear the buffer & set the viewport to draw.
     * Post process passes will be initialized here, the first one being bound as a render target for
     * subsequent draw calls.
     * @param {import("../Map.js").FrameState} frameState current frame state
     * @param {boolean} [disableAlphaBlend] If true, no alpha blending will happen.
     * @param {boolean} [enableDepth] If true, enables depth testing.
     */
    prepareDraw(frameState, disableAlphaBlend, enableDepth) {
      const gl = this.gl_;
      const canvas = this.getCanvas();
      const size = frameState.size;
      const pixelRatio = frameState.pixelRatio;

      if (
        canvas.width !== size[0] * pixelRatio ||
        canvas.height !== size[1] * pixelRatio
      ) {
        canvas.width = size[0] * pixelRatio;
        canvas.height = size[1] * pixelRatio;
        canvas.style.width = size[0] + 'px';
        canvas.style.height = size[1] + 'px';
      }

      // loop backwards in post processes list
      for (let i = this.postProcessPasses_.length - 1; i >= 0; i--) {
        this.postProcessPasses_[i].init(frameState);
      }

      gl.bindTexture(gl.TEXTURE_2D, null);

      gl.clearColor(0.0, 0.0, 0.0, 0.0);
      gl.depthRange(0.0, 1.0);
      gl.clearDepth(1.0);
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

      gl.enable(gl.BLEND);
      gl.blendFunc(gl.ONE, disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA);
      if (enableDepth) {
        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);
      } else {
        gl.disable(gl.DEPTH_TEST);
      }
    }

    /**
     * @param {WebGLFramebuffer|null} frameBuffer The frame buffer.
     * @param {WebGLTexture} [texture] The texture.
     */
    bindFrameBuffer(frameBuffer, texture) {
      const gl = this.getGL();
      gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
      if (texture) {
        gl.framebufferTexture2D(
          gl.FRAMEBUFFER,
          gl.COLOR_ATTACHMENT0,
          gl.TEXTURE_2D,
          texture,
          0,
        );
      }
    }

    /**
     * Bind the frame buffer from the initial render.
     */
    bindInitialFrameBuffer() {
      const gl = this.getGL();
      const frameBuffer = this.postProcessPasses_[0].getFrameBuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
      const texture = this.postProcessPasses_[0].getRenderTargetTexture();
      gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.COLOR_ATTACHMENT0,
        gl.TEXTURE_2D,
        texture,
        0,
      );
    }

    /**
     * Prepare a program to use a texture.
     * @param {WebGLTexture} texture The texture.
     * @param {number} slot The texture slot.
     * @param {string} uniformName The corresponding uniform name.
     */
    bindTexture(texture, slot, uniformName) {
      const gl = this.gl_;
      gl.activeTexture(gl.TEXTURE0 + slot);
      gl.bindTexture(gl.TEXTURE_2D, texture);
      gl.uniform1i(this.getUniformLocation(uniformName), slot);
    }

    /**
     * Set up an attribute array buffer for use in the vertex shader.
     * @param {import("./Buffer").default} buffer The buffer.
     * @param {string} attributeName The attribute name.
     * @param {number} size The number of components per attribute vertex.
     */
    bindAttribute(buffer, attributeName, size) {
      const gl = this.getGL();
      this.bindBuffer(buffer);
      const index = this.getAttributeLocation(attributeName);
      gl.enableVertexAttribArray(index);
      gl.vertexAttribPointer(index, size, gl.FLOAT, false, 0, 0);
    }

    /**
     * Clear the render target & bind it for future draw operations.
     * This is similar to `prepareDraw`, only post processes will not be applied.
     * Note: the whole viewport will be drawn to the render target, regardless of its size.
     * @param {import("../Map.js").FrameState} frameState current frame state
     * @param {import("./RenderTarget.js").default} renderTarget Render target to draw to
     * @param {boolean} [disableAlphaBlend] If true, no alpha blending will happen.
     * @param {boolean} [enableDepth] If true, enables depth testing.
     */
    prepareDrawToRenderTarget(
      frameState,
      renderTarget,
      disableAlphaBlend,
      enableDepth,
    ) {
      const gl = this.gl_;
      const size = renderTarget.getSize();

      gl.bindFramebuffer(gl.FRAMEBUFFER, renderTarget.getFramebuffer());
      gl.bindRenderbuffer(gl.RENDERBUFFER, renderTarget.getDepthbuffer());
      gl.viewport(0, 0, size[0], size[1]);
      gl.bindTexture(gl.TEXTURE_2D, renderTarget.getTexture());
      gl.clearColor(0.0, 0.0, 0.0, 0.0);
      gl.depthRange(0.0, 1.0);
      gl.clearDepth(1.0);
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      gl.enable(gl.BLEND);
      gl.blendFunc(gl.ONE, disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA);
      if (enableDepth) {
        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);
      } else {
        gl.disable(gl.DEPTH_TEST);
      }
    }

    /**
     * Execute a draw call based on the currently bound program, texture, buffers, attributes.
     * @param {number} start Start index.
     * @param {number} end End index.
     */
    drawElements(start, end) {
      const gl = this.gl_;
      this.getExtension('OES_element_index_uint');

      const elementType = gl.UNSIGNED_INT;
      const elementSize = 4;

      const numItems = end - start;
      const offsetInBytes = start * elementSize;
      gl.drawElements(gl.TRIANGLES, numItems, elementType, offsetInBytes);
    }

    /**
     * Apply the successive post process passes which will eventually render to the actual canvas.
     * @param {import("../Map.js").FrameState} frameState current frame state
     * @param {function(WebGLRenderingContext, import("../Map.js").FrameState):void} [preCompose] Called before composing.
     * @param {function(WebGLRenderingContext, import("../Map.js").FrameState):void} [postCompose] Called before composing.
     */
    finalizeDraw(frameState, preCompose, postCompose) {
      // apply post processes using the next one as target
      for (let i = 0, ii = this.postProcessPasses_.length; i < ii; i++) {
        if (i === ii - 1) {
          this.postProcessPasses_[i].apply(
            frameState,
            null,
            preCompose,
            postCompose,
          );
        } else {
          this.postProcessPasses_[i].apply(
            frameState,
            this.postProcessPasses_[i + 1],
          );
        }
      }
    }

    /**
     * @return {HTMLCanvasElement} Canvas.
     */
    getCanvas() {
      return /** @type {HTMLCanvasElement} */ (this.gl_.canvas);
    }

    /**
     * Get the WebGL rendering context
     * @return {WebGLRenderingContext} The rendering context.
     */
    getGL() {
      return this.gl_;
    }

    /**
     * Sets the default matrix uniforms for a given frame state. This is called internally in `prepareDraw`.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     */
    applyFrameState(frameState) {
      const size = frameState.size;
      const rotation = frameState.viewState.rotation;
      const pixelRatio = frameState.pixelRatio;

      this.setUniformFloatValue(
        DefaultUniform.TIME,
        (Date.now() - this.startTime_) * 0.001,
      );
      this.setUniformFloatValue(DefaultUniform.ZOOM, frameState.viewState.zoom);
      this.setUniformFloatValue(
        DefaultUniform.RESOLUTION,
        frameState.viewState.resolution,
      );
      this.setUniformFloatValue(DefaultUniform.PIXEL_RATIO, pixelRatio);
      this.setUniformFloatVec2(DefaultUniform.VIEWPORT_SIZE_PX, [
        size[0],
        size[1],
      ]);
      this.setUniformFloatValue(DefaultUniform.ROTATION, rotation);
    }

    /**
     * Sets the `u_hitDetection` uniform.
     * @param {boolean} enabled Whether to enable the hit detection code path
     */
    applyHitDetectionUniform(enabled) {
      const loc = this.getUniformLocation(DefaultUniform.HIT_DETECTION);
      this.getGL().uniform1i(loc, enabled ? 1 : 0);

      // hit detection uses a fixed pixel ratio
      if (enabled) {
        this.setUniformFloatValue(DefaultUniform.PIXEL_RATIO, 0.5);
      }
    }

    /**
     * Sets the custom uniforms based on what was given in the constructor. This is called internally in `prepareDraw`.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     */
    applyUniforms(frameState) {
      const gl = this.gl_;

      let value;
      let textureSlot = 0;
      this.uniforms_.forEach((uniform) => {
        value =
          typeof uniform.value === 'function'
            ? uniform.value(frameState)
            : uniform.value;

        // apply value based on type
        if (
          value instanceof HTMLCanvasElement ||
          value instanceof HTMLImageElement ||
          value instanceof ImageData ||
          value instanceof WebGLTexture
        ) {
          // create a texture & put data
          if (value instanceof WebGLTexture && !uniform.texture) {
            uniform.prevValue = undefined;
            uniform.texture = value;
          } else if (!uniform.texture) {
            uniform.prevValue = undefined;
            uniform.texture = gl.createTexture();
          }
          this.bindTexture(uniform.texture, textureSlot, uniform.name);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

          const imageReady =
            !(value instanceof HTMLImageElement) ||
            /** @type {HTMLImageElement} */ (value).complete;
          if (
            !(value instanceof WebGLTexture) &&
            imageReady &&
            uniform.prevValue !== value
          ) {
            uniform.prevValue = value;
            gl.texImage2D(
              gl.TEXTURE_2D,
              0,
              gl.RGBA,
              gl.RGBA,
              gl.UNSIGNED_BYTE,
              value,
            );
          }
          textureSlot++;
        } else if (Array.isArray(value) && value.length === 6) {
          this.setUniformMatrixValue(
            uniform.name,
            fromTransform(this.tmpMat4_, value),
          );
        } else if (Array.isArray(value) && value.length <= 4) {
          switch (value.length) {
            case 2:
              gl.uniform2f(
                this.getUniformLocation(uniform.name),
                value[0],
                value[1],
              );
              return;
            case 3:
              gl.uniform3f(
                this.getUniformLocation(uniform.name),
                value[0],
                value[1],
                value[2],
              );
              return;
            case 4:
              gl.uniform4f(
                this.getUniformLocation(uniform.name),
                value[0],
                value[1],
                value[2],
                value[3],
              );
              return;
            default:
              return;
          }
        } else if (typeof value === 'number') {
          gl.uniform1f(this.getUniformLocation(uniform.name), value);
        }
      });
    }

    /**
     * Set up a program for use. The program will be set as the current one. Then, the uniforms used
     * in the program will be set based on the current frame state and the helper configuration.
     * @param {WebGLProgram} program Program.
     * @param {import("../Map.js").FrameState} [frameState] Frame state.
     */
    useProgram(program, frameState) {
      this.disableAllAttributes_();
      const gl = this.gl_;
      gl.useProgram(program);
      this.currentProgram_ = program;
      if (frameState) {
        this.applyFrameState(frameState);
        this.applyUniforms(frameState);
      }
    }

    /**
     * Will attempt to compile a vertex or fragment shader based on source
     * On error, the shader will be returned but
     * `gl.getShaderParameter(shader, gl.COMPILE_STATUS)` will return `true`
     * Use `gl.getShaderInfoLog(shader)` to have details
     * @param {string} source Shader source
     * @param {ShaderType} type VERTEX_SHADER or FRAGMENT_SHADER
     * @return {WebGLShader} Shader object
     */
    compileShader(source, type) {
      const gl = this.gl_;
      const shader = gl.createShader(type);
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      return shader;
    }

    /**
     * Create a program for a vertex and fragment shader.  Throws if shader compilation fails.
     * @param {string} fragmentShaderSource Fragment shader source.
     * @param {string} vertexShaderSource Vertex shader source.
     * @return {WebGLProgram} Program
     */
    getProgram(fragmentShaderSource, vertexShaderSource) {
      const gl = this.gl_;

      const fragmentShader = this.compileShader(
        fragmentShaderSource,
        gl.FRAGMENT_SHADER,
      );

      const vertexShader = this.compileShader(
        vertexShaderSource,
        gl.VERTEX_SHADER,
      );

      const program = gl.createProgram();
      gl.attachShader(program, fragmentShader);
      gl.attachShader(program, vertexShader);
      gl.linkProgram(program);

      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        const message = `Fragment shader compilation failed: ${gl.getShaderInfoLog(
        fragmentShader,
      )}`;
        throw new Error(message);
      }
      gl.deleteShader(fragmentShader);

      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        const message = `Vertex shader compilation failed: ${gl.getShaderInfoLog(
        vertexShader,
      )}`;
        throw new Error(message);
      }
      gl.deleteShader(vertexShader);

      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        const message = `GL program linking failed: ${gl.getProgramInfoLog(
        program,
      )}`;
        throw new Error(message);
      }

      return program;
    }

    /**
     * Will get the location from the shader or the cache
     * @param {string} name Uniform name
     * @return {WebGLUniformLocation} uniformLocation
     */
    getUniformLocation(name) {
      const programUid = getUid(this.currentProgram_);
      if (this.uniformLocationsByProgram_[programUid] === undefined) {
        this.uniformLocationsByProgram_[programUid] = {};
      }
      if (this.uniformLocationsByProgram_[programUid][name] === undefined) {
        this.uniformLocationsByProgram_[programUid][name] =
          this.gl_.getUniformLocation(this.currentProgram_, name);
      }
      return this.uniformLocationsByProgram_[programUid][name];
    }

    /**
     * Will get the location from the shader or the cache
     * @param {string} name Attribute name
     * @return {number} attribLocation
     */
    getAttributeLocation(name) {
      const programUid = getUid(this.currentProgram_);
      if (this.attribLocationsByProgram_[programUid] === undefined) {
        this.attribLocationsByProgram_[programUid] = {};
      }
      if (this.attribLocationsByProgram_[programUid][name] === undefined) {
        this.attribLocationsByProgram_[programUid][name] =
          this.gl_.getAttribLocation(this.currentProgram_, name);
      }
      return this.attribLocationsByProgram_[programUid][name];
    }

    /**
     * Sets the given transform to apply the rotation/translation/scaling of the given frame state.
     * The resulting transform can be used to convert world space coordinates to view coordinates in the [-1, 1] range.
     * @param {import("../Map.js").FrameState} frameState Frame state.
     * @param {import("../transform").Transform} transform Transform to update.
     * @return {import("../transform").Transform} The updated transform object.
     */
    makeProjectionTransform(frameState, transform) {
      const size = frameState.size;
      const rotation = frameState.viewState.rotation;
      const resolution = frameState.viewState.resolution;
      const center = frameState.viewState.center;
      compose(
        transform,
        0,
        0,
        2 / (resolution * size[0]),
        2 / (resolution * size[1]),
        -rotation,
        -center[0],
        -center[1],
      );
      return transform;
    }

    /**
     * Give a value for a standard float uniform
     * @param {string} uniform Uniform name
     * @param {number} value Value
     */
    setUniformFloatValue(uniform, value) {
      this.gl_.uniform1f(this.getUniformLocation(uniform), value);
    }

    /**
     * Give a value for a vec2 uniform
     * @param {string} uniform Uniform name
     * @param {Array<number>} value Array of length 4.
     */
    setUniformFloatVec2(uniform, value) {
      this.gl_.uniform2fv(this.getUniformLocation(uniform), value);
    }

    /**
     * Give a value for a vec4 uniform
     * @param {string} uniform Uniform name
     * @param {Array<number>} value Array of length 4.
     */
    setUniformFloatVec4(uniform, value) {
      this.gl_.uniform4fv(this.getUniformLocation(uniform), value);
    }

    /**
     * Give a value for a standard matrix4 uniform
     * @param {string} uniform Uniform name
     * @param {Array<number>} value Matrix value
     */
    setUniformMatrixValue(uniform, value) {
      this.gl_.uniformMatrix4fv(this.getUniformLocation(uniform), false, value);
    }

    /**
     * Disable all vertex attributes.
     * @private
     */
    disableAllAttributes_() {
      for (let i = 0; i < this.maxAttributeCount_; i++) {
        this.gl_.disableVertexAttribArray(i);
      }
    }

    /**
     * Will set the currently bound buffer to an attribute of the shader program. Used by `#enableAttributes`
     * internally.
     * @param {string} attribName Attribute name
     * @param {number} size Number of components per attributes
     * @param {number} type UNSIGNED_INT, UNSIGNED_BYTE, UNSIGNED_SHORT or FLOAT
     * @param {number} stride Stride in bytes (0 means attribs are packed)
     * @param {number} offset Offset in bytes
     * @private
     */
    enableAttributeArray_(attribName, size, type, stride, offset) {
      const location = this.getAttributeLocation(attribName);
      // the attribute has not been found in the shaders or is not used; do not enable it
      if (location < 0) {
        return;
      }
      this.gl_.enableVertexAttribArray(location);
      this.gl_.vertexAttribPointer(location, size, type, false, stride, offset);
    }

    /**
     * Will enable the following attributes to be read from the currently bound buffer,
     * i.e. tell the GPU where to read the different attributes in the buffer. An error in the
     * size/type/order of attributes will most likely break the rendering and throw a WebGL exception.
     * @param {Array<AttributeDescription>} attributes Ordered list of attributes to read from the buffer
     */
    enableAttributes(attributes) {
      const stride = computeAttributesStride(attributes);
      let offset = 0;
      for (let i = 0; i < attributes.length; i++) {
        const attr = attributes[i];
        this.enableAttributeArray_(
          attr.name,
          attr.size,
          attr.type || FLOAT,
          stride,
          offset,
        );
        offset += attr.size * getByteSizeFromType(attr.type);
      }
    }

    /**
     * WebGL context was lost
     * @param {WebGLContextEvent} event The context loss event.
     * @private
     */
    handleWebGLContextLost(event) {
      clear$2(this.bufferCache_);
      this.currentProgram_ = null;

      event.preventDefault();
    }

    /**
     * WebGL context was restored
     * @private
     */
    handleWebGLContextRestored() {
      this.needsToBeRecreated_ = true;
    }

    /**
     * Returns whether this helper needs to be recreated, as the context was lost and then restored.
     * @return {boolean} Whether this helper needs to be recreated.
     */
    needsToBeRecreated() {
      return this.needsToBeRecreated_;
    }

    /**
     * Will create or reuse a given webgl texture and apply the given size. If no image data
     * specified, the texture will be empty, otherwise image data will be used and the `size`
     * parameter will be ignored.  If a Uint8Array is provided for data, a size must also be provided.
     * Note: wrap parameters are set to clamp to edge, min filter is set to linear.
     * @param {Array<number>} size Expected size of the texture
     * @param {ImageData|HTMLImageElement|HTMLCanvasElement|Uint8Array|null} data Image data/object to bind to the texture
     * @param {WebGLTexture} [texture] Existing texture to reuse
     * @param {boolean} [nearest] Use gl.NEAREST for min/mag filter.
     * @return {WebGLTexture} The generated texture
     */
    createTexture(size, data, texture, nearest) {
      const gl = this.gl_;
      texture = texture || gl.createTexture();
      const filter = nearest ? gl.NEAREST : gl.LINEAR;

      gl.bindTexture(gl.TEXTURE_2D, texture);

      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

      const level = 0;
      const internalFormat = gl.RGBA;
      const border = 0;
      const format = gl.RGBA;
      const type = gl.UNSIGNED_BYTE;

      if (data instanceof Uint8Array) {
        gl.texImage2D(
          gl.TEXTURE_2D,
          level,
          internalFormat,
          size[0],
          size[1],
          border,
          format,
          type,
          data,
        );
      } else if (data) {
        gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, format, type, data);
      } else {
        gl.texImage2D(
          gl.TEXTURE_2D,
          level,
          internalFormat,
          size[0],
          size[1],
          border,
          format,
          type,
          null,
        );
      }
      return texture;
    }
  }

  /**
   * Compute a stride in bytes based on a list of attributes
   * @param {Array<AttributeDescription>} attributes Ordered list of attributes
   * @return {number} Stride, ie amount of values for each vertex in the vertex buffer
   */
  function computeAttributesStride(attributes) {
    let stride = 0;
    for (let i = 0; i < attributes.length; i++) {
      const attr = attributes[i];
      stride += attr.size * getByteSizeFromType(attr.type);
    }
    return stride;
  }

  /**
   * Computes the size in byte of an attribute type.
   * @param {AttributeType} type Attribute type
   * @return {number} The size in bytes
   */
  function getByteSizeFromType(type) {
    switch (type) {
      case AttributeType.UNSIGNED_BYTE:
        return Uint8Array.BYTES_PER_ELEMENT;
      case AttributeType.UNSIGNED_SHORT:
        return Uint16Array.BYTES_PER_ELEMENT;
      case AttributeType.UNSIGNED_INT:
        return Uint32Array.BYTES_PER_ELEMENT;
      case AttributeType.FLOAT:
      default:
        return Float32Array.BYTES_PER_ELEMENT;
    }
  }

  /**
   * @module ol/DataTile
   */

  /**
   * @typedef {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap} ImageLike
   */

  /**
   * @typedef {Uint8Array|Uint8ClampedArray|Float32Array|DataView} ArrayLike
   */

  /**
   * Data that can be used with a DataTile.
   * @typedef {ArrayLike|ImageLike} Data
   */

  /**
   * @param {Data} data Tile data.
   * @return {ImageLike|null} The image-like data.
   */
  function asImageLike(data) {
    return data instanceof Image ||
      data instanceof HTMLCanvasElement ||
      data instanceof HTMLVideoElement ||
      data instanceof ImageBitmap
      ? data
      : null;
  }

  /**
   * @param {Data} data Tile data.
   * @return {ArrayLike|null} The array-like data.
   */
  function asArrayLike(data) {
    return data instanceof Uint8Array ||
      data instanceof Uint8ClampedArray ||
      data instanceof Float32Array ||
      data instanceof DataView
      ? data
      : null;
  }

  /**
   * This is set as the cancellation reason when a tile is disposed.
   */
  const disposedError = new Error('disposed');

  /**
   * @type {CanvasRenderingContext2D|null}
   */
  let sharedContext$1 = null;

  /**
   * @param {ImageLike} image The image.
   * @return {Uint8ClampedArray} The data.
   */
  function toArray(image) {
    if (!sharedContext$1) {
      sharedContext$1 = createCanvasContext2D(
        image.width,
        image.height,
        undefined,
        {willReadFrequently: true},
      );
    }
    const canvas = sharedContext$1.canvas;
    const width = image.width;
    if (canvas.width !== width) {
      canvas.width = width;
    }
    const height = image.height;
    if (canvas.height !== height) {
      canvas.height = height;
    }
    sharedContext$1.clearRect(0, 0, width, height);
    sharedContext$1.drawImage(image, 0, 0);
    return sharedContext$1.getImageData(0, 0, width, height).data;
  }

  /**
   * @type {import('./size.js').Size}
   */
  const defaultSize = [256, 256];

  /**
   * @typedef {Object} Options
   * @property {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
   * @property {function(): Promise<Data>} loader Data loader.  For loaders that generate images,
   * the promise should not resolve until the image is loaded.
   * @property {number} [transition=250] A duration for tile opacity
   * transitions in milliseconds. A duration of 0 disables the opacity transition.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   * @property {import('./size.js').Size} [size=[256, 256]] Tile size.
   * @property {AbortController} [controller] An abort controller.
   * @api
   */

  class DataTile extends Tile {
    /**
     * @param {Options} options Tile options.
     */
    constructor(options) {
      const state = TileState.IDLE;

      super(options.tileCoord, state, {
        transition: options.transition,
        interpolate: options.interpolate,
      });

      /**
       * @type {function(): Promise<Data>}
       * @private
       */
      this.loader_ = options.loader;

      /**
       * @type {Data}
       * @private
       */
      this.data_ = null;

      /**
       * @type {Error}
       * @private
       */
      this.error_ = null;

      /**
       * @type {import('./size.js').Size|null}
       * @private
       */
      this.size_ = options.size || null;

      /**
       * @type {AbortController|null}
       * @private
       */
      this.controller_ = options.controller || null;
    }

    /**
     * Get the tile size.
     * @return {import('./size.js').Size} Tile size.
     */
    getSize() {
      if (this.size_) {
        return this.size_;
      }
      const imageData = asImageLike(this.data_);
      if (imageData) {
        return [imageData.width, imageData.height];
      }
      return defaultSize;
    }

    /**
     * Get the data for the tile.
     * @return {Data} Tile data.
     * @api
     */
    getData() {
      return this.data_;
    }

    /**
     * Get any loading error.
     * @return {Error} Loading error.
     * @api
     */
    getError() {
      return this.error_;
    }

    /**
     * Load the tile data.
     * @api
     * @override
     */
    load() {
      if (this.state !== TileState.IDLE && this.state !== TileState.ERROR) {
        return;
      }
      this.state = TileState.LOADING;
      this.changed();

      const self = this;
      this.loader_()
        .then(function (data) {
          self.data_ = data;
          self.state = TileState.LOADED;
          self.changed();
        })
        .catch(function (error) {
          self.error_ = error;
          self.state = TileState.ERROR;
          self.changed();
        });
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      if (this.controller_) {
        this.controller_.abort(disposedError);
        this.controller_ = null;
      }
      super.disposeInternal();
    }
  }

  /**
   * @module ol/reproj
   */

  let brokenDiagonalRendering_;

  /**
   * @type {Array<HTMLCanvasElement>}
   */
  const canvasPool$1 = [];

  /**
   * This draws a small triangle into a canvas by setting the triangle as the clip region
   * and then drawing a (too large) rectangle
   *
   * @param {CanvasRenderingContext2D} ctx The context in which to draw the triangle
   * @param {number} u1 The x-coordinate of the second point. The first point is 0,0.
   * @param {number} v1 The y-coordinate of the second point.
   * @param {number} u2 The x-coordinate of the third point.
   * @param {number} v2 The y-coordinate of the third point.
   */
  function drawTestTriangle(ctx, u1, v1, u2, v2) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(u1, v1);
    ctx.lineTo(u2, v2);
    ctx.closePath();
    ctx.save();
    ctx.clip();
    ctx.fillRect(0, 0, Math.max(u1, u2) + 1, Math.max(v1, v2));
    ctx.restore();
  }

  /**
   * Given the data from getImageData, see if the right values appear at the provided offset.
   * Returns true if either the color or transparency is off
   *
   * @param {Uint8ClampedArray} data The data returned from getImageData
   * @param {number} offset The pixel offset from the start of data.
   * @return {boolean} true if the diagonal rendering is broken
   */
  function verifyBrokenDiagonalRendering(data, offset) {
    // the values ought to be close to the rgba(210, 0, 0, 0.75)
    return (
      Math.abs(data[offset * 4] - 210) > 2 ||
      Math.abs(data[offset * 4 + 3] - 0.75 * 255) > 2
    );
  }

  /**
   * Determines if the current browser configuration can render triangular clip regions correctly.
   * This value is cached so the function is only expensive the first time called.
   * Firefox on Windows (as of now) does not if HWA is enabled. See https://bugzilla.mozilla.org/show_bug.cgi?id=1606976
   * Chrome works, and everything seems to work on OSX and Android. This function caches the
   * result. I suppose that it is conceivably possible that a browser might flip modes while the app is
   * running, but lets hope not.
   *
   * @return {boolean} true if the Diagonal Rendering is broken.
   */
  function isBrokenDiagonalRendering() {
    if (brokenDiagonalRendering_ === undefined) {
      const ctx = createCanvasContext2D(6, 6, canvasPool$1);
      ctx.globalCompositeOperation = 'lighter';
      ctx.fillStyle = 'rgba(210, 0, 0, 0.75)';
      drawTestTriangle(ctx, 4, 5, 4, 0);
      drawTestTriangle(ctx, 4, 5, 0, 5);
      const data = ctx.getImageData(0, 0, 3, 3).data;
      brokenDiagonalRendering_ =
        verifyBrokenDiagonalRendering(data, 0) ||
        verifyBrokenDiagonalRendering(data, 4) ||
        verifyBrokenDiagonalRendering(data, 8);
      releaseCanvas$1(ctx);
      canvasPool$1.push(ctx.canvas);
    }

    return brokenDiagonalRendering_;
  }

  /**
   * Calculates ideal resolution to use from the source in order to achieve
   * pixel mapping as close as possible to 1:1 during reprojection.
   * The resolution is calculated regardless of what resolutions
   * are actually available in the dataset (TileGrid, Image, ...).
   *
   * @param {import("./proj/Projection.js").default} sourceProj Source projection.
   * @param {import("./proj/Projection.js").default} targetProj Target projection.
   * @param {import("./coordinate.js").Coordinate} targetCenter Target center.
   * @param {number} targetResolution Target resolution.
   * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.
   */
  function calculateSourceResolution(
    sourceProj,
    targetProj,
    targetCenter,
    targetResolution,
  ) {
    const sourceCenter = transform(targetCenter, targetProj, sourceProj);

    // calculate the ideal resolution of the source data
    let sourceResolution = getPointResolution(
      targetProj,
      targetResolution,
      targetCenter,
    );

    const targetMetersPerUnit = targetProj.getMetersPerUnit();
    if (targetMetersPerUnit !== undefined) {
      sourceResolution *= targetMetersPerUnit;
    }
    const sourceMetersPerUnit = sourceProj.getMetersPerUnit();
    if (sourceMetersPerUnit !== undefined) {
      sourceResolution /= sourceMetersPerUnit;
    }

    // Based on the projection properties, the point resolution at the specified
    // coordinates may be slightly different. We need to reverse-compensate this
    // in order to achieve optimal results.

    const sourceExtent = sourceProj.getExtent();
    if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) {
      const compensationFactor =
        getPointResolution(sourceProj, sourceResolution, sourceCenter) /
        sourceResolution;
      if (isFinite(compensationFactor) && compensationFactor > 0) {
        sourceResolution /= compensationFactor;
      }
    }

    return sourceResolution;
  }

  /**
   * Calculates ideal resolution to use from the source in order to achieve
   * pixel mapping as close as possible to 1:1 during reprojection.
   * The resolution is calculated regardless of what resolutions
   * are actually available in the dataset (TileGrid, Image, ...).
   *
   * @param {import("./proj/Projection.js").default} sourceProj Source projection.
   * @param {import("./proj/Projection.js").default} targetProj Target projection.
   * @param {import("./extent.js").Extent} targetExtent Target extent
   * @param {number} targetResolution Target resolution.
   * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.
   */
  function calculateSourceExtentResolution(
    sourceProj,
    targetProj,
    targetExtent,
    targetResolution,
  ) {
    const targetCenter = getCenter(targetExtent);
    let sourceResolution = calculateSourceResolution(
      sourceProj,
      targetProj,
      targetCenter,
      targetResolution,
    );

    if (!isFinite(sourceResolution) || sourceResolution <= 0) {
      forEachCorner(targetExtent, function (corner) {
        sourceResolution = calculateSourceResolution(
          sourceProj,
          targetProj,
          corner,
          targetResolution,
        );
        return isFinite(sourceResolution) && sourceResolution > 0;
      });
    }

    return sourceResolution;
  }

  /**
   * @typedef {Object} ImageExtent
   * @property {import("./extent.js").Extent} extent Extent.
   * @property {import("./extent.js").Extent} [clipExtent] Clip extent.
   * @property {import('./DataTile.js').ImageLike} image Image.
   */

  /**
   * Renders the source data into new canvas based on the triangulation.
   *
   * @param {number} width Width of the canvas.
   * @param {number} height Height of the canvas.
   * @param {number} pixelRatio Pixel ratio.
   * @param {number} sourceResolution Source resolution.
   * @param {import("./extent.js").Extent} sourceExtent Extent of the data source.
   * @param {number} targetResolution Target resolution.
   * @param {import("./extent.js").Extent} targetExtent Target extent.
   * @param {import("./reproj/Triangulation.js").default} triangulation Calculated triangulation.
   * @param {Array<ImageExtent>} sources Array of sources.
   * @param {number} gutter Gutter of the sources.
   * @param {boolean} [renderEdges] Render reprojection edges.
   * @param {boolean} [interpolate] Use linear interpolation when resampling.
   * @param {boolean} [drawSingle] Draw single source images directly without stitchContext.
   * @param {boolean} [clipExtent] Clip stitchContext to sourceExtent.
   * @return {HTMLCanvasElement} Canvas with reprojected data.
   */
  function render$1(
    width,
    height,
    pixelRatio,
    sourceResolution,
    sourceExtent,
    targetResolution,
    targetExtent,
    triangulation,
    sources,
    gutter,
    renderEdges,
    interpolate,
    drawSingle,
    clipExtent,
  ) {
    const context = createCanvasContext2D(
      Math.round(pixelRatio * width),
      Math.round(pixelRatio * height),
      canvasPool$1,
    );

    if (!interpolate) {
      context.imageSmoothingEnabled = false;
    }

    if (sources.length === 0) {
      return context.canvas;
    }

    context.scale(pixelRatio, pixelRatio);

    function pixelRound(value) {
      return Math.round(value * pixelRatio) / pixelRatio;
    }

    context.globalCompositeOperation = 'lighter';

    const sourceDataExtent = createEmpty();
    sources.forEach(function (src, i, arr) {
      extend$1(sourceDataExtent, src.extent);
    });

    let stitchContext;
    const stitchScale = pixelRatio / sourceResolution;
    // Round up Float32 scale values to prevent interpolation in Firefox.
    const inverseScale = (interpolate ? 1 : 1 + Math.pow(2, -24)) / stitchScale;

    if (!drawSingle || sources.length !== 1 || gutter !== 0) {
      stitchContext = createCanvasContext2D(
        Math.round(getWidth(sourceDataExtent) * stitchScale),
        Math.round(getHeight(sourceDataExtent) * stitchScale),
        canvasPool$1,
      );

      if (!interpolate) {
        stitchContext.imageSmoothingEnabled = false;
      }

      sources.forEach(function (src, i, arr) {
        // This test should never fail -- but it does. Need to find a fix the upstream condition
        if (src.image.width > 0 && src.image.height > 0) {
          if (src.clipExtent) {
            stitchContext.save();
            const xPos = (src.clipExtent[0] - sourceDataExtent[0]) * stitchScale;
            const yPos = -(src.clipExtent[3] - sourceDataExtent[3]) * stitchScale;
            const width = getWidth(src.clipExtent) * stitchScale;
            const height = getHeight(src.clipExtent) * stitchScale;
            stitchContext.rect(
              interpolate ? xPos : Math.round(xPos),
              interpolate ? yPos : Math.round(yPos),
              interpolate ? width : Math.round(xPos + width) - Math.round(xPos),
              interpolate ? height : Math.round(yPos + height) - Math.round(yPos),
            );
            stitchContext.clip();
          }

          const xPos = (src.extent[0] - sourceDataExtent[0]) * stitchScale;
          const yPos = -(src.extent[3] - sourceDataExtent[3]) * stitchScale;
          const srcWidth = getWidth(src.extent) * stitchScale;
          const srcHeight = getHeight(src.extent) * stitchScale;
          stitchContext.drawImage(
            src.image,
            gutter,
            gutter,
            src.image.width - 2 * gutter,
            src.image.height - 2 * gutter,
            interpolate ? xPos : Math.round(xPos),
            interpolate ? yPos : Math.round(yPos),
            interpolate
              ? srcWidth
              : Math.round(xPos + srcWidth) - Math.round(xPos),
            interpolate
              ? srcHeight
              : Math.round(yPos + srcHeight) - Math.round(yPos),
          );

          if (src.clipExtent) {
            stitchContext.restore();
          }
        }
      });
    }
    const targetTopLeft = getTopLeft(targetExtent);

    triangulation.getTriangles().forEach(function (triangle, i, arr) {
      /* Calculate affine transform (src -> dst)
       * Resulting matrix can be used to transform coordinate
       * from `sourceProjection` to destination pixels.
       *
       * To optimize number of context calls and increase numerical stability,
       * we also do the following operations:
       * trans(-topLeftExtentCorner), scale(1 / targetResolution), scale(1, -1)
       * here before solving the linear system so [ui, vi] are pixel coordinates.
       *
       * Src points: xi, yi
       * Dst points: ui, vi
       * Affine coefficients: aij
       *
       * | x0 y0 1  0  0 0 |   |a00|   |u0|
       * | x1 y1 1  0  0 0 |   |a01|   |u1|
       * | x2 y2 1  0  0 0 | x |a02| = |u2|
       * |  0  0 0 x0 y0 1 |   |a10|   |v0|
       * |  0  0 0 x1 y1 1 |   |a11|   |v1|
       * |  0  0 0 x2 y2 1 |   |a12|   |v2|
       */
      const source = triangle.source;
      const target = triangle.target;
      let x0 = source[0][0],
        y0 = source[0][1];
      let x1 = source[1][0],
        y1 = source[1][1];
      let x2 = source[2][0],
        y2 = source[2][1];
      // Make sure that everything is on pixel boundaries
      const u0 = pixelRound((target[0][0] - targetTopLeft[0]) / targetResolution);
      const v0 = pixelRound(
        -(target[0][1] - targetTopLeft[1]) / targetResolution,
      );
      const u1 = pixelRound((target[1][0] - targetTopLeft[0]) / targetResolution);
      const v1 = pixelRound(
        -(target[1][1] - targetTopLeft[1]) / targetResolution,
      );
      const u2 = pixelRound((target[2][0] - targetTopLeft[0]) / targetResolution);
      const v2 = pixelRound(
        -(target[2][1] - targetTopLeft[1]) / targetResolution,
      );

      // Shift all the source points to improve numerical stability
      // of all the subsequent calculations. The [x0, y0] is used here.
      // This is also used to simplify the linear system.
      const sourceNumericalShiftX = x0;
      const sourceNumericalShiftY = y0;
      x0 = 0;
      y0 = 0;
      x1 -= sourceNumericalShiftX;
      y1 -= sourceNumericalShiftY;
      x2 -= sourceNumericalShiftX;
      y2 -= sourceNumericalShiftY;

      const augmentedMatrix = [
        [x1, y1, 0, 0, u1 - u0],
        [x2, y2, 0, 0, u2 - u0],
        [0, 0, x1, y1, v1 - v0],
        [0, 0, x2, y2, v2 - v0],
      ];
      const affineCoefs = solveLinearSystem(augmentedMatrix);
      if (!affineCoefs) {
        return;
      }

      context.save();
      context.beginPath();

      if (isBrokenDiagonalRendering() || !interpolate) {
        // Make sure that all lines are horizontal or vertical
        context.moveTo(u1, v1);
        // This is the diagonal line. Do it in 4 steps
        const steps = 4;
        const ud = u0 - u1;
        const vd = v0 - v1;
        for (let step = 0; step < steps; step++) {
          // Go horizontally
          context.lineTo(
            u1 + pixelRound(((step + 1) * ud) / steps),
            v1 + pixelRound((step * vd) / (steps - 1)),
          );
          // Go vertically
          if (step != steps - 1) {
            context.lineTo(
              u1 + pixelRound(((step + 1) * ud) / steps),
              v1 + pixelRound(((step + 1) * vd) / (steps - 1)),
            );
          }
        }
        // We are almost at u0r, v0r
        context.lineTo(u2, v2);
      } else {
        context.moveTo(u1, v1);
        context.lineTo(u0, v0);
        context.lineTo(u2, v2);
      }

      context.clip();

      context.transform(
        affineCoefs[0],
        affineCoefs[2],
        affineCoefs[1],
        affineCoefs[3],
        u0,
        v0,
      );

      context.translate(
        sourceDataExtent[0] - sourceNumericalShiftX,
        sourceDataExtent[3] - sourceNumericalShiftY,
      );

      let image;
      if (stitchContext) {
        image = stitchContext.canvas;
        context.scale(inverseScale, -inverseScale);
      } else {
        const source = sources[0];
        const extent = source.extent;
        image = source.image;
        context.scale(
          getWidth(extent) / image.width,
          -getHeight(extent) / image.height,
        );
      }

      context.drawImage(image, 0, 0);
      context.restore();
    });

    if (stitchContext) {
      releaseCanvas$1(stitchContext);
      canvasPool$1.push(stitchContext.canvas);
    }

    if (renderEdges) {
      context.save();

      context.globalCompositeOperation = 'source-over';
      context.strokeStyle = 'black';
      context.lineWidth = 1;

      triangulation.getTriangles().forEach(function (triangle, i, arr) {
        const target = triangle.target;
        const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution;
        const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution;
        const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution;
        const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution;
        const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution;
        const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution;

        context.beginPath();
        context.moveTo(u1, v1);
        context.lineTo(u0, v0);
        context.lineTo(u2, v2);
        context.closePath();
        context.stroke();
      });

      context.restore();
    }
    return context.canvas;
  }

  /**
   * @module ol/reproj/Triangulation
   */

  /**
   * Single triangle; consists of 3 source points and 3 target points.
   * @typedef {Object} Triangle
   * @property {Array<import("../coordinate.js").Coordinate>} source Source.
   * @property {Array<import("../coordinate.js").Coordinate>} target Target.
   */

  /**
   * Maximum number of subdivision steps during raster reprojection triangulation.
   * Prevents high memory usage and large number of proj4 calls (for certain
   * transformations and areas). At most `2*(2^this)` triangles are created for
   * each triangulated extent (tile/image).
   * @type {number}
   */
  const MAX_SUBDIVISION = 10;

  /**
   * Maximum allowed size of triangle relative to world width. When transforming
   * corners of world extent between certain projections, the resulting
   * triangulation seems to have zero error and no subdivision is performed. If
   * the triangle width is more than this (relative to world width; 0-1),
   * subdivison is forced (up to `MAX_SUBDIVISION`). Default is `0.25`.
   * @type {number}
   */
  const MAX_TRIANGLE_WIDTH = 0.25;

  /**
   * @classdesc
   * Class containing triangulation of the given target extent.
   * Used for determining source data and the reprojection itself.
   */
  class Triangulation {
    /**
     * @param {import("../proj/Projection.js").default} sourceProj Source projection.
     * @param {import("../proj/Projection.js").default} targetProj Target projection.
     * @param {import("../extent.js").Extent} targetExtent Target extent to triangulate.
     * @param {import("../extent.js").Extent} maxSourceExtent Maximal source extent that can be used.
     * @param {number} errorThreshold Acceptable error (in source units).
     * @param {?number} destinationResolution The (optional) resolution of the destination.
     * @param {import("../transform.js").Transform} [sourceMatrix] Source transform matrix.
     */
    constructor(
      sourceProj,
      targetProj,
      targetExtent,
      maxSourceExtent,
      errorThreshold,
      destinationResolution,
      sourceMatrix,
    ) {
      /**
       * @type {import("../proj/Projection.js").default}
       * @private
       */
      this.sourceProj_ = sourceProj;

      /**
       * @type {import("../proj/Projection.js").default}
       * @private
       */
      this.targetProj_ = targetProj;

      /** @type {!Object<string, import("../coordinate.js").Coordinate>} */
      let transformInvCache = {};
      const transformInv = sourceMatrix
        ? createTransformFromCoordinateTransform((input) =>
            apply(
              sourceMatrix,
              transform(input, this.targetProj_, this.sourceProj_),
            ),
          )
        : getTransform(this.targetProj_, this.sourceProj_);

      /**
       * @param {import("../coordinate.js").Coordinate} c A coordinate.
       * @return {import("../coordinate.js").Coordinate} Transformed coordinate.
       * @private
       */
      this.transformInv_ = function (c) {
        const key = c[0] + '/' + c[1];
        if (!transformInvCache[key]) {
          transformInvCache[key] = transformInv(c);
        }
        return transformInvCache[key];
      };

      /**
       * @type {import("../extent.js").Extent}
       * @private
       */
      this.maxSourceExtent_ = maxSourceExtent;

      /**
       * @type {number}
       * @private
       */
      this.errorThresholdSquared_ = errorThreshold * errorThreshold;

      /**
       * @type {Array<Triangle>}
       * @private
       */
      this.triangles_ = [];

      /**
       * Indicates that the triangulation crosses edge of the source projection.
       * @type {boolean}
       * @private
       */
      this.wrapsXInSource_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.canWrapXInSource_ =
        this.sourceProj_.canWrapX() &&
        !!maxSourceExtent &&
        !!this.sourceProj_.getExtent() &&
        getWidth(maxSourceExtent) >= getWidth(this.sourceProj_.getExtent());

      /**
       * @type {?number}
       * @private
       */
      this.sourceWorldWidth_ = this.sourceProj_.getExtent()
        ? getWidth(this.sourceProj_.getExtent())
        : null;

      /**
       * @type {?number}
       * @private
       */
      this.targetWorldWidth_ = this.targetProj_.getExtent()
        ? getWidth(this.targetProj_.getExtent())
        : null;

      const destinationTopLeft = getTopLeft(targetExtent);
      const destinationTopRight = getTopRight(targetExtent);
      const destinationBottomRight = getBottomRight(targetExtent);
      const destinationBottomLeft = getBottomLeft(targetExtent);
      const sourceTopLeft = this.transformInv_(destinationTopLeft);
      const sourceTopRight = this.transformInv_(destinationTopRight);
      const sourceBottomRight = this.transformInv_(destinationBottomRight);
      const sourceBottomLeft = this.transformInv_(destinationBottomLeft);

      /*
       * The maxSubdivision controls how many splittings of the target area can
       * be done. The idea here is to do a linear mapping of the target areas
       * but the actual overall reprojection (can be) extremely non-linear. The
       * default value of MAX_SUBDIVISION was chosen based on mapping a 256x256
       * tile size. However this function is also called to remap canvas rendered
       * layers which can be much larger. This calculation increases the maxSubdivision
       * value by the right factor so that each 256x256 pixel area has
       * MAX_SUBDIVISION divisions.
       */
      const maxSubdivision =
        MAX_SUBDIVISION +
        (destinationResolution
          ? Math.max(
              0,
              Math.ceil(
                Math.log2(
                  getArea$1(targetExtent) /
                    (destinationResolution * destinationResolution * 256 * 256),
                ),
              ),
            )
          : 0);

      this.addQuad_(
        destinationTopLeft,
        destinationTopRight,
        destinationBottomRight,
        destinationBottomLeft,
        sourceTopLeft,
        sourceTopRight,
        sourceBottomRight,
        sourceBottomLeft,
        maxSubdivision,
      );

      if (this.wrapsXInSource_) {
        let leftBound = Infinity;
        this.triangles_.forEach(function (triangle, i, arr) {
          leftBound = Math.min(
            leftBound,
            triangle.source[0][0],
            triangle.source[1][0],
            triangle.source[2][0],
          );
        });

        // Shift triangles to be as close to `leftBound` as possible
        // (if the distance is more than `worldWidth / 2` it can be closer.
        this.triangles_.forEach((triangle) => {
          if (
            Math.max(
              triangle.source[0][0],
              triangle.source[1][0],
              triangle.source[2][0],
            ) -
              leftBound >
            this.sourceWorldWidth_ / 2
          ) {
            const newTriangle = [
              [triangle.source[0][0], triangle.source[0][1]],
              [triangle.source[1][0], triangle.source[1][1]],
              [triangle.source[2][0], triangle.source[2][1]],
            ];
            if (newTriangle[0][0] - leftBound > this.sourceWorldWidth_ / 2) {
              newTriangle[0][0] -= this.sourceWorldWidth_;
            }
            if (newTriangle[1][0] - leftBound > this.sourceWorldWidth_ / 2) {
              newTriangle[1][0] -= this.sourceWorldWidth_;
            }
            if (newTriangle[2][0] - leftBound > this.sourceWorldWidth_ / 2) {
              newTriangle[2][0] -= this.sourceWorldWidth_;
            }

            // Rarely (if the extent contains both the dateline and prime meridian)
            // the shift can in turn break some triangles.
            // Detect this here and don't shift in such cases.
            const minX = Math.min(
              newTriangle[0][0],
              newTriangle[1][0],
              newTriangle[2][0],
            );
            const maxX = Math.max(
              newTriangle[0][0],
              newTriangle[1][0],
              newTriangle[2][0],
            );
            if (maxX - minX < this.sourceWorldWidth_ / 2) {
              triangle.source = newTriangle;
            }
          }
        });
      }

      transformInvCache = {};
    }

    /**
     * Adds triangle to the triangulation.
     * @param {import("../coordinate.js").Coordinate} a The target a coordinate.
     * @param {import("../coordinate.js").Coordinate} b The target b coordinate.
     * @param {import("../coordinate.js").Coordinate} c The target c coordinate.
     * @param {import("../coordinate.js").Coordinate} aSrc The source a coordinate.
     * @param {import("../coordinate.js").Coordinate} bSrc The source b coordinate.
     * @param {import("../coordinate.js").Coordinate} cSrc The source c coordinate.
     * @private
     */
    addTriangle_(a, b, c, aSrc, bSrc, cSrc) {
      this.triangles_.push({
        source: [aSrc, bSrc, cSrc],
        target: [a, b, c],
      });
    }

    /**
     * Adds quad (points in clock-wise order) to the triangulation
     * (and reprojects the vertices) if valid.
     * Performs quad subdivision if needed to increase precision.
     *
     * @param {import("../coordinate.js").Coordinate} a The target a coordinate.
     * @param {import("../coordinate.js").Coordinate} b The target b coordinate.
     * @param {import("../coordinate.js").Coordinate} c The target c coordinate.
     * @param {import("../coordinate.js").Coordinate} d The target d coordinate.
     * @param {import("../coordinate.js").Coordinate} aSrc The source a coordinate.
     * @param {import("../coordinate.js").Coordinate} bSrc The source b coordinate.
     * @param {import("../coordinate.js").Coordinate} cSrc The source c coordinate.
     * @param {import("../coordinate.js").Coordinate} dSrc The source d coordinate.
     * @param {number} maxSubdivision Maximal allowed subdivision of the quad.
     * @private
     */
    addQuad_(a, b, c, d, aSrc, bSrc, cSrc, dSrc, maxSubdivision) {
      const sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]);
      const sourceCoverageX = this.sourceWorldWidth_
        ? getWidth(sourceQuadExtent) / this.sourceWorldWidth_
        : null;
      const sourceWorldWidth = /** @type {number} */ (this.sourceWorldWidth_);

      // when the quad is wrapped in the source projection
      // it covers most of the projection extent, but not fully
      const wrapsX =
        this.sourceProj_.canWrapX() &&
        sourceCoverageX > 0.5 &&
        sourceCoverageX < 1;

      let needsSubdivision = false;

      if (maxSubdivision > 0) {
        if (this.targetProj_.isGlobal() && this.targetWorldWidth_) {
          const targetQuadExtent = boundingExtent([a, b, c, d]);
          const targetCoverageX =
            getWidth(targetQuadExtent) / this.targetWorldWidth_;
          needsSubdivision =
            targetCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;
        }
        if (!wrapsX && this.sourceProj_.isGlobal() && sourceCoverageX) {
          needsSubdivision =
            sourceCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;
        }
      }

      if (!needsSubdivision && this.maxSourceExtent_) {
        if (
          isFinite(sourceQuadExtent[0]) &&
          isFinite(sourceQuadExtent[1]) &&
          isFinite(sourceQuadExtent[2]) &&
          isFinite(sourceQuadExtent[3])
        ) {
          if (!intersects$2(sourceQuadExtent, this.maxSourceExtent_)) {
            // whole quad outside source projection extent -> ignore
            return;
          }
        }
      }

      let isNotFinite = 0;

      if (!needsSubdivision) {
        if (
          !isFinite(aSrc[0]) ||
          !isFinite(aSrc[1]) ||
          !isFinite(bSrc[0]) ||
          !isFinite(bSrc[1]) ||
          !isFinite(cSrc[0]) ||
          !isFinite(cSrc[1]) ||
          !isFinite(dSrc[0]) ||
          !isFinite(dSrc[1])
        ) {
          if (maxSubdivision > 0) {
            needsSubdivision = true;
          } else {
            // It might be the case that only 1 of the points is infinite. In this case
            // we can draw a single triangle with the other three points
            isNotFinite =
              (!isFinite(aSrc[0]) || !isFinite(aSrc[1]) ? 8 : 0) +
              (!isFinite(bSrc[0]) || !isFinite(bSrc[1]) ? 4 : 0) +
              (!isFinite(cSrc[0]) || !isFinite(cSrc[1]) ? 2 : 0) +
              (!isFinite(dSrc[0]) || !isFinite(dSrc[1]) ? 1 : 0);
            if (
              isNotFinite != 1 &&
              isNotFinite != 2 &&
              isNotFinite != 4 &&
              isNotFinite != 8
            ) {
              return;
            }
          }
        }
      }

      if (maxSubdivision > 0) {
        if (!needsSubdivision) {
          const center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2];
          const centerSrc = this.transformInv_(center);

          let dx;
          if (wrapsX) {
            const centerSrcEstimX =
              (modulo(aSrc[0], sourceWorldWidth) +
                modulo(cSrc[0], sourceWorldWidth)) /
              2;
            dx = centerSrcEstimX - modulo(centerSrc[0], sourceWorldWidth);
          } else {
            dx = (aSrc[0] + cSrc[0]) / 2 - centerSrc[0];
          }
          const dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1];
          const centerSrcErrorSquared = dx * dx + dy * dy;
          needsSubdivision = centerSrcErrorSquared > this.errorThresholdSquared_;
        }
        if (needsSubdivision) {
          if (Math.abs(a[0] - c[0]) <= Math.abs(a[1] - c[1])) {
            // split horizontally (top & bottom)
            const bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2];
            const bcSrc = this.transformInv_(bc);
            const da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2];
            const daSrc = this.transformInv_(da);

            this.addQuad_(
              a,
              b,
              bc,
              da,
              aSrc,
              bSrc,
              bcSrc,
              daSrc,
              maxSubdivision - 1,
            );
            this.addQuad_(
              da,
              bc,
              c,
              d,
              daSrc,
              bcSrc,
              cSrc,
              dSrc,
              maxSubdivision - 1,
            );
          } else {
            // split vertically (left & right)
            const ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
            const abSrc = this.transformInv_(ab);
            const cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2];
            const cdSrc = this.transformInv_(cd);

            this.addQuad_(
              a,
              ab,
              cd,
              d,
              aSrc,
              abSrc,
              cdSrc,
              dSrc,
              maxSubdivision - 1,
            );
            this.addQuad_(
              ab,
              b,
              c,
              cd,
              abSrc,
              bSrc,
              cSrc,
              cdSrc,
              maxSubdivision - 1,
            );
          }
          return;
        }
      }

      if (wrapsX) {
        if (!this.canWrapXInSource_) {
          return;
        }
        this.wrapsXInSource_ = true;
      }

      // Exactly zero or one of *Src is not finite
      // The triangles must have the diagonal line as the first side
      // This is to allow easy code in reproj.s to make it straight for broken
      // browsers that can't handle diagonal clipping
      if ((isNotFinite & 0xb) == 0) {
        this.addTriangle_(a, c, d, aSrc, cSrc, dSrc);
      }
      if ((isNotFinite & 0xe) == 0) {
        this.addTriangle_(a, c, b, aSrc, cSrc, bSrc);
      }
      if (isNotFinite) {
        // Try the other two triangles
        if ((isNotFinite & 0xd) == 0) {
          this.addTriangle_(b, d, a, bSrc, dSrc, aSrc);
        }
        if ((isNotFinite & 0x7) == 0) {
          this.addTriangle_(b, d, c, bSrc, dSrc, cSrc);
        }
      }
    }

    /**
     * Calculates extent of the `source` coordinates from all the triangles.
     *
     * @return {import("../extent.js").Extent} Calculated extent.
     */
    calculateSourceExtent() {
      const extent = createEmpty();

      this.triangles_.forEach(function (triangle, i, arr) {
        const src = triangle.source;
        extendCoordinate(extent, src[0]);
        extendCoordinate(extent, src[1]);
        extendCoordinate(extent, src[2]);
      });

      return extent;
    }

    /**
     * @return {Array<Triangle>} Array of the calculated triangles.
     */
    getTriangles() {
      return this.triangles_;
    }
  }

  /**
   * @module ol/reproj/common
   */

  /**
   * Default maximum allowed threshold  (in pixels) for reprojection
   * triangulation.
   * @type {number}
   */
  const ERROR_THRESHOLD = 0.5;

  /**
   * @module ol/reproj/Tile
   */


  /**
   * @typedef {function(number, number, number, number) : (import("../ImageTile.js").default)} FunctionType
   */

  /**
   * @typedef {Object} TileOffset
   * @property {import("../ImageTile.js").default} tile Tile.
   * @property {number} offset Offset.
   */

  /**
   * @classdesc
   * Class encapsulating single reprojected tile.
   * See {@link module:ol/source/TileImage~TileImage}.
   *
   */
  class ReprojTile extends Tile {
    /**
     * @param {import("../proj/Projection.js").default} sourceProj Source projection.
     * @param {import("../tilegrid/TileGrid.js").default} sourceTileGrid Source tile grid.
     * @param {import("../proj/Projection.js").default} targetProj Target projection.
     * @param {import("../tilegrid/TileGrid.js").default} targetTileGrid Target tile grid.
     * @param {import("../tilecoord.js").TileCoord} tileCoord Coordinate of the tile.
     * @param {import("../tilecoord.js").TileCoord} wrappedTileCoord Coordinate of the tile wrapped in X.
     * @param {number} pixelRatio Pixel ratio.
     * @param {number} gutter Gutter of the source tiles.
     * @param {FunctionType} getTileFunction
     *     Function returning source tiles (z, x, y, pixelRatio).
     * @param {number} [errorThreshold] Acceptable reprojection error (in px).
     * @param {boolean} [renderEdges] Render reprojection edges.
     * @param {import("../Tile.js").Options} [options] Tile options.
     */
    constructor(
      sourceProj,
      sourceTileGrid,
      targetProj,
      targetTileGrid,
      tileCoord,
      wrappedTileCoord,
      pixelRatio,
      gutter,
      getTileFunction,
      errorThreshold,
      renderEdges,
      options,
    ) {
      super(tileCoord, TileState.IDLE, options);

      /**
       * @private
       * @type {boolean}
       */
      this.renderEdges_ = renderEdges !== undefined ? renderEdges : false;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = pixelRatio;

      /**
       * @private
       * @type {number}
       */
      this.gutter_ = gutter;

      /**
       * @private
       * @type {HTMLCanvasElement}
       */
      this.canvas_ = null;

      /**
       * @private
       * @type {import("../tilegrid/TileGrid.js").default}
       */
      this.sourceTileGrid_ = sourceTileGrid;

      /**
       * @private
       * @type {import("../tilegrid/TileGrid.js").default}
       */
      this.targetTileGrid_ = targetTileGrid;

      /**
       * @private
       * @type {import("../tilecoord.js").TileCoord}
       */
      this.wrappedTileCoord_ = wrappedTileCoord ? wrappedTileCoord : tileCoord;

      /**
       * @private
       * @type {!Array<TileOffset>}
       */
      this.sourceTiles_ = [];

      /**
       * @private
       * @type {?Array<import("../events.js").EventsKey>}
       */
      this.sourcesListenerKeys_ = null;

      /**
       * @private
       * @type {number}
       */
      this.sourceZ_ = 0;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.clipExtent_ = sourceProj.canWrapX()
        ? sourceProj.getExtent()
        : undefined;

      const targetExtent = targetTileGrid.getTileCoordExtent(
        this.wrappedTileCoord_,
      );
      const maxTargetExtent = this.targetTileGrid_.getExtent();
      let maxSourceExtent = this.sourceTileGrid_.getExtent();

      const limitedTargetExtent = maxTargetExtent
        ? getIntersection(targetExtent, maxTargetExtent)
        : targetExtent;

      if (getArea$1(limitedTargetExtent) === 0) {
        // Tile is completely outside range -> EMPTY
        // TODO: is it actually correct that the source even creates the tile ?
        this.state = TileState.EMPTY;
        return;
      }

      const sourceProjExtent = sourceProj.getExtent();
      if (sourceProjExtent) {
        if (!maxSourceExtent) {
          maxSourceExtent = sourceProjExtent;
        } else {
          maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent);
        }
      }

      const targetResolution = targetTileGrid.getResolution(
        this.wrappedTileCoord_[0],
      );

      const sourceResolution = calculateSourceExtentResolution(
        sourceProj,
        targetProj,
        limitedTargetExtent,
        targetResolution,
      );

      if (!isFinite(sourceResolution) || sourceResolution <= 0) {
        // invalid sourceResolution -> EMPTY
        // probably edges of the projections when no extent is defined
        this.state = TileState.EMPTY;
        return;
      }

      const errorThresholdInPixels =
        errorThreshold !== undefined ? errorThreshold : ERROR_THRESHOLD;

      /**
       * @private
       * @type {!import("./Triangulation.js").default}
       */
      this.triangulation_ = new Triangulation(
        sourceProj,
        targetProj,
        limitedTargetExtent,
        maxSourceExtent,
        sourceResolution * errorThresholdInPixels,
        targetResolution,
      );

      if (this.triangulation_.getTriangles().length === 0) {
        // no valid triangles -> EMPTY
        this.state = TileState.EMPTY;
        return;
      }

      this.sourceZ_ = sourceTileGrid.getZForResolution(sourceResolution);
      let sourceExtent = this.triangulation_.calculateSourceExtent();

      if (maxSourceExtent) {
        if (sourceProj.canWrapX()) {
          sourceExtent[1] = clamp$1(
            sourceExtent[1],
            maxSourceExtent[1],
            maxSourceExtent[3],
          );
          sourceExtent[3] = clamp$1(
            sourceExtent[3],
            maxSourceExtent[1],
            maxSourceExtent[3],
          );
        } else {
          sourceExtent = getIntersection(sourceExtent, maxSourceExtent);
        }
      }

      if (!getArea$1(sourceExtent)) {
        this.state = TileState.EMPTY;
      } else {
        let worldWidth = 0;
        let worldsAway = 0;
        if (sourceProj.canWrapX()) {
          worldWidth = getWidth(sourceProjExtent);
          worldsAway = Math.floor(
            (sourceExtent[0] - sourceProjExtent[0]) / worldWidth,
          );
        }

        const sourceExtents = wrapAndSliceX(
          sourceExtent.slice(),
          sourceProj,
          true,
        );
        sourceExtents.forEach((extent) => {
          const sourceRange = sourceTileGrid.getTileRangeForExtentAndZ(
            extent,
            this.sourceZ_,
          );

          for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) {
            for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) {
              const tile = getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio);
              if (tile) {
                const offset = worldsAway * worldWidth;
                this.sourceTiles_.push({tile, offset});
              }
            }
          }
          ++worldsAway;
        });

        if (this.sourceTiles_.length === 0) {
          this.state = TileState.EMPTY;
        }
      }
    }

    /**
     * Get the HTML Canvas element for this tile.
     * @return {HTMLCanvasElement} Canvas.
     */
    getImage() {
      return this.canvas_;
    }

    /**
     * @private
     */
    reproject_() {
      const sources = [];
      this.sourceTiles_.forEach((source) => {
        const tile = source.tile;
        if (tile && tile.getState() == TileState.LOADED) {
          const extent = this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord);
          extent[0] += source.offset;
          extent[2] += source.offset;
          const clipExtent = this.clipExtent_?.slice();
          if (clipExtent) {
            clipExtent[0] += source.offset;
            clipExtent[2] += source.offset;
          }
          sources.push({
            extent: extent,
            clipExtent: clipExtent,
            image: tile.getImage(),
          });
        }
      });
      this.sourceTiles_.length = 0;

      if (sources.length === 0) {
        this.state = TileState.ERROR;
      } else {
        const z = this.wrappedTileCoord_[0];
        const size = this.targetTileGrid_.getTileSize(z);
        const width = typeof size === 'number' ? size : size[0];
        const height = typeof size === 'number' ? size : size[1];
        const targetResolution = this.targetTileGrid_.getResolution(z);
        const sourceResolution = this.sourceTileGrid_.getResolution(
          this.sourceZ_,
        );

        const targetExtent = this.targetTileGrid_.getTileCoordExtent(
          this.wrappedTileCoord_,
        );

        this.canvas_ = render$1(
          width,
          height,
          this.pixelRatio_,
          sourceResolution,
          this.sourceTileGrid_.getExtent(),
          targetResolution,
          targetExtent,
          this.triangulation_,
          sources,
          this.gutter_,
          this.renderEdges_,
          this.interpolate,
        );

        this.state = TileState.LOADED;
      }
      this.changed();
    }

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {
      if (this.state == TileState.IDLE) {
        this.state = TileState.LOADING;
        this.changed();

        let leftToLoad = 0;

        this.sourcesListenerKeys_ = [];
        this.sourceTiles_.forEach(({tile}) => {
          const state = tile.getState();
          if (state == TileState.IDLE || state == TileState.LOADING) {
            leftToLoad++;

            const sourceListenKey = listen(tile, EventType.CHANGE, (e) => {
              const state = tile.getState();
              if (
                state == TileState.LOADED ||
                state == TileState.ERROR ||
                state == TileState.EMPTY
              ) {
                unlistenByKey(sourceListenKey);
                leftToLoad--;
                if (leftToLoad === 0) {
                  this.unlistenSources_();
                  this.reproject_();
                }
              }
            });
            this.sourcesListenerKeys_.push(sourceListenKey);
          }
        });

        if (leftToLoad === 0) {
          setTimeout(this.reproject_.bind(this), 0);
        } else {
          this.sourceTiles_.forEach(function ({tile}, i, arr) {
            const state = tile.getState();
            if (state == TileState.IDLE) {
              tile.load();
            }
          });
        }
      }
    }

    /**
     * @private
     */
    unlistenSources_() {
      this.sourcesListenerKeys_.forEach(unlistenByKey);
      this.sourcesListenerKeys_ = null;
    }

    /**
     * Remove from the cache due to expiry
     * @override
     */
    release() {
      if (this.canvas_) {
        releaseCanvas$1(this.canvas_.getContext('2d'));
        canvasPool$1.push(this.canvas_);
        this.canvas_ = null;
      }
      super.release();
    }
  }

  /**
   * @module ol/webgl/BaseTileRepresentation
   */


  /**
   * @typedef {import("../Tile.js").default} BaseTileType
   */

  /**
   * @template {BaseTileType} TileType
   * @typedef {Object} TileRepresentationOptions
   * @property {TileType} tile The tile.
   * @property {import("../tilegrid/TileGrid.js").default} grid Tile grid.
   * @property {import("../webgl/Helper.js").default} helper WebGL helper.
   * @property {number} [gutter=0] The size in pixels of the gutter around image tiles to ignore.
   */

  /**
   * @classdesc
   * Base class for representing a tile in a webgl context
   * @template {import("../Tile.js").default} TileType
   * @abstract
   */
  class BaseTileRepresentation extends Target {
    /**
     * @param {TileRepresentationOptions<TileType>} options The tile representation options.
     */
    constructor(options) {
      super();

      /**
       * @type {TileType}
       */
      this.tile;

      /**
       * @private
       */
      this.handleTileChange_ = this.handleTileChange_.bind(this);

      /**
       * @type {number}
       * @protected
       */
      this.gutter = options.gutter || 0;

      /**
       * @type {import("../webgl/Helper.js").default}
       * @protected
       */
      this.helper = options.helper;

      this.loaded = false;
      this.ready = false;
    }

    /**
     * @param {TileType} tile Tile.
     */
    setTile(tile) {
      if (tile !== this.tile) {
        if (this.tile) {
          this.tile.removeEventListener(EventType.CHANGE, this.handleTileChange_);
        }
        this.tile = tile;
        this.loaded = tile.getState() === TileState.LOADED;
        if (this.loaded) {
          this.uploadTile();
        } else {
          if (tile instanceof ImageTile) {
            const image = tile.getImage();
            if (image instanceof Image && !image.crossOrigin) {
              image.crossOrigin = 'anonymous';
            }
          }
          tile.addEventListener(EventType.CHANGE, this.handleTileChange_);
        }
      }
    }

    /**
     * @abstract
     * @protected
     */
    uploadTile() {
      abstract();
    }

    setReady() {
      this.ready = true;
      this.dispatchEvent(EventType.CHANGE);
    }

    handleTileChange_() {
      if (this.tile.getState() === TileState.LOADED) {
        this.loaded = true;
        this.uploadTile();
      }
    }

    /**
     * @param {import("./Helper.js").default} helper The WebGL helper.
     */
    setHelper(helper) {
      this.helper = helper;
      if (this.helper && this.loaded) {
        this.uploadTile();
      }
    }

    /**
     * @override
     */
    disposeInternal() {
      this.setHelper(null);
      this.tile.removeEventListener(EventType.CHANGE, this.handleTileChange_);
    }
  }

  /**
   * @module ol/webgl/TileTexture
   */


  /**
   * @param {WebGLRenderingContext} gl The WebGL context.
   * @param {WebGLTexture} texture The texture.
   * @param {boolean} interpolate Interpolate when resampling.
   */
  function bindAndConfigure(gl, texture, interpolate) {
    const resampleFilter = interpolate ? gl.LINEAR : gl.NEAREST;
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, resampleFilter);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, resampleFilter);
  }

  /**
   * @param {WebGLRenderingContext} gl The WebGL context.
   * @param {WebGLTexture} texture The texture.
   * @param {import("../DataTile.js").ImageLike} image The image.
   * @param {boolean} interpolate Interpolate when resampling.
   */
  function uploadImageTexture(gl, texture, image, interpolate) {
    bindAndConfigure(gl, texture, interpolate);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  }

  /**
   * @param {import("./Helper.js").default} helper The WebGL helper.
   * @param {WebGLTexture} texture The texture.
   * @param {import("../DataTile.js").ArrayLike} data The pixel data.
   * @param {import("../size.js").Size} size The pixel size.
   * @param {number} bandCount The band count.
   * @param {boolean} interpolate Interpolate when resampling.
   */
  function uploadDataTexture(
    helper,
    texture,
    data,
    size,
    bandCount,
    interpolate,
  ) {
    const gl = helper.getGL();
    let textureType;
    let canInterpolate;
    if (data instanceof Float32Array) {
      textureType = gl.FLOAT;
      helper.getExtension('OES_texture_float');
      const extension = helper.getExtension('OES_texture_float_linear');
      canInterpolate = extension !== null;
    } else {
      textureType = gl.UNSIGNED_BYTE;
      canInterpolate = true;
    }
    bindAndConfigure(gl, texture, interpolate && canInterpolate);

    const bytesPerRow = data.byteLength / size[1];
    let unpackAlignment = 1;
    if (bytesPerRow % 8 === 0) {
      unpackAlignment = 8;
    } else if (bytesPerRow % 4 === 0) {
      unpackAlignment = 4;
    } else if (bytesPerRow % 2 === 0) {
      unpackAlignment = 2;
    }

    let format;
    switch (bandCount) {
      case 1: {
        format = gl.LUMINANCE;
        break;
      }
      case 2: {
        format = gl.LUMINANCE_ALPHA;
        break;
      }
      case 3: {
        format = gl.RGB;
        break;
      }
      case 4: {
        format = gl.RGBA;
        break;
      }
      default: {
        throw new Error(`Unsupported number of bands: ${bandCount}`);
      }
    }

    const oldUnpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
    gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);
    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      format,
      size[0],
      size[1],
      0,
      format,
      textureType,
      data,
    );
    gl.pixelStorei(gl.UNPACK_ALIGNMENT, oldUnpackAlignment);
  }

  /**
   * @type {CanvasRenderingContext2D}
   */
  let pixelContext = null;

  function createPixelContext() {
    pixelContext = createCanvasContext2D(1, 1, undefined, {
      willReadFrequently: true,
    });
  }

  /**
   * @typedef {import("../DataTile.js").default|ImageTile|ReprojTile} TileType
   */

  /**
   * @extends {BaseTileRepresentation<TileType>}
   */
  class TileTexture extends BaseTileRepresentation {
    /**
     * @param {import("./BaseTileRepresentation.js").TileRepresentationOptions<TileType>} options The tile texture options.
     */
    constructor(options) {
      super(options);

      /**
       * @type {Array<WebGLTexture>}
       */
      this.textures = [];

      /**
       * @type {import("../size.js").Size}
       * @private
       */
      this.renderSize_ = toSize(
        options.grid.getTileSize(options.tile.tileCoord[0]),
      );

      /**
       * @type {number}
       */
      this.bandCount = NaN;

      const coords = new WebGLArrayBuffer(ARRAY_BUFFER, STATIC_DRAW);
      coords.fromArray([
        0, // P0
        1,
        1, // P1
        1,
        1, // P2
        0,
        0, // P3
        0,
      ]);
      this.helper.flushBufferData(coords);

      /**
       * @type {WebGLArrayBuffer}
       */
      this.coords = coords;

      this.setTile(options.tile);
    }

    /**
     * @override
     * @param {import("./Helper.js").default} helper The WebGL helper.
     */
    setHelper(helper) {
      const gl = this.helper?.getGL();
      if (gl) {
        this.helper.deleteBuffer(this.coords);
        for (let i = 0; i < this.textures.length; ++i) {
          gl.deleteTexture(this.textures[i]);
        }
      }

      super.setHelper(helper);

      if (helper) {
        helper.flushBufferData(this.coords);
      }
    }

    /**
     * @override
     */
    uploadTile() {
      const helper = this.helper;
      const gl = helper.getGL();
      const tile = this.tile;

      this.textures.length = 0;

      /**
       * @type {import("../DataTile.js").Data}
       */
      let data;

      if (tile instanceof ImageTile || tile instanceof ReprojTile) {
        data = tile.getImage();
      } else {
        data = tile.getData();
      }

      const image = asImageLike(data);
      if (image) {
        const texture = gl.createTexture();
        this.textures.push(texture);
        this.bandCount = 4;
        uploadImageTexture(gl, texture, image, tile.interpolate);
        this.setReady();
        return;
      }

      data = asArrayLike(data);

      const sourceTileSize = /** @type {DataTile} */ (tile).getSize();
      const pixelSize = [
        sourceTileSize[0] + 2 * this.gutter,
        sourceTileSize[1] + 2 * this.gutter,
      ];
      const isFloat = data instanceof Float32Array;
      const pixelCount = pixelSize[0] * pixelSize[1];
      const DataType = isFloat ? Float32Array : Uint8Array;
      const bytesPerElement = DataType.BYTES_PER_ELEMENT;
      const bytesPerRow = data.byteLength / pixelSize[1];

      this.bandCount = Math.floor(bytesPerRow / bytesPerElement / pixelSize[0]);
      const textureCount = Math.ceil(this.bandCount / 4);

      if (textureCount === 1) {
        const texture = gl.createTexture();
        this.textures.push(texture);
        uploadDataTexture(
          helper,
          texture,
          data,
          pixelSize,
          this.bandCount,
          tile.interpolate,
        );
        this.setReady();
        return;
      }

      const textureDataArrays = new Array(textureCount);
      for (let textureIndex = 0; textureIndex < textureCount; ++textureIndex) {
        const texture = gl.createTexture();
        this.textures.push(texture);

        const bandCount =
          textureIndex < textureCount - 1 ? 4 : ((this.bandCount - 1) % 4) + 1;
        textureDataArrays[textureIndex] = new DataType(pixelCount * bandCount);
      }

      let dataIndex = 0;
      let rowOffset = 0;
      const colCount = pixelSize[0] * this.bandCount;
      for (let rowIndex = 0; rowIndex < pixelSize[1]; ++rowIndex) {
        for (let colIndex = 0; colIndex < colCount; ++colIndex) {
          const dataValue = data[rowOffset + colIndex];

          const pixelIndex = Math.floor(dataIndex / this.bandCount);
          const bandIndex = colIndex % this.bandCount;
          const textureIndex = Math.floor(bandIndex / 4);
          const textureData = textureDataArrays[textureIndex];
          const bandCount = textureData.length / pixelCount;
          const textureBandIndex = bandIndex % 4;
          textureData[pixelIndex * bandCount + textureBandIndex] = dataValue;

          ++dataIndex;
        }
        rowOffset += bytesPerRow / bytesPerElement;
      }

      for (let textureIndex = 0; textureIndex < textureCount; ++textureIndex) {
        const texture = this.textures[textureIndex];
        const textureData = textureDataArrays[textureIndex];
        const bandCount = textureData.length / pixelCount;
        uploadDataTexture(
          helper,
          texture,
          textureData,
          pixelSize,
          bandCount,
          tile.interpolate,
        );
      }

      this.setReady();
    }

    /**
     * @param {import("../DataTile.js").ImageLike} image The image.
     * @param {number} renderCol The column index (in rendered tile space).
     * @param {number} renderRow The row index (in rendered tile space).
     * @return {Uint8ClampedArray|null} The data.
     * @private
     */
    getImagePixelData_(image, renderCol, renderRow) {
      const gutter = this.gutter;
      const renderWidth = this.renderSize_[0];
      const renderHeight = this.renderSize_[1];

      if (!pixelContext) {
        createPixelContext();
      }
      pixelContext.clearRect(0, 0, 1, 1);

      const sourceWidth = image.width;
      const sourceHeight = image.height;

      const sourceWidthWithoutGutter = sourceWidth - 2 * gutter;
      const sourceHeightWithoutGutter = sourceHeight - 2 * gutter;

      const sourceCol =
        gutter + Math.floor(sourceWidthWithoutGutter * (renderCol / renderWidth));

      const sourceRow =
        gutter +
        Math.floor(sourceHeightWithoutGutter * (renderRow / renderHeight));

      let data;
      try {
        pixelContext.drawImage(image, sourceCol, sourceRow, 1, 1, 0, 0, 1, 1);
        data = pixelContext.getImageData(0, 0, 1, 1).data;
      } catch {
        pixelContext = null;
        return null;
      }
      return data;
    }

    /**
     * @param {import("../DataTile.js").ArrayLike} data The data.
     * @param {import("../size.js").Size} sourceSize The size.
     * @param {number} renderCol The column index (in rendered tile space).
     * @param {number} renderRow The row index (in rendered tile space).
     * @return {import("../DataTile.js").ArrayLike|null} The data.
     * @private
     */
    getArrayPixelData_(data, sourceSize, renderCol, renderRow) {
      const gutter = this.gutter;
      const renderWidth = this.renderSize_[0];
      const renderHeight = this.renderSize_[1];

      const sourceWidthWithoutGutter = sourceSize[0];
      const sourceHeightWithoutGutter = sourceSize[1];
      const sourceWidth = sourceWidthWithoutGutter + 2 * gutter;
      const sourceHeight = sourceHeightWithoutGutter + 2 * gutter;

      const sourceCol =
        gutter + Math.floor(sourceWidthWithoutGutter * (renderCol / renderWidth));

      const sourceRow =
        gutter +
        Math.floor(sourceHeightWithoutGutter * (renderRow / renderHeight));

      if (data instanceof DataView) {
        const bytesPerPixel = data.byteLength / (sourceWidth * sourceHeight);
        const offset = bytesPerPixel * (sourceRow * sourceWidth + sourceCol);
        const buffer = data.buffer.slice(offset, offset + bytesPerPixel);
        return new DataView(buffer);
      }

      const offset = this.bandCount * (sourceRow * sourceWidth + sourceCol);
      return data.slice(offset, offset + this.bandCount);
    }

    /**
     * Get data for a pixel.  If the tile is not loaded, null is returned.
     * @param {number} renderCol The column index (in rendered tile space).
     * @param {number} renderRow The row index (in rendered tile space).
     * @return {import("../DataTile.js").ArrayLike|null} The data.
     */
    getPixelData(renderCol, renderRow) {
      if (!this.loaded) {
        return null;
      }

      if (this.tile instanceof DataTile) {
        const data = this.tile.getData();
        const arrayData = asArrayLike(data);
        if (arrayData) {
          const sourceSize = this.tile.getSize();
          return this.getArrayPixelData_(
            arrayData,
            sourceSize,
            renderCol,
            renderRow,
          );
        }
        return this.getImagePixelData_(asImageLike(data), renderCol, renderRow);
      }

      return this.getImagePixelData_(this.tile.getImage(), renderCol, renderRow);
    }
  }

  /**
   * @module ol/TileRange
   */

  /**
   * A representation of a contiguous block of tiles.  A tile range is specified
   * by its min/max tile coordinates and is inclusive of coordinates.
   */
  class TileRange {
    /**
     * @param {number} minX Minimum X.
     * @param {number} maxX Maximum X.
     * @param {number} minY Minimum Y.
     * @param {number} maxY Maximum Y.
     */
    constructor(minX, maxX, minY, maxY) {
      /**
       * @type {number}
       */
      this.minX = minX;

      /**
       * @type {number}
       */
      this.maxX = maxX;

      /**
       * @type {number}
       */
      this.minY = minY;

      /**
       * @type {number}
       */
      this.maxY = maxY;
    }

    /**
     * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @return {boolean} Contains tile coordinate.
     */
    contains(tileCoord) {
      return this.containsXY(tileCoord[1], tileCoord[2]);
    }

    /**
     * @param {TileRange} tileRange Tile range.
     * @return {boolean} Contains.
     */
    containsTileRange(tileRange) {
      return (
        this.minX <= tileRange.minX &&
        tileRange.maxX <= this.maxX &&
        this.minY <= tileRange.minY &&
        tileRange.maxY <= this.maxY
      );
    }

    /**
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @return {boolean} Contains coordinate.
     */
    containsXY(x, y) {
      return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY;
    }

    /**
     * @param {TileRange} tileRange Tile range.
     * @return {boolean} Equals.
     */
    equals(tileRange) {
      return (
        this.minX == tileRange.minX &&
        this.minY == tileRange.minY &&
        this.maxX == tileRange.maxX &&
        this.maxY == tileRange.maxY
      );
    }

    /**
     * @param {TileRange} tileRange Tile range.
     */
    extend(tileRange) {
      if (tileRange.minX < this.minX) {
        this.minX = tileRange.minX;
      }
      if (tileRange.maxX > this.maxX) {
        this.maxX = tileRange.maxX;
      }
      if (tileRange.minY < this.minY) {
        this.minY = tileRange.minY;
      }
      if (tileRange.maxY > this.maxY) {
        this.maxY = tileRange.maxY;
      }
    }

    /**
     * @return {number} Height.
     */
    getHeight() {
      return this.maxY - this.minY + 1;
    }

    /**
     * @return {import("./size.js").Size} Size.
     */
    getSize() {
      return [this.getWidth(), this.getHeight()];
    }

    /**
     * @return {number} Width.
     */
    getWidth() {
      return this.maxX - this.minX + 1;
    }

    /**
     * @param {TileRange} tileRange Tile range.
     * @return {boolean} Intersects.
     */
    intersects(tileRange) {
      return (
        this.minX <= tileRange.maxX &&
        this.maxX >= tileRange.minX &&
        this.minY <= tileRange.maxY &&
        this.maxY >= tileRange.minY
      );
    }
  }

  /**
   * @param {number} minX Minimum X.
   * @param {number} maxX Maximum X.
   * @param {number} minY Minimum Y.
   * @param {number} maxY Maximum Y.
   * @param {TileRange} [tileRange] TileRange.
   * @return {TileRange} Tile range.
   */
  function createOrUpdate$1(minX, maxX, minY, maxY, tileRange) {
    if (tileRange !== undefined) {
      tileRange.minX = minX;
      tileRange.maxX = maxX;
      tileRange.minY = minY;
      tileRange.maxY = maxY;
      return tileRange;
    }
    return new TileRange(minX, maxX, minY, maxY);
  }

  /**
   * @module ol/structs/LRUCache
   */


  /**
   * @typedef {Object} Entry
   * @property {string} key_ Key.
   * @property {Entry|null} newer Newer.
   * @property {Entry|null} older Older.
   * @property {*} value_ Value.
   */

  /**
   * @classdesc
   * Implements a Least-Recently-Used cache where the keys do not conflict with
   * Object's properties (e.g. 'hasOwnProperty' is not allowed as a key). Expiring
   * items from the cache is the responsibility of the user.
   *
   * @fires import("../events/Event.js").default
   * @template T
   */
  class LRUCache {
    /**
     * @param {number} [highWaterMark] High water mark.
     */
    constructor(highWaterMark) {
      /**
       * Desired max cache size after expireCache(). If set to 0, no cache entries
       * will be pruned at all.
       * @type {number}
       */
      this.highWaterMark = highWaterMark !== undefined ? highWaterMark : 2048;

      /**
       * @private
       * @type {number}
       */
      this.count_ = 0;

      /**
       * @private
       * @type {!Object<string, Entry>}
       */
      this.entries_ = {};

      /**
       * @private
       * @type {?Entry}
       */
      this.oldest_ = null;

      /**
       * @private
       * @type {?Entry}
       */
      this.newest_ = null;
    }

    deleteOldest() {
      const entry = this.pop();
      if (entry instanceof Disposable) {
        entry.dispose();
      }
    }

    /**
     * @return {boolean} Can expire cache.
     */
    canExpireCache() {
      return this.highWaterMark > 0 && this.getCount() > this.highWaterMark;
    }

    /**
     * Expire the cache. When the cache entry is a {@link module:ol/Disposable~Disposable},
     * the entry will be disposed.
     * @param {!Object<string, boolean>} [keep] Keys to keep. To be implemented by subclasses.
     */
    expireCache(keep) {
      while (this.canExpireCache()) {
        this.deleteOldest();
      }
    }

    /**
     * FIXME empty description for jsdoc
     */
    clear() {
      while (this.oldest_) {
        this.deleteOldest();
      }
    }

    /**
     * @param {string} key Key.
     * @return {boolean} Contains key.
     */
    containsKey(key) {
      return this.entries_.hasOwnProperty(key);
    }

    /**
     * @param {function(T, string, LRUCache<T>): ?} f The function
     *     to call for every entry from the oldest to the newer. This function takes
     *     3 arguments (the entry value, the entry key and the LRUCache object).
     *     The return value is ignored.
     */
    forEach(f) {
      let entry = this.oldest_;
      while (entry) {
        f(entry.value_, entry.key_, this);
        entry = entry.newer;
      }
    }

    /**
     * @param {string} key Key.
     * @param {*} [options] Options (reserved for subclasses).
     * @return {T} Value.
     */
    get(key, options) {
      const entry = this.entries_[key];
      assert(
        entry !== undefined,
        'Tried to get a value for a key that does not exist in the cache',
      );
      if (entry === this.newest_) {
        return entry.value_;
      }
      if (entry === this.oldest_) {
        this.oldest_ = /** @type {Entry} */ (this.oldest_.newer);
        this.oldest_.older = null;
      } else {
        entry.newer.older = entry.older;
        entry.older.newer = entry.newer;
      }
      entry.newer = null;
      entry.older = this.newest_;
      this.newest_.newer = entry;
      this.newest_ = entry;
      return entry.value_;
    }

    /**
     * Remove an entry from the cache.
     * @param {string} key The entry key.
     * @return {T} The removed entry.
     */
    remove(key) {
      const entry = this.entries_[key];
      assert(
        entry !== undefined,
        'Tried to get a value for a key that does not exist in the cache',
      );
      if (entry === this.newest_) {
        this.newest_ = /** @type {Entry} */ (entry.older);
        if (this.newest_) {
          this.newest_.newer = null;
        }
      } else if (entry === this.oldest_) {
        this.oldest_ = /** @type {Entry} */ (entry.newer);
        if (this.oldest_) {
          this.oldest_.older = null;
        }
      } else {
        entry.newer.older = entry.older;
        entry.older.newer = entry.newer;
      }
      delete this.entries_[key];
      --this.count_;
      return entry.value_;
    }

    /**
     * @return {number} Count.
     */
    getCount() {
      return this.count_;
    }

    /**
     * @return {Array<string>} Keys.
     */
    getKeys() {
      const keys = new Array(this.count_);
      let i = 0;
      let entry;
      for (entry = this.newest_; entry; entry = entry.older) {
        keys[i++] = entry.key_;
      }
      return keys;
    }

    /**
     * @return {Array<T>} Values.
     */
    getValues() {
      const values = new Array(this.count_);
      let i = 0;
      let entry;
      for (entry = this.newest_; entry; entry = entry.older) {
        values[i++] = entry.value_;
      }
      return values;
    }

    /**
     * @return {T} Last value.
     */
    peekLast() {
      return this.oldest_.value_;
    }

    /**
     * @return {string} Last key.
     */
    peekLastKey() {
      return this.oldest_.key_;
    }

    /**
     * Get the key of the newest item in the cache.  Throws if the cache is empty.
     * @return {string} The newest key.
     */
    peekFirstKey() {
      return this.newest_.key_;
    }

    /**
     * Return an entry without updating least recently used time.
     * @param {string} key Key.
     * @return {T|undefined} Value.
     */
    peek(key) {
      return this.entries_[key]?.value_;
    }

    /**
     * @return {T} value Value.
     */
    pop() {
      const entry = this.oldest_;
      delete this.entries_[entry.key_];
      if (entry.newer) {
        entry.newer.older = null;
      }
      this.oldest_ = /** @type {Entry} */ (entry.newer);
      if (!this.oldest_) {
        this.newest_ = null;
      }
      --this.count_;
      return entry.value_;
    }

    /**
     * @param {string} key Key.
     * @param {T} value Value.
     */
    replace(key, value) {
      this.get(key); // update `newest_`
      this.entries_[key].value_ = value;
    }

    /**
     * @param {string} key Key.
     * @param {T} value Value.
     */
    set(key, value) {
      assert(
        !(key in this.entries_),
        'Tried to set a value for a key that is used already',
      );
      const entry = {
        key_: key,
        newer: null,
        older: this.newest_,
        value_: value,
      };
      if (!this.newest_) {
        this.oldest_ = entry;
      } else {
        this.newest_.newer = entry;
      }
      this.newest_ = entry;
      this.entries_[key] = entry;
      ++this.count_;
    }

    /**
     * Set a maximum number of entries for the cache.
     * @param {number} size Cache size.
     * @api
     */
    setSize(size) {
      this.highWaterMark = size;
    }
  }

  /**
   * @module ol/tilecoord
   */

  /**
   * An array of three numbers representing the location of a tile in a tile
   * grid. The order is `z` (zoom level), `x` (column), and `y` (row).
   * @typedef {Array<number>} TileCoord
   * @api
   */

  /**
   * @param {number} z Z.
   * @param {number} x X.
   * @param {number} y Y.
   * @param {TileCoord} [tileCoord] Tile coordinate.
   * @return {TileCoord} Tile coordinate.
   */
  function createOrUpdate(z, x, y, tileCoord) {
    if (tileCoord !== undefined) {
      tileCoord[0] = z;
      tileCoord[1] = x;
      tileCoord[2] = y;
      return tileCoord;
    }
    return [z, x, y];
  }

  /**
   * @param {number} z Z.
   * @param {number} x X.
   * @param {number} y Y.
   * @return {string} Key.
   */
  function getKeyZXY(z, x, y) {
    return z + '/' + x + '/' + y;
  }

  /**
   * Get the key for a tile coord.
   * @param {TileCoord} tileCoord The tile coord.
   * @return {string} Key.
   */
  function getKey(tileCoord) {
    return getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]);
  }

  /**
   * @param {TileCoord} tileCoord Tile coord.
   * @return {number} Hash.
   */
  function hash(tileCoord) {
    return hashZXY(tileCoord[0], tileCoord[1], tileCoord[2]);
  }

  /**
   * @param {number} z The tile z coordinate.
   * @param {number} x The tile x coordinate.
   * @param {number} y The tile y coordinate.
   * @return {number} Hash.
   */
  function hashZXY(z, x, y) {
    return (x << z) + y;
  }

  /**
   * @param {TileCoord} tileCoord Tile coordinate.
   * @param {!import("./tilegrid/TileGrid.js").default} tileGrid Tile grid.
   * @return {boolean} Tile coordinate is within extent and zoom level range.
   */
  function withinExtentAndZ(tileCoord, tileGrid) {
    const z = tileCoord[0];
    const x = tileCoord[1];
    const y = tileCoord[2];

    if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) {
      return false;
    }
    const tileRange = tileGrid.getFullTileRange(z);
    if (!tileRange) {
      return true;
    }
    return tileRange.containsXY(x, y);
  }

  /**
   * @module ol/renderer/webgl/Layer
   */

  /**
   * @typedef {Object} PostProcessesOptions
   * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than
   * the main canvas that will then be sampled up (useful for saving resource on blur steps).
   * @property {string} [vertexShader] Vertex shader source
   * @property {string} [fragmentShader] Fragment shader source
   * @property {Object<string,import("../../webgl/Helper").UniformValue>} [uniforms] Uniform definitions for the post process step
   */

  /**
   * @typedef {Object} Options
   * @property {Object<string,import("../../webgl/Helper").UniformValue>} [uniforms] Uniform definitions for the post process steps
   * @property {Array<PostProcessesOptions>} [postProcesses] Post-processes definitions
   */

  /**
   * @classdesc
   * Base WebGL renderer class.
   * Holds all logic related to data manipulation & some common rendering logic
   * @template {import("../../layer/Layer.js").default} LayerType
   * @extends {LayerRenderer<LayerType>}
   */
  class WebGLLayerRenderer extends LayerRenderer {
    /**
     * @param {LayerType} layer Layer.
     * @param {Options} [options] Options.
     */
    constructor(layer, options) {
      super(layer);

      options = options || {};

      /**
       * The transform for viewport CSS pixels to rendered pixels.  This transform is only
       * set before dispatching rendering events.
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.inversePixelTransform_ = create$3();

      /**
       * @private
       */
      this.postProcesses_ = options.postProcesses;

      /**
       * @private
       */
      this.uniforms_ = options.uniforms;

      /**
       * @type {WebGLHelper}
       * @protected
       */
      this.helper;

      this.onMapChanged_ = () => {
        this.clearCache();
        this.removeHelper();
      };

      layer.addChangeListener(LayerProperty.MAP, this.onMapChanged_);

      this.dispatchPreComposeEvent = this.dispatchPreComposeEvent.bind(this);
      this.dispatchPostComposeEvent = this.dispatchPostComposeEvent.bind(this);
    }

    /**
     * @param {WebGLRenderingContext} context The WebGL rendering context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    dispatchPreComposeEvent(context, frameState) {
      const layer = this.getLayer();
      if (layer.hasListener(RenderEventType.PRECOMPOSE)) {
        const event = new RenderEvent(
          RenderEventType.PRECOMPOSE,
          undefined,
          frameState,
          context,
        );
        layer.dispatchEvent(event);
      }
    }

    /**
     * @param {WebGLRenderingContext} context The WebGL rendering context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    dispatchPostComposeEvent(context, frameState) {
      const layer = this.getLayer();
      if (layer.hasListener(RenderEventType.POSTCOMPOSE)) {
        const event = new RenderEvent(
          RenderEventType.POSTCOMPOSE,
          undefined,
          frameState,
          context,
        );
        layer.dispatchEvent(event);
      }
    }

    /**
     * Reset options (only handles uniforms).
     * @param {Options} options Options.
     */
    reset(options) {
      this.uniforms_ = options.uniforms;
      if (this.helper) {
        this.helper.setUniforms(this.uniforms_);
      }
    }

    /**
     * @protected
     */
    removeHelper() {
      if (this.helper) {
        this.helper.dispose();
        delete this.helper;
      }
    }

    /**
     * Determine whether renderFrame should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      if (this.getLayer().getRenderSource()) {
        let incrementGroup = true;
        let groupNumber = -1;
        let className;
        for (let i = 0, ii = frameState.layerStatesArray.length; i < ii; i++) {
          const layer = frameState.layerStatesArray[i].layer;
          const renderer = layer.getRenderer();
          if (!(renderer instanceof WebGLLayerRenderer)) {
            incrementGroup = true;
            continue;
          }
          const layerClassName = layer.getClassName();
          if (incrementGroup || layerClassName !== className) {
            groupNumber += 1;
            incrementGroup = false;
          }
          className = layerClassName;
          if (renderer === this) {
            break;
          }
        }

        const canvasCacheKey =
          'map/' + frameState.mapId + '/group/' + groupNumber;

        if (
          !this.helper ||
          !this.helper.canvasCacheKeyMatches(canvasCacheKey) ||
          this.helper.needsToBeRecreated()
        ) {
          this.removeHelper();

          this.helper = new WebGLHelper({
            postProcesses: this.postProcesses_,
            uniforms: this.uniforms_,
            canvasCacheKey: canvasCacheKey,
          });

          if (className) {
            this.helper.getCanvas().className = className;
          }

          this.afterHelperCreated();
        }
      }

      return this.prepareFrameInternal(frameState);
    }

    /**
     * @protected
     */
    afterHelperCreated() {}

    /**
     * Determine whether renderFrame should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @protected
     */
    prepareFrameInternal(frameState) {
      return true;
    }

    /**
     * @protected
     */
    clearCache() {}

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.clearCache();
      this.removeHelper();
      this.getLayer()?.removeChangeListener(
        LayerProperty.MAP,
        this.onMapChanged_,
      );
      super.disposeInternal();
    }

    /**
     * @param {import("../../render/EventType.js").default} type Event type.
     * @param {WebGLRenderingContext} context The rendering context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @private
     */
    dispatchRenderEvent_(type, context, frameState) {
      const layer = this.getLayer();
      if (layer.hasListener(type)) {
        compose(
          this.inversePixelTransform_,
          0,
          0,
          frameState.pixelRatio,
          -frameState.pixelRatio,
          0,
          0,
          -frameState.size[1],
        );

        const event = new RenderEvent(
          type,
          this.inversePixelTransform_,
          frameState,
          context,
        );
        layer.dispatchEvent(event);
      }
    }

    /**
     * @param {WebGLRenderingContext} context The rendering context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    preRender(context, frameState) {
      this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState);
    }

    /**
     * @param {WebGLRenderingContext} context The rendering context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    postRender(context, frameState) {
      this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState);
    }
  }

  /**
   * @module ol/renderer/webgl/TileLayerBase
   */

  const Uniforms$3 = {
    TILE_TRANSFORM: 'u_tileTransform',
    TRANSITION_ALPHA: 'u_transitionAlpha',
    DEPTH: 'u_depth',
    RENDER_EXTENT: 'u_renderExtent', // intersection of layer, source, and view extent
    PATTERN_ORIGIN: 'u_patternOrigin',
    RESOLUTION: 'u_resolution',
    ZOOM: 'u_zoom',
    GLOBAL_ALPHA: 'u_globalAlpha',
    PROJECTION_MATRIX: 'u_projectionMatrix',
    SCREEN_TO_WORLD_MATRIX: 'u_screenToWorldMatrix',
  };

  /**
   * Transform a zoom level into a depth value; zoom level zero has a depth value of 0.5, and increasing values
   * have a depth trending towards 0
   * @param {number} z A zoom level.
   * @return {number} A depth value.
   */
  function depthForZ(z) {
    return 1 / (z + 2);
  }

  /**
   * @typedef {import("../../webgl/BaseTileRepresentation.js").default<import("../../Tile.js").default>} AbstractTileRepresentation
   */
  /**
   * @typedef {Object} TileRepresentationLookup
   * @property {Set<string>} tileIds The set of tile ids in the lookup.
   * @property {Object<number, Set<AbstractTileRepresentation>>} representationsByZ Tile representations by zoom level.
   */

  /**
   * @return {TileRepresentationLookup} A new tile representation lookup.
   */
  function newTileRepresentationLookup() {
    return {tileIds: new Set(), representationsByZ: {}};
  }

  /**
   * Check if a tile is already in the tile representation lookup.
   * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of tile representations by zoom level.
   * @param {import("../../Tile.js").default} tile A tile.
   * @return {boolean} The tile is already in the lookup.
   */
  function lookupHasTile(tileRepresentationLookup, tile) {
    return tileRepresentationLookup.tileIds.has(getUid(tile));
  }

  /**
   * Add a tile representation to the lookup.
   * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of tile representations by zoom level.
   * @param {AbstractTileRepresentation} tileRepresentation A tile representation.
   * @param {number} z The zoom level.
   */
  function addTileRepresentationToLookup(
    tileRepresentationLookup,
    tileRepresentation,
    z,
  ) {
    const representationsByZ = tileRepresentationLookup.representationsByZ;
    if (!(z in representationsByZ)) {
      representationsByZ[z] = new Set();
    }
    representationsByZ[z].add(tileRepresentation);
    tileRepresentationLookup.tileIds.add(getUid(tileRepresentation.tile));
  }

  /**
   * @param {import("../../Map.js").FrameState} frameState Frame state.
   * @param {import("../../extent.js").Extent} extent The frame extent.
   * @return {import("../../extent.js").Extent} Frame extent intersected with layer extents.
   */
  function getRenderExtent$1(frameState, extent) {
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    if (layerState.extent) {
      extent = getIntersection(
        extent,
        fromUserExtent(layerState.extent, frameState.viewState.projection),
      );
    }
    const source = /** @type {import("../../source/Tile.js").default} */ (
      layerState.layer.getRenderSource()
    );
    if (!source.getWrapX()) {
      const gridExtent = source
        .getTileGridForProjection(frameState.viewState.projection)
        .getExtent();
      if (gridExtent) {
        extent = getIntersection(extent, gridExtent);
      }
    }
    return extent;
  }

  /**
   * @param {import("../../source/Tile.js").default} source The source.
   * @param {import('../../tilecoord.js').TileCoord} tileCoord The tile coordinate.
   * @return {string} The cache key.
   */
  function getCacheKey$1(source, tileCoord) {
    return `${getUid(source)},${source.getKey()},${source.getRevision()},${getKey(tileCoord)}`;
  }

  /**
   * @typedef {Object} Options
   * @property {Object<string, import("../../webgl/Helper").UniformValue>} [uniforms] Additional uniforms
   * made available to shaders.
   * @property {number} [cacheSize=512] The tile representation cache size.
   * @property {Array<import('./Layer.js').PostProcessesOptions>} [postProcesses] Post-processes definitions.
   */

  /**
   * @typedef {import("../../layer/BaseTile.js").default} BaseLayerType
   */

  /**
   * @classdesc
   * Base WebGL renderer for tile layers.
   * @template {BaseLayerType} LayerType
   * @template {import("../../Tile.js").default} TileType
   * @template {import("../../webgl/BaseTileRepresentation.js").default<TileType>} TileRepresentation
   * @extends {WebGLLayerRenderer<LayerType>}
   */
  class WebGLBaseTileLayerRenderer extends WebGLLayerRenderer {
    /**
     * @param {LayerType} tileLayer Tile layer.
     * @param {Options} options Options.
     */
    constructor(tileLayer, options) {
      super(tileLayer, {
        uniforms: options.uniforms,
        postProcesses: options.postProcesses,
      });

      /**
       * The last call to `renderFrame` was completed with all tiles loaded
       * @type {boolean}
       */
      this.renderComplete = false;

      /**
       * This transform converts representation coordinates to screen coordinates.
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.tileTransform_ = create$3();

      /**
       * @type {Array<number>}
       * @protected
       */
      this.tempMat4 = create$2();

      /**
       * @type {import("../../TileRange.js").default}
       * @private
       */
      this.tempTileRange_ = new TileRange(0, 0, 0, 0);

      /**
       * @type {import("../../tilecoord.js").TileCoord}
       * @private
       */
      this.tempTileCoord_ = createOrUpdate(0, 0, 0);

      /**
       * @type {import("../../size.js").Size}
       * @private
       */
      this.tempSize_ = [0, 0];

      const cacheSize = options.cacheSize !== undefined ? options.cacheSize : 512;
      /**
       * @type {import("../../structs/LRUCache.js").default<TileRepresentation>}
       * @protected
       */
      this.tileRepresentationCache = new LRUCache(cacheSize);

      /**
       * @protected
       * @type {import("../../Map.js").FrameState|null}
       */
      this.frameState = null;

      /**
       * @private
       * @type {import("../../proj/Projection.js").default}
       */
      this.renderedProjection_ = undefined;
    }

    /**
     * @param {Options} options Options.
     * @override
     */
    reset(options) {
      super.reset({
        uniforms: options.uniforms,
      });
    }

    /**
     * Determine whether renderFrame should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrameInternal(frameState) {
      if (!this.renderedProjection_) {
        this.renderedProjection_ = frameState.viewState.projection;
      } else if (frameState.viewState.projection !== this.renderedProjection_) {
        this.clearCache();
        this.renderedProjection_ = frameState.viewState.projection;
      }

      const layer = this.getLayer();
      const source = layer.getRenderSource();
      if (!source) {
        return false;
      }

      if (isEmpty(getRenderExtent$1(frameState, frameState.extent))) {
        return false;
      }
      return source.getState() === 'ready';
    }

    /**
     * @abstract
     * @param {import("../../webgl/BaseTileRepresentation.js").TileRepresentationOptions<TileType>} options tile representation options
     * @return {TileRepresentation} A new tile representation
     * @protected
     */
    createTileRepresentation(options) {
      return abstract();
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {import("../../extent.js").Extent} extent The extent to be rendered.
     * @param {number} initialZ The zoom level.
     * @param {TileRepresentationLookup} tileRepresentationLookup The zoom level.
     * @param {number} preload Number of additional levels to load.
     */
    enqueueTiles(
      frameState,
      extent,
      initialZ,
      tileRepresentationLookup,
      preload,
    ) {
      const viewState = frameState.viewState;
      const tileLayer = this.getLayer();
      const tileSource = tileLayer.getRenderSource();
      const tileGrid = tileSource.getTileGridForProjection(viewState.projection);
      const gutter = tileSource.getGutterForProjection(viewState.projection);

      const tileSourceKey = getUid(tileSource);
      if (!(tileSourceKey in frameState.wantedTiles)) {
        frameState.wantedTiles[tileSourceKey] = {};
      }

      const wantedTiles = frameState.wantedTiles[tileSourceKey];
      const tileRepresentationCache = this.tileRepresentationCache;

      const map = tileLayer.getMapInternal();
      const minZ = Math.max(
        initialZ - preload,
        tileGrid.getMinZoom(),
        tileGrid.getZForResolution(
          Math.min(
            tileLayer.getMaxResolution(),
            map
              ? map
                  .getView()
                  .getResolutionForZoom(Math.max(tileLayer.getMinZoom(), 0))
              : tileGrid.getResolution(0),
          ),
          tileSource.zDirection,
        ),
      );
      const rotation = viewState.rotation;
      const viewport = rotation
        ? getRotatedViewport(
            viewState.center,
            viewState.resolution,
            rotation,
            frameState.size,
          )
        : undefined;
      for (let z = initialZ; z >= minZ; --z) {
        const tileRange = tileGrid.getTileRangeForExtentAndZ(
          extent,
          z,
          this.tempTileRange_,
        );

        const tileResolution = tileGrid.getResolution(z);

        for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {
          for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {
            if (
              rotation &&
              !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)
            ) {
              continue;
            }
            const tileCoord = createOrUpdate(z, x, y, this.tempTileCoord_);
            const cacheKey = getCacheKey$1(tileSource, tileCoord);

            /** @type {TileRepresentation} */
            let tileRepresentation;

            /** @type {TileType} */
            let tile;

            if (tileRepresentationCache.containsKey(cacheKey)) {
              tileRepresentation = tileRepresentationCache.get(cacheKey);
              tile = tileRepresentation.tile;
            }
            if (
              !tileRepresentation ||
              tileRepresentation.tile.key !== tileSource.getKey()
            ) {
              tile = tileSource.getTile(
                z,
                x,
                y,
                frameState.pixelRatio,
                viewState.projection,
              );
              if (!tile) {
                continue;
              }
            }

            if (lookupHasTile(tileRepresentationLookup, tile)) {
              continue;
            }

            if (!tileRepresentation) {
              tileRepresentation = this.createTileRepresentation({
                tile: tile,
                grid: tileGrid,
                helper: this.helper,
                gutter: gutter,
              });
              tileRepresentationCache.set(cacheKey, tileRepresentation);
            } else {
              tileRepresentation.setTile(tile);
            }

            addTileRepresentationToLookup(
              tileRepresentationLookup,
              tileRepresentation,
              z,
            );

            const tileQueueKey = tile.getKey();
            wantedTiles[tileQueueKey] = true;

            if (tile.getState() === TileState.IDLE) {
              if (!frameState.tileQueue.isKeyQueued(tileQueueKey)) {
                frameState.tileQueue.enqueue([
                  tile,
                  tileSourceKey,
                  tileGrid.getTileCoordCenter(tileCoord),
                  tileResolution,
                ]);
              }
            }
          }
        }
      }
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {boolean} tilesWithAlpha True if at least one of the rendered tiles has alpha
     * @protected
     */
    beforeTilesRender(frameState, tilesWithAlpha) {
      this.helper.prepareDraw(this.frameState, !tilesWithAlpha, true);
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} If returns false, tile mask rendering will be skipped
     * @protected
     */
    beforeTilesMaskRender(frameState) {
      return false;
    }

    /**
     * @param {TileRepresentation} tileRepresentation Tile representation
     * @param {import("../../transform.js").Transform} tileTransform Tile transform
     * @param {import("../../Map.js").FrameState} frameState Frame state
     * @param {import("../../extent.js").Extent} renderExtent Render extent
     * @param {number} tileResolution Tile resolution
     * @param {import("../../size.js").Size} tileSize Tile size
     * @param {import("../../coordinate.js").Coordinate} tileOrigin Tile origin
     * @param {import("../../extent.js").Extent} tileExtent tile Extent
     * @param {number} depth Depth
     * @param {number} gutter Gutter
     * @param {number} alpha Alpha
     * @protected
     */
    renderTile(
      tileRepresentation,
      tileTransform,
      frameState,
      renderExtent,
      tileResolution,
      tileSize,
      tileOrigin,
      tileExtent,
      depth,
      gutter,
      alpha,
    ) {}

    /**
     * @param {TileRepresentation} tileRepresentation Tile representation
     * @param {number} tileZ Tile Z
     * @param {import("../../extent.js").Extent} extent Render extent
     * @param {number} depth Depth
     * @protected
     */
    renderTileMask(tileRepresentation, tileZ, extent, depth) {}

    drawTile_(
      frameState,
      tileRepresentation,
      tileZ,
      gutter,
      extent,
      alphaLookup,
      tileGrid,
    ) {
      if (!tileRepresentation.ready) {
        return;
      }
      const tile = tileRepresentation.tile;
      const tileCoord = tile.tileCoord;
      const tileCoordKey = getKey(tileCoord);
      const alpha = tileCoordKey in alphaLookup ? alphaLookup[tileCoordKey] : 1;

      const tileResolution = tileGrid.getResolution(tileZ);
      const tileSize = toSize(tileGrid.getTileSize(tileZ), this.tempSize_);
      const tileOrigin = tileGrid.getOrigin(tileZ);
      const tileExtent = tileGrid.getTileCoordExtent(tileCoord);
      // tiles with alpha are rendered last to allow blending
      const depth = alpha < 1 ? -1 : depthForZ(tileZ);
      if (alpha < 1) {
        frameState.animate = true;
      }

      const viewState = frameState.viewState;
      const centerX = viewState.center[0];
      const centerY = viewState.center[1];

      const tileWidthWithGutter = tileSize[0] + 2 * gutter;
      const tileHeightWithGutter = tileSize[1] + 2 * gutter;

      const aspectRatio = tileWidthWithGutter / tileHeightWithGutter;

      const centerI = (centerX - tileOrigin[0]) / (tileSize[0] * tileResolution);
      const centerJ = (tileOrigin[1] - centerY) / (tileSize[1] * tileResolution);

      const tileScale = viewState.resolution / tileResolution;

      const tileCenterI = tileCoord[1];
      const tileCenterJ = tileCoord[2];

      reset(this.tileTransform_);
      scale$3(
        this.tileTransform_,
        2 / ((frameState.size[0] * tileScale) / tileWidthWithGutter),
        -2 / ((frameState.size[1] * tileScale) / tileWidthWithGutter),
      );
      rotate$1(this.tileTransform_, viewState.rotation);
      scale$3(this.tileTransform_, 1, 1 / aspectRatio);
      translate$2(
        this.tileTransform_,
        (tileSize[0] * (tileCenterI - centerI) - gutter) / tileWidthWithGutter,
        (tileSize[1] * (tileCenterJ - centerJ) - gutter) / tileHeightWithGutter,
      );

      this.renderTile(
        /** @type {TileRepresentation} */ (tileRepresentation),
        this.tileTransform_,
        frameState,
        extent,
        tileResolution,
        tileSize,
        tileOrigin,
        tileExtent,
        depth,
        gutter,
        alpha,
      );
    }

    /**
     * Render the layer.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState) {
      this.frameState = frameState;
      this.renderComplete = true;
      const gl = this.helper.getGL();
      this.preRender(gl, frameState);

      const viewState = frameState.viewState;
      const tileLayer = this.getLayer();
      const tileSource = tileLayer.getRenderSource();
      const tileGrid = tileSource.getTileGridForProjection(viewState.projection);
      const gutter = tileSource.getGutterForProjection(viewState.projection);
      const extent = getRenderExtent$1(frameState, frameState.extent);
      const z = tileGrid.getZForResolution(
        viewState.resolution,
        tileSource.zDirection,
      );

      /**
       * @type {TileRepresentationLookup}
       */
      const tileRepresentationLookup = newTileRepresentationLookup();

      const preload = tileLayer.getPreload();
      if (frameState.nextExtent) {
        const targetZ = tileGrid.getZForResolution(
          viewState.nextResolution,
          tileSource.zDirection,
        );
        const nextExtent = getRenderExtent$1(frameState, frameState.nextExtent);
        this.enqueueTiles(
          frameState,
          nextExtent,
          targetZ,
          tileRepresentationLookup,
          preload,
        );
      }

      this.enqueueTiles(frameState, extent, z, tileRepresentationLookup, 0);
      if (preload > 0) {
        setTimeout(() => {
          this.enqueueTiles(
            frameState,
            extent,
            z - 1,
            tileRepresentationLookup,
            preload - 1,
          );
        }, 0);
      }

      /**
       * A lookup of alpha values for tiles at the target rendering resolution
       * for tiles that are in transition.  If a tile coord key is absent from
       * this lookup, the tile should be rendered at alpha 1.
       * @type {Object<string, number>}
       */
      const alphaLookup = {};

      let blend = false;
      const representationsByZ = tileRepresentationLookup.representationsByZ;

      // look for cached tiles to use if a target tile is not ready
      if (z in representationsByZ) {
        const uid = getUid(this);
        const time = frameState.time;
        for (const tileRepresentation of representationsByZ[z]) {
          const tile = tileRepresentation.tile;
          if (tile.getState() === TileState.EMPTY) {
            continue;
          }
          const tileCoord = tile.tileCoord;

          if (tileRepresentation.ready) {
            const alpha = tile.getAlpha(uid, time);
            if (alpha === 1) {
              // no need to look for alt tiles
              tile.endTransition(uid);
              continue;
            }
            blend = true;
            const tileCoordKey = getKey(tileCoord);
            alphaLookup[tileCoordKey] = alpha;
          }
          this.renderComplete = false;

          // first look for child tiles (at z + 1)
          const coveredByChildren = this.findAltTiles_(
            tileGrid,
            tileCoord,
            z + 1,
            tileRepresentationLookup,
          );

          if (coveredByChildren) {
            continue;
          }

          // next look for parent tiles
          const minZoom = tileGrid.getMinZoom();
          for (let parentZ = z - 1; parentZ >= minZoom; --parentZ) {
            const coveredByParent = this.findAltTiles_(
              tileGrid,
              tileCoord,
              parentZ,
              tileRepresentationLookup,
            );

            if (coveredByParent) {
              break;
            }
          }
        }
      }

      const zs = Object.keys(representationsByZ).map(Number).sort(descending);

      const renderTileMask = this.beforeTilesMaskRender(frameState);

      if (renderTileMask) {
        for (let j = 0, jj = zs.length; j < jj; ++j) {
          const tileZ = zs[j];
          for (const tileRepresentation of representationsByZ[tileZ]) {
            const tileCoord = tileRepresentation.tile.tileCoord;
            const tileCoordKey = getKey(tileCoord);
            // do not render the tile mask if alpha < 1
            if (tileCoordKey in alphaLookup) {
              continue;
            }
            const tileExtent = tileGrid.getTileCoordExtent(tileCoord);
            this.renderTileMask(
              /** @type {TileRepresentation} */ (tileRepresentation),
              tileZ,
              tileExtent,
              depthForZ(tileZ),
            );
          }
        }
      }

      this.beforeTilesRender(frameState, blend);

      for (let j = 0, jj = zs.length; j < jj; ++j) {
        const tileZ = zs[j];
        for (const tileRepresentation of representationsByZ[tileZ]) {
          const tileCoord = tileRepresentation.tile.tileCoord;
          const tileCoordKey = getKey(tileCoord);
          if (tileCoordKey in alphaLookup) {
            continue;
          }

          this.drawTile_(
            frameState,
            tileRepresentation,
            tileZ,
            gutter,
            extent,
            alphaLookup,
            tileGrid,
          );
        }
      }

      if (z in representationsByZ) {
        for (const tileRepresentation of representationsByZ[z]) {
          const tileCoord = tileRepresentation.tile.tileCoord;
          const tileCoordKey = getKey(tileCoord);
          if (tileCoordKey in alphaLookup) {
            this.drawTile_(
              frameState,
              tileRepresentation,
              z,
              gutter,
              extent,
              alphaLookup,
              tileGrid,
            );
          }
        }
      }

      this.beforeFinalize(frameState);
      this.helper.finalizeDraw(
        frameState,
        this.dispatchPreComposeEvent,
        this.dispatchPostComposeEvent,
      );

      const canvas = this.helper.getCanvas();

      const tileRepresentationCache = this.tileRepresentationCache;
      while (tileRepresentationCache.canExpireCache()) {
        const tileRepresentation = tileRepresentationCache.pop();
        tileRepresentation.dispose();
      }

      this.postRender(gl, frameState);
      return canvas;
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @protected
     */
    beforeFinalize(frameState) {
      return;
    }

    /**
     * Look for tiles covering the provided tile coordinate at an alternate
     * zoom level.  Loaded tiles will be added to the provided tile representation lookup.
     * @param {import("../../tilegrid/TileGrid.js").default} tileGrid The tile grid.
     * @param {import("../../tilecoord.js").TileCoord} tileCoord The target tile coordinate.
     * @param {number} altZ The alternate zoom level.
     * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of
     * tile representations by zoom level.
     * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.
     * @private
     */
    findAltTiles_(tileGrid, tileCoord, altZ, tileRepresentationLookup) {
      const tileRange = tileGrid.getTileRangeForTileCoordAndZ(
        tileCoord,
        altZ,
        this.tempTileRange_,
      );

      if (!tileRange) {
        return false;
      }

      let covered = true;
      const tileRepresentationCache = this.tileRepresentationCache;
      const source = this.getLayer().getRenderSource();
      for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {
        for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {
          const cacheKey = getCacheKey$1(source, [altZ, x, y]);
          let loaded = false;
          if (tileRepresentationCache.containsKey(cacheKey)) {
            const tileRepresentation = tileRepresentationCache.get(cacheKey);
            if (
              tileRepresentation.ready &&
              !lookupHasTile(tileRepresentationLookup, tileRepresentation.tile)
            ) {
              addTileRepresentationToLookup(
                tileRepresentationLookup,
                tileRepresentation,
                altZ,
              );
              loaded = true;
            }
          }
          if (!loaded) {
            covered = false;
          }
        }
      }
      return covered;
    }

    /**
     * @override
     */
    clearCache() {
      super.clearCache();

      const tileRepresentationCache = this.tileRepresentationCache;
      tileRepresentationCache.forEach((tileRepresentation) =>
        tileRepresentation.dispose(),
      );
      tileRepresentationCache.clear();
    }

    /**
     * @override
     */
    afterHelperCreated() {
      super.afterHelperCreated();

      this.tileRepresentationCache.forEach((tileRepresentation) =>
        tileRepresentation.setHelper(this.helper),
      );
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      super.disposeInternal();
      delete this.frameState;
    }
  }

  /**
   * @module ol/renderer/webgl/TileLayer
   */

  const Uniforms$2 = {
    ...Uniforms$3,
    TILE_TEXTURE_ARRAY: 'u_tileTextures',
    TEXTURE_PIXEL_WIDTH: 'u_texturePixelWidth',
    TEXTURE_PIXEL_HEIGHT: 'u_texturePixelHeight',
    TEXTURE_RESOLUTION: 'u_textureResolution', // map units per texture pixel
    TEXTURE_ORIGIN_X: 'u_textureOriginX', // map x coordinate of left edge of texture
    TEXTURE_ORIGIN_Y: 'u_textureOriginY', // map y coordinate of top edge of texture
  };

  const Attributes$2 = {
    TEXTURE_COORD: 'a_textureCoord',
  };

  /**
   * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
   */
  const attributeDescriptions = [
    {
      name: Attributes$2.TEXTURE_COORD,
      size: 2,
      type: AttributeType.FLOAT,
    },
  ];

  /**
   * @typedef {Object} Options
   * @property {string} vertexShader Vertex shader source.
   * @property {string} fragmentShader Fragment shader source.
   * @property {Object<string, import("../../webgl/Helper").UniformValue>} [uniforms] Additional uniforms
   * made available to shaders.
   * @property {Array<import("../../webgl/PaletteTexture.js").default>} [paletteTextures] Palette textures.
   * @property {number} [cacheSize=512] The texture cache size.
   * @property {Array<import('./Layer.js').PostProcessesOptions>} [postProcesses] Post-processes definitions.
   */

  /**
   * @typedef {import("../../webgl/TileTexture.js").TileType} TileTextureType
   */

  /**
   * @typedef {import("../../webgl/TileTexture.js").default} TileTextureRepresentation
   */

  /**
   * @classdesc
   * WebGL renderer for tile layers.
   * @template {import("../../layer/WebGLTile.js").default|import("../../layer/Flow.js").default} LayerType
   * @extends {WebGLBaseTileLayerRenderer<LayerType, TileTextureType, TileTextureRepresentation>}
   * @api
   */
  class WebGLTileLayerRenderer extends WebGLBaseTileLayerRenderer {
    /**
     * @param {LayerType} tileLayer Tile layer.
     * @param {Options} options Options.
     */
    constructor(tileLayer, options) {
      super(tileLayer, options);

      /**
       * @type {WebGLProgram}
       * @private
       */
      this.program_;

      /**
       * @private
       */
      this.vertexShader_ = options.vertexShader;

      /**
       * @private
       */
      this.fragmentShader_ = options.fragmentShader;

      /**
       * Tiles are rendered as a quad with the following structure:
       *
       *  [P3]---------[P2]
       *   |`           |
       *   |  `     B   |
       *   |    `       |
       *   |      `     |
       *   |   A    `   |
       *   |          ` |
       *  [P0]---------[P1]
       *
       * Triangle A: P0, P1, P3
       * Triangle B: P1, P2, P3
       *
       * @private
       */
      this.indices_ = new WebGLArrayBuffer(ELEMENT_ARRAY_BUFFER, STATIC_DRAW);
      this.indices_.fromArray([0, 1, 3, 1, 2, 3]);

      /**
       * @type {Array<import("../../webgl/PaletteTexture.js").default>}
       * @private
       */
      this.paletteTextures_ = options.paletteTextures || [];
    }

    /**
     * @param {Options} options Options.
     * @override
     */
    reset(options) {
      super.reset(options);
      if (this.helper) {
        const gl = this.helper.getGL();
        for (const paletteTexture of this.paletteTextures_) {
          paletteTexture.delete(gl);
        }
      }

      this.vertexShader_ = options.vertexShader;
      this.fragmentShader_ = options.fragmentShader;
      this.paletteTextures_ = options.paletteTextures || [];

      if (this.helper) {
        this.program_ = this.helper.getProgram(
          this.fragmentShader_,
          this.vertexShader_,
        );
        const gl = this.helper.getGL();
        for (const paletteTexture of this.paletteTextures_) {
          // upload the texture data
          paletteTexture.getTexture(gl);
        }
      }
    }

    /**
     * @override
     */
    afterHelperCreated() {
      super.afterHelperCreated();

      const gl = this.helper.getGL();
      for (const paletteTexture of this.paletteTextures_) {
        // upload the texture data
        paletteTexture.getTexture(gl);
      }

      this.program_ = this.helper.getProgram(
        this.fragmentShader_,
        this.vertexShader_,
      );
      this.helper.flushBufferData(this.indices_);
    }

    /**
     * @override
     */
    removeHelper() {
      if (this.helper) {
        const gl = this.helper.getGL();
        for (const paletteTexture of this.paletteTextures_) {
          paletteTexture.delete(gl);
        }
      }

      super.removeHelper();
    }

    /**
     * @override
     */
    createTileRepresentation(options) {
      return new TileTexture(options);
    }

    /**
     * @override
     */
    beforeTilesRender(frameState, tilesWithAlpha) {
      super.beforeTilesRender(frameState, tilesWithAlpha);
      this.helper.useProgram(this.program_, frameState);
    }

    /**
     * @override
     */
    renderTile(
      tileTexture,
      tileTransform,
      frameState,
      renderExtent,
      tileResolution,
      tileSize,
      tileOrigin,
      tileExtent,
      depth,
      gutter,
      alpha,
    ) {
      const gl = this.helper.getGL();
      this.helper.bindBuffer(tileTexture.coords);
      this.helper.bindBuffer(this.indices_);
      this.helper.enableAttributes(attributeDescriptions);

      let textureSlot = 0;
      while (textureSlot < tileTexture.textures.length) {
        const uniformName = `${Uniforms$2.TILE_TEXTURE_ARRAY}[${textureSlot}]`;
        this.helper.bindTexture(
          tileTexture.textures[textureSlot],
          textureSlot,
          uniformName,
        );
        ++textureSlot;
      }

      for (
        let paletteIndex = 0;
        paletteIndex < this.paletteTextures_.length;
        ++paletteIndex
      ) {
        const paletteTexture = this.paletteTextures_[paletteIndex];
        const texture = paletteTexture.getTexture(gl);
        this.helper.bindTexture(texture, textureSlot, paletteTexture.name);
        ++textureSlot;
      }

      const viewState = frameState.viewState;

      const tileWidthWithGutter = tileSize[0] + 2 * gutter;
      const tileHeightWithGutter = tileSize[1] + 2 * gutter;

      const tile = tileTexture.tile;
      const tileCoord = tile.tileCoord;

      const tileCenterI = tileCoord[1];
      const tileCenterJ = tileCoord[2];

      this.helper.setUniformMatrixValue(
        Uniforms$2.TILE_TRANSFORM,
        fromTransform(this.tempMat4, tileTransform),
      );

      this.helper.setUniformFloatValue(Uniforms$2.TRANSITION_ALPHA, alpha);
      this.helper.setUniformFloatValue(Uniforms$2.DEPTH, depth);

      let gutterExtent = renderExtent;
      if (gutter > 0) {
        gutterExtent = tileExtent;
        getIntersection(gutterExtent, renderExtent, gutterExtent);
      }
      this.helper.setUniformFloatVec4(Uniforms$2.RENDER_EXTENT, gutterExtent);

      this.helper.setUniformFloatValue(Uniforms$2.RESOLUTION, viewState.resolution);
      this.helper.setUniformFloatValue(Uniforms$2.ZOOM, viewState.zoom);

      this.helper.setUniformFloatValue(
        Uniforms$2.TEXTURE_PIXEL_WIDTH,
        tileWidthWithGutter,
      );
      this.helper.setUniformFloatValue(
        Uniforms$2.TEXTURE_PIXEL_HEIGHT,
        tileHeightWithGutter,
      );
      this.helper.setUniformFloatValue(
        Uniforms$2.TEXTURE_RESOLUTION,
        tileResolution,
      );
      this.helper.setUniformFloatValue(
        Uniforms$2.TEXTURE_ORIGIN_X,
        tileOrigin[0] +
          tileCenterI * tileSize[0] * tileResolution -
          gutter * tileResolution,
      );
      this.helper.setUniformFloatValue(
        Uniforms$2.TEXTURE_ORIGIN_Y,
        tileOrigin[1] -
          tileCenterJ * tileSize[1] * tileResolution +
          gutter * tileResolution,
      );

      this.helper.drawElements(0, this.indices_.getSize());
    }

    /**
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView} Data at the pixel location.
     * @override
     */
    getData(pixel) {
      const gl = this.helper.getGL();
      if (!gl) {
        return null;
      }

      const frameState = this.frameState;
      if (!frameState) {
        return null;
      }

      const layer = this.getLayer();
      const coordinate = apply(
        frameState.pixelToCoordinateTransform,
        pixel.slice(),
      );

      const viewState = frameState.viewState;
      const layerExtent = layer.getExtent();
      if (layerExtent) {
        if (
          !containsCoordinate(
            fromUserExtent(layerExtent, viewState.projection),
            coordinate,
          )
        ) {
          return null;
        }
      }

      // determine last source suitable for rendering at coordinate
      const sources = layer.getSources(
        boundingExtent([coordinate]),
        viewState.resolution,
      );
      let i, source, tileGrid;
      for (i = sources.length - 1; i >= 0; --i) {
        source = sources[i];
        if (source.getState() === 'ready') {
          tileGrid = source.getTileGridForProjection(viewState.projection);
          if (source.getWrapX()) {
            break;
          }
          const gridExtent = tileGrid.getExtent();
          if (!gridExtent || containsCoordinate(gridExtent, coordinate)) {
            break;
          }
        }
      }
      if (i < 0) {
        return null;
      }

      const tileTextureCache = this.tileRepresentationCache;
      for (
        let z = tileGrid.getZForResolution(viewState.resolution);
        z >= tileGrid.getMinZoom();
        --z
      ) {
        const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);
        const cacheKey = getCacheKey$1(source, tileCoord);
        if (!tileTextureCache.containsKey(cacheKey)) {
          continue;
        }
        const tileTexture = tileTextureCache.get(cacheKey);
        const tile = tileTexture.tile;
        if (tile.getState() === TileState.EMPTY) {
          return null;
        }
        if (!tileTexture.loaded) {
          continue;
        }
        const tileOrigin = tileGrid.getOrigin(z);
        const tileSize = toSize(tileGrid.getTileSize(z));
        const tileResolution = tileGrid.getResolution(z);

        const col =
          (coordinate[0] - tileOrigin[0]) / tileResolution -
          tileCoord[1] * tileSize[0];

        const row =
          (tileOrigin[1] - coordinate[1]) / tileResolution -
          tileCoord[2] * tileSize[1];

        return tileTexture.getPixelData(col, row);
      }
      return null;
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      const helper = this.helper;
      if (helper) {
        const gl = helper.getGL();
        for (const paletteTexture of this.paletteTextures_) {
          paletteTexture.delete(gl);
        }
        this.paletteTextures_.length = 0;

        gl.deleteProgram(this.program_);
        delete this.program_;
        helper.deleteBuffer(this.indices_);
      }
      super.disposeInternal();
      delete this.indices_;
    }
  }

  /**
   * @module ol/webgl/PaletteTexture
   */

  class PaletteTexture {
    /**
     * @param {string} name The name of the texture.
     * @param {Uint8Array} data The texture data.
     */
    constructor(name, data) {
      this.name = name;
      this.data = data;

      /**
       * @type {WebGLTexture|null}
       * @private
       */
      this.texture_ = null;
    }

    /**
     * @param {WebGLRenderingContext} gl Rendering context.
     * @return {WebGLTexture} The texture.
     */
    getTexture(gl) {
      if (!this.texture_) {
        const texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texImage2D(
          gl.TEXTURE_2D,
          0,
          gl.RGBA,
          this.data.length / 4,
          1,
          0,
          gl.RGBA,
          gl.UNSIGNED_BYTE,
          this.data,
        );
        this.texture_ = texture;
      }
      return this.texture_;
    }

    /**
     * @param {WebGLRenderingContext} gl Rendering context.
     */
    delete(gl) {
      if (this.texture_) {
        gl.deleteTexture(this.texture_);
      }
      this.texture_ = null;
    }
  }

  /**
   * @module ol/expr/gpu
   */

  /**
   * @param {string} operator Operator
   * @param {CompilationContext} context Compilation context
   * @return {string} A function name based on the operator, unique in the given context
   */
  function computeOperatorFunctionName(operator, context) {
    return `operator_${operator}_${Object.keys(context.functions).length}`;
  }

  /**
   * Will return the number as a float with a dot separator, which is required by GLSL.
   * @param {number} v Numerical value.
   * @return {string} The value as string.
   */
  function numberToGlsl(v) {
    const s = v.toString();
    return s.includes('.') ? s : s + '.0';
  }

  /**
   * Will return the number array as a float with a dot separator, concatenated with ', '.
   * @param {Array<number>} array Numerical values array.
   * @return {string} The array as a vector, e. g.: `vec3(1.0, 2.0, 3.0)`.
   */
  function arrayToGlsl(array) {
    if (array.length < 2 || array.length > 4) {
      throw new Error(
        '`formatArray` can only output `vec2`, `vec3` or `vec4` arrays.',
      );
    }
    return `vec${array.length}(${array.map(numberToGlsl).join(', ')})`;
  }

  /**
   * Will normalize and converts to string a `vec4` color array compatible with GLSL.
   * @param {string|import("../color.js").Color} color Color either in string format or [r, g, b, a] array format,
   * with RGB components in the 0..255 range and the alpha component in the 0..1 range.
   * Note that the final array will always have 4 components.
   * @return {string} The color expressed in the `vec4(1.0, 1.0, 1.0, 1.0)` form.
   */
  function colorToGlsl(color) {
    const array = asArray(color);
    const alpha = array.length > 3 ? array[3] : 1;
    return arrayToGlsl([array[0] / 255, array[1] / 255, array[2] / 255, alpha]);
  }

  /**
   * Normalizes and converts a number or array toa `vec2` array compatible with GLSL.
   * @param {number|import('../size.js').Size} size Size.
   * @return {string} The color expressed in the `vec4(1.0, 1.0, 1.0, 1.0)` form.
   */
  function sizeToGlsl(size) {
    const array = toSize(size);
    return arrayToGlsl(array);
  }

  /** @type {Object<string, number>} */
  const stringToFloatMap = {};
  let stringToFloatCounter = 0;

  /**
   * Returns a stable equivalent number for the string literal.
   * @param {string} string String literal value
   * @return {number} Number equivalent
   */
  function getStringNumberEquivalent(string) {
    if (!(string in stringToFloatMap)) {
      stringToFloatMap[string] = stringToFloatCounter++;
    }
    return stringToFloatMap[string];
  }

  /**
   * Returns a stable equivalent number for the string literal, for use in shaders. This number is then
   * converted to be a GLSL-compatible string.
   * Note: with a float precision of `mediump`, the amount of unique strings supported is 16,777,216
   * @param {string} string String literal value
   * @return {string} GLSL-compatible string containing a number
   */
  function stringToGlsl(string) {
    return numberToGlsl(getStringNumberEquivalent(string));
  }

  /**
   * Get the uniform name given a variable name.
   * @param {string} variableName The variable name.
   * @return {string} The uniform name.
   */
  function uniformNameForVariable(variableName) {
    return 'u_var_' + variableName;
  }

  /**
   * @typedef {import('./expression.js').ParsingContext} ParsingContext
   */
  /**
   *
   * @typedef {import("./expression.js").Expression} Expression
   */
  /**
   *
   * @typedef {import("./expression.js").LiteralExpression} LiteralExpression
   */

  /**
   * @typedef {Object} CompilationContextProperty
   * @property {string} name Name
   * @property {number} type Resolved property type
   */

  /**
   * @typedef {Object} CompilationContextVariable
   * @property {string} name Name
   * @property {number} type Resolved variable type
   */

  /**
   * @typedef {Object} CompilationContext
   * @property {Object<string, CompilationContextProperty>} properties The values for properties used in 'get' expressions.
   * @property {Object<string, CompilationContextVariable>} variables The values for variables used in 'var' expressions.
   * @property {Object<string, string>} functions Lookup of functions used by the style.
   * @property {number} [bandCount] Number of bands per pixel.
   * @property {Array<PaletteTexture>} [paletteTextures] List of palettes used by the style.
   * @property {boolean} featureId Whether the feature ID is used in the expression
   * @property {boolean} geometryType Whether the geometry type is used in the expression
   */

  /**
   * @return {CompilationContext} A new compilation context.
   */
  function newCompilationContext() {
    return {
      variables: {},
      properties: {},
      functions: {},
      bandCount: 0,
      featureId: false,
      geometryType: false,
    };
  }

  const GET_BAND_VALUE_FUNC = 'getBandValue';

  const PALETTE_TEXTURE_ARRAY = 'u_paletteTextures';

  const FEATURE_ID_PROPERTY_NAME = 'featureId';
  const GEOMETRY_TYPE_PROPERTY_NAME = 'geometryType';

  /**
   * The value `-9999999` will be used to indicate that a property on a feature is not defined, similar to a "no data" value.
   */
  const UNDEFINED_PROP_VALUE = -9999999;

  /**
   * @typedef {string} CompiledExpression
   */

  /**
   * @typedef {function(CompilationContext, CallExpression, number): string} Compiler
   * Third argument is the expected value types
   */

  /**
   * @param {import('./expression.js').EncodedExpression} encoded The encoded expression.
   * @param {number} type The expected type.
   * @param {import('./expression.js').ParsingContext} parsingContext The parsing context.
   * @param {CompilationContext} compilationContext An existing compilation context
   * @return {CompiledExpression} The compiled expression.
   */
  function buildExpression(
    encoded,
    type,
    parsingContext,
    compilationContext,
  ) {
    const expression = parse$1(encoded, type, parsingContext);
    return compile(expression, type, compilationContext);
  }

  /**
   * @param {function(Array<CompiledExpression>, CompilationContext): string} output Function that takes in parsed arguments and returns a string
   * @return {function(CompilationContext, import("./expression.js").CallExpression, number): string} Compiler for the call expression
   */
  function createCompiler(output) {
    return (context, expression, type) => {
      const length = expression.args.length;
      const args = new Array(length);
      for (let i = 0; i < length; ++i) {
        args[i] = compile(expression.args[i], type, context);
      }
      return output(args, context);
    };
  }

  /**
   * @type {Object<string, Compiler>}
   */
  const compilers = {
    [Ops.Get]: (context, expression) => {
      const firstArg = /** @type {LiteralExpression} */ (expression.args[0]);
      const propName = /** @type {string} */ (firstArg.value);
      const isExisting = propName in context.properties;
      if (!isExisting) {
        context.properties[propName] = {
          name: propName,
          type: expression.type,
        };
      }
      return 'a_prop_' + propName;
    },
    [Ops.Id]: (context) => {
      context.featureId = true;
      return 'a_' + FEATURE_ID_PROPERTY_NAME;
    },
    [Ops.GeometryType]: (context) => {
      context.geometryType = true;
      return 'a_' + GEOMETRY_TYPE_PROPERTY_NAME;
    },
    [Ops.LineMetric]: () => 'currentLineMetric', // this variable is assumed to always be present in shaders, default is 0.
    [Ops.Var]: (context, expression) => {
      const firstArg = /** @type {LiteralExpression} */ (expression.args[0]);
      const varName = /** @type {string} */ (firstArg.value);
      const isExisting = varName in context.variables;
      if (!isExisting) {
        context.variables[varName] = {
          name: varName,
          type: expression.type,
        };
      }
      return uniformNameForVariable(varName);
    },
    [Ops.Has]: (context, expression) => {
      const firstArg = /** @type {LiteralExpression} */ (expression.args[0]);
      const propName = /** @type {string} */ (firstArg.value);
      const isExisting = propName in context.properties;
      if (!isExisting) {
        context.properties[propName] = {
          name: propName,
          type: expression.type,
        };
      }
      return `(a_prop_${propName} != ${numberToGlsl(UNDEFINED_PROP_VALUE)})`;
    },
    [Ops.Resolution]: () => 'u_resolution',
    [Ops.Zoom]: () => 'u_zoom',
    [Ops.Time]: () => 'u_time',
    [Ops.Any]: createCompiler((compiledArgs) => `(${compiledArgs.join(` || `)})`),
    [Ops.All]: createCompiler((compiledArgs) => `(${compiledArgs.join(` && `)})`),
    [Ops.Not]: createCompiler(([value]) => `(!${value})`),
    [Ops.Equal]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} == ${secondValue})`,
    ),
    [Ops.NotEqual]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} != ${secondValue})`,
    ),
    [Ops.GreaterThan]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} > ${secondValue})`,
    ),
    [Ops.GreaterThanOrEqualTo]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} >= ${secondValue})`,
    ),
    [Ops.LessThan]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} < ${secondValue})`,
    ),
    [Ops.LessThanOrEqualTo]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} <= ${secondValue})`,
    ),
    [Ops.Multiply]: createCompiler(
      (compiledArgs) => `(${compiledArgs.join(' * ')})`,
    ),
    [Ops.Divide]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} / ${secondValue})`,
    ),
    [Ops.Add]: createCompiler((compiledArgs) => `(${compiledArgs.join(' + ')})`),
    [Ops.Subtract]: createCompiler(
      ([firstValue, secondValue]) => `(${firstValue} - ${secondValue})`,
    ),
    [Ops.Clamp]: createCompiler(
      ([value, min, max]) => `clamp(${value}, ${min}, ${max})`,
    ),
    [Ops.Mod]: createCompiler(([value, modulo]) => `mod(${value}, ${modulo})`),
    [Ops.Pow]: createCompiler(([value, power]) => `pow(${value}, ${power})`),
    [Ops.Abs]: createCompiler(([value]) => `abs(${value})`),
    [Ops.Floor]: createCompiler(([value]) => `floor(${value})`),
    [Ops.Ceil]: createCompiler(([value]) => `ceil(${value})`),
    [Ops.Round]: createCompiler(([value]) => `floor(${value} + 0.5)`),
    [Ops.Sin]: createCompiler(([value]) => `sin(${value})`),
    [Ops.Cos]: createCompiler(([value]) => `cos(${value})`),
    [Ops.Atan]: createCompiler(([firstValue, secondValue]) => {
      return secondValue !== undefined
        ? `atan(${firstValue}, ${secondValue})`
        : `atan(${firstValue})`;
    }),
    [Ops.Sqrt]: createCompiler(([value]) => `sqrt(${value})`),
    [Ops.Match]: createCompiler((compiledArgs) => {
      const input = compiledArgs[0];
      const fallback = compiledArgs[compiledArgs.length - 1];
      let result = null;
      for (let i = compiledArgs.length - 3; i >= 1; i -= 2) {
        const match = compiledArgs[i];
        const output = compiledArgs[i + 1];
        result = `(${input} == ${match} ? ${output} : ${result || fallback})`;
      }
      return result;
    }),
    [Ops.Between]: createCompiler(
      ([value, min, max]) => `(${value} >= ${min} && ${value} <= ${max})`,
    ),
    [Ops.Interpolate]: createCompiler(([exponent, input, ...compiledArgs]) => {
      let result = '';
      for (let i = 0; i < compiledArgs.length - 2; i += 2) {
        const stop1 = compiledArgs[i];
        const output1 = result || compiledArgs[i + 1];
        const stop2 = compiledArgs[i + 2];
        const output2 = compiledArgs[i + 3];
        let ratio;
        if (exponent === numberToGlsl(1)) {
          ratio = `(${input} - ${stop1}) / (${stop2} - ${stop1})`;
        } else {
          ratio = `(pow(${exponent}, (${input} - ${stop1})) - 1.0) / (pow(${exponent}, (${stop2} - ${stop1})) - 1.0)`;
        }
        result = `mix(${output1}, ${output2}, clamp(${ratio}, 0.0, 1.0))`;
      }
      return result;
    }),
    [Ops.Case]: createCompiler((compiledArgs) => {
      const fallback = compiledArgs[compiledArgs.length - 1];
      let result = null;
      for (let i = compiledArgs.length - 3; i >= 0; i -= 2) {
        const condition = compiledArgs[i];
        const output = compiledArgs[i + 1];
        result = `(${condition} ? ${output} : ${result || fallback})`;
      }
      return result;
    }),
    [Ops.In]: createCompiler(([needle, ...haystack], context) => {
      const funcName = computeOperatorFunctionName('in', context);
      const tests = [];
      for (let i = 0; i < haystack.length; i += 1) {
        tests.push(`  if (inputValue == ${haystack[i]}) { return true; }`);
      }
      context.functions[funcName] = `bool ${funcName}(float inputValue) {
${tests.join('\n')}
  return false;
}`;
      return `${funcName}(${needle})`;
    }),
    [Ops.Array]: createCompiler(
      (args) => `vec${args.length}(${args.join(', ')})`,
    ),
    [Ops.Color]: createCompiler((compiledArgs) => {
      if (compiledArgs.length === 1) {
        //grayscale
        return `vec4(vec3(${compiledArgs[0]} / 255.0), 1.0)`;
      }
      if (compiledArgs.length === 2) {
        //grayscale with alpha
        return `vec4(vec3(${compiledArgs[0]} / 255.0), ${compiledArgs[1]})`;
      }
      const rgb = compiledArgs.slice(0, 3).map((color) => `${color} / 255.0`);
      if (compiledArgs.length === 3) {
        return `vec4(${rgb.join(', ')}, 1.0)`;
      }
      const alpha = compiledArgs[3];
      return `vec4(${rgb.join(', ')}, ${alpha})`;
    }),
    [Ops.Band]: createCompiler(([band, xOffset, yOffset], context) => {
      if (!(GET_BAND_VALUE_FUNC in context.functions)) {
        let ifBlocks = '';
        const bandCount = context.bandCount || 1;
        for (let i = 0; i < bandCount; i++) {
          const colorIndex = Math.floor(i / 4);
          let bandIndex = i % 4;
          if (i === bandCount - 1 && bandIndex === 1) {
            // LUMINANCE_ALPHA - band 1 assigned to rgb and band 2 assigned to alpha
            bandIndex = 3;
          }
          const textureName = `${Uniforms$2.TILE_TEXTURE_ARRAY}[${colorIndex}]`;
          ifBlocks += `  if (band == ${i + 1}.0) {
    return texture2D(${textureName}, v_textureCoord + vec2(dx, dy))[${bandIndex}];
  }
`;
        }

        context.functions[GET_BAND_VALUE_FUNC] =
          `float getBandValue(float band, float xOffset, float yOffset) {
  float dx = xOffset / ${Uniforms$2.TEXTURE_PIXEL_WIDTH};
  float dy = yOffset / ${Uniforms$2.TEXTURE_PIXEL_HEIGHT};
${ifBlocks}
}`;
      }

      return `${GET_BAND_VALUE_FUNC}(${band}, ${xOffset ?? '0.0'}, ${
      yOffset ?? '0.0'
    })`;
    }),
    [Ops.Palette]: (context, expression) => {
      const [index, ...colors] = expression.args;
      const numColors = colors.length;
      const palette = new Uint8Array(numColors * 4);
      for (let i = 0; i < colors.length; i++) {
        const parsedValue = /** @type {string | Array<number>} */ (
          /** @type {LiteralExpression} */ (colors[i]).value
        );
        const color = asArray(parsedValue);
        const offset = i * 4;
        palette[offset] = color[0];
        palette[offset + 1] = color[1];
        palette[offset + 2] = color[2];
        palette[offset + 3] = color[3] * 255;
      }
      if (!context.paletteTextures) {
        context.paletteTextures = [];
      }
      const paletteName = `${PALETTE_TEXTURE_ARRAY}[${context.paletteTextures.length}]`;
      const paletteTexture = new PaletteTexture(paletteName, palette);
      context.paletteTextures.push(paletteTexture);
      const compiledIndex = compile(index, NumberType$1, context);
      return `texture2D(${paletteName}, vec2((${compiledIndex} + 0.5) / ${numColors}.0, 0.5))`;
    },
    // TODO: unimplemented
    // Ops.Number
    // Ops.String
    // Ops.Coalesce
    // Ops.Concat
    // Ops.ToString
  };

  /**
   * @param {Expression} expression The expression.
   * @param {number} returnType The expected return type.
   * @param {CompilationContext} context The compilation context.
   * @return {CompiledExpression} The compiled expression
   */
  function compile(expression, returnType, context) {
    // operator
    if (expression instanceof CallExpression) {
      const compiler = compilers[expression.operator];
      if (compiler === undefined) {
        throw new Error(
          `No compiler defined for this operator: ${JSON.stringify(
          expression.operator,
        )}`,
        );
      }
      return compiler(context, expression, returnType);
    }

    if ((expression.type & NumberType$1) > 0) {
      return numberToGlsl(/** @type {number} */ (expression.value));
    }

    if ((expression.type & BooleanType$1) > 0) {
      return expression.value.toString();
    }

    if ((expression.type & StringType$1) > 0) {
      return stringToGlsl(expression.value.toString());
    }

    if ((expression.type & ColorType$1) > 0) {
      return colorToGlsl(
        /** @type {Array<number> | string} */ (expression.value),
      );
    }

    if ((expression.type & NumberArrayType$1) > 0) {
      return arrayToGlsl(/** @type {Array<number>} */ (expression.value));
    }

    if ((expression.type & SizeType) > 0) {
      return sizeToGlsl(
        /** @type {number|import('../size.js').Size} */ (expression.value),
      );
    }

    throw new Error(
      `Unexpected expression ${expression.value} (expected type ${typeName(
      returnType,
    )})`,
    );
  }

  /**
   * @module ol/style/flat
   */

  /**
   * @api
   * @fileoverview Vector layers can be styled with an object literal containing properties for
   * stroke, fill, image, and text styles.  The types below can be composed into a single object.
   * For example, a style with both stroke and fill properties could look like this:
   *
   *     const style = {
   *       'stroke-color': 'yellow',
   *       'stroke-width': 1.5,
   *       'fill-color': 'orange',
   *     };
   *
   * See details about the available properties depending on what type of symbolizer should be applied:
   *  {@link module:ol/style/flat~FlatStroke Stroke} - properties for applying a stroke to lines and polygons
   *  {@link module:ol/style/flat~FlatFill Fill} - properties for filling polygons
   *  {@link module:ol/style/flat~FlatText Text} - properties for labeling points, lines, and polygons
   *  {@link module:ol/style/flat~FlatIcon Icon} - properties for rendering points with an icon
   *  {@link module:ol/style/flat~FlatCircle Circle} - properties for rendering points with a circle
   *  {@link module:ol/style/flat~FlatShape Shape} - properties for rendering points with a regular shape
   *
   * To conditionally apply styles based on a filter, a list of {@link module:ol/style/flat~Rule rules} can be used.
   * For example, to style points with a big orange circle if the population is greater than 1 million and
   * a smaller blue circle otherwise:
   *
   *     const rules = [
   *       {
   *         filter: ['>', ['get', 'population'], 1_000_000],
   *         style: {
   *           'circle-radius': 10,
   *           'circle-fill-color': 'red',
   *         }
   *       },
   *       {
   *         else: true,
   *         style: {
   *           'circle-radius': 5,
   *           'circle-fill-color': 'blue',
   *         },
   *       },
   *     ];
   */

  /**
   * A literal boolean (e.g. `true`) or an expression that evaluates to a boolean (e.g. `['>', ['get', 'population'], 1_000_000]`).
   *
   * @typedef {boolean|Array} BooleanExpression
   */

  /**
   * A literal string (e.g. `'hello'`) or an expression that evaluates to a string (e.g. `['get', 'greeting']`).
   *
   * @typedef {string|Array} StringExpression
   */

  /**
   * A literal number (e.g. `42`) or an expression that evaluates to a number (e.g. `['+', 40, 2]`).
   *
   * @typedef {number|Array} NumberExpression
   */

  /**
   * A CSS named color (e.g. `'blue'`), an array of 3 RGB values (e.g. `[0, 255, 0]`), an array of 4 RGBA values
   * (e.g. `[0, 255, 0, 0.5]`), or an expression that evaluates to one of these color types (e.g. `['get', 'color']`).
   *
   * @typedef {import("../color.js").Color|string|Array} ColorExpression
   */

  /**
   * An array of numbers (e.g. `[1, 2, 3]`) or an expression that evaluates to the same (e.g. `['get', 'values']`).
   *
   * @typedef {Array<number>|Array} NumberArrayExpression
   */

  /**
   * An array of two numbers (e.g. `[10, 20]`) or an expression that evaluates to the same (e.g. `['get', 'size']`).
   *
   * @typedef {number|Array<number>|Array} SizeExpression
   */

  /**
   * For static styling, the [layer.setStyle()]{@link module:ol/layer/Vector~VectorLayer#setStyle} method
   * can be called with an object literal that has fill, stroke, text, icon, regular shape, and/or circle properties.
   * @api
   *
   * @typedef {FlatFill & FlatStroke & FlatText & FlatIcon & FlatShape & FlatCircle} FlatStyle
   */

  /**
   * A flat style literal or an array of the same.
   *
   * @typedef {FlatStyle|Array<FlatStyle>|Array<Rule>} FlatStyleLike
   */

  /**
   * Fill style properties applied to polygon features.
   *
   * @typedef {Object} FlatFill
   * @property {ColorExpression} [fill-color] The fill color. `'none'` means no fill and no hit detection (applies to Canvas only).
   * @property {StringExpression} [fill-pattern-src] Fill pattern image source URI. If `fill-color` is defined as well,
   * it will be used to tint this image. (Expressions only in Canvas)
   * @property {SizeExpression} [fill-pattern-size] Fill pattern image size in pixels.
   * Can be used together with `fill-pattern-offset` to define the sub-rectangle to use
   * from a fill pattern image sprite sheet.
   * @property {SizeExpression} [fill-pattern-offset=[0, 0]] Offset, which, together with the size and the offset origin, define the
   * sub-rectangle to use from the original fill pattern image.
   * @property {import("./Icon.js").IconOrigin} [fill-pattern-offset-origin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`. (WebGL only)
   */

  /**
   * Stroke style properties applied to line strings and polygon boundaries. To apply a stroke, at least one of
   * `stroke-color` or `stroke-width` must be provided.
   *
   * @typedef {Object} FlatStroke
   * @property {ColorExpression} [stroke-color] The stroke color.
   * @property {NumberExpression} [stroke-width] Stroke pixel width.
   * @property {StringExpression} [stroke-line-cap='round'] Line cap style: `butt`, `round`, or `square`.
   * @property {StringExpression} [stroke-line-join='round'] Line join style: `bevel`, `round`, or `miter`.
   * @property {NumberArrayExpression} [stroke-line-dash] Line dash pattern.
   * @property {NumberExpression} [stroke-line-dash-offset=0] Line dash offset.
   * @property {NumberExpression} [stroke-miter-limit=10] Miter limit.
   * @property {NumberExpression} [stroke-offset] Stroke offset in pixel. A positive value offsets the line to the right,
   * relative to the direction of the line. (WebGL only)
   * @property {string} [stroke-pattern-src] Stroke pattern image source URI. If `stroke-color` is defined as well,
   * it will be used to tint this image. (WebGL only)
   * @property {SizeExpression} [stroke-pattern-offset=[0, 0]] Offset, which, together with the size and the offset origin,
   * define the sub-rectangle to use from the original fill pattern image. (WebGL only)
   * @property {import("./Icon.js").IconOrigin} [stroke-pattern-offset-origin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`. (WebGL only)
   * @property {SizeExpression} [stroke-pattern-size] Stroke pattern image size in pixel. Can be used together with `stroke-pattern-offset` to define the
   * sub-rectangle to use from the origin (sprite) fill pattern image. (WebGL only)
   * @property {NumberExpression} [stroke-pattern-spacing] Spacing between each pattern occurrence in pixels; 0 if undefined.
   * @property {NumberExpression} [z-index] The zIndex of the style.
   */

  /**
   * Label style properties applied to all features. At a minimum, a `text-value` must be provided.
   * Note: text style is currently not supported in WebGL layers
   *
   * @typedef {Object} FlatText
   * @property {StringExpression} [text-value] Text content (with `\n` for line breaks).
   * @property {StringExpression} [text-font='10px sans-serif'] Font style as [CSS `font`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/font) value.
   * @property {NumberExpression} [text-max-angle=Math.PI/4] When `text-placement` is set to `'line'`, allow a maximum angle between adjacent characters.
   * The expected value is in radians, and the default is 45° (`Math.PI / 4`).
   * @property {NumberExpression} [text-offset-x=0] Horizontal text offset in pixels. A positive will shift the text right.
   * @property {NumberExpression} [text-offset-y=0] Vertical text offset in pixels. A positive will shift the text down.
   * @property {BooleanExpression} [text-overflow=false] For polygon labels or when `placement` is set to `'line'`, allow text to exceed
   * the width of the polygon at the label position or the length of the path that it follows.
   * @property {StringExpression} [text-placement='point'] Text placement.
   * @property {NumberExpression} [text-repeat] Repeat interval in pixels. When set, the text will be repeated at this interval. Only available when
   * `text-placement` is set to `'line'`. Overrides `text-align`.
   * @property {SizeExpression} [text-scale] Scale.
   * @property {BooleanExpression} [text-rotate-with-view=false] Whether to rotate the text with the view.
   * @property {NumberExpression} [text-rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {StringExpression} [text-align] Text alignment. Possible values: `'left'`, `'right'`, `'center'`, `'end'` or `'start'`.
   * Default is `'center'` for `'text-placement': 'point'`. For `'text-placement': 'line'`, the default is to let the renderer choose a
   * placement where `text-max-angle` is not exceeded.
   * @property {StringExpression} [text-justify] Text justification within the text box.
   * If not set, text is justified towards the `textAlign` anchor.
   * Otherwise, use options `'left'`, `'center'`, or `'right'` to justify the text within the text box.
   * **Note:** `text-justify` is ignored for immediate rendering and also for `'text-placement': 'line'`.
   * @property {StringExpression} [text-baseline='middle'] Text base line. Possible values: `'bottom'`, `'top'`, `'middle'`, `'alphabetic'`,
   * `'hanging'`, `'ideographic'`.
   * @property {NumberArrayExpression} [text-padding=[0, 0, 0, 0]] Padding in pixels around the text for decluttering and background. The order of
   * values in the array is `[top, right, bottom, left]`.
   * @property {ColorExpression} [text-fill-color] The fill color. `'none'` means no fill and no hit detection.
   * @property {ColorExpression} [text-background-fill-color] The fill color. `'none'` means no fill and no hit detection.
   * @property {ColorExpression} [text-stroke-color] The stroke color.
   * @property {StringExpression} [text-stroke-line-cap='round'] Line cap style: `butt`, `round`, or `square`.
   * @property {StringExpression} [text-stroke-line-join='round'] Line join style: `bevel`, `round`, or `miter`.
   * @property {NumberArrayExpression} [text-stroke-line-dash] Line dash pattern.
   * @property {NumberExpression} [text-stroke-line-dash-offset=0] Line dash offset.
   * @property {NumberExpression} [text-stroke-miter-limit=10] Miter limit.
   * @property {NumberExpression} [text-stroke-width] Stroke pixel width.
   * @property {ColorExpression} [text-background-stroke-color] The stroke color.
   * @property {StringExpression} [text-background-stroke-line-cap='round'] Line cap style: `butt`, `round`, or `square`.
   * @property {StringExpression} [text-background-stroke-line-join='round'] Line join style: `bevel`, `round`, or `miter`.
   * @property {NumberArrayExpression} [text-background-stroke-line-dash] Line dash pattern.
   * @property {NumberExpression} [text-background-stroke-line-dash-offset=0] Line dash offset.
   * @property {NumberExpression} [text-background-stroke-miter-limit=10] Miter limit.
   * @property {NumberExpression} [text-background-stroke-width] Stroke pixel width.
   * @property {import("./Style.js").DeclutterMode} [text-declutter-mode] Declutter mode
   * @property {NumberExpression} [z-index] The zIndex of the style.
   */

  /**
   * Icon style properties applied to point features. `icon-src` must be provided to render
   * points with an icon.
   *
   * @typedef {Object} FlatIcon
   * @property {string} [icon-src] Image source URI.
   * @property {NumberArrayExpression} [icon-anchor=[0.5, 0.5]] Anchor. Default value is the icon center.
   * @property {import("./Icon.js").IconOrigin} [icon-anchor-origin='top-left'] Origin of the anchor: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`.
   * @property {import("./Icon.js").IconAnchorUnits} [icon-anchor-x-units='fraction'] Units in which the anchor x value is
   * specified. A value of `'fraction'` indicates the x value is a fraction of the icon. A value of `'pixels'` indicates
   * the x value in pixels.
   * @property {import("./Icon.js").IconAnchorUnits} [icon-anchor-y-units='fraction'] Units in which the anchor y value is
   * specified. A value of `'fraction'` indicates the y value is a fraction of the icon. A value of `'pixels'` indicates
   * the y value in pixels.
   * @property {ColorExpression} [icon-color] Color to tint the icon. If not specified,
   * the icon will be left as is.
   * @property {null|string} [icon-cross-origin] The `crossOrigin` attribute for loaded images. Note that you must provide a
   * `icon-cross-origin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {SizeExpression} [icon-offset=[0, 0]] Offset, which, together with the size and the offset origin, define the
   * sub-rectangle to use from the original icon image.
   * @property {NumberArrayExpression} [icon-displacement=[0,0]] Displacement of the icon.
   * @property {import("./Icon.js").IconOrigin} [icon-offset-origin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,
   * `top-left` or `top-right`.
   * @property {NumberExpression} [icon-opacity=1] Opacity of the icon.
   * @property {SizeExpression} [icon-scale=1] Scale.
   * @property {NumberExpression} [icon-width] Width of the icon. If not specified, the actual image width will be used. Cannot be combined
   * with `scale`. (Expressions only in WebGL)
   * @property {NumberExpression} [icon-height] Height of the icon. If not specified, the actual image height will be used. Cannot be combined
   * with `scale`. (Expressions only in WebGL)
   * @property {NumberExpression} [icon-rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {BooleanExpression} [icon-rotate-with-view=false] Whether to rotate the icon with the view. (Expressions only supported in Canvas)
   * @property {SizeExpression} [icon-size] Icon size in pixel. Can be used together with `icon-offset` to define the
   * sub-rectangle to use from the origin (sprite) icon image. (Expressions only in WebGL)
   * @property {import("./Style.js").DeclutterMode} [icon-declutter-mode] Declutter mode (Canvas only)
   * @property {NumberExpression} [z-index] The zIndex of the style. (Canvas only)
   */

  /**
   * Regular shape style properties for rendering point features. At least `shape-points` must be provided.
   *
   * @typedef {Object} FlatShape
   * @property {NumberExpression} [shape-points] Number of points for stars and regular polygons. In case of a polygon, the number of points
   * is the number of sides. (Expressions only in WebGL)
   * @property {ColorExpression} [shape-fill-color] The fill color. `'none'` means no fill and no hit detection.
   * @property {ColorExpression} [shape-stroke-color] The stroke color.
   * @property {NumberExpression} [shape-stroke-width] Stroke pixel width.
   * @property {StringExpression} [shape-stroke-line-cap='round'] Line cap style: `butt`, `round`, or `square`. (Canvas only)
   * @property {StringExpression} [shape-stroke-line-join='round'] Line join style: `bevel`, `round`, or `miter`. (Canvas only)
   * @property {NumberArrayExpression} [shape-stroke-line-dash] Line dash pattern. (Canvas only)
   * @property {NumberExpression} [shape-stroke-line-dash-offset=0] Line dash offset. (Canvas only)
   * @property {NumberExpression} [shape-stroke-miter-limit=10] Miter limit. (Canvas only)
   * @property {NumberExpression} [shape-radius] Radius of a regular polygon. (Expressions only in WebGL)
   * @property {NumberExpression} [shape-radius2] Second radius to make a star instead of a regular polygon. (Expressions only in WebGL)
   * @property {NumberExpression} [shape-angle=0] Shape's angle in radians. A value of 0 will have one of the shape's point facing up. (Expressions only in WebGL)
   * @property {NumberArrayExpression} [shape-displacement=[0,0]] Displacement of the shape
   * @property {NumberExpression} [shape-opacity] Shape opacity. (WebGL only)
   * @property {NumberExpression} [shape-rotation=0] Rotation in radians (positive rotation clockwise).
   * @property {BooleanExpression} [shape-rotate-with-view=false] Whether to rotate the shape with the view. (Expression only supported in Canvas)
   * @property {SizeExpression} [shape-scale=1] Scale. Unless two-dimensional scaling is required a better
   * result may be obtained with appropriate settings for `shape-radius` and `shape-radius2`.
   * @property {import("./Style.js").DeclutterMode} [shape-declutter-mode] Declutter mode. (Canvas only)
   * @property {NumberExpression} [z-index] The zIndex of the style. (Canvas only)
   */

  /**
   * Circle style properties for rendering point features. At least `circle-radius` must be provided.
   *
   * @typedef {Object} FlatCircle
   * @property {NumberExpression} [circle-radius] Circle radius.
   * @property {ColorExpression} [circle-fill-color] The fill color. `'none'` means no fill and no hit detection.
   * @property {ColorExpression} [circle-stroke-color] The stroke color.
   * @property {NumberExpression} [circle-stroke-width] Stroke pixel width.
   * @property {StringExpression} [circle-stroke-line-cap='round'] Line cap style: `butt`, `round`, or `square`. (Canvas only)
   * @property {StringExpression} [circle-stroke-line-join='round'] Line join style: `bevel`, `round`, or `miter`. (Canvas only)
   * @property {NumberArrayExpression} [circle-stroke-line-dash] Line dash pattern. (Canvas only)
   * @property {NumberExpression} [circle-stroke-line-dash-offset=0] Line dash offset. (Canvas only)
   * @property {NumberExpression} [circle-stroke-miter-limit=10] Miter limit. (Canvas only)
   * @property {NumberArrayExpression} [circle-displacement=[0,0]] displacement
   * @property {SizeExpression} [circle-scale=1] Scale. A two-dimensional scale will produce an ellipse.
   * Unless two-dimensional scaling is required a better result may be obtained with an appropriate setting for `circle-radius`.
   * @property {NumberExpression} [circle-opacity] Circle opacity. (WebGL only)
   * @property {NumberExpression} [circle-rotation=0] Rotation in radians
   * (positive rotation clockwise, meaningful only when used in conjunction with a two-dimensional scale).
   * @property {BooleanExpression} [circle-rotate-with-view=false] Whether to rotate the shape with the view (Expression only supported in Canvas)
   * (meaningful only when used in conjunction with a two-dimensional scale).
   * @property {import("./Style.js").DeclutterMode} [circle-declutter-mode] Declutter mode (Canvas only)
   * @property {NumberExpression} [z-index] The zIndex of the style. (Canvas only)
   */

  /**
   * These default style properties are applied when no other style is given.
   *
   * @typedef {Object} DefaultStyle
   * @property {string} fill-color `'rgba(255,255,255,0.4)'`
   * @property {string} stroke-color `'#3399CC'`
   * @property {number} stroke-width `1.25`
   * @property {number} circle-radius `5`
   * @property {string} circle-fill-color `'rgba(255,255,255,0.4)'`
   * @property {number} circle-stroke-width `1.25`
   * @property {string} circle-stroke-color `'#3399CC'`
   */

  /**
   * @return {DefaultStyle} The default flat style.
   */
  function createDefaultStyle() {
    return {
      'fill-color': 'rgba(255,255,255,0.4)',
      'stroke-color': '#3399CC',
      'stroke-width': 1.25,
      'circle-radius': 5,
      'circle-fill-color': 'rgba(255,255,255,0.4)',
      'circle-stroke-width': 1.25,
      'circle-stroke-color': '#3399CC',
    };
  }

  /**
   * A rule is used to conditionally apply a style. If the rule's filter evaluates to true,
   * the style will be applied.
   *
   * @typedef {Object} Rule
   * @property {FlatStyle|Array<FlatStyle>} style The style to be applied if the filter matches.
   * @property {import("../expr/expression.js").EncodedExpression} [filter] The filter used
   * to determine if a style applies. If no filter is included, the rule always applies
   * (unless it is an else rule).
   * @property {boolean} [else] If true, the rule applies only if no other previous rule applies.
   * If the else rule also has a filter, the rule will not apply if the filter does not match.
   */

  /**
   * Style variables are provided as an object. The variables can be read in a {@link import("../expr/expression.js").ExpressionValue style expression}
   * using the `['var', 'varName']` operator.
   * Each variable must hold a literal value (not an expression).
   * @typedef {Object<string, number|Array<number>|string|boolean>} StyleVariables
   */

  /**
   * Utilities for filling WebGL buffers
   * @module ol/render/webgl/bufferUtil
   */

  const LINESTRING_ANGLE_COSINE_CUTOFF = 0.985;

  /**
   * Class for generating shaders from literal style objects
   * @module ol/render/webgl/ShaderBuilder
   */

  const COMMON_HEADER = `#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
uniform mat4 u_projectionMatrix;
uniform mat4 u_screenToWorldMatrix;
uniform vec2 u_viewportSizePx;
uniform float u_pixelRatio;
uniform float u_globalAlpha;
uniform float u_time;
uniform float u_zoom;
uniform float u_resolution;
uniform float u_rotation;
uniform vec4 u_renderExtent;
uniform vec2 u_patternOrigin;
uniform float u_depth;
uniform mediump int u_hitDetection;

const float PI = 3.141592653589793238;
const float TWO_PI = 2.0 * PI;
float currentLineMetric = 0.; // an actual value will be used in the stroke shaders
`;

  const DEFAULT_STYLE$1 = createDefaultStyle();

  /**
   * @typedef {Object} AttributeDescription
   * @property {string} name Attribute name, as will be declared in the header of the vertex shader (including a_)
   * @property {string} type Attribute GLSL type, either `float`, `vec2`, `vec4`...
   * @property {string} varyingName Varying name, as will be declared in the header of both shaders (including v_)
   * @property {string} varyingType Varying type, either `float`, `vec2`, `vec4`...
   * @property {string} varyingExpression GLSL expression to assign to the varying in the vertex shader (e.g. `unpackColor(a_myAttr)`)
   */

  /**
   * @typedef {Object} UniformDescription
   * @property {string} name Uniform name, as will be declared in the header of the vertex shader (including u_)
   * @property {string} type Uniform GLSL type, either `float`, `vec2`, `vec4`...
   */

  /**
   * @classdesc
   * This class implements a classic builder pattern for generating many different types of shaders.
   * Methods can be chained, e. g.:
   *
   * ```js
   * const shader = new ShaderBuilder()
   *   .addAttribute('a_width', 'float')
   *   .addUniform('u_time', 'float)
   *   .setColorExpression('...')
   *   .setSymbolSizeExpression('...')
   *   .getSymbolFragmentShader();
   * ```
   *
   * A note on [alpha premultiplication](https://en.wikipedia.org/wiki/Alpha_compositing#Straight_versus_premultiplied):
   * The ShaderBuilder class expects all colors to **not having been alpha-premultiplied!** This is because alpha
   * premultiplication is done at the end of each fragment shader.
   */
  class ShaderBuilder {
    constructor() {
      /**
       * Uniforms; these will be declared in the header (should include the type).
       * @type {Array<UniformDescription>}
       * @private
       */
      this.uniforms_ = [];

      /**
       * Attributes; these will be declared in the header (should include the type).
       * @type {Array<AttributeDescription>}
       * @private
       */
      this.attributes_ = [];

      /**
       * @type {boolean}
       * @private
       */
      this.hasSymbol_ = false;

      /**
       * @type {string}
       * @private
       */
      this.symbolSizeExpression_ = `vec2(${numberToGlsl(
      DEFAULT_STYLE$1['circle-radius'],
    )} + ${numberToGlsl(DEFAULT_STYLE$1['circle-stroke-width'] * 0.5)})`;

      /**
       * @type {string}
       * @private
       */
      this.symbolRotationExpression_ = '0.0';

      /**
       * @type {string}
       * @private
       */
      this.symbolOffsetExpression_ = 'vec2(0.0)';

      /**
       * @type {string}
       * @private
       */
      this.symbolColorExpression_ = colorToGlsl(
        /** @type {string} */ (DEFAULT_STYLE$1['circle-fill-color']),
      );

      /**
       * @type {string}
       * @private
       */
      this.texCoordExpression_ = 'vec4(0.0, 0.0, 1.0, 1.0)';

      /**
       * @type {string}
       * @private
       */
      this.discardExpression_ = 'false';

      /**
       * @type {boolean}
       * @private
       */
      this.symbolRotateWithView_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.hasStroke_ = false;

      /**
       * @type {string}
       * @private
       */
      this.strokeWidthExpression_ = numberToGlsl(DEFAULT_STYLE$1['stroke-width']);

      /**
       * @type {string}
       * @private
       */
      this.strokeColorExpression_ = colorToGlsl(
        /** @type {string} */ (DEFAULT_STYLE$1['stroke-color']),
      );

      /**
       * @private
       */
      this.strokeOffsetExpression_ = '0.';

      /**
       * @private
       */
      this.strokeCapExpression_ = stringToGlsl('round');

      /**
       * @private
       */
      this.strokeJoinExpression_ = stringToGlsl('round');

      /**
       * @private
       */
      this.strokeMiterLimitExpression_ = '10.';

      /**
       * @private
       */
      this.strokeDistanceFieldExpression_ = '-1000.';

      /**
       * @type {boolean}
       * @private
       */
      this.hasFill_ = false;

      /**
       * @type {string}
       * @private
       */
      this.fillColorExpression_ = colorToGlsl(
        /** @type {string} */ (DEFAULT_STYLE$1['fill-color']),
      );

      /**
       * @type {Array<string>}
       * @private
       */
      this.vertexShaderFunctions_ = [];

      /**
       * @type {Array<string>}
       * @private
       */
      this.fragmentShaderFunctions_ = [];
    }

    /**
     * Adds a uniform accessible in both fragment and vertex shaders.
     * The given name should include a type, such as `sampler2D u_texture`.
     * @param {string} name Uniform name, including the `u_` prefix
     * @param {'float'|'vec2'|'vec3'|'vec4'|'sampler2D'} type GLSL type
     * @return {ShaderBuilder} the builder object
     */
    addUniform(name, type) {
      this.uniforms_.push({
        name,
        type,
      });
      return this;
    }

    /**
     * Adds an attribute accessible in the vertex shader, read from the geometry buffer.
     * The given name should include a type, such as `vec2 a_position`.
     * Attributes will also be made available under the same name in fragment shaders.
     * @param {string} name Attribute name, including the `a_` prefix
     * @param {'float'|'vec2'|'vec3'|'vec4'} type GLSL type
     * @param {string} [varyingExpression] Expression which will be assigned to the varying in the vertex shader, and
     * passed on to the fragment shader.
     * @param {'float'|'vec2'|'vec3'|'vec4'} [varyingType] Type of the attribute after transformation;
     * e.g. `vec4` after unpacking color components
     * @return {ShaderBuilder} the builder object
     */
    addAttribute(name, type, varyingExpression, varyingType) {
      this.attributes_.push({
        name,
        type,
        varyingName: name.replace(/^a_/, 'v_'),
        varyingType: varyingType ?? type,
        varyingExpression: varyingExpression ?? name,
      });
      return this;
    }

    /**
     * Sets an expression to compute the size of the shape.
     * This expression can use all the uniforms and attributes available
     * in the vertex shader, and should evaluate to a `vec2` value.
     * @param {string} expression Size expression
     * @return {ShaderBuilder} the builder object
     */
    setSymbolSizeExpression(expression) {
      this.hasSymbol_ = true;
      this.symbolSizeExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current symbol size expression
     */
    getSymbolSizeExpression() {
      return this.symbolSizeExpression_;
    }

    /**
     * Sets an expression to compute the rotation of the shape.
     * This expression can use all the uniforms and attributes available
     * in the vertex shader, and should evaluate to a `float` value in radians.
     * @param {string} expression Size expression
     * @return {ShaderBuilder} the builder object
     */
    setSymbolRotationExpression(expression) {
      this.symbolRotationExpression_ = expression;
      return this;
    }

    /**
     * Sets an expression to compute the offset of the symbol from the point center.
     * This expression can use all the uniforms and attributes available
     * in the vertex shader, and should evaluate to a `vec2` value.
     * @param {string} expression Offset expression
     * @return {ShaderBuilder} the builder object
     */
    setSymbolOffsetExpression(expression) {
      this.symbolOffsetExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current symbol offset expression
     */
    getSymbolOffsetExpression() {
      return this.symbolOffsetExpression_;
    }

    /**
     * Sets an expression to compute the color of the shape.
     * This expression can use all the uniforms, varyings and attributes available
     * in the fragment shader, and should evaluate to a `vec4` value.
     * @param {string} expression Color expression
     * @return {ShaderBuilder} the builder object
     */
    setSymbolColorExpression(expression) {
      this.hasSymbol_ = true;
      this.symbolColorExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current symbol color expression
     */
    getSymbolColorExpression() {
      return this.symbolColorExpression_;
    }

    /**
     * Sets an expression to compute the texture coordinates of the vertices.
     * This expression can use all the uniforms and attributes available
     * in the vertex shader, and should evaluate to a `vec4` value.
     * @param {string} expression Texture coordinate expression
     * @return {ShaderBuilder} the builder object
     */
    setTextureCoordinateExpression(expression) {
      this.texCoordExpression_ = expression;
      return this;
    }

    /**
     * Sets an expression to determine whether a fragment (pixel) should be discarded,
     * i.e. not drawn at all.
     * This expression can use all the uniforms, varyings and attributes available
     * in the fragment shader, and should evaluate to a `bool` value (it will be
     * used in an `if` statement)
     * @param {string} expression Fragment discard expression
     * @return {ShaderBuilder} the builder object
     */
    setFragmentDiscardExpression(expression) {
      this.discardExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current fragment discard expression
     */
    getFragmentDiscardExpression() {
      return this.discardExpression_;
    }

    /**
     * Sets whether the symbols should rotate with the view or stay aligned with the map.
     * Note: will only be used for point geometry shaders.
     * @param {boolean} rotateWithView Rotate with view
     * @return {ShaderBuilder} the builder object
     */
    setSymbolRotateWithView(rotateWithView) {
      this.symbolRotateWithView_ = rotateWithView;
      return this;
    }

    /**
     * @param {string} expression Stroke width expression, returning value in pixels
     * @return {ShaderBuilder} the builder object
     */
    setStrokeWidthExpression(expression) {
      this.hasStroke_ = true;
      this.strokeWidthExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Stroke color expression, evaluate to `vec4`: can rely on currentLengthPx and currentRadiusPx
     * @return {ShaderBuilder} the builder object
     */
    setStrokeColorExpression(expression) {
      this.hasStroke_ = true;
      this.strokeColorExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current stroke color expression
     */
    getStrokeColorExpression() {
      return this.strokeColorExpression_;
    }

    /**
     * @param {string} expression Stroke color expression, evaluate to `float`
     * @return {ShaderBuilder} the builder object
     */
    setStrokeOffsetExpression(expression) {
      this.strokeOffsetExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Stroke line cap expression, evaluate to `float`
     * @return {ShaderBuilder} the builder object
     */
    setStrokeCapExpression(expression) {
      this.strokeCapExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Stroke line join expression, evaluate to `float`
     * @return {ShaderBuilder} the builder object
     */
    setStrokeJoinExpression(expression) {
      this.strokeJoinExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Stroke miter limit expression, evaluate to `float`
     * @return {ShaderBuilder} the builder object
     */
    setStrokeMiterLimitExpression(expression) {
      this.strokeMiterLimitExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Stroke distance field expression, evaluate to `float`
     * This can override the default distance field; can rely on currentLengthPx and currentRadiusPx
     * @return {ShaderBuilder} the builder object
     */
    setStrokeDistanceFieldExpression(expression) {
      this.strokeDistanceFieldExpression_ = expression;
      return this;
    }

    /**
     * @param {string} expression Fill color expression, evaluate to `vec4`
     * @return {ShaderBuilder} the builder object
     */
    setFillColorExpression(expression) {
      this.hasFill_ = true;
      this.fillColorExpression_ = expression;
      return this;
    }

    /**
     * @return {string} The current fill color expression
     */
    getFillColorExpression() {
      return this.fillColorExpression_;
    }

    addVertexShaderFunction(code) {
      if (this.vertexShaderFunctions_.includes(code)) {
        return this;
      }
      this.vertexShaderFunctions_.push(code);
      return this;
    }
    addFragmentShaderFunction(code) {
      if (this.fragmentShaderFunctions_.includes(code)) {
        return this;
      }
      this.fragmentShaderFunctions_.push(code);
      return this;
    }

    /**
     * Generates a symbol vertex shader from the builder parameters
     * @return {string|null} The full shader as a string; null if no size or color specified
     */
    getSymbolVertexShader() {
      if (!this.hasSymbol_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
attribute vec2 a_position;
attribute float a_index;
attribute vec4 a_hitColor;

varying vec2 v_texCoord;
varying vec2 v_quadCoord;
varying vec4 v_hitColor;
varying vec2 v_centerPx;
varying float v_angle;
varying vec2 v_quadSizePx;

${this.attributes_
  .map(
    (attribute) => `attribute ${attribute.type} ${attribute.name};
varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.vertexShaderFunctions_.join('\n')}
vec2 pxToScreen(vec2 coordPx) {
  vec2 scaled = coordPx / u_viewportSizePx / 0.5;
  return scaled;
}

vec2 screenToPx(vec2 coordScreen) {
  return (coordScreen * 0.5 + 0.5) * u_viewportSizePx;
}

void main(void) {
  v_quadSizePx = ${this.symbolSizeExpression_};
  vec2 halfSizePx = v_quadSizePx * 0.5;
  vec2 centerOffsetPx = ${this.symbolOffsetExpression_};
  vec2 offsetPx = centerOffsetPx;
  if (a_index == 0.0) {
    offsetPx -= halfSizePx;
  } else if (a_index == 1.0) {
    offsetPx += halfSizePx * vec2(1., -1.);
  } else if (a_index == 2.0) {
    offsetPx += halfSizePx;
  } else {
    offsetPx += halfSizePx * vec2(-1., 1.);
  }
  float angle = ${this.symbolRotationExpression_}${this.symbolRotateWithView_ ? ' + u_rotation' : ''};
  float c = cos(-angle);
  float s = sin(-angle);
  offsetPx = vec2(c * offsetPx.x - s * offsetPx.y, s * offsetPx.x + c * offsetPx.y);
  vec4 center = u_projectionMatrix * vec4(a_position, 0.0, 1.0);
  gl_Position = center + vec4(pxToScreen(offsetPx), u_depth, 0.);
  vec4 texCoord = ${this.texCoordExpression_};
  float u = a_index == 0.0 || a_index == 3.0 ? texCoord.s : texCoord.p;
  float v = a_index == 2.0 || a_index == 3.0 ? texCoord.t : texCoord.q;
  v_texCoord = vec2(u, v);
  v_hitColor = a_hitColor;
  v_angle = angle;
  c = cos(-v_angle);
  s = sin(-v_angle);
  centerOffsetPx = vec2(c * centerOffsetPx.x - s * centerOffsetPx.y, s * centerOffsetPx.x + c * centerOffsetPx.y);
  v_centerPx = screenToPx(center.xy) + centerOffsetPx;
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingName} = ${attribute.varyingExpression};`,
  )
  .join('\n')}
}`;
    }

    /**
     * Generates a symbol fragment shader from the builder parameters
     * @return {string|null} The full shader as a string; null if no size or color specified
     */
    getSymbolFragmentShader() {
      if (!this.hasSymbol_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
varying vec2 v_texCoord;
varying vec4 v_hitColor;
varying vec2 v_centerPx;
varying float v_angle;
varying vec2 v_quadSizePx;
${this.attributes_
  .map(
    (attribute) => `varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.fragmentShaderFunctions_.join('\n')}

void main(void) {
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingType} ${attribute.name} = ${attribute.varyingName}; // assign to original attribute name`,
  )
  .join('\n')}
  if (${this.discardExpression_}) { discard; }
  vec2 coordsPx = gl_FragCoord.xy / u_pixelRatio - v_centerPx; // relative to center
  float c = cos(v_angle);
  float s = sin(v_angle);
  coordsPx = vec2(c * coordsPx.x - s * coordsPx.y, s * coordsPx.x + c * coordsPx.y);
  gl_FragColor = ${this.symbolColorExpression_};
  gl_FragColor.rgb *= gl_FragColor.a;
  if (u_hitDetection > 0) {
    if (gl_FragColor.a < 0.05) { discard; };
    gl_FragColor = v_hitColor;
  }
}`;
    }

    /**
     * Generates a stroke vertex shader from the builder parameters
     * @return {string|null} The full shader as a string; null if no size or color specified
     */
    getStrokeVertexShader() {
      if (!this.hasStroke_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
attribute vec2 a_segmentStart;
attribute vec2 a_segmentEnd;
attribute float a_measureStart;
attribute float a_measureEnd;
attribute float a_parameters;
attribute float a_distance;
attribute vec2 a_joinAngles;
attribute vec4 a_hitColor;

varying vec2 v_segmentStart;
varying vec2 v_segmentEnd;
varying float v_angleStart;
varying float v_angleEnd;
varying float v_width;
varying vec4 v_hitColor;
varying float v_distanceOffsetPx;
varying float v_measureStart;
varying float v_measureEnd;

${this.attributes_
  .map(
    (attribute) => `attribute ${attribute.type} ${attribute.name};
varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.vertexShaderFunctions_.join('\n')}
vec2 worldToPx(vec2 worldPos) {
  vec4 screenPos = u_projectionMatrix * vec4(worldPos, 0.0, 1.0);
  return (0.5 * screenPos.xy + 0.5) * u_viewportSizePx;
}

vec4 pxToScreen(vec2 pxPos) {
  vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;
  return vec4(screenPos, u_depth, 1.0);
}

bool isCap(float joinAngle) {
  return joinAngle < -0.1;
}

vec2 getJoinOffsetDirection(vec2 normalPx, float joinAngle) {
  float halfAngle = joinAngle / 2.0;
  float c = cos(halfAngle);
  float s = sin(halfAngle);
  vec2 angleBisectorNormal = vec2(s * normalPx.x + c * normalPx.y, -c * normalPx.x + s * normalPx.y);
  float length = 1.0 / s;
  return angleBisectorNormal * length;
}

vec2 getOffsetPoint(vec2 point, vec2 normal, float joinAngle, float offsetPx) {
  // if on a cap or the join angle is too high, offset the line along the segment normal
  if (cos(joinAngle) > 0.998 || isCap(joinAngle)) {
    return point - normal * offsetPx;
  }
  // offset is applied along the inverted normal (positive offset goes "right" relative to line direction)
  return point - getJoinOffsetDirection(normal, joinAngle) * offsetPx;
}

void main(void) {
  v_angleStart = a_joinAngles.x;
  v_angleEnd = a_joinAngles.y;
  float vertexNumber = floor(abs(a_parameters) / 10000. + 0.5);
  currentLineMetric = vertexNumber < 1.5 ? a_measureStart : a_measureEnd;
  // we're reading the fractional part while keeping the sign (so -4.12 gives -0.12, 3.45 gives 0.45)
  float angleTangentSum = fract(abs(a_parameters) / 10000.) * 10000. * sign(a_parameters);

  float lineWidth = ${this.strokeWidthExpression_};
  float lineOffsetPx = ${this.strokeOffsetExpression_};

  // compute segment start/end in px with offset
  vec2 segmentStartPx = worldToPx(a_segmentStart);
  vec2 segmentEndPx = worldToPx(a_segmentEnd);
  vec2 tangentPx = normalize(segmentEndPx - segmentStartPx);
  vec2 normalPx = vec2(-tangentPx.y, tangentPx.x);
  segmentStartPx = getOffsetPoint(segmentStartPx, normalPx, v_angleStart, lineOffsetPx),
  segmentEndPx = getOffsetPoint(segmentEndPx, normalPx, v_angleEnd, lineOffsetPx);

  // compute current vertex position
  float normalDir = vertexNumber < 0.5 || (vertexNumber > 1.5 && vertexNumber < 2.5) ? 1.0 : -1.0;
  float tangentDir = vertexNumber < 1.5 ? 1.0 : -1.0;
  float angle = vertexNumber < 1.5 ? v_angleStart : v_angleEnd;
  vec2 joinDirection;
  vec2 positionPx = vertexNumber < 1.5 ? segmentStartPx : segmentEndPx;
  // if angle is too high, do not make a proper join
  if (cos(angle) > ${LINESTRING_ANGLE_COSINE_CUTOFF} || isCap(angle)) {
    joinDirection = normalPx * normalDir - tangentPx * tangentDir;
  } else {
    joinDirection = getJoinOffsetDirection(normalPx * normalDir, angle);
  }
  positionPx = positionPx + joinDirection * (lineWidth * 0.5 + 1.); // adding 1 pixel for antialiasing
  gl_Position = pxToScreen(positionPx);

  v_segmentStart = segmentStartPx;
  v_segmentEnd = segmentEndPx;
  v_width = lineWidth;
  v_hitColor = a_hitColor;
  v_distanceOffsetPx = a_distance / u_resolution - (lineOffsetPx * angleTangentSum);
  v_measureStart = a_measureStart;
  v_measureEnd = a_measureEnd;
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingName} = ${attribute.varyingExpression};`,
  )
  .join('\n')}
}`;
    }

    /**
     * Generates a stroke fragment shader from the builder parameters
     *
     * @return {string|null} The full shader as a string; null if no size or color specified
     */
    getStrokeFragmentShader() {
      if (!this.hasStroke_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
varying vec2 v_segmentStart;
varying vec2 v_segmentEnd;
varying float v_angleStart;
varying float v_angleEnd;
varying float v_width;
varying vec4 v_hitColor;
varying float v_distanceOffsetPx;
varying float v_measureStart;
varying float v_measureEnd;
${this.attributes_
  .map(
    (attribute) => `varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.fragmentShaderFunctions_.join('\n')}

vec2 pxToWorld(vec2 pxPos) {
  vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;
  return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;
}

bool isCap(float joinAngle) {
  return joinAngle < -0.1;
}

float segmentDistanceField(vec2 point, vec2 start, vec2 end, float width) {
  vec2 tangent = normalize(end - start);
  vec2 normal = vec2(-tangent.y, tangent.x);
  vec2 startToPoint = point - start;
  return abs(dot(startToPoint, normal)) - width * 0.5;
}

float buttCapDistanceField(vec2 point, vec2 start, vec2 end) {
  vec2 startToPoint = point - start;
  vec2 tangent = normalize(end - start);
  return dot(startToPoint, -tangent);
}

float squareCapDistanceField(vec2 point, vec2 start, vec2 end, float width) {
  return buttCapDistanceField(point, start, end) - width * 0.5;
}

float roundCapDistanceField(vec2 point, vec2 start, vec2 end, float width) {
  float onSegment = max(0., 1000. * dot(point - start, end - start)); // this is very high when inside the segment
  return length(point - start) - width * 0.5 - onSegment;
}

float roundJoinDistanceField(vec2 point, vec2 start, vec2 end, float width) {
  return roundCapDistanceField(point, start, end, width);
}

float bevelJoinField(vec2 point, vec2 start, vec2 end, float width, float joinAngle) {
  vec2 startToPoint = point - start;
  vec2 tangent = normalize(end - start);
  float c = cos(joinAngle * 0.5);
  float s = sin(joinAngle * 0.5);
  float direction = -sign(sin(joinAngle));
  vec2 bisector = vec2(c * tangent.x - s * tangent.y, s * tangent.x + c * tangent.y);
  float radius = width * 0.5 * s;
  return dot(startToPoint, bisector * direction) - radius;
}

float miterJoinDistanceField(vec2 point, vec2 start, vec2 end, float width, float joinAngle) {
  if (cos(joinAngle) > ${LINESTRING_ANGLE_COSINE_CUTOFF}) { // avoid risking a division by zero
    return bevelJoinField(point, start, end, width, joinAngle);
  }
  float miterLength = 1. / sin(joinAngle * 0.5);
  float miterLimit = ${this.strokeMiterLimitExpression_};
  if (miterLength > miterLimit) {
    return bevelJoinField(point, start, end, width, joinAngle);
  }
  return -1000.;
}

float capDistanceField(vec2 point, vec2 start, vec2 end, float width, float capType) {
   if (capType == ${stringToGlsl('butt')}) {
    return buttCapDistanceField(point, start, end);
  } else if (capType == ${stringToGlsl('square')}) {
    return squareCapDistanceField(point, start, end, width);
  }
  return roundCapDistanceField(point, start, end, width);
}

float joinDistanceField(vec2 point, vec2 start, vec2 end, float width, float joinAngle, float joinType) {
  if (joinType == ${stringToGlsl('bevel')}) {
    return bevelJoinField(point, start, end, width, joinAngle);
  } else if (joinType == ${stringToGlsl('miter')}) {
    return miterJoinDistanceField(point, start, end, width, joinAngle);
  }
  return roundJoinDistanceField(point, start, end, width);
}

float computeSegmentPointDistance(vec2 point, vec2 start, vec2 end, float width, float joinAngle, float capType, float joinType) {
  if (isCap(joinAngle)) {
    return capDistanceField(point, start, end, width, capType);
  }
  return joinDistanceField(point, start, end, width, joinAngle, joinType);
}

float distanceFromSegment(vec2 point, vec2 start, vec2 end) {
  vec2 tangent = end - start;
  vec2 startToPoint = point - start;
  // inspire by capsule fn in https://iquilezles.org/articles/distfunctions/
  float h = clamp(dot(startToPoint, tangent) / dot(tangent, tangent), 0.0, 1.0);
  return length(startToPoint - tangent * h);
}

void main(void) {
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingType} ${attribute.name} = ${attribute.varyingName}; // assign to original attribute name`,
  )
  .join('\n')}

  vec2 currentPoint = gl_FragCoord.xy / u_pixelRatio;
  #ifdef GL_FRAGMENT_PRECISION_HIGH
  vec2 worldPos = pxToWorld(currentPoint);
  if (
    abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (
      worldPos[0] < u_renderExtent[0] ||
      worldPos[1] < u_renderExtent[1] ||
      worldPos[0] > u_renderExtent[2] ||
      worldPos[1] > u_renderExtent[3]
    )
  ) {
    discard;
  }
  #endif

  float segmentLength = length(v_segmentEnd - v_segmentStart);
  vec2 segmentTangent = (v_segmentEnd - v_segmentStart) / segmentLength;
  vec2 segmentNormal = vec2(-segmentTangent.y, segmentTangent.x);
  vec2 startToPoint = currentPoint - v_segmentStart;
  float lengthToPoint = max(0., min(dot(segmentTangent, startToPoint), segmentLength));
  float currentLengthPx = lengthToPoint + v_distanceOffsetPx;
  float currentRadiusPx = distanceFromSegment(currentPoint, v_segmentStart, v_segmentEnd);
  float currentRadiusRatio = dot(segmentNormal, startToPoint) * 2. / v_width;
  currentLineMetric = mix(
    v_measureStart,
    v_measureEnd,
    lengthToPoint / max(segmentLength, 1.17549429e-38)
  );

  if (${this.discardExpression_}) { discard; }

  float capType = ${this.strokeCapExpression_};
  float joinType = ${this.strokeJoinExpression_};
  float segmentStartDistance = computeSegmentPointDistance(currentPoint, v_segmentStart, v_segmentEnd, v_width, v_angleStart, capType, joinType);
  float segmentEndDistance = computeSegmentPointDistance(currentPoint, v_segmentEnd, v_segmentStart, v_width, v_angleEnd, capType, joinType);
  float distanceField = max(
    segmentDistanceField(currentPoint, v_segmentStart, v_segmentEnd, v_width),
    max(segmentStartDistance, segmentEndDistance)
  );
  distanceField = max(distanceField, ${this.strokeDistanceFieldExpression_});

  vec4 color = ${this.strokeColorExpression_};
  color.a *= smoothstep(0.5, -0.5, distanceField);
  gl_FragColor = color;
  gl_FragColor.a *= u_globalAlpha;
  gl_FragColor.rgb *= gl_FragColor.a;
  if (u_hitDetection > 0) {
    if (gl_FragColor.a < 0.1) { discard; };
    gl_FragColor = v_hitColor;
  }
}`;
    }

    /**
     * Generates a fill vertex shader from the builder parameters
     *
     * @return {string|null} The full shader as a string; null if no color specified
     */
    getFillVertexShader() {
      if (!this.hasFill_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
attribute vec2 a_position;
attribute vec4 a_hitColor;

varying vec4 v_hitColor;

${this.attributes_
  .map(
    (attribute) => `attribute ${attribute.type} ${attribute.name};
varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.vertexShaderFunctions_.join('\n')}
void main(void) {
  gl_Position = u_projectionMatrix * vec4(a_position, u_depth, 1.0);
  v_hitColor = a_hitColor;
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingName} = ${attribute.varyingExpression};`,
  )
  .join('\n')}
}`;
    }

    /**
     * Generates a fill fragment shader from the builder parameters
     * @return {string|null} The full shader as a string; null if no color specified
     */
    getFillFragmentShader() {
      if (!this.hasFill_) {
        return null;
      }

      return `${COMMON_HEADER}
${this.uniforms_.map((uniform) => `uniform ${uniform.type} ${uniform.name};`).join('\n')}
varying vec4 v_hitColor;
${this.attributes_
  .map(
    (attribute) => `varying ${attribute.varyingType} ${attribute.varyingName};`,
  )
  .join('\n')}
${this.fragmentShaderFunctions_.join('\n')}
vec2 pxToWorld(vec2 pxPos) {
  vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;
  return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;
}

vec2 worldToPx(vec2 worldPos) {
  vec4 screenPos = u_projectionMatrix * vec4(worldPos, 0.0, 1.0);
  return (0.5 * screenPos.xy + 0.5) * u_viewportSizePx;
}

void main(void) {
${this.attributes_
  .map(
    (attribute) =>
      `  ${attribute.varyingType} ${attribute.name} = ${attribute.varyingName}; // assign to original attribute name`,
  )
  .join('\n')}
  vec2 pxPos = gl_FragCoord.xy / u_pixelRatio;
  vec2 pxOrigin = worldToPx(u_patternOrigin);
  #ifdef GL_FRAGMENT_PRECISION_HIGH
  vec2 worldPos = pxToWorld(pxPos);
  if (
    abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (
      worldPos[0] < u_renderExtent[0] ||
      worldPos[1] < u_renderExtent[1] ||
      worldPos[0] > u_renderExtent[2] ||
      worldPos[1] > u_renderExtent[3]
    )
  ) {
    discard;
  }
  #endif
  if (${this.discardExpression_}) { discard; }
  gl_FragColor = ${this.fillColorExpression_};
  gl_FragColor.a *= u_globalAlpha;
  gl_FragColor.rgb *= gl_FragColor.a;
  if (u_hitDetection > 0) {
    if (gl_FragColor.a < 0.1) { discard; };
    gl_FragColor = v_hitColor;
  }
}`;
    }
  }

  function create$1() {
            const source = "function t(t,n,x=2){const o=n&&n.length,i=o?n[0]*x:t.length;let u=e(t,0,i,x,!0);const l=[];if(!u||u.next===u.prev)return l;let c,h,y;if(o&&(u=function(t,n,r,x){const o=[];for(let r=0,i=n.length;r<i;r++){const u=e(t,n[r]*x,r<i-1?n[r+1]*x:t.length,x,!1);u===u.next&&(u.steiner=!0),o.push(a(u))}o.sort(f);for(let t=0;t<o.length;t++)r=s(o[t],r);return r}(t,n,u,x)),t.length>80*x){c=1/0,h=1/0;let e=-1/0,n=-1/0;for(let r=x;r<i;r+=x){const x=t[r],o=t[r+1];x<c&&(c=x),o<h&&(h=o),x>e&&(e=x),o>n&&(n=o)}y=Math.max(e-c,n-h),y=0!==y?32767/y:0}return r(u,l,x,c,h,y,0),l}function e(t,e,n,r,x){let o;if(x===function(t,e,n,r){let x=0;for(let o=e,i=n-r;o<n;o+=r)x+=(t[i]-t[o])*(t[o+1]+t[i+1]),i=o;return x}(t,e,n,r)>0)for(let x=e;x<n;x+=r)o=w(x/r|0,t[x],t[x+1],o);else for(let x=n-r;x>=e;x-=r)o=w(x/r|0,t[x],t[x+1],o);return o&&g(o,o.next)&&(A(o),o=o.next),o}function n(t,e){if(!t)return t;e||(e=t);let n,r=t;do{if(n=!1,r.steiner||!g(r,r.next)&&0!==v(r.prev,r,r.next))r=r.next;else{if(A(r),r=e=r.prev,r===r.next)break;n=!0}}while(n||r!==e);return e}function r(t,e,f,s,l,a,h){if(!t)return;!h&&a&&function(t,e,n,r){let x=t;do{0===x.z&&(x.z=c(x.x,x.y,e,n,r)),x.prevZ=x.prev,x.nextZ=x.next,x=x.next}while(x!==t);x.prevZ.nextZ=null,x.prevZ=null,function(t){let e,n=1;do{let r,x=t;t=null;let o=null;for(e=0;x;){e++;let i=x,u=0;for(let t=0;t<n&&(u++,i=i.nextZ,i);t++);let f=n;for(;u>0||f>0&&i;)0!==u&&(0===f||!i||x.z<=i.z)?(r=x,x=x.nextZ,u--):(r=i,i=i.nextZ,f--),o?o.nextZ=r:t=r,r.prevZ=o,o=r;x=i}o.nextZ=null,n*=2}while(e>1)}(x)}(t,s,l,a);let y=t;for(;t.prev!==t.next;){const c=t.prev,p=t.next;if(a?o(t,s,l,a):x(t))e.push(c.i,t.i,p.i),A(t),t=p.next,y=p.next;else if((t=p)===y){h?1===h?r(t=i(n(t),e),e,f,s,l,a,2):2===h&&u(t,e,f,s,l,a):r(n(t),e,f,s,l,a,1);break}}}function x(t){const e=t.prev,n=t,r=t.next;if(v(e,n,r)>=0)return!1;const x=e.x,o=n.x,i=r.x,u=e.y,f=n.y,s=r.y,l=Math.min(x,o,i),c=Math.min(u,f,s),a=Math.max(x,o,i),h=Math.max(u,f,s);let p=r.next;for(;p!==e;){if(p.x>=l&&p.x<=a&&p.y>=c&&p.y<=h&&y(x,u,o,f,i,s,p.x,p.y)&&v(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function o(t,e,n,r){const x=t.prev,o=t,i=t.next;if(v(x,o,i)>=0)return!1;const u=x.x,f=o.x,s=i.x,l=x.y,a=o.y,h=i.y,p=Math.min(u,f,s),g=Math.min(l,a,h),b=Math.max(u,f,s),M=Math.max(l,a,h),m=c(p,g,e,n,r),Z=c(b,M,e,n,r);let d=t.prevZ,w=t.nextZ;for(;d&&d.z>=m&&w&&w.z<=Z;){if(d.x>=p&&d.x<=b&&d.y>=g&&d.y<=M&&d!==x&&d!==i&&y(u,l,f,a,s,h,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,w.x>=p&&w.x<=b&&w.y>=g&&w.y<=M&&w!==x&&w!==i&&y(u,l,f,a,s,h,w.x,w.y)&&v(w.prev,w,w.next)>=0)return!1;w=w.nextZ}for(;d&&d.z>=m;){if(d.x>=p&&d.x<=b&&d.y>=g&&d.y<=M&&d!==x&&d!==i&&y(u,l,f,a,s,h,d.x,d.y)&&v(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;w&&w.z<=Z;){if(w.x>=p&&w.x<=b&&w.y>=g&&w.y<=M&&w!==x&&w!==i&&y(u,l,f,a,s,h,w.x,w.y)&&v(w.prev,w,w.next)>=0)return!1;w=w.nextZ}return!0}function i(t,e){let r=t;do{const n=r.prev,x=r.next.next;!g(n,x)&&b(n,r,r.next,x)&&Z(n,x)&&Z(x,n)&&(e.push(n.i,r.i,x.i),A(r),A(r.next),r=t=x),r=r.next}while(r!==t);return n(r)}function u(t,e,x,o,i,u){let f=t;do{let t=f.next.next;for(;t!==f.prev;){if(f.i!==t.i&&p(f,t)){let s=d(f,t);return f=n(f,f.next),s=n(s,s.next),r(f,e,x,o,i,u,0),void r(s,e,x,o,i,u,0)}t=t.next}f=f.next}while(f!==t)}function f(t,e){let n=t.x-e.x;if(0===n&&(n=t.y-e.y,0===n)){n=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)}return n}function s(t,e){const r=function(t,e){let n=e;const r=t.x,x=t.y;let o,i=-1/0;if(g(t,n))return n;do{if(g(t,n.next))return n.next;if(x<=n.y&&x>=n.next.y&&n.next.y!==n.y){const t=n.x+(x-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(t<=r&&t>i&&(i=t,o=n.x<n.next.x?n:n.next,t===r))return o}n=n.next}while(n!==e);if(!o)return null;const u=o,f=o.x,s=o.y;let c=1/0;n=o;do{if(r>=n.x&&n.x>=f&&r!==n.x&&h(x<s?r:i,x,f,s,x<s?i:r,x,n.x,n.y)){const e=Math.abs(x-n.y)/(r-n.x);Z(n,t)&&(e<c||e===c&&(n.x>o.x||n.x===o.x&&l(o,n)))&&(o=n,c=e)}n=n.next}while(n!==u);return o}(t,e);if(!r)return e;const x=d(r,t);return n(x,x.next),n(r,r.next)}function l(t,e){return v(t.prev,t,e.prev)<0&&v(e.next,t,t.next)<0}function c(t,e,n,r,x){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*x|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*x|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function a(t){let e=t,n=t;do{(e.x<n.x||e.x===n.x&&e.y<n.y)&&(n=e),e=e.next}while(e!==t);return n}function h(t,e,n,r,x,o,i,u){return(x-i)*(e-u)>=(t-i)*(o-u)&&(t-i)*(r-u)>=(n-i)*(e-u)&&(n-i)*(o-u)>=(x-i)*(r-u)}function y(t,e,n,r,x,o,i,u){return!(t===i&&e===u)&&h(t,e,n,r,x,o,i,u)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&b(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(Z(t,e)&&Z(e,t)&&function(t,e){let n=t,r=!1;const x=(t.x+e.x)/2,o=(t.y+e.y)/2;do{n.y>o!=n.next.y>o&&n.next.y!==n.y&&x<(n.next.x-n.x)*(o-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==t);return r}(t,e)&&(v(t.prev,t,e.prev)||v(t,e.prev,e))||g(t,e)&&v(t.prev,t,t.next)>0&&v(e.prev,e,e.next)>0)}function v(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function g(t,e){return t.x===e.x&&t.y===e.y}function b(t,e,n,r){const x=m(v(t,e,n)),o=m(v(t,e,r)),i=m(v(n,r,t)),u=m(v(n,r,e));return x!==o&&i!==u||(!(0!==x||!M(t,n,e))||(!(0!==o||!M(t,r,e))||(!(0!==i||!M(n,t,r))||!(0!==u||!M(n,e,r)))))}function M(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function m(t){return t>0?1:t<0?-1:0}function Z(t,e){return v(t.prev,t,t.next)<0?v(t,e,t.next)>=0&&v(t,t.prev,e)>=0:v(t,e,t.prev)<0||v(t,t.next,e)<0}function d(t,e){const n=E(t.i,t.x,t.y),r=E(e.i,e.x,e.y),x=t.next,o=e.prev;return t.next=e,e.prev=t,n.next=x,x.prev=n,r.next=n,n.prev=r,o.next=r,r.prev=o,r}function w(t,e,n,r){const x=E(t,e,n);return r?(x.next=r.next,x.prev=r,r.next.prev=x,r.next=x):(x.prev=x,x.next=x),x}function A(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function E(t,e,n){return{i:t,x:e,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function I(t,e){const n=e[0],r=e[1];return e[0]=t[0]*n+t[2]*r+t[4],e[1]=t[1]*n+t[3]*r+t[5],e}function z(t,e){const n=(r=e)[0]*r[3]-r[1]*r[2];var r;!function(t,e){if(!t)throw new Error(e)}(0!==n,\"Transformation matrix cannot be inverted\");const x=e[0],o=e[1],i=e[2],u=e[3],f=e[4],s=e[5];return t[0]=u/n,t[1]=-o/n,t[2]=-i/n,t[3]=x/n,t[4]=(i*s-u*f)/n,t[5]=-(x*s-o*f)/n,t}new Array(6);const F=[],P={vertexPosition:0,indexPosition:0};function B(t,e,n,r,x){t[e+0]=n,t[e+1]=r,t[e+2]=x}function N(t,e,n,r,x,o){const i=3+x,u=t[e+0],f=t[e+1],s=F;s.length=x;for(let n=0;n<s.length;n++)s[n]=t[e+2+n];let l=o?o.vertexPosition:0,c=o?o.indexPosition:0;const a=l/i;return B(n,l,u,f,0),s.length&&n.set(s,l+3),l+=i,B(n,l,u,f,1),s.length&&n.set(s,l+3),l+=i,B(n,l,u,f,2),s.length&&n.set(s,l+3),l+=i,B(n,l,u,f,3),s.length&&n.set(s,l+3),l+=i,r[c++]=a,r[c++]=a+1,r[c++]=a+3,r[c++]=a+1,r[c++]=a+2,r[c++]=a+3,P.vertexPosition=l,P.indexPosition=c,P}function R(t,e,n,r,x,o,i,u,f,s,l){const c=10+u.length,a=o.length/c,h=[t[e+0],t[e+1]],y=[t[n],t[n+1]],p=t[e+2],v=t[n+2],g=I(f,[...h]),b=I(f,[...y]);function M(t,e,n){const r=Math.sqrt((e[0]-t[0])*(e[0]-t[0])+(e[1]-t[1])*(e[1]-t[1])),x=[(e[0]-t[0])/r,(e[1]-t[1])/r],o=[-x[1],x[0]],i=Math.sqrt((n[0]-t[0])*(n[0]-t[0])+(n[1]-t[1])*(n[1]-t[1])),u=[(n[0]-t[0])/i,(n[1]-t[1])/i],f=0===r||0===i?0:Math.acos((s=u[0]*x[0]+u[1]*x[1],l=-1,c=1,Math.min(Math.max(s,l),c)));var s,l,c;return u[0]*o[0]+u[1]*o[1]>0?f:2*Math.PI-f}let m=-1,Z=-1,d=l;const w=null!==x;if(null!==r){m=M(g,b,I(f,[...[t[r],t[r+1]]])),Math.cos(m)<=.985&&(d+=Math.tan((m-Math.PI)/2))}if(w){Z=M(b,g,I(f,[...[t[x],t[x+1]]])),Math.cos(Z)<=.985&&(d+=Math.tan((Math.PI-Z)/2))}function A(t,e){return 0===e?1e4*t:Math.sign(e)*(1e4*t+Math.abs(e))}return o.push(h[0],h[1],p,y[0],y[1],v,m,Z,s,A(0,l)),o.push(...u),o.push(h[0],h[1],p,y[0],y[1],v,m,Z,s,A(1,l)),o.push(...u),o.push(h[0],h[1],p,y[0],y[1],v,m,Z,s,A(2,l)),o.push(...u),o.push(h[0],h[1],p,y[0],y[1],v,m,Z,s,A(3,l)),o.push(...u),i.push(a,a+1,a+2,a+1,a+3,a+2),{length:s+Math.sqrt((b[0]-g[0])*(b[0]-g[0])+(b[1]-g[1])*(b[1]-g[1])),angle:d}}function S(e,n,r,x,o){const i=2+o;let u=n;const f=e.slice(u,u+o);u+=o;const s=e[u++];let l=0;const c=new Array(s-1);for(let t=0;t<s;t++)l+=e[u++],t<s-1&&(c[t]=l);const a=e.slice(u,u+2*l),h=t(a,c,2);for(let t=0;t<h.length;t++)x.push(h[t]+r.length/i);for(let t=0;t<a.length;t+=2)r.push(a[t],a[t+1],...f);return u+2*l}const T=\"GENERATE_POLYGON_BUFFERS\",_=\"GENERATE_POINT_BUFFERS\",O=\"GENERATE_LINE_STRING_BUFFERS\",U=self;U.onmessage=t=>{const e=t.data;switch(e.type){case _:{const t=3,n=2,r=e.customAttributesSize,x=n+r,o=new Float32Array(e.renderInstructions),i=o.length/x,u=4*i*(r+t),f=new Uint32Array(6*i),s=new Float32Array(u);let l;for(let t=0;t<o.length;t+=x)l=N(o,t,s,f,r,l);const c=Object.assign({vertexBuffer:s.buffer,indexBuffer:f.buffer,renderInstructions:o.buffer},e);U.postMessage(c,[s.buffer,f.buffer,o.buffer]);break}case O:{const t=[],n=[],r=e.customAttributesSize,x=3,o=new Float32Array(e.renderInstructions);let i=0;const u=[1,0,0,1,0,0];let f,s;for(z(u,e.renderInstructionsTransform);i<o.length;){s=Array.from(o.slice(i,i+r)),i+=r,f=o[i++];const e=i,l=i+(f-1)*x,c=o[e]===o[l]&&o[e+1]===o[l+1];let a=0,h=0;for(let r=0;r<f-1;r++){let y=null;r>0?y=i+(r-1)*x:c&&(y=l-x);let p=null;r<f-2?p=i+(r+2)*x:c&&(p=e+x);const v=R(o,i+r*x,i+(r+1)*x,y,p,t,n,s,u,a,h);a=v.length,h=v.angle}i+=f*x}const l=Uint32Array.from(n),c=Float32Array.from(t),a=Object.assign({vertexBuffer:c.buffer,indexBuffer:l.buffer,renderInstructions:o.buffer},e);U.postMessage(a,[c.buffer,l.buffer,o.buffer]);break}case T:{const t=[],n=[],r=e.customAttributesSize,x=new Float32Array(e.renderInstructions);let o=0;for(;o<x.length;)o=S(x,o,t,n,r);const i=Uint32Array.from(n),u=Float32Array.from(t),f=Object.assign({vertexBuffer:u.buffer,indexBuffer:i.buffer,renderInstructions:x.buffer},e);U.postMessage(f,[u.buffer,i.buffer,x.buffer]);break}}};";
            return new Worker(typeof Blob === 'undefined'
              ? 'data:application/javascript;base64,' + Buffer.from(source, 'binary').toString('base64')
              : URL.createObjectURL(new Blob([source], {type: 'application/javascript'})));
          }

  /**
   * @module ol/render/webgl/constants
   */

  /**
   * @enum {string}
   */
  const WebGLWorkerMessageType = {
    GENERATE_POLYGON_BUFFERS: 'GENERATE_POLYGON_BUFFERS',
    GENERATE_POINT_BUFFERS: 'GENERATE_POINT_BUFFERS',
    GENERATE_LINE_STRING_BUFFERS: 'GENERATE_LINE_STRING_BUFFERS',
  };

  /**
   * @typedef {Object} WebGLWorkerGenerateBuffersMessage
   * This message will trigger the generation of a vertex and an index buffer based on the given render instructions.
   * When the buffers are generated, the worked will send a message of the same type to the main thread, with
   * the generated buffers in it.
   * Note that any addition properties present in the message *will* be sent back to the main thread.
   * @property {number} id Message id; will be used both in request and response as a means of identification
   * @property {WebGLWorkerMessageType} type Message type
   * @property {ArrayBuffer} renderInstructions render instructions raw binary buffer.
   * @property {number} [customAttributesSize] Amount of hit detection + custom attributes count in the render instructions.
   * @property {ArrayBuffer} [vertexBuffer] Vertices array raw binary buffer (sent by the worker).
   * @property {ArrayBuffer} [indexBuffer] Indices array raw binary buffer (sent by the worker).
   * @property {import("../../transform").Transform} [renderInstructionsTransform] Transformation matrix used to project the instructions coordinates
   */

  /**
   * Utilities for encoding/decoding values to be used in shaders
   * @module ol/render/webgl/encodeUtil
   */

  /**
   * Generates a color array based on a numerical id
   * Note: the range for each component is 0 to 1 with 256 steps
   * @param {number} id Id
   * @param {Array<number>} [array] Reusable array
   * @return {Array<number>} Color array containing the encoded id
   */
  function colorEncodeId(id, array) {
    array = array || [];
    const radix = 256;
    const divide = radix - 1;
    array[0] = Math.floor(id / radix / radix / radix) / divide;
    array[1] = (Math.floor(id / radix / radix) % radix) / divide;
    array[2] = (Math.floor(id / radix) % radix) / divide;
    array[3] = (id % radix) / divide;
    return array;
  }

  /**
   * Reads an id from a color-encoded array
   * Note: the expected range for each component is 0 to 1 with 256 steps.
   * @param {Array<number>} color Color array containing the encoded id
   * @return {number} Decoded id
   */
  function colorDecodeId(color) {
    let id = 0;
    const radix = 256;
    const mult = radix - 1;
    id += Math.round(color[0] * radix * radix * radix * mult);
    id += Math.round(color[1] * radix * radix * mult);
    id += Math.round(color[2] * radix * mult);
    id += Math.round(color[3] * mult);
    return id;
  }

  /**
   * @module ol/render/webgl/renderinstructions
   */

  /**
   * @param {Float32Array} renderInstructions Render instructions
   * @param {import('./VectorStyleRenderer.js').AttributeDefinitions} customAttributes Custom attributes
   * @param {import("./MixedGeometryBatch.js").GeometryBatchItem} batchEntry Batch item
   * @param {number} currentIndex Current index
   * @return {number} The amount of values pushed
   */
  function pushCustomAttributesInRenderInstructions(
    renderInstructions,
    customAttributes,
    batchEntry,
    currentIndex,
  ) {
    let shift = 0;
    for (const key in customAttributes) {
      const attr = customAttributes[key];
      const value = attr.callback.call(batchEntry, batchEntry.feature);
      let first = value?.[0] ?? value;
      if (first === UNDEFINED_PROP_VALUE) {
        console.warn('The "has" operator might return false positives.'); // eslint-disable-line no-console
      }
      if (first === undefined) {
        first = UNDEFINED_PROP_VALUE;
      } else if (first === null) {
        first = 0;
      }
      renderInstructions[currentIndex + shift++] = first;
      if (!attr.size || attr.size === 1) {
        continue;
      }
      renderInstructions[currentIndex + shift++] = value[1];
      if (attr.size < 3) {
        continue;
      }
      renderInstructions[currentIndex + shift++] = value[2];
      if (attr.size < 4) {
        continue;
      }
      renderInstructions[currentIndex + shift++] = value[3];
    }
    return shift;
  }

  /**
   * @param {import('./VectorStyleRenderer.js').AttributeDefinitions} customAttributes Custom attributes
   * @return {number} Cumulated size of all attributes
   */
  function getCustomAttributesSize(customAttributes) {
    return Object.keys(customAttributes).reduce(
      (prev, curr) => prev + (customAttributes[curr].size || 1),
      0,
    );
  }

  /**
   * Render instructions for lines are structured like so:
   * [ x0, y0, customAttr0, ... , xN, yN, customAttrN ]
   * @param {import("./MixedGeometryBatch.js").PointGeometryBatch} batch Point geometry batch
   * @param {Float32Array} renderInstructions Render instructions
   * @param {import('./VectorStyleRenderer.js').AttributeDefinitions} customAttributes Custom attributes
   * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
   * @return {Float32Array} Generated render instructions
   */
  function generatePointRenderInstructions(
    batch,
    renderInstructions,
    customAttributes,
    transform,
  ) {
    // here we anticipate the amount of render instructions for points:
    // 2 instructions per vertex for position (x and y)
    // + 1 instruction per vertex per custom attributes
    const totalInstructionsCount =
      (2 + getCustomAttributesSize(customAttributes)) * batch.geometriesCount;
    if (
      !renderInstructions ||
      renderInstructions.length !== totalInstructionsCount
    ) {
      renderInstructions = new Float32Array(totalInstructionsCount);
    }

    // loop on features to fill the render instructions
    const tmpCoords = [];
    let renderIndex = 0;
    for (const featureUid in batch.entries) {
      const batchEntry = batch.entries[featureUid];
      for (let i = 0, ii = batchEntry.flatCoordss.length; i < ii; i++) {
        tmpCoords[0] = batchEntry.flatCoordss[i][0];
        tmpCoords[1] = batchEntry.flatCoordss[i][1];
        apply(transform, tmpCoords);

        renderInstructions[renderIndex++] = tmpCoords[0];
        renderInstructions[renderIndex++] = tmpCoords[1];
        renderIndex += pushCustomAttributesInRenderInstructions(
          renderInstructions,
          customAttributes,
          batchEntry,
          renderIndex,
        );
      }
    }
    return renderInstructions;
  }

  /**
   * Render instructions for lines are structured like so:
   * [ customAttr0, ... , customAttrN, numberOfVertices0, x0, y0, ... , xN, yN, numberOfVertices1, ... ]
   * @param {import("./MixedGeometryBatch.js").LineStringGeometryBatch} batch Line String geometry batch
   * @param {Float32Array} renderInstructions Render instructions
   * @param {import('./VectorStyleRenderer.js').AttributeDefinitions} customAttributes Custom attributes
   * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
   * @return {Float32Array} Generated render instructions
   */
  function generateLineStringRenderInstructions(
    batch,
    renderInstructions,
    customAttributes,
    transform,
  ) {
    // here we anticipate the amount of render instructions for lines:
    // 3 instructions per vertex for position (x, y and m)
    // + 1 instruction per line per custom attributes
    // + 1 instruction per line (for vertices count)
    const totalInstructionsCount =
      3 * batch.verticesCount +
      (1 + getCustomAttributesSize(customAttributes)) * batch.geometriesCount;
    if (
      !renderInstructions ||
      renderInstructions.length !== totalInstructionsCount
    ) {
      renderInstructions = new Float32Array(totalInstructionsCount);
    }

    // loop on features to fill the render instructions
    const flatCoords = [];
    let renderIndex = 0;
    for (const featureUid in batch.entries) {
      const batchEntry = batch.entries[featureUid];
      for (let i = 0, ii = batchEntry.flatCoordss.length; i < ii; i++) {
        flatCoords.length = batchEntry.flatCoordss[i].length;
        transform2D(
          batchEntry.flatCoordss[i],
          0,
          flatCoords.length,
          3,
          transform,
          flatCoords,
          3,
        );
        renderIndex += pushCustomAttributesInRenderInstructions(
          renderInstructions,
          customAttributes,
          batchEntry,
          renderIndex,
        );

        // vertices count
        renderInstructions[renderIndex++] = flatCoords.length / 3;

        // looping on points for positions
        for (let j = 0, jj = flatCoords.length; j < jj; j += 3) {
          renderInstructions[renderIndex++] = flatCoords[j];
          renderInstructions[renderIndex++] = flatCoords[j + 1];
          renderInstructions[renderIndex++] = flatCoords[j + 2];
        }
      }
    }
    return renderInstructions;
  }

  /**
   * Render instructions for polygons are structured like so:
   * [ customAttr0, ..., customAttrN, numberOfRings, numberOfVerticesInRing0, ..., numberOfVerticesInRingN, x0, y0, ..., xN, yN, numberOfRings,... ]
   * @param {import("./MixedGeometryBatch.js").PolygonGeometryBatch} batch Polygon geometry batch
   * @param {Float32Array} renderInstructions Render instructions
   * @param {import('./VectorStyleRenderer.js').AttributeDefinitions} customAttributes Custom attributes
   * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
   * @return {Float32Array} Generated render instructions
   */
  function generatePolygonRenderInstructions(
    batch,
    renderInstructions,
    customAttributes,
    transform,
  ) {
    // here we anticipate the amount of render instructions for polygons:
    // 2 instructions per vertex for position (x and y)
    // + 1 instruction per polygon per custom attributes
    // + 1 instruction per polygon (for vertices count in polygon)
    // + 1 instruction per ring (for vertices count in ring)
    const totalInstructionsCount =
      2 * batch.verticesCount +
      (1 + getCustomAttributesSize(customAttributes)) * batch.geometriesCount +
      batch.ringsCount;
    if (
      !renderInstructions ||
      renderInstructions.length !== totalInstructionsCount
    ) {
      renderInstructions = new Float32Array(totalInstructionsCount);
    }

    // loop on features to fill the render instructions
    const flatCoords = [];
    let renderIndex = 0;
    for (const featureUid in batch.entries) {
      const batchEntry = batch.entries[featureUid];
      for (let i = 0, ii = batchEntry.flatCoordss.length; i < ii; i++) {
        flatCoords.length = batchEntry.flatCoordss[i].length;
        transform2D(
          batchEntry.flatCoordss[i],
          0,
          flatCoords.length,
          2,
          transform,
          flatCoords,
        );
        renderIndex += pushCustomAttributesInRenderInstructions(
          renderInstructions,
          customAttributes,
          batchEntry,
          renderIndex,
        );

        // ring count
        renderInstructions[renderIndex++] =
          batchEntry.ringsVerticesCounts[i].length;

        // vertices count in each ring
        for (
          let j = 0, jj = batchEntry.ringsVerticesCounts[i].length;
          j < jj;
          j++
        ) {
          renderInstructions[renderIndex++] =
            batchEntry.ringsVerticesCounts[i][j];
        }

        // looping on points for positions
        for (let j = 0, jj = flatCoords.length; j < jj; j += 2) {
          renderInstructions[renderIndex++] = flatCoords[j];
          renderInstructions[renderIndex++] = flatCoords[j + 1];
        }
      }
    }
    return renderInstructions;
  }

  /**
   * Utilities for compiling expressions and turning them into WebGL concepts
   * @module ol/render/webgl/compileUtil
   */


  /**
   * Recursively parses a style expression and outputs a GLSL-compatible string. Takes in a compilation context that
   * will be read and modified during the parsing operation.
   * @param {import("../../expr/gpu.js").CompilationContext} compilationContext Compilation context
   * @param {import("../../expr/expression.js").EncodedExpression} value Value
   * @param {number} [expectedType] Expected final type (can be several types combined)
   * @return {string} GLSL-compatible output
   */
  function expressionToGlsl(compilationContext, value, expectedType) {
    const parsingContext = newParsingContext();
    return buildExpression(
      value,
      expectedType,
      parsingContext,
      compilationContext,
    );
  }

  /**
   * Packs all components of a color into a two-floats array
   * @param {import("../../color.js").Color|string} color Color as array of numbers or string
   * @return {Array<number>} Vec2 array containing the color in compressed form
   */
  function packColor(color) {
    const array = asArray(color);
    const r = array[0] * 256;
    const g = array[1];
    const b = array[2] * 256;
    const a = Math.round(array[3] * 255);
    return [r + g, b + a];
  }

  const UNPACK_COLOR_FN = `vec4 unpackColor(vec2 packedColor) {
  return vec4(
    fract(floor(packedColor[0] / 256.0) / 256.0),
    fract(packedColor[0] / 256.0),
    fract(floor(packedColor[1] / 256.0) / 256.0),
    fract(packedColor[1] / 256.0)
  );
}`;

  /**
   * @param {number} type Value type
   * @return {1|2|3|4} The amount of components for this value
   */
  function getGlslSizeFromType(type) {
    if (type === ColorType$1 || type === SizeType) {
      return 2;
    }
    if (type === NumberArrayType$1) {
      return 4;
    }
    return 1;
  }

  /**
   * @param {number} type Value type
   * @return {'float'|'vec2'|'vec3'|'vec4'} The corresponding GLSL type for this value
   */
  function getGlslTypeFromType(type) {
    const size = getGlslSizeFromType(type);
    if (size > 1) {
      return /** @type {'vec2'|'vec3'|'vec4'} */ (`vec${size}`);
    }
    return 'float';
  }

  /**
   * Applies the properties and variables collected in a compilation context to a ShaderBuilder instance:
   * properties will show up as attributes in shaders, and variables will show up as uniforms.
   * @param {import("./ShaderBuilder.js").ShaderBuilder} builder Shader builder
   * @param {import("../../expr/gpu.js").CompilationContext} context Compilation context
   */
  function applyContextToBuilder(builder, context) {
    // define one uniform per variable
    for (const varName in context.variables) {
      const variable = context.variables[varName];
      const uniformName = uniformNameForVariable(variable.name);
      let glslType = getGlslTypeFromType(variable.type);
      if (variable.type === ColorType$1) {
        // we're not packing colors when they're passed as uniforms
        glslType = 'vec4';
      }
      builder.addUniform(uniformName, glslType);
    }

    // for each feature attribute used in the fragment shader, define a varying that will be used to pass data
    // from the vertex to the fragment shader, as well as an attribute in the vertex shader (if not already present)
    for (const propName in context.properties) {
      const property = context.properties[propName];
      const glslType = getGlslTypeFromType(property.type);
      const attributeName = `a_prop_${property.name}`;
      if (property.type === ColorType$1) {
        builder.addAttribute(
          attributeName,
          glslType,
          `unpackColor(${attributeName})`,
          'vec4',
        );
        builder.addVertexShaderFunction(UNPACK_COLOR_FN);
      } else {
        builder.addAttribute(attributeName, glslType);
      }
    }

    // add functions that were collected in the compilation contexts
    for (const functionName in context.functions) {
      builder.addVertexShaderFunction(context.functions[functionName]);
      builder.addFragmentShaderFunction(context.functions[functionName]);
    }
  }

  /**
   * Generates a set of uniforms from variables collected in a compilation context,
   * to be fed to a WebGLHelper instance
   * @param {import("../../expr/gpu.js").CompilationContext} context Compilation context
   * @param {import('../../style/flat.js').StyleVariables} [variables] Style variables.
   * @return {Object<string,import("../../webgl/Helper").UniformValue>} Uniforms
   */
  function generateUniformsFromContext(context, variables) {
    /** @type {Object<string,import("../../webgl/Helper").UniformValue>} */
    const uniforms = {};

    // define one uniform per variable
    for (const varName in context.variables) {
      const variable = context.variables[varName];
      const uniformName = uniformNameForVariable(variable.name);

      uniforms[uniformName] = () => {
        const value = variables[variable.name];
        if (typeof value === 'number') {
          return value;
        }
        if (typeof value === 'boolean') {
          return value ? 1 : 0;
        }
        if (variable.type === ColorType$1) {
          const color = [...asArray(value || '#eee')];
          color[0] /= 255;
          color[1] /= 255;
          color[2] /= 255;
          color[3] ??= 1;
          return color;
        }
        if (typeof value === 'string') {
          return getStringNumberEquivalent(value);
        }
        return value;
      };
    }

    return uniforms;
  }

  /**
   * Generates a set of attributes from properties collected in a compilation context,
   * to be fed to a WebGLHelper instance
   * @param {import("../../expr/gpu.js").CompilationContext} context Compilation context
   * @return {import('./VectorStyleRenderer.js').AttributeDefinitions} Attributes
   */
  function generateAttributesFromContext(context) {
    /**
     * @type {import('./VectorStyleRenderer.js').AttributeDefinitions}
     */
    const attributes = {};

    // Define attributes with their callback for each property used in the vertex shader
    for (const propName in context.properties) {
      const property = context.properties[propName];
      const callback = (feature) => {
        const value = feature.get(property.name);
        if (property.type === ColorType$1) {
          return packColor([...asArray(value || '#eee')]);
        }
        if (typeof value === 'string') {
          return getStringNumberEquivalent(value);
        }
        if (typeof value === 'boolean') {
          return value ? 1 : 0;
        }
        return value;
      };

      attributes[`prop_${property.name}`] = {
        size: getGlslSizeFromType(property.type),
        callback,
      };
    }
    return attributes;
  }

  /**
   * Utilities for parsing flat styles for WebGL renderers
   * @module ol/render/webgl/style
   */

  /**
   * see https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript
   * @param {Object|string} input The hash input, either an object or string
   * @return {string} Hash (if the object cannot be serialized, it is based on `getUid`)
   */
  function computeHash(input) {
    const hash = JSON.stringify(input)
      .split('')
      .reduce((prev, curr) => (prev << 5) - prev + curr.charCodeAt(0), 0);
    return (hash >>> 0).toString();
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader builder
   * @param {import("../../expr/gpu.js").CompilationContext} vertContext Vertex shader compilation context
   * @param {'shape-'|'circle-'|'icon-'} prefix Properties prefix
   */
  function parseCommonSymbolProperties(style, builder, vertContext, prefix) {
    if (`${prefix}radius` in style && prefix !== 'icon-') {
      let radius = expressionToGlsl(
        vertContext,
        style[`${prefix}radius`],
        NumberType$1,
      );
      if (`${prefix}radius2` in style) {
        const radius2 = expressionToGlsl(
          vertContext,
          style[`${prefix}radius2`],
          NumberType$1,
        );
        radius = `max(${radius}, ${radius2})`;
      }
      if (`${prefix}stroke-width` in style) {
        radius = `(${radius} + ${expressionToGlsl(
        vertContext,
        style[`${prefix}stroke-width`],
        NumberType$1,
      )} * 0.5)`;
      }
      builder.setSymbolSizeExpression(`vec2(${radius} * 2. + 0.5)`); // adding some padding for antialiasing
    }
    if (`${prefix}scale` in style) {
      const scale = expressionToGlsl(
        vertContext,
        style[`${prefix}scale`],
        SizeType,
      );
      builder.setSymbolSizeExpression(
        `${builder.getSymbolSizeExpression()} * ${scale}`,
      );
    }
    if (`${prefix}displacement` in style) {
      builder.setSymbolOffsetExpression(
        expressionToGlsl(
          vertContext,
          style[`${prefix}displacement`],
          NumberArrayType$1,
        ),
      );
    }
    if (`${prefix}rotation` in style) {
      builder.setSymbolRotationExpression(
        expressionToGlsl(vertContext, style[`${prefix}rotation`], NumberType$1),
      );
    }
    if (`${prefix}rotate-with-view` in style) {
      builder.setSymbolRotateWithView(!!style[`${prefix}rotate-with-view`]);
    }
  }

  /**
   * @param {string} distanceField The distance field expression
   * @param {string|null} fillColor The fill color expression; null if no fill
   * @param {string|null} strokeColor The stroke color expression; null if no stroke
   * @param {string|null} strokeWidth The stroke width expression; null if no stroke
   * @param {string|null} opacity The opacity expression; null if no stroke
   * @return {string} The final color expression, based on the distance field and given params
   */
  function getColorFromDistanceField(
    distanceField,
    fillColor,
    strokeColor,
    strokeWidth,
    opacity,
  ) {
    let color = 'vec4(0.)';
    if (fillColor !== null) {
      color = fillColor;
    }
    if (strokeColor !== null && strokeWidth !== null) {
      const strokeFillRatio = `smoothstep(-${strokeWidth} + 0.63, -${strokeWidth} - 0.58, ${distanceField})`;
      color = `mix(${strokeColor}, ${color}, ${strokeFillRatio})`;
    }
    const shapeOpacity = `(1.0 - smoothstep(-0.63, 0.58, ${distanceField}))`;
    let result = `${color} * vec4(1.0, 1.0, 1.0, ${shapeOpacity})`;
    if (opacity !== null) {
      result = `${result} * vec4(1.0, 1.0, 1.0, ${opacity})`;
    }
    return result;
  }

  /**
   * This will parse an image property provided by `<prefix>-src`
   * The image size expression in GLSL will be returned
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {'icon-'|'fill-pattern-'|'stroke-pattern-'} prefix Property prefix
   * @param {string} textureId A identifier that will be used in the generated uniforms: `sample2d u_texture<id>` and `vec2 u_texture<id>_size`
   * @return {string} The image size expression
   */
  function parseImageProperties(style, builder, uniforms, prefix, textureId) {
    const image = new Image();
    image.crossOrigin =
      style[`${prefix}cross-origin`] === undefined
        ? 'anonymous'
        : style[`${prefix}cross-origin`];
    assert(
      typeof style[`${prefix}src`] === 'string',
      `WebGL layers do not support expressions for the ${prefix}src style property`,
    );
    image.src = /** @type {string} */ (style[`${prefix}src`]);

    // the size is provided asynchronously using a uniform
    uniforms[`u_texture${textureId}_size`] = () => {
      return image.complete ? [image.width, image.height] : [0, 0];
    };
    builder.addUniform(`u_texture${textureId}_size`, 'vec2');
    const size = `u_texture${textureId}_size`;

    uniforms[`u_texture${textureId}`] = image;
    builder.addUniform(`u_texture${textureId}`, 'sampler2D');
    return size;
  }

  /**
   * This will parse an image's offset properties provided by `<prefix>-offset`, `<prefix>-offset-origin` and `<prefix>-size`
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {'icon-'|'fill-pattern-'|'stroke-pattern-'} prefix Property prefix
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context (vertex or fragment)
   * @param {string} imageSize Pixel size of the full image as a GLSL expression
   * @param {string} sampleSize Pixel size of the sample in the image as a GLSL expression
   * @return {string} The offset expression
   */
  function parseImageOffsetProperties(
    style,
    prefix,
    context,
    imageSize,
    sampleSize,
  ) {
    let offsetExpression = expressionToGlsl(
      context,
      style[`${prefix}offset`],
      SizeType,
    );
    if (`${prefix}offset-origin` in style) {
      switch (style[`${prefix}offset-origin`]) {
        case 'top-right':
          offsetExpression = `vec2(${imageSize}.x, 0.) + ${sampleSize} * vec2(-1., 0.) + ${offsetExpression} * vec2(-1., 1.)`;
          break;
        case 'bottom-left':
          offsetExpression = `vec2(0., ${imageSize}.y) + ${sampleSize} * vec2(0., -1.) + ${offsetExpression} * vec2(1., -1.)`;
          break;
        case 'bottom-right':
          offsetExpression = `${imageSize} - ${sampleSize} - ${offsetExpression}`;
          break;
      }
    }
    return offsetExpression;
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context
   */
  function parseCircleProperties(style, builder, uniforms, context) {
    // this function takes in screen coordinates in pixels and returns the signed distance field
    // (0 on the boundary, negative inside the circle, positive outside, values in pixels)
    context.functions['circleDistanceField'] =
      `float circleDistanceField(vec2 point, float radius) {
  return length(point) - radius;
}`;

    parseCommonSymbolProperties(style, builder, context, 'circle-');

    // OPACITY
    let opacity = null;
    if ('circle-opacity' in style) {
      opacity = expressionToGlsl(context, style['circle-opacity'], NumberType$1);
    }

    // SCALE
    let currentPoint = 'coordsPx';
    if ('circle-scale' in style) {
      const scale = expressionToGlsl(context, style['circle-scale'], SizeType);
      currentPoint = `coordsPx / ${scale}`;
    }

    // FILL COLOR
    let fillColor = null;
    if ('circle-fill-color' in style) {
      fillColor = expressionToGlsl(
        context,
        style['circle-fill-color'],
        ColorType$1,
      );
    }

    // STROKE COLOR
    let strokeColor = null;
    if ('circle-stroke-color' in style) {
      strokeColor = expressionToGlsl(
        context,
        style['circle-stroke-color'],
        ColorType$1,
      );
    }

    // RADIUS
    let radius = expressionToGlsl(context, style['circle-radius'], NumberType$1);

    // STROKE WIDTH
    let strokeWidth = null;
    if ('circle-stroke-width' in style) {
      strokeWidth = expressionToGlsl(
        context,
        style['circle-stroke-width'],
        NumberType$1,
      );
      radius = `(${radius} + ${strokeWidth} * 0.5)`;
    }

    // FINAL COLOR
    const distanceField = `circleDistanceField(${currentPoint}, ${radius})`;
    const colorExpression = getColorFromDistanceField(
      distanceField,
      fillColor,
      strokeColor,
      strokeWidth,
      opacity,
    );
    builder.setSymbolColorExpression(colorExpression);
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context
   */
  function parseShapeProperties(style, builder, uniforms, context) {
    context.functions['round'] = `float round(float v) {
  return sign(v) * floor(abs(v) + 0.5);
}`;

    // these functions take in screen coordinates in pixels and returns the signed distance field
    // (0 on the boundary, negative inside the polygon, positive outside, values in pixels)
    // inspired by https://github.com/zranger1/PixelblazePatterns/blob/master/Toolkit/sdf2d.md#n-sided-regular-polygon
    context.functions['starDistanceField'] =
      `float starDistanceField(vec2 point, float numPoints, float radius, float radius2, float angle) {
  float startAngle = -PI * 0.5 + angle; // tip starts upwards and rotates clockwise with angle
  float c = cos(startAngle);
  float s = sin(startAngle);
  vec2 pointRotated = vec2(c * point.x - s * point.y, s * point.x + c * point.y);
  float alpha = TWO_PI / numPoints; // the angle of one sector
  float beta = atan(pointRotated.y, pointRotated.x);
  float gamma = round(beta / alpha) * alpha; // angle in sector
  c = cos(-gamma);
  s = sin(-gamma);
  vec2 inSector = vec2(c * pointRotated.x - s * pointRotated.y, abs(s * pointRotated.x + c * pointRotated.y));
  vec2 tipToPoint = inSector + vec2(-radius, 0.);
  vec2 edgeNormal = vec2(radius2 * sin(alpha * 0.5), -radius2 * cos(alpha * 0.5) + radius);
  return dot(normalize(edgeNormal), tipToPoint);
}`;
    context.functions['regularDistanceField'] =
      `float regularDistanceField(vec2 point, float numPoints, float radius, float angle) {
  float startAngle = -PI * 0.5 + angle; // tip starts upwards and rotates clockwise with angle
  float c = cos(startAngle);
  float s = sin(startAngle);
  vec2 pointRotated = vec2(c * point.x - s * point.y, s * point.x + c * point.y);
  float alpha = TWO_PI / numPoints; // the angle of one sector
  float radiusIn = radius * cos(PI / numPoints);
  float beta = atan(pointRotated.y, pointRotated.x);
  float gamma = round((beta - alpha * 0.5) / alpha) * alpha + alpha * 0.5; // angle in sector from mid
  c = cos(-gamma);
  s = sin(-gamma);
  vec2 inSector = vec2(c * pointRotated.x - s * pointRotated.y, abs(s * pointRotated.x + c * pointRotated.y));
  return inSector.x - radiusIn;
}`;

    parseCommonSymbolProperties(style, builder, context, 'shape-');

    // OPACITY
    let opacity = null;
    if ('shape-opacity' in style) {
      opacity = expressionToGlsl(context, style['shape-opacity'], NumberType$1);
    }

    // SCALE
    let currentPoint = 'coordsPx';
    if ('shape-scale' in style) {
      const scale = expressionToGlsl(context, style['shape-scale'], SizeType);
      currentPoint = `coordsPx / ${scale}`;
    }

    // FILL COLOR
    let fillColor = null;
    if ('shape-fill-color' in style) {
      fillColor = expressionToGlsl(context, style['shape-fill-color'], ColorType$1);
    }

    // STROKE COLOR
    let strokeColor = null;
    if ('shape-stroke-color' in style) {
      strokeColor = expressionToGlsl(
        context,
        style['shape-stroke-color'],
        ColorType$1,
      );
    }

    // STROKE WIDTH
    let strokeWidth = null;
    if ('shape-stroke-width' in style) {
      strokeWidth = expressionToGlsl(
        context,
        style['shape-stroke-width'],
        NumberType$1,
      );
    }

    // SHAPE TYPE
    const numPoints = expressionToGlsl(
      context,
      style['shape-points'],
      NumberType$1,
    );
    let angle = '0.';
    if ('shape-angle' in style) {
      angle = expressionToGlsl(context, style['shape-angle'], NumberType$1);
    }
    let shapeField;
    let radius = expressionToGlsl(context, style['shape-radius'], NumberType$1);
    if (strokeWidth !== null) {
      radius = `${radius} + ${strokeWidth} * 0.5`;
    }
    if ('shape-radius2' in style) {
      let radius2 = expressionToGlsl(context, style['shape-radius2'], NumberType$1);
      if (strokeWidth !== null) {
        radius2 = `${radius2} + ${strokeWidth} * 0.5`;
      }
      shapeField = `starDistanceField(${currentPoint}, ${numPoints}, ${radius}, ${radius2}, ${angle})`;
    } else {
      shapeField = `regularDistanceField(${currentPoint}, ${numPoints}, ${radius}, ${angle})`;
    }

    // FINAL COLOR
    const colorExpression = getColorFromDistanceField(
      shapeField,
      fillColor,
      strokeColor,
      strokeWidth,
      opacity,
    );
    builder.setSymbolColorExpression(colorExpression);
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context
   */
  function parseIconProperties(style, builder, uniforms, context) {
    // COLOR
    let color = 'vec4(1.0)';
    if ('icon-color' in style) {
      color = expressionToGlsl(context, style['icon-color'], ColorType$1);
    }

    // OPACITY
    if ('icon-opacity' in style) {
      color = `${color} * vec4(1.0, 1.0, 1.0, ${expressionToGlsl(
      context,
      style['icon-opacity'],
      NumberType$1,
    )})`;
    }

    // IMAGE & SIZE
    const textureId = computeHash(style['icon-src']);
    const sizeExpression = parseImageProperties(
      style,
      builder,
      uniforms,
      'icon-',
      textureId,
    );
    builder
      .setSymbolColorExpression(
        `${color} * texture2D(u_texture${textureId}, v_texCoord)`,
      )
      .setSymbolSizeExpression(sizeExpression);

    // override size if width/height were specified
    if ('icon-width' in style && 'icon-height' in style) {
      builder.setSymbolSizeExpression(
        `vec2(${expressionToGlsl(
        context,
        style['icon-width'],
        NumberType$1,
      )}, ${expressionToGlsl(context, style['icon-height'], NumberType$1)})`,
      );
    }

    // tex coord
    if ('icon-offset' in style && 'icon-size' in style) {
      const sampleSize = expressionToGlsl(
        context,
        style['icon-size'],
        NumberArrayType$1,
      );
      const fullsize = builder.getSymbolSizeExpression();
      builder.setSymbolSizeExpression(sampleSize);
      const offset = parseImageOffsetProperties(
        style,
        'icon-',
        context,
        'v_quadSizePx',
        sampleSize,
      );
      builder.setTextureCoordinateExpression(
        `(vec4((${offset}).xyxy) + vec4(0., 0., ${sampleSize})) / (${fullsize}).xyxy`,
      );
    }

    parseCommonSymbolProperties(style, builder, context, 'icon-');

    if ('icon-anchor' in style) {
      const anchor = expressionToGlsl(
        context,
        style['icon-anchor'],
        NumberArrayType$1,
      );
      let scale = `1.0`;
      if (`icon-scale` in style) {
        scale = expressionToGlsl(context, style[`icon-scale`], SizeType);
      }
      let shiftPx;
      if (
        style['icon-anchor-x-units'] === 'pixels' &&
        style['icon-anchor-y-units'] === 'pixels'
      ) {
        shiftPx = `${anchor} * ${scale}`;
      } else if (style['icon-anchor-x-units'] === 'pixels') {
        shiftPx = `${anchor} * vec2(vec2(${scale}).x, v_quadSizePx.y)`;
      } else if (style['icon-anchor-y-units'] === 'pixels') {
        shiftPx = `${anchor} * vec2(v_quadSizePx.x, vec2(${scale}).x)`;
      } else {
        shiftPx = `${anchor} * v_quadSizePx`;
      }
      // default origin is top-left
      let offsetPx = `v_quadSizePx * vec2(0.5, -0.5) + ${shiftPx} * vec2(-1., 1.)`;
      if ('icon-anchor-origin' in style) {
        switch (style['icon-anchor-origin']) {
          case 'top-right':
            offsetPx = `v_quadSizePx * -0.5 + ${shiftPx}`;
            break;
          case 'bottom-left':
            offsetPx = `v_quadSizePx * 0.5 - ${shiftPx}`;
            break;
          case 'bottom-right':
            offsetPx = `v_quadSizePx * vec2(-0.5, 0.5) + ${shiftPx} * vec2(1., -1.)`;
            break;
        }
      }
      builder.setSymbolOffsetExpression(
        `${builder.getSymbolOffsetExpression()} + ${offsetPx}`,
      );
    }
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader Builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context
   */
  function parseStrokeProperties(style, builder, uniforms, context) {
    if ('stroke-color' in style) {
      builder.setStrokeColorExpression(
        expressionToGlsl(context, style['stroke-color'], ColorType$1),
      );
    }
    if ('stroke-pattern-src' in style) {
      const textureId = computeHash(style['stroke-pattern-src']);
      const sizeExpression = parseImageProperties(
        style,
        builder,
        uniforms,
        'stroke-pattern-',
        textureId,
      );
      let sampleSizeExpression = sizeExpression;
      let offsetExpression = 'vec2(0.)';
      if ('stroke-pattern-offset' in style && 'stroke-pattern-size' in style) {
        sampleSizeExpression = expressionToGlsl(
          context,
          style[`stroke-pattern-size`],
          NumberArrayType$1,
        );
        offsetExpression = parseImageOffsetProperties(
          style,
          'stroke-pattern-',
          context,
          sizeExpression,
          sampleSizeExpression,
        );
      }
      let spacingExpression = '0.';
      if ('stroke-pattern-spacing' in style) {
        spacingExpression = expressionToGlsl(
          context,
          style['stroke-pattern-spacing'],
          NumberType$1,
        );
      }
      context.functions['sampleStrokePattern'] =
        `vec4 sampleStrokePattern(sampler2D texture, vec2 textureSize, vec2 textureOffset, vec2 sampleSize, float spacingPx, float currentLengthPx, float currentRadiusRatio, float lineWidth) {
  float currentLengthScaled = currentLengthPx * sampleSize.y / lineWidth;
  float spacingScaled = spacingPx * sampleSize.y / lineWidth;
  float uCoordPx = mod(currentLengthScaled, (sampleSize.x + spacingScaled));
  // make sure that we're not sampling too close to the borders to avoid interpolation with outside pixels
  uCoordPx = clamp(uCoordPx, 0.5, sampleSize.x - 0.5);
  float vCoordPx = (-currentRadiusRatio * 0.5 + 0.5) * sampleSize.y;
  vec2 texCoord = (vec2(uCoordPx, vCoordPx) + textureOffset) / textureSize;
  return texture2D(texture, texCoord);
}`;
      const textureName = `u_texture${textureId}`;
      let tintExpression = '1.';
      if ('stroke-color' in style) {
        tintExpression = builder.getStrokeColorExpression();
      }
      builder.setStrokeColorExpression(
        `${tintExpression} * sampleStrokePattern(${textureName}, ${sizeExpression}, ${offsetExpression}, ${sampleSizeExpression}, ${spacingExpression}, currentLengthPx, currentRadiusRatio, v_width)`,
      );
    }

    if ('stroke-width' in style) {
      builder.setStrokeWidthExpression(
        expressionToGlsl(context, style['stroke-width'], NumberType$1),
      );
    }

    if ('stroke-offset' in style) {
      builder.setStrokeOffsetExpression(
        expressionToGlsl(context, style['stroke-offset'], NumberType$1),
      );
    }

    if ('stroke-line-cap' in style) {
      builder.setStrokeCapExpression(
        expressionToGlsl(context, style['stroke-line-cap'], StringType$1),
      );
    }

    if ('stroke-line-join' in style) {
      builder.setStrokeJoinExpression(
        expressionToGlsl(context, style['stroke-line-join'], StringType$1),
      );
    }

    if ('stroke-miter-limit' in style) {
      builder.setStrokeMiterLimitExpression(
        expressionToGlsl(context, style['stroke-miter-limit'], NumberType$1),
      );
    }

    if ('stroke-line-dash' in style) {
      context.functions['getSingleDashDistance'] =
        `float getSingleDashDistance(float distance, float radius, float dashOffset, float dashLength, float dashLengthTotal, float capType, float lineWidth) {
  float localDistance = mod(distance, dashLengthTotal);
  float distanceSegment = abs(localDistance - dashOffset - dashLength * 0.5) - dashLength * 0.5;
  distanceSegment = min(distanceSegment, dashLengthTotal - localDistance);
  if (capType == ${stringToGlsl('square')}) {
    distanceSegment -= lineWidth * 0.5;
  } else if (capType == ${stringToGlsl('round')}) {
    distanceSegment = min(distanceSegment, sqrt(distanceSegment * distanceSegment + radius * radius) - lineWidth * 0.5);
  }
  return distanceSegment;
}`;

      let dashPattern = style['stroke-line-dash'].map((v) =>
        expressionToGlsl(context, v, NumberType$1),
      );
      // if pattern has odd length, concatenate it with itself to be even
      if (dashPattern.length % 2 === 1) {
        dashPattern = [...dashPattern, ...dashPattern];
      }

      let offsetExpression = '0.';
      if ('stroke-line-dash-offset' in style) {
        offsetExpression = expressionToGlsl(
          context,
          style['stroke-line-dash-offset'],
          NumberType$1,
        );
      }

      // define a function for this dash specifically
      const uniqueDashKey = computeHash(style['stroke-line-dash']);
      const dashFunctionName = `dashDistanceField_${uniqueDashKey}`;

      const dashLengthsParamsDef = dashPattern
        .map((v, i) => `float dashLength${i}`)
        .join(', ');
      const totalLengthDef = dashPattern
        .map((v, i) => `dashLength${i}`)
        .join(' + ');
      let currentDashOffset = '0.';
      let distanceExpression = `getSingleDashDistance(distance, radius, ${currentDashOffset}, dashLength0, totalDashLength, capType, lineWidth)`;
      for (let i = 2; i < dashPattern.length; i += 2) {
        currentDashOffset = `${currentDashOffset} + dashLength${
        i - 2
      } + dashLength${i - 1}`;
        distanceExpression = `min(${distanceExpression}, getSingleDashDistance(distance, radius, ${currentDashOffset}, dashLength${i}, totalDashLength, capType, lineWidth))`;
      }

      context.functions[dashFunctionName] =
        `float ${dashFunctionName}(float distance, float radius, float capType, float lineWidth, ${dashLengthsParamsDef}) {
  float totalDashLength = ${totalLengthDef};
  return ${distanceExpression};
}`;
      const dashLengthsCalls = dashPattern.map((v, i) => `${v}`).join(', ');
      builder.setStrokeDistanceFieldExpression(
        `${dashFunctionName}(currentLengthPx + ${offsetExpression}, currentRadiusPx, capType, v_width, ${dashLengthsCalls})`,
      );
    }
  }

  /**
   * @param {import("../../style/flat.js").FlatStyle} style Style
   * @param {ShaderBuilder} builder Shader Builder
   * @param {Object<string,import("../../webgl/Helper").UniformValue>} uniforms Uniforms
   * @param {import("../../expr/gpu.js").CompilationContext} context Shader compilation context
   */
  function parseFillProperties(style, builder, uniforms, context) {
    if ('fill-color' in style) {
      builder.setFillColorExpression(
        expressionToGlsl(context, style['fill-color'], ColorType$1),
      );
    }
    if ('fill-pattern-src' in style) {
      const textureId = computeHash(style['fill-pattern-src']);
      const sizeExpression = parseImageProperties(
        style,
        builder,
        uniforms,
        'fill-pattern-',
        textureId,
      );
      let sampleSizeExpression = sizeExpression;
      let offsetExpression = 'vec2(0.)';
      if ('fill-pattern-offset' in style && 'fill-pattern-size' in style) {
        sampleSizeExpression = expressionToGlsl(
          context,
          style[`fill-pattern-size`],
          NumberArrayType$1,
        );
        offsetExpression = parseImageOffsetProperties(
          style,
          'fill-pattern-',
          context,
          sizeExpression,
          sampleSizeExpression,
        );
      }
      context.functions['sampleFillPattern'] =
        `vec4 sampleFillPattern(sampler2D texture, vec2 textureSize, vec2 textureOffset, vec2 sampleSize, vec2 pxOrigin, vec2 pxPosition) {
  float scaleRatio = pow(2., mod(u_zoom + 0.5, 1.) - 0.5);
  vec2 pxRelativePos = pxPosition - pxOrigin;
  // rotate the relative position from origin by the current view rotation
  pxRelativePos = vec2(pxRelativePos.x * cos(u_rotation) - pxRelativePos.y * sin(u_rotation), pxRelativePos.x * sin(u_rotation) + pxRelativePos.y * cos(u_rotation));
  // sample position is computed according to the sample offset & size
  vec2 samplePos = mod(pxRelativePos / scaleRatio, sampleSize);
  // also make sure that we're not sampling too close to the borders to avoid interpolation with outside pixels
  samplePos = clamp(samplePos, vec2(0.5), sampleSize - vec2(0.5));
  samplePos.y = sampleSize.y - samplePos.y; // invert y axis so that images appear upright
  return texture2D(texture, (samplePos + textureOffset) / textureSize);
}`;
      const textureName = `u_texture${textureId}`;
      let tintExpression = '1.';
      if ('fill-color' in style) {
        tintExpression = builder.getFillColorExpression();
      }
      builder.setFillColorExpression(
        `${tintExpression} * sampleFillPattern(${textureName}, ${sizeExpression}, ${offsetExpression}, ${sampleSizeExpression}, pxOrigin, pxPos)`,
      );
    }
  }

  /**
   * @typedef {Object} StyleParseResult
   * @property {ShaderBuilder} builder Shader builder pre-configured according to a given style
   * @property {import("./VectorStyleRenderer.js").UniformDefinitions} uniforms Uniform definitions
   * @property {import("./VectorStyleRenderer.js").AttributeDefinitions} attributes Attribute definitions
   */

  /**
   * Parses a {@link import("../../style/flat.js").FlatStyle} object and returns a {@link ShaderBuilder}
   * object that has been configured according to the given style, as well as `attributes` and `uniforms`
   * arrays to be fed to the `WebGLPointsRenderer` class.
   *
   * Also returns `uniforms` and `attributes` properties as expected by the
   * {@link module:ol/renderer/webgl/PointsLayer~WebGLPointsLayerRenderer}.
   *
   * @param {import("../../style/flat.js").FlatStyle} style Flat style.
   * @param {import('../../style/flat.js').StyleVariables} [variables] Style variables.
   * @param {import("../../expr/expression.js").EncodedExpression} [filter] Filter (if any)
   * @return {StyleParseResult} Result containing shader params, attributes and uniforms.
   */
  function parseLiteralStyle(style, variables, filter) {
    const context = newCompilationContext();

    const builder = new ShaderBuilder();

    /** @type {Object<string,import("../../webgl/Helper").UniformValue>} */
    const uniforms = {};

    if ('icon-src' in style) {
      parseIconProperties(style, builder, uniforms, context);
    } else if ('shape-points' in style) {
      parseShapeProperties(style, builder, uniforms, context);
    } else if ('circle-radius' in style) {
      parseCircleProperties(style, builder, uniforms, context);
    }
    parseStrokeProperties(style, builder, uniforms, context);
    parseFillProperties(style, builder, uniforms, context);

    // note that the style filter may have already been applied earlier when building the rendering instructions
    // this is still needed in case a filter cannot be evaluated statically beforehand (e.g. depending on time)
    if (filter) {
      const parsedFilter = expressionToGlsl(context, filter, BooleanType$1);
      builder.setFragmentDiscardExpression(`!${parsedFilter}`);
    }

    /**
     * @type {import('./VectorStyleRenderer.js').AttributeDefinitions}
     */
    const attributes = {};

    // Define attributes for special inputs
    function defineSpecialInput(contextPropName, glslPropName, type, callback) {
      if (!context[contextPropName]) {
        return;
      }
      const glslType = getGlslTypeFromType(type);
      const attrSize = getGlslSizeFromType(type);
      builder.addAttribute(`a_${glslPropName}`, glslType);

      attributes[glslPropName] = {
        size: attrSize,
        callback,
      };
    }
    defineSpecialInput(
      'geometryType',
      GEOMETRY_TYPE_PROPERTY_NAME,
      StringType$1,
      (feature) =>
        getStringNumberEquivalent(computeGeometryType(feature.getGeometry())),
    );
    defineSpecialInput(
      'featureId',
      FEATURE_ID_PROPERTY_NAME,
      StringType$1 | NumberType$1,
      (feature) => {
        const id = feature.getId() ?? null;
        return typeof id === 'string' ? getStringNumberEquivalent(id) : id;
      },
    );

    applyContextToBuilder(builder, context);

    return {
      builder,
      attributes: {...attributes, ...generateAttributesFromContext(context)},
      uniforms: {
        ...uniforms,
        ...generateUniformsFromContext(context, variables),
      },
    };
  }

  /**
   * @typedef {import('./VectorStyleRenderer.js').AsShaders} StyleAsShaders
   */
  /**
   * @typedef {import('./VectorStyleRenderer.js').AsRule} StyleAsRule
   */

  /**
   * Takes in either a Flat Style or an array of shaders (used as input for the webgl vector layer classes)
   * and breaks it down into separate styles to be used by the VectorStyleRenderer class.
   * @param {import('../../style/flat.js').FlatStyleLike | Array<StyleAsShaders> | StyleAsShaders} style Flat style or shaders
   * @return {Array<StyleAsShaders | StyleAsRule>} Separate styles as shaders or rules with a single flat style and a filter
   */
  function breakDownFlatStyle(style) {
    // possible cases:
    // - single shader
    // - multiple shaders
    // - single style
    // - multiple styles
    // - multiple rules
    const asArray = Array.isArray(style) ? style : [style];

    // if array of rules: break rules into separate styles, compute "else" filters
    if ('style' in asArray[0]) {
      /** @type {Array<StyleAsRule>} */
      const styles = [];
      const rules = /** @type {Array<import('../../style/flat.js').Rule>} */ (
        asArray
      );
      const previousFilters = [];
      for (const rule of rules) {
        const ruleStyles = Array.isArray(rule.style) ? rule.style : [rule.style];
        /** @type {import("../../expr/expression.js").EncodedExpression} */
        let currentFilter = rule.filter;
        if (rule.else && previousFilters.length) {
          currentFilter = [
            'all',
            ...previousFilters.map((filter) => ['!', filter]),
          ];
          if (rule.filter) {
            currentFilter.push(rule.filter);
          }
          if (currentFilter.length < 3) {
            currentFilter = currentFilter[1];
          }
        }
        if (rule.filter) {
          previousFilters.push(rule.filter);
        }
        /** @type {Array<StyleAsRule>} */
        const stylesWithFilters = ruleStyles.map((style) => ({
          style,
          ...(currentFilter && {filter: currentFilter}),
        }));
        styles.push(...stylesWithFilters);
      }
      return styles;
    }

    // if array of shaders: return as is
    if ('builder' in asArray[0]) {
      return /** @type {Array<StyleAsShaders>} */ (asArray);
    }

    return asArray.map(
      (style) =>
        /** @type {StyleAsRule} */ ({
          style,
        }),
    );
  }

  /**
   * @module ol/render/webgl/VectorStyleRenderer
   */

  const tmpColor = [];
  /** @type {Worker|undefined} */
  let WEBGL_WORKER;
  function getWebGLWorker() {
    if (!WEBGL_WORKER) {
      WEBGL_WORKER = create$1();
    }
    return WEBGL_WORKER;
  }
  let workerMessageCounter = 0;

  /**
   * Names of attributes made available to the vertex shader.
   * Please note: changing these *will* break custom shaders!
   * @enum {string}
   */
  const Attributes$1 = {
    POSITION: 'a_position',
    INDEX: 'a_index',
    SEGMENT_START: 'a_segmentStart',
    SEGMENT_END: 'a_segmentEnd',
    MEASURE_START: 'a_measureStart',
    MEASURE_END: 'a_measureEnd',
    PARAMETERS: 'a_parameters',
    JOIN_ANGLES: 'a_joinAngles',
    DISTANCE: 'a_distance',
  };

  /**
   * @typedef {Object} AttributeDefinition A description of a custom attribute to be passed on to the GPU, with a value different
   * for each feature.
   * @property {number} [size] Amount of numerical values composing the attribute, either 1, 2, 3 or 4; in case size is > 1, the return value
   * of the callback should be an array; if unspecified, assumed to be a single float value
   * @property {function(this:import("./MixedGeometryBatch.js").GeometryBatchItem, import("../../Feature").FeatureLike):number|Array<number>} callback This callback computes the numerical value of the
   * attribute for a given feature.
   */

  /**
   * @typedef {Object<string, AttributeDefinition>} AttributeDefinitions
   * @typedef {Object<string, import("../../webgl/Helper").UniformValue>} UniformDefinitions
   */

  /**
   * @typedef {Object} WebGLBuffers
   * @property {Array<WebGLArrayBuffer>} polygonBuffers Array containing indices and vertices buffers for polygons
   * @property {Array<WebGLArrayBuffer>} lineStringBuffers Array containing indices and vertices buffers for line strings
   * @property {Array<WebGLArrayBuffer>} pointBuffers Array containing indices and vertices buffers for points
   * @property {import("../../transform.js").Transform} invertVerticesTransform Inverse of the transform applied when generating buffers
   */

  /**
   * @typedef {Object} RenderInstructions
   * @property {Float32Array|null} polygonInstructions Polygon instructions; null if nothing to render
   * @property {Float32Array|null} lineStringInstructions LineString instructions; null if nothing to render
   * @property {Float32Array|null} pointInstructions Point instructions; null if nothing to render
   */

  /**
   * @typedef {Object} ShaderProgram An object containing both shaders (vertex and fragment)
   * @property {string} vertex Vertex shader source
   * @property {string} fragment Fragment shader source
   */

  /**
   * @typedef {Object} AsShaders
   * @property {import("./ShaderBuilder.js").ShaderBuilder} builder Shader builder with the appropriate presets.
   * @property {AttributeDefinitions} [attributes] Custom attributes made available in the vertex shaders.
   * Default shaders rely on the attributes in {@link Attributes}.
   * @property {UniformDefinitions} [uniforms] Additional uniforms usable in shaders.
   */

  /**
   * @typedef {Object} AsRule
   * @property {import('../../style/flat.js').FlatStyle} style Style
   * @property {import("../../expr/expression.js").EncodedExpression} [filter] Filter
   */

  /**
   * @typedef {AsRule|AsShaders} VectorStyle
   */

  /**
   * @classdesc This class is responsible for:
   * 1. generate WebGL buffers according to a provided style, using a MixedGeometryBatch as input
   * 2. rendering geometries contained in said buffers
   *
   * A layer renderer will typically maintain several of these in order to have several styles rendered separately.
   *
   * A VectorStyleRenderer instance can be created either from a literal style or from shaders using either
   * `VectorStyleRenderer.fromStyle` or `VectorStyleRenderer.fromShaders`. The shaders should not be provided explicitly
   * but instead as a preconfigured ShaderBuilder instance.
   *
   * The `generateBuffers` method returns a promise resolving to WebGL buffers that are intended to be rendered by the
   * same renderer.
   */
  class VectorStyleRenderer {
    /**
     * @param {VectorStyle} styleOrShaders Literal style or custom shaders
     * @param {import('../../style/flat.js').StyleVariables} variables Style variables
     * @param {import('../../webgl/Helper.js').default} helper Helper
     * @param {boolean} [enableHitDetection] Whether to enable the hit detection (needs compatible shader)
     * @param {import("../../expr/expression.js").ExpressionValue} [filter] Optional filter expression
     */
    constructor(styleOrShaders, variables, helper, enableHitDetection, filter) {
      /**
       * @private
       * @type {import('../../webgl/Helper.js').default}
       */
      this.helper_;

      /**
       * @private
       */
      this.hitDetectionEnabled_ = !!enableHitDetection;

      let asShaders = /** @type {AsShaders} */ (styleOrShaders);
      const isShaders = 'builder' in styleOrShaders;
      if (!isShaders) {
        const asRule = /** @type {AsRule} */ (styleOrShaders);
        const parseResult = parseLiteralStyle(
          asRule.style,
          variables,
          asRule.filter,
        );
        asShaders = {
          builder: parseResult.builder,
          attributes: parseResult.attributes,
          uniforms: parseResult.uniforms,
        };
      }

      /**
       * @private
       * @type {WebGLProgram}
       */
      this.fillProgram_;

      /**
       * @private
       * @type {WebGLProgram}
       */
      this.strokeProgram_;

      /**
       * @private
       * @type {WebGLProgram}
       */
      this.symbolProgram_;

      /**
       * @type {boolean}
       * @private
       */
      this.hasFill_ = !!asShaders.builder.getFillVertexShader();
      if (this.hasFill_) {
        /**
         * @private
         */
        this.fillVertexShader_ = asShaders.builder.getFillVertexShader();
        /**
         * @private
         */
        this.fillFragmentShader_ = asShaders.builder.getFillFragmentShader();
      }

      /**
       * @type {boolean}
       * @private
       */
      this.hasStroke_ = !!asShaders.builder.getStrokeVertexShader();
      if (this.hasStroke_) {
        /**
         * @private
         */
        this.strokeVertexShader_ = asShaders.builder.getStrokeVertexShader();
        /**
         * @private
         */
        this.strokeFragmentShader_ = asShaders.builder.getStrokeFragmentShader();
      }

      /**
       * @type {boolean}
       * @private
       */
      this.hasSymbol_ = !!asShaders.builder.getSymbolVertexShader();
      if (this.hasSymbol_) {
        /**
         * @private
         */
        this.symbolVertexShader_ = asShaders.builder.getSymbolVertexShader();
        /**
         * @private
         */
        this.symbolFragmentShader_ = asShaders.builder.getSymbolFragmentShader();
      }

      /**
       * @type {function(import('../../Feature.js').FeatureLike): boolean}
       * @private
       */
      this.featureFilter_ = null;
      if (filter) {
        this.featureFilter_ = this.computeFeatureFilter(filter);
      }

      const hitDetectionAttributes = this.hitDetectionEnabled_
        ? {
            hitColor: {
              callback() {
                return colorEncodeId(this.ref, tmpColor);
              },
              size: 4,
            },
          }
        : {};

      /**
       * @private
       */
      this.customAttributes_ = Object.assign(
        {},
        hitDetectionAttributes,
        asShaders.attributes,
      );
      /**
       * @private
       */
      this.uniforms_ = asShaders.uniforms;

      const customAttributesDesc = Object.entries(this.customAttributes_).map(
        ([name, value]) => ({
          name: `a_${name}`,
          size: value.size || 1,
          type: AttributeType.FLOAT,
        }),
      );
      /**
       * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
       * @private
       */
      this.polygonAttributesDesc_ = [
        {
          name: Attributes$1.POSITION,
          size: 2,
          type: AttributeType.FLOAT,
        },
        ...customAttributesDesc,
      ];
      /**
       * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
       * @private
       */
      this.lineStringAttributesDesc_ = [
        {
          name: Attributes$1.SEGMENT_START,
          size: 2,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.MEASURE_START,
          size: 1,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.SEGMENT_END,
          size: 2,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.MEASURE_END,
          size: 1,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.JOIN_ANGLES,
          size: 2,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.DISTANCE,
          size: 1,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.PARAMETERS,
          size: 1,
          type: AttributeType.FLOAT,
        },
        ...customAttributesDesc,
      ];
      /**
       * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
       * @private
       */
      this.pointAttributesDesc_ = [
        {
          name: Attributes$1.POSITION,
          size: 2,
          type: AttributeType.FLOAT,
        },
        {
          name: Attributes$1.INDEX,
          size: 1,
          type: AttributeType.FLOAT,
        },
        ...customAttributesDesc,
      ];

      this.setHelper(helper);
    }

    /**
     * Will apply the style filter when generating geometry batches (if it can be evaluated outside a map context)
     * @param {import("../../expr/expression.js").ExpressionValue} filter Style filter
     * @return {function(import('../../Feature.js').FeatureLike): boolean} Feature filter
     * @private
     */
    computeFeatureFilter(filter) {
      const parsingContext = newParsingContext();
      /**
       * @type {import('../../expr/cpu.js').ExpressionEvaluator}
       */
      let compiled;
      try {
        compiled = buildExpression$1(filter, BooleanType$1, parsingContext);
      } catch {
        // filter expression failed to compile for CPU: ignore it
        return null;
      }

      // do not apply the filter if it depends on map state (e.g. zoom level) or any variable
      if (parsingContext.mapState || parsingContext.variables.size > 0) {
        return null;
      }

      const evalContext = newEvaluationContext();
      return (feature) => {
        evalContext.properties = feature.getPropertiesInternal();
        if (parsingContext.featureId) {
          const id = feature.getId();
          if (id !== undefined) {
            evalContext.featureId = id;
          } else {
            evalContext.featureId = null;
          }
        }
        evalContext.geometryType = computeGeometryType(feature.getGeometry());
        return /** @type {boolean} */ (compiled(evalContext));
      };
    }

    /**
     * @param {import('./MixedGeometryBatch.js').default} geometryBatch Geometry batch
     * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
     * @return {Promise<WebGLBuffers|null>} A promise resolving to WebGL buffers; returns null if buffers are empty
     */
    async generateBuffers(geometryBatch, transform) {
      let filteredBatch = geometryBatch;
      if (this.featureFilter_) {
        filteredBatch = filteredBatch.filter(this.featureFilter_);
        if (filteredBatch.isEmpty()) {
          return null;
        }
      }
      const renderInstructions = this.generateRenderInstructions_(
        filteredBatch,
        transform,
      );
      const [polygonBuffers, lineStringBuffers, pointBuffers] = await Promise.all(
        [
          this.generateBuffersForType_(
            renderInstructions.polygonInstructions,
            'Polygon',
            transform,
          ),
          this.generateBuffersForType_(
            renderInstructions.lineStringInstructions,
            'LineString',
            transform,
          ),
          this.generateBuffersForType_(
            renderInstructions.pointInstructions,
            'Point',
            transform,
          ),
        ],
      );
      // also return the inverse of the transform that was applied when generating buffers
      const invertVerticesTransform = makeInverse(
        create$3(),
        transform,
      );
      return {
        polygonBuffers: polygonBuffers,
        lineStringBuffers: lineStringBuffers,
        pointBuffers: pointBuffers,
        invertVerticesTransform: invertVerticesTransform,
      };
    }

    /**
     * @param {import('./MixedGeometryBatch.js').default} geometryBatch Geometry batch
     * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
     * @return {RenderInstructions} Render instructions
     * @private
     */
    generateRenderInstructions_(geometryBatch, transform) {
      const polygonInstructions = this.hasFill_
        ? generatePolygonRenderInstructions(
            geometryBatch.polygonBatch,
            new Float32Array(0),
            this.customAttributes_,
            transform,
          )
        : null;
      const lineStringInstructions = this.hasStroke_
        ? generateLineStringRenderInstructions(
            geometryBatch.lineStringBatch,
            new Float32Array(0),
            this.customAttributes_,
            transform,
          )
        : null;
      const pointInstructions = this.hasSymbol_
        ? generatePointRenderInstructions(
            geometryBatch.pointBatch,
            new Float32Array(0),
            this.customAttributes_,
            transform,
          )
        : null;

      return {
        polygonInstructions,
        lineStringInstructions,
        pointInstructions,
      };
    }

    /**
     * @param {Float32Array|null} renderInstructions Render instructions
     * @param {import("../../geom/Geometry.js").Type} geometryType Geometry type
     * @param {import("../../transform.js").Transform} transform Transform to apply to coordinates
     * @return {Promise<Array<WebGLArrayBuffer>>|null} Indices buffer and vertices buffer; null if nothing to render
     * @private
     */
    generateBuffersForType_(renderInstructions, geometryType, transform) {
      if (renderInstructions === null) {
        return null;
      }

      const messageId = workerMessageCounter++;
      let messageType;
      switch (geometryType) {
        case 'Polygon':
          messageType = WebGLWorkerMessageType.GENERATE_POLYGON_BUFFERS;
          break;
        case 'LineString':
          messageType = WebGLWorkerMessageType.GENERATE_LINE_STRING_BUFFERS;
          break;
        case 'Point':
          messageType = WebGLWorkerMessageType.GENERATE_POINT_BUFFERS;
          break;
        // pass
      }

      /** @type {import('./constants.js').WebGLWorkerGenerateBuffersMessage} */
      const message = {
        id: messageId,
        type: messageType,
        renderInstructions: renderInstructions.buffer,
        renderInstructionsTransform: transform,
        customAttributesSize: getCustomAttributesSize(this.customAttributes_),
      };
      const WEBGL_WORKER = getWebGLWorker();
      WEBGL_WORKER.postMessage(message, [renderInstructions.buffer]);

      // leave ownership of render instructions
      renderInstructions = null;

      return new Promise((resolve) => {
        /**
         * @param {*} event Event.
         */
        const handleMessage = (event) => {
          const received = event.data;

          // this is not the response to our request: skip
          if (received.id !== messageId) {
            return;
          }

          // we've received our response: stop listening
          WEBGL_WORKER.removeEventListener('message', handleMessage);

          // the helper has disposed in the meantime; the promise will not be resolved
          if (!this.helper_.getGL()) {
            return;
          }

          // copy & flush received buffers to GPU
          const verticesBuffer = new WebGLArrayBuffer(
            ARRAY_BUFFER,
            DYNAMIC_DRAW,
          ).fromArrayBuffer(received.vertexBuffer);
          const indicesBuffer = new WebGLArrayBuffer(
            ELEMENT_ARRAY_BUFFER,
            DYNAMIC_DRAW,
          ).fromArrayBuffer(received.indexBuffer);
          this.helper_.flushBufferData(verticesBuffer);
          this.helper_.flushBufferData(indicesBuffer);

          resolve([indicesBuffer, verticesBuffer]);
        };

        WEBGL_WORKER.addEventListener('message', handleMessage);
      });
    }

    /**
     * Render the geometries in the given buffers.
     * @param {WebGLBuffers} buffers WebGL Buffers to draw
     * @param {import("../../Map.js").FrameState} frameState Frame state
     * @param {function(): void} preRenderCallback This callback will be called right before drawing, and can be used to set uniforms
     */
    render(buffers, frameState, preRenderCallback) {
      this.hasFill_ &&
        this.renderInternal_(
          buffers.polygonBuffers[0],
          buffers.polygonBuffers[1],
          this.fillProgram_,
          this.polygonAttributesDesc_,
          frameState,
          preRenderCallback,
        );
      this.hasStroke_ &&
        this.renderInternal_(
          buffers.lineStringBuffers[0],
          buffers.lineStringBuffers[1],
          this.strokeProgram_,
          this.lineStringAttributesDesc_,
          frameState,
          preRenderCallback,
        );
      this.hasSymbol_ &&
        this.renderInternal_(
          buffers.pointBuffers[0],
          buffers.pointBuffers[1],
          this.symbolProgram_,
          this.pointAttributesDesc_,
          frameState,
          preRenderCallback,
        );
    }

    /**
     * @param {WebGLArrayBuffer} indicesBuffer Indices buffer
     * @param {WebGLArrayBuffer} verticesBuffer Vertices buffer
     * @param {WebGLProgram} program Program
     * @param {Array<import('../../webgl/Helper.js').AttributeDescription>} attributes Attribute descriptions
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {function(): void} preRenderCallback This callback will be called right before drawing, and can be used to set uniforms
     * @private
     */
    renderInternal_(
      indicesBuffer,
      verticesBuffer,
      program,
      attributes,
      frameState,
      preRenderCallback,
    ) {
      const renderCount = indicesBuffer.getSize();
      if (renderCount === 0) {
        return;
      }
      this.helper_.useProgram(program, frameState);
      this.helper_.bindBuffer(verticesBuffer);
      this.helper_.bindBuffer(indicesBuffer);
      this.helper_.enableAttributes(attributes);
      preRenderCallback();
      this.helper_.drawElements(0, renderCount);
    }

    /**
     * @param {import('../../webgl/Helper.js').default} helper Helper
     * @param {WebGLBuffers} buffers WebGL Buffers to reload if any
     */
    setHelper(helper, buffers = null) {
      this.helper_ = helper;

      if (this.hasFill_) {
        this.fillProgram_ = this.helper_.getProgram(
          this.fillFragmentShader_,
          this.fillVertexShader_,
        );
      }
      if (this.hasStroke_) {
        this.strokeProgram_ = this.helper_.getProgram(
          this.strokeFragmentShader_,
          this.strokeVertexShader_,
        );
      }
      if (this.hasSymbol_) {
        this.symbolProgram_ = this.helper_.getProgram(
          this.symbolFragmentShader_,
          this.symbolVertexShader_,
        );
      }
      this.helper_.addUniforms(this.uniforms_);

      if (buffers) {
        if (buffers.polygonBuffers) {
          this.helper_.flushBufferData(buffers.polygonBuffers[0]);
          this.helper_.flushBufferData(buffers.polygonBuffers[1]);
        }
        if (buffers.lineStringBuffers) {
          this.helper_.flushBufferData(buffers.lineStringBuffers[0]);
          this.helper_.flushBufferData(buffers.lineStringBuffers[1]);
        }
        if (buffers.pointBuffers) {
          this.helper_.flushBufferData(buffers.pointBuffers[0]);
          this.helper_.flushBufferData(buffers.pointBuffers[1]);
        }
      }
    }
  }

  /**
   * A wrapper class to simplify rendering to a texture instead of the final canvas
   * @module ol/webgl/RenderTarget
   */

  // for pixel color reading
  const tmpArray4 = new Uint8Array(4);

  /**
   * @classdesc
   * This class is a wrapper around the association of both a `WebGLTexture` and a `WebGLFramebuffer` instances,
   * simplifying initialization and binding for rendering.
   */
  class WebGLRenderTarget {
    /**
     * @param {import("./Helper.js").default} helper WebGL helper; mandatory.
     * @param {Array<number>} [size] Expected size of the render target texture; note: this can be changed later on.
     */
    constructor(helper, size) {
      /**
       * @private
       * @type {import("./Helper.js").default}
       */
      this.helper_ = helper;
      const gl = helper.getGL();

      /**
       * @private
       * @type {WebGLTexture}
       */
      this.texture_ = gl.createTexture();

      /**
       * @private
       * @type {WebGLFramebuffer}
       */
      this.framebuffer_ = gl.createFramebuffer();

      /**
       * @private
       * @type {WebGLRenderbuffer}
       */
      this.depthbuffer_ = gl.createRenderbuffer();

      /**
       * @type {Array<number>}
       * @private
       */
      this.size_ = size || [1, 1];

      /**
       * @type {Uint8Array}
       * @private
       */
      this.data_ = new Uint8Array(0);

      /**
       * @type {boolean}
       * @private
       */
      this.dataCacheDirty_ = true;

      this.updateSize_();
    }

    /**
     * Changes the size of the render target texture. Note: will do nothing if the size
     * is already the same.
     * @param {Array<number>} size Expected size of the render target texture
     */
    setSize(size) {
      if (equals$2(size, this.size_)) {
        return;
      }
      this.size_[0] = size[0];
      this.size_[1] = size[1];
      this.updateSize_();
    }

    /**
     * Returns the size of the render target texture
     * @return {Array<number>} Size of the render target texture
     */
    getSize() {
      return this.size_;
    }

    /**
     * This will cause following calls to `#readAll` or `#readPixel` to download the content of the
     * render target into memory, which is an expensive operation.
     * This content will be kept in cache but should be cleared after each new render.
     */
    clearCachedData() {
      this.dataCacheDirty_ = true;
    }

    /**
     * Returns the full content of the frame buffer as a series of r, g, b, a components
     * in the 0-255 range (unsigned byte).
     * @return {Uint8Array} Integer array of color values
     */
    readAll() {
      if (this.dataCacheDirty_) {
        const size = this.size_;
        const gl = this.helper_.getGL();

        gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);
        gl.readPixels(
          0,
          0,
          size[0],
          size[1],
          gl.RGBA,
          gl.UNSIGNED_BYTE,
          this.data_,
        );
        this.dataCacheDirty_ = false;
      }
      return this.data_;
    }

    /**
     * Reads one pixel of the frame buffer as an array of r, g, b, a components
     * in the 0-255 range (unsigned byte).
     * If x and/or y are outside of existing data, an array filled with 0 is returned.
     * @param {number} x Pixel coordinate
     * @param {number} y Pixel coordinate
     * @return {Uint8Array} Integer array with one color value (4 components)
     */
    readPixel(x, y) {
      if (x < 0 || y < 0 || x > this.size_[0] || y >= this.size_[1]) {
        tmpArray4[0] = 0;
        tmpArray4[1] = 0;
        tmpArray4[2] = 0;
        tmpArray4[3] = 0;
        return tmpArray4;
      }

      this.readAll();
      const index =
        Math.floor(x) + (this.size_[1] - Math.floor(y) - 1) * this.size_[0];
      tmpArray4[0] = this.data_[index * 4];
      tmpArray4[1] = this.data_[index * 4 + 1];
      tmpArray4[2] = this.data_[index * 4 + 2];
      tmpArray4[3] = this.data_[index * 4 + 3];
      return tmpArray4;
    }

    /**
     * @return {WebGLTexture} Texture to render to
     */
    getTexture() {
      return this.texture_;
    }

    /**
     * @return {WebGLFramebuffer} Frame buffer of the render target
     */
    getFramebuffer() {
      return this.framebuffer_;
    }

    /**
     * @return {WebGLRenderbuffer} Depth buffer of the render target
     */
    getDepthbuffer() {
      return this.depthbuffer_;
    }

    /**
     * @private
     */
    updateSize_() {
      const size = this.size_;
      const gl = this.helper_.getGL();

      this.texture_ = this.helper_.createTexture(size, null, this.texture_);

      gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);
      gl.viewport(0, 0, size[0], size[1]);
      gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.COLOR_ATTACHMENT0,
        gl.TEXTURE_2D,
        this.texture_,
        0,
      );

      gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthbuffer_);
      gl.renderbufferStorage(
        gl.RENDERBUFFER,
        gl.DEPTH_COMPONENT16,
        size[0],
        size[1],
      );
      gl.framebufferRenderbuffer(
        gl.FRAMEBUFFER,
        gl.DEPTH_ATTACHMENT,
        gl.RENDERBUFFER,
        this.depthbuffer_,
      );

      this.data_ = new Uint8Array(size[0] * size[1] * 4);
    }
  }

  /**
   * @module ol/render/webgl/MixedGeometryBatch
   */

  /**
   * @typedef {import("../../Feature.js").default} Feature
   */
  /**
   * @typedef {import("../../geom/Geometry.js").Type} GeometryType
   */

  /**
   * @typedef {Object} GeometryBatchItem Object that holds a reference to a feature as well as the raw coordinates of its various geometries
   * @property {Feature|RenderFeature} feature Feature
   * @property {Array<Array<number>>} flatCoordss Array of flat coordinates arrays, one for each geometry related to the feature
   * @property {number} [verticesCount] Only defined for linestring and polygon batches
   * @property {number} [ringsCount] Only defined for polygon batches
   * @property {Array<Array<number>>} [ringsVerticesCounts] Array of vertices counts in each ring for each geometry; only defined for polygons batches
   * @property {number} [ref] The reference in the global batch (used for hit detection)
   */

  /**
   * @typedef {PointGeometryBatch|LineStringGeometryBatch|PolygonGeometryBatch} GeometryBatch
   */

  /**
   * @typedef {Object} PolygonGeometryBatch A geometry batch specific to polygons
   * @property {Object<string, GeometryBatchItem>} entries Dictionary of all entries in the batch with associated computed values.
   * One entry corresponds to one feature. Key is feature uid.
   * @property {number} geometriesCount Amount of geometries in the batch.
   * @property {number} verticesCount Amount of vertices from geometries in the batch.
   * @property {number} ringsCount How many outer and inner rings in this batch.
   */

  /**
   * @typedef {Object} LineStringGeometryBatch A geometry batch specific to lines
   * @property {Object<string, GeometryBatchItem>} entries Dictionary of all entries in the batch with associated computed values.
   * One entry corresponds to one feature. Key is feature uid.
   * @property {number} geometriesCount Amount of geometries in the batch.
   * @property {number} verticesCount Amount of vertices from geometries in the batch.
   */

  /**
   * @typedef {Object} PointGeometryBatch A geometry batch specific to points
   * @property {Object<string, GeometryBatchItem>} entries Dictionary of all entries in the batch with associated computed values.
   * One entry corresponds to one feature. Key is feature uid.
   * @property {number} geometriesCount Amount of geometries in the batch.
   */

  /**
   * @classdesc This class is used to group several geometries of various types together for faster rendering.
   * Three inner batches are maintained for polygons, lines and points. Each time a feature is added, changed or removed
   * from the batch, these inner batches are modified accordingly in order to keep them up-to-date.
   *
   * A feature can be present in several inner batches, for example a polygon geometry will be present in the polygon batch
   * and its linear rings will be present in the line batch. Multi geometries are also broken down into individual geometries
   * and added to the corresponding batches in a recursive manner.
   *
   * Corresponding {@link module:ol/render/webgl/BatchRenderer} instances are then used to generate the render instructions
   * and WebGL buffers (vertices and indices) for each inner batches; render instructions are stored on the inner batches,
   * alongside the transform used to convert world coords to screen coords at the time these instructions were generated.
   * The resulting WebGL buffers are stored on the batches as well.
   *
   * An important aspect of geometry batches is that there is no guarantee that render instructions and WebGL buffers
   * are synchronized, i.e. render instructions can describe a new state while WebGL buffers might not have been written yet.
   * This is why two world-to-screen transforms are stored on each batch: one for the render instructions and one for
   * the WebGL buffers.
   */
  class MixedGeometryBatch {
    constructor() {
      /**
       * @private
       */
      this.globalCounter_ = 0;

      /**
       * Refs are used as keys for hit detection.
       * @type {Map<number, Feature|RenderFeature>}
       * @private
       */
      this.refToFeature_ = new Map();

      /**
       * Features are split in "entries", which are individual geometries. We use the following map to share a single ref for all those entries.
       * @type {Map<string, number>}
       * @private
       */
      this.uidToRef_ = new Map();

      /**
       * The precision in WebGL shaders is limited.
       * To keep the refs as small as possible we maintain an array of freed up references.
       * @type {Array<number>}
       * @private
       */
      this.freeGlobalRef_ = [];

      /**
       * @type {PolygonGeometryBatch}
       */
      this.polygonBatch = {
        entries: {},
        geometriesCount: 0,
        verticesCount: 0,
        ringsCount: 0,
      };

      /**
       * @type {PointGeometryBatch}
       */
      this.pointBatch = {
        entries: {},
        geometriesCount: 0,
      };

      /**
       * @type {LineStringGeometryBatch}
       */
      this.lineStringBatch = {
        entries: {},
        geometriesCount: 0,
        verticesCount: 0,
      };
    }

    /**
     * @param {Array<Feature|RenderFeature>} features Array of features to add to the batch
     * @param {import("../../proj.js").TransformFunction} [projectionTransform] Projection transform.
     */
    addFeatures(features, projectionTransform) {
      for (let i = 0; i < features.length; i++) {
        this.addFeature(features[i], projectionTransform);
      }
    }

    /**
     * @param {Feature|RenderFeature} feature Feature to add to the batch
     * @param {import("../../proj.js").TransformFunction} [projectionTransform] Projection transform.
     */
    addFeature(feature, projectionTransform) {
      let geometry = feature.getGeometry();
      if (!geometry) {
        return;
      }
      if (projectionTransform) {
        geometry = geometry.clone();
        geometry.applyTransform(projectionTransform);
      }
      this.addGeometry_(geometry, feature);
    }

    /**
     * @param {Feature|RenderFeature} feature Feature
     * @return {GeometryBatchItem|void} the cleared entry
     * @private
     */
    clearFeatureEntryInPointBatch_(feature) {
      const featureUid = getUid(feature);
      const entry = this.pointBatch.entries[featureUid];
      if (!entry) {
        return;
      }
      this.pointBatch.geometriesCount -= entry.flatCoordss.length;
      delete this.pointBatch.entries[featureUid];
      return entry;
    }

    /**
     * @param {Feature|RenderFeature} feature Feature
     * @return {GeometryBatchItem|void} the cleared entry
     * @private
     */
    clearFeatureEntryInLineStringBatch_(feature) {
      const featureUid = getUid(feature);
      const entry = this.lineStringBatch.entries[featureUid];
      if (!entry) {
        return;
      }
      this.lineStringBatch.verticesCount -= entry.verticesCount;
      this.lineStringBatch.geometriesCount -= entry.flatCoordss.length;
      delete this.lineStringBatch.entries[featureUid];
      return entry;
    }

    /**
     * @param {Feature|RenderFeature} feature Feature
     * @return {GeometryBatchItem|void} the cleared entry
     * @private
     */
    clearFeatureEntryInPolygonBatch_(feature) {
      const featureUid = getUid(feature);
      const entry = this.polygonBatch.entries[featureUid];
      if (!entry) {
        return;
      }
      this.polygonBatch.verticesCount -= entry.verticesCount;
      this.polygonBatch.ringsCount -= entry.ringsCount;
      this.polygonBatch.geometriesCount -= entry.flatCoordss.length;
      delete this.polygonBatch.entries[featureUid];
      return entry;
    }

    /**
     * @param {import("../../geom.js").Geometry|RenderFeature} geometry Geometry
     * @param {Feature|RenderFeature} feature Feature
     * @private
     */
    addGeometry_(geometry, feature) {
      const type = geometry.getType();
      switch (type) {
        case 'GeometryCollection': {
          const geometries =
            /** @type {import("../../geom.js").GeometryCollection} */ (
              geometry
            ).getGeometriesArray();
          for (const geometry of geometries) {
            this.addGeometry_(geometry, feature);
          }
          break;
        }
        case 'MultiPolygon': {
          const multiPolygonGeom =
            /** @type {import("../../geom.js").MultiPolygon} */ (geometry);
          this.addCoordinates_(
            type,
            multiPolygonGeom.getFlatCoordinates(),
            multiPolygonGeom.getEndss(),
            feature,
            getUid(feature),
            multiPolygonGeom.getStride(),
          );
          break;
        }
        case 'MultiLineString': {
          const multiLineGeom =
            /** @type {import("../../geom.js").MultiLineString|RenderFeature} */ (
              geometry
            );
          this.addCoordinates_(
            type,
            multiLineGeom.getFlatCoordinates(),
            multiLineGeom.getEnds(),
            feature,
            getUid(feature),
            multiLineGeom.getStride(),
          );
          break;
        }
        case 'MultiPoint': {
          const multiPointGeom =
            /** @type {import("../../geom.js").MultiPoint|RenderFeature} */ (
              geometry
            );
          this.addCoordinates_(
            type,
            multiPointGeom.getFlatCoordinates(),
            null,
            feature,
            getUid(feature),
            multiPointGeom.getStride(),
          );
          break;
        }
        case 'Polygon': {
          const polygonGeom =
            /** @type {import("../../geom.js").Polygon|RenderFeature} */ (
              geometry
            );
          this.addCoordinates_(
            type,
            polygonGeom.getFlatCoordinates(),
            polygonGeom.getEnds(),
            feature,
            getUid(feature),
            polygonGeom.getStride(),
          );
          break;
        }
        case 'Point': {
          const pointGeom = /** @type {import("../../geom.js").Point} */ (
            geometry
          );
          this.addCoordinates_(
            type,
            pointGeom.getFlatCoordinates(),
            null,
            feature,
            getUid(feature),
            pointGeom.getStride(),
          );
          break;
        }
        case 'LineString':
        case 'LinearRing': {
          const lineGeom = /** @type {import("../../geom.js").LineString} */ (
            geometry
          );

          const stride = lineGeom.getStride();

          this.addCoordinates_(
            type,
            lineGeom.getFlatCoordinates(),
            null,
            feature,
            getUid(feature),
            stride,
            lineGeom.getLayout?.(),
          );
          break;
        }
        // pass
      }
    }

    /**
     * @param {GeometryType} type Geometry type
     * @param {Array<number>} flatCoords Flat coordinates
     * @param {Array<number> | Array<Array<number>> | null} ends Coordinate ends
     * @param {Feature|RenderFeature} feature Feature
     * @param {string} featureUid Feature uid
     * @param {number} stride Stride
     * @param {import('../../geom/Geometry.js').GeometryLayout} [layout] Layout
     * @private
     */
    addCoordinates_(type, flatCoords, ends, feature, featureUid, stride, layout) {
      /** @type {number} */
      let verticesCount;
      switch (type) {
        case 'MultiPolygon': {
          const multiPolygonEndss = /** @type {Array<Array<number>>} */ (ends);
          for (let i = 0, ii = multiPolygonEndss.length; i < ii; i++) {
            let polygonEnds = multiPolygonEndss[i];
            const prevPolygonEnds = i > 0 ? multiPolygonEndss[i - 1] : null;
            const startIndex = prevPolygonEnds
              ? prevPolygonEnds[prevPolygonEnds.length - 1]
              : 0;
            const endIndex = polygonEnds[polygonEnds.length - 1];
            polygonEnds =
              startIndex > 0
                ? polygonEnds.map((end) => end - startIndex)
                : polygonEnds;
            this.addCoordinates_(
              'Polygon',
              flatCoords.slice(startIndex, endIndex),
              polygonEnds,
              feature,
              featureUid,
              stride,
              layout,
            );
          }
          break;
        }
        case 'MultiLineString': {
          const multiLineEnds = /** @type {Array<number>} */ (ends);
          for (let i = 0, ii = multiLineEnds.length; i < ii; i++) {
            const startIndex = i > 0 ? multiLineEnds[i - 1] : 0;
            this.addCoordinates_(
              'LineString',
              flatCoords.slice(startIndex, multiLineEnds[i]),
              null,
              feature,
              featureUid,
              stride,
              layout,
            );
          }
          break;
        }
        case 'MultiPoint':
          for (let i = 0, ii = flatCoords.length; i < ii; i += stride) {
            this.addCoordinates_(
              'Point',
              flatCoords.slice(i, i + 2),
              null,
              feature,
              featureUid,
              null,
              null,
            );
          }
          break;
        case 'Polygon': {
          const polygonEnds = /** @type {Array<number>} */ (ends);
          if (feature instanceof RenderFeature) {
            const multiPolygonEnds = inflateEnds(flatCoords, polygonEnds);
            if (multiPolygonEnds.length > 1) {
              this.addCoordinates_(
                'MultiPolygon',
                flatCoords,
                multiPolygonEnds,
                feature,
                featureUid,
                stride,
                layout,
              );
              return;
            }
          }
          if (!this.polygonBatch.entries[featureUid]) {
            this.polygonBatch.entries[featureUid] = this.addRefToEntry_(
              featureUid,
              {
                feature: feature,
                flatCoordss: [],
                verticesCount: 0,
                ringsCount: 0,
                ringsVerticesCounts: [],
              },
            );
          }
          verticesCount = flatCoords.length / stride;
          const ringsCount = ends.length;
          const ringsVerticesCount = ends.map((end, ind, arr) =>
            ind > 0 ? (end - arr[ind - 1]) / stride : end / stride,
          );
          this.polygonBatch.verticesCount += verticesCount;
          this.polygonBatch.ringsCount += ringsCount;
          this.polygonBatch.geometriesCount++;
          this.polygonBatch.entries[featureUid].flatCoordss.push(
            getFlatCoordinatesXY(flatCoords, stride),
          );
          this.polygonBatch.entries[featureUid].ringsVerticesCounts.push(
            ringsVerticesCount,
          );
          this.polygonBatch.entries[featureUid].verticesCount += verticesCount;
          this.polygonBatch.entries[featureUid].ringsCount += ringsCount;
          for (let i = 0, ii = polygonEnds.length; i < ii; i++) {
            const startIndex = i > 0 ? polygonEnds[i - 1] : 0;
            this.addCoordinates_(
              'LinearRing',
              flatCoords.slice(startIndex, polygonEnds[i]),
              null,
              feature,
              featureUid,
              stride,
              layout,
            );
          }
          break;
        }
        case 'Point':
          if (!this.pointBatch.entries[featureUid]) {
            this.pointBatch.entries[featureUid] = this.addRefToEntry_(
              featureUid,
              {
                feature: feature,
                flatCoordss: [],
              },
            );
          }
          this.pointBatch.geometriesCount++;
          this.pointBatch.entries[featureUid].flatCoordss.push(flatCoords);
          break;
        case 'LineString':
        case 'LinearRing':
          if (!this.lineStringBatch.entries[featureUid]) {
            this.lineStringBatch.entries[featureUid] = this.addRefToEntry_(
              featureUid,
              {
                feature: feature,
                flatCoordss: [],
                verticesCount: 0,
              },
            );
          }
          verticesCount = flatCoords.length / stride;
          this.lineStringBatch.verticesCount += verticesCount;
          this.lineStringBatch.geometriesCount++;
          this.lineStringBatch.entries[featureUid].flatCoordss.push(
            getFlatCoordinatesXYM(flatCoords, stride, layout),
          );
          this.lineStringBatch.entries[featureUid].verticesCount += verticesCount;
          break;
        // pass
      }
    }

    /**
     * @param {string} featureUid Feature uid
     * @param {GeometryBatchItem} entry The entry to add
     * @return {GeometryBatchItem} the added entry
     * @private
     */
    addRefToEntry_(featureUid, entry) {
      const currentRef = this.uidToRef_.get(featureUid);

      // the ref starts at 1 to distinguish from white color (no feature)
      const ref =
        currentRef || this.freeGlobalRef_.pop() || ++this.globalCounter_;
      entry.ref = ref;
      if (!currentRef) {
        this.refToFeature_.set(ref, entry.feature);
        this.uidToRef_.set(featureUid, ref);
      }
      return entry;
    }

    /**
     * Return a ref to the pool of available refs.
     * @param {number} ref the ref to return
     * @param {string} featureUid the feature uid
     * @private
     */
    removeRef_(ref, featureUid) {
      if (!ref) {
        throw new Error('This feature has no ref: ' + featureUid);
      }
      this.refToFeature_.delete(ref);
      this.uidToRef_.delete(featureUid);
      this.freeGlobalRef_.push(ref);
    }

    /**
     * @param {Feature|RenderFeature} feature Feature
     * @param {import("../../proj.js").TransformFunction} [projectionTransform] Projection transform.
     */
    changeFeature(feature, projectionTransform) {
      // the feature is not present in the batch; do not add it to avoid unexpected behaviors
      if (!this.uidToRef_.get(getUid(feature))) {
        return;
      }
      this.removeFeature(feature);
      let geometry = feature.getGeometry();
      if (!geometry) {
        return;
      }
      if (projectionTransform) {
        geometry = geometry.clone();
        geometry.applyTransform(projectionTransform);
      }
      this.addGeometry_(geometry, feature);
    }

    /**
     * @param {Feature|RenderFeature} feature Feature
     */
    removeFeature(feature) {
      let entry = this.clearFeatureEntryInPointBatch_(feature);
      entry = this.clearFeatureEntryInPolygonBatch_(feature) || entry;
      entry = this.clearFeatureEntryInLineStringBatch_(feature) || entry;
      if (entry) {
        this.removeRef_(entry.ref, getUid(entry.feature));
      }
    }

    clear() {
      this.polygonBatch.entries = {};
      this.polygonBatch.geometriesCount = 0;
      this.polygonBatch.verticesCount = 0;
      this.polygonBatch.ringsCount = 0;
      this.lineStringBatch.entries = {};
      this.lineStringBatch.geometriesCount = 0;
      this.lineStringBatch.verticesCount = 0;
      this.pointBatch.entries = {};
      this.pointBatch.geometriesCount = 0;
      this.globalCounter_ = 0;
      this.freeGlobalRef_ = [];
      this.refToFeature_.clear();
      this.uidToRef_.clear();
    }

    /**
     * Resolve the feature associated to a ref.
     * @param {number} ref Hit detected ref
     * @return {Feature|RenderFeature} feature
     */
    getFeatureFromRef(ref) {
      return this.refToFeature_.get(ref);
    }

    isEmpty() {
      return this.globalCounter_ === 0;
    }

    /**
     * Will return a new instance of this class that only contains the features
     * for which the provided callback returned true
     * @param {function((Feature|RenderFeature)): boolean} featureFilter Feature filter callback
     * @return {MixedGeometryBatch} Filtered geometry batch
     */
    filter(featureFilter) {
      const filtered = new MixedGeometryBatch();
      filtered.globalCounter_ = this.globalCounter_;
      filtered.uidToRef_ = this.uidToRef_;
      filtered.refToFeature_ = this.refToFeature_;
      let empty = true;
      for (const feature of this.refToFeature_.values()) {
        if (featureFilter(feature)) {
          filtered.addFeature(feature);
          empty = false;
        }
      }
      // no feature was added at all; simply return an empty batch for consistency downstream
      if (empty) {
        return new MixedGeometryBatch();
      }
      return filtered;
    }
  }

  /**
   * @param {Array<number>} flatCoords Flat coords
   * @param {number} stride Stride
   * @return {Array<number>} Flat coords with only XY components
   */
  function getFlatCoordinatesXY(flatCoords, stride) {
    if (stride === 2) {
      return flatCoords;
    }
    return flatCoords.filter((v, i) => i % stride < 2);
  }

  /**
   * @param {Array<number>} flatCoords Flat coords
   * @param {number} stride Stride
   * @param {string} layout Layout
   * @return {Array<number>} Flat coords with only XY components
   */
  function getFlatCoordinatesXYM(flatCoords, stride, layout) {
    if (stride === 3 && layout === 'XYM') {
      return flatCoords;
    }
    // this is XYZM layout
    if (stride === 4) {
      return flatCoords.filter((v, i) => i % stride !== 2);
    }
    // this is XYZ layout
    if (stride === 3) {
      return flatCoords.map((v, i) => (i % stride !== 2 ? v : 0));
    }
    // this is XY layout
    return new Array(flatCoords.length * 1.5)
      .fill(0)
      .map((v, i) => (i % 3 === 2 ? 0 : flatCoords[Math.round(i / 1.5)]));
  }

  /**
   * @module ol/webgl/TileGeometry
   */


  /**
   * @typedef {import("../VectorRenderTile").default} TileType
   */

  /**
   * @extends {BaseTileRepresentation<TileType>}
   */
  class TileGeometry extends BaseTileRepresentation {
    /**
     * @param {import("./BaseTileRepresentation.js").TileRepresentationOptions<TileType>} options The tile texture options.
     * @param {Array<import("../render/webgl/VectorStyleRenderer.js").default>} styleRenderers Array of vector style renderers
     */
    constructor(options, styleRenderers) {
      super(options);

      /**
       * @private
       */
      this.batch_ = new MixedGeometryBatch();

      /**
       * @private
       */
      this.styleRenderers_ = styleRenderers;

      /**
       * @type {Array<import("../render/webgl/VectorStyleRenderer.js").WebGLBuffers>}
       */
      this.buffers = [];

      /**
       * Each geometry tile also has a mask which consisted of a quad (two triangles); this mask is intended to
       * be rendered to an offscreen buffer, and be used to correctly mask tiles according to their zoom level
       * during rendering
       */
      this.maskVertices = new WebGLArrayBuffer(ARRAY_BUFFER, STATIC_DRAW);

      this.setTile(options.tile);
    }

    /**
     * @private
     */
    generateMaskBuffer_() {
      const extent = this.tile.getSourceTiles()[0].extent;
      this.maskVertices.fromArray([
        extent[0],
        extent[1],
        extent[2],
        extent[1],
        extent[2],
        extent[3],
        extent[0],
        extent[3],
      ]);
      this.helper.flushBufferData(this.maskVertices);
    }

    /**
     * @override
     */
    uploadTile() {
      this.generateMaskBuffer_();

      this.batch_.clear();
      const sourceTiles = this.tile.getSourceTiles();
      const features = sourceTiles.reduce(
        (accumulator, sourceTile) => accumulator.concat(sourceTile.getFeatures()),
        [],
      );
      this.batch_.addFeatures(features);

      const tileOriginX = sourceTiles[0].extent[0];
      const tileOriginY = sourceTiles[0].extent[1];
      const transform = translate$2(
        create$3(),
        -tileOriginX,
        -tileOriginY,
      );

      const generatePromises = this.styleRenderers_.map((renderer, i) =>
        renderer.generateBuffers(this.batch_, transform).then((buffers) => {
          this.buffers[i] = buffers;
        }),
      );
      Promise.all(generatePromises).then(() => {
        this.setReady();
      });
    }

    /**
     * @override
     */
    disposeInternal() {
      this.buffers.forEach((buffers) => {
        this.disposeBuffers(buffers);
      });
      super.disposeInternal();
    }

    /**
     * Will release a set of Webgl buffers
     * @param {import('../render/webgl/VectorStyleRenderer.js').WebGLBuffers|null} buffers Buffers
     */
    disposeBuffers(buffers) {
      if (!buffers) {
        return;
      }
      /**
       * @param {Array<WebGLArrayBuffer>} typeBuffers Buffers
       */
      const disposeBuffersOfType = (typeBuffers) => {
        for (const buffer of typeBuffers) {
          if (buffer) {
            this.helper.deleteBuffer(buffer);
          }
        }
      };
      if (buffers.pointBuffers) {
        disposeBuffersOfType(buffers.pointBuffers);
      }
      if (buffers.lineStringBuffers) {
        disposeBuffersOfType(buffers.lineStringBuffers);
      }
      if (buffers.polygonBuffers) {
        disposeBuffersOfType(buffers.polygonBuffers);
      }
    }
  }

  /**
   * @module ol/renderer/webgl/VectorTileLayer
   */

  const Uniforms$1 = {
    ...Uniforms$3,
    TILE_MASK_TEXTURE: 'u_depthMask',
    TILE_ZOOM_LEVEL: 'u_tileZoomLevel',
  };

  const Attributes = {
    POSITION: 'a_position',
  };

  /**
   * @typedef {import('../../render/webgl/VectorStyleRenderer.js').AsShaders} StyleAsShaders
   */
  /**
   * @typedef {import('../../render/webgl/VectorStyleRenderer.js').AsRule} StyleAsRule
   */

  /**
   * @typedef {Object} Options
   * @property {import('../../style/flat.js').FlatStyleLike | Array<StyleAsShaders> | StyleAsShaders} style Flat vector style; also accepts shaders
   * @property {import('../../style/flat.js').StyleVariables} [variables] Style variables. Each variable must hold a literal value (not
   * an expression). These variables can be used as {@link import("../../expr/expression.js").ExpressionValue expressions} in the styles properties
   * using the `['var', 'varName']` operator.
   * @property {boolean} [disableHitDetection=false] Setting this to true will provide a slight performance boost, but will
   * prevent all hit detection on the layer.
   * @property {number} [cacheSize=512] The vector tile cache size.
   */

  /**
   * @typedef {import("../../layer/BaseTile.js").default} LayerType
   */

  /**
   * @classdesc
   * WebGL renderer for vector tile layers. Experimental.
   * @extends {WebGLBaseTileLayerRenderer<LayerType>}
   */
  class WebGLVectorTileLayerRenderer extends WebGLBaseTileLayerRenderer {
    /**
     * @param {LayerType} tileLayer Tile layer.
     * @param {Options} options Options.
     */
    constructor(tileLayer, options) {
      super(tileLayer, {
        cacheSize: options.cacheSize,
        uniforms: {
          [Uniforms$1.PATTERN_ORIGIN]: [0, 0],
          [Uniforms$1.TILE_MASK_TEXTURE]: () => this.tileMaskTarget_.getTexture(),
        },
      });

      /**
       * @type {boolean}
       * @private
       */
      this.hitDetectionEnabled_ = !options.disableHitDetection;

      /**
       * @type {Array<StyleAsRule | StyleAsShaders>}
       * @private
       */
      this.styles_ = [];

      /**
       * @type {import('../../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = options.variables || {};

      /**
       * @type {Array<VectorStyleRenderer>}
       * @private
       */
      this.styleRenderers_ = [];

      /**
       * This transform is updated on every frame and is the composition of:
       * - invert of the world->screen transform that was used when rebuilding buffers (see `this.renderTransform_`)
       * - current world->screen transform
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.currentFrameStateTransform_ = create$3();

      /**
       * @private
       */
      this.tmpTransform_ = create$3();
      /**
       * @private
       */
      this.tmpMat4_ = create$2();

      /**
       * @type {WebGLRenderTarget}
       * @private
       */
      this.tileMaskTarget_ = null;

      /**
       * @private
       */
      this.tileMaskIndices_ = new WebGLArrayBuffer(
        ELEMENT_ARRAY_BUFFER,
        STATIC_DRAW,
      );
      this.tileMaskIndices_.fromArray([0, 1, 3, 1, 2, 3]);

      /**
       * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
       * @private
       */
      this.tileMaskAttributes_ = [
        {
          name: Attributes.POSITION,
          size: 2,
          type: AttributeType.FLOAT,
        },
      ];

      /**
       * @type {WebGLProgram}
       * @private
       */
      this.tileMaskProgram_;

      this.applyOptions_(options);
    }

    /**
     * @param {Options} options Options.
     * @override
     */
    reset(options) {
      super.reset(options);

      this.applyOptions_(options);
      if (this.helper) {
        this.createRenderers_();
        this.initTileMask_();
      }
    }

    /**
     * @param {Options} options Options.
     * @private
     */
    applyOptions_(options) {
      this.styles_ = breakDownFlatStyle(options.style);
    }

    /**
     * @private
     */
    createRenderers_() {
      function addBuilderParams(builder) {
        const exisitingDiscard = builder.getFragmentDiscardExpression();
        const discardFromMask = `texture2D(${Uniforms$1.TILE_MASK_TEXTURE}, gl_FragCoord.xy / u_pixelRatio / u_viewportSizePx).r * 50. > ${Uniforms$1.TILE_ZOOM_LEVEL} + 0.5`;
        builder.setFragmentDiscardExpression(
          exisitingDiscard !== 'false'
            ? `(${exisitingDiscard}) || (${discardFromMask})`
            : discardFromMask,
        );
        builder.addUniform(Uniforms$1.TILE_MASK_TEXTURE, 'sampler2D');
        builder.addUniform(Uniforms$1.TILE_ZOOM_LEVEL, 'float');
      }

      this.styleRenderers_ = this.styles_.map((style) => {
        const isShaders = 'builder' in style;
        /** @type {StyleAsShaders} */
        let shaders;
        if (!isShaders) {
          const parseResult = parseLiteralStyle(
            style.style,
            this.styleVariables_,
            style.filter,
          );
          addBuilderParams(parseResult.builder);
          shaders = {
            builder: parseResult.builder,
            attributes: parseResult.attributes,
            uniforms: parseResult.uniforms,
          };
        } else {
          addBuilderParams(style.builder);
          shaders = style;
        }
        return new VectorStyleRenderer(
          shaders,
          this.styleVariables_,
          this.helper,
          this.hitDetectionEnabled_,
          'filter' in style ? style.filter : null,
        );
      });
    }

    /**
     * @private
     */
    initTileMask_() {
      this.tileMaskTarget_ = new WebGLRenderTarget(this.helper);
      const builder = new ShaderBuilder()
        .setFillColorExpression(
          `vec4(${Uniforms$1.TILE_ZOOM_LEVEL} / 50., 0., 0., 1.)`,
        )
        .addUniform(Uniforms$1.TILE_ZOOM_LEVEL, 'float');
      this.tileMaskProgram_ = this.helper.getProgram(
        builder.getFillFragmentShader(),
        builder.getFillVertexShader(),
      );
      this.helper.flushBufferData(this.tileMaskIndices_);
    }

    /**
     * @override
     */
    afterHelperCreated() {
      this.createRenderers_();
      this.initTileMask_();
    }

    /**
     * @override
     */
    createTileRepresentation(options) {
      const tileRep = new TileGeometry(options, this.styleRenderers_);
      // redraw the layer when the tile is ready
      const listener = () => {
        if (tileRep.ready) {
          this.getLayer().changed();
          tileRep.removeEventListener(EventType.CHANGE, listener);
        }
      };
      tileRep.addEventListener(EventType.CHANGE, listener);
      return tileRep;
    }

    /**
     * @override
     */
    beforeTilesRender(frameState, tilesWithAlpha) {
      super.beforeTilesRender(frameState, true); // always consider that tiles need alpha blending
      this.helper.makeProjectionTransform(
        frameState,
        this.currentFrameStateTransform_,
      );
    }

    /**
     * @override
     */
    beforeTilesMaskRender(frameState) {
      this.helper.makeProjectionTransform(
        frameState,
        this.currentFrameStateTransform_,
      );
      const pixelRatio = frameState.pixelRatio;
      const size = frameState.size;
      this.tileMaskTarget_.setSize([size[0] * pixelRatio, size[1] * pixelRatio]);
      this.helper.prepareDrawToRenderTarget(
        frameState,
        this.tileMaskTarget_,
        true,
        true,
      );
      this.helper.useProgram(this.tileMaskProgram_, frameState);
      setFromArray(this.tmpTransform_, this.currentFrameStateTransform_);
      this.helper.setUniformMatrixValue(
        Uniforms$1.PROJECTION_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );
      makeInverse(this.tmpTransform_, this.currentFrameStateTransform_);
      this.helper.setUniformMatrixValue(
        Uniforms$1.SCREEN_TO_WORLD_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );
      return true;
    }

    /**
     * @override
     */
    renderTileMask(tileRepresentation, tileZ, extent, depth) {
      if (!tileRepresentation.ready) {
        return;
      }
      this.helper.setUniformFloatValue(Uniforms$1.DEPTH, depth);
      this.helper.setUniformFloatValue(Uniforms$1.TILE_ZOOM_LEVEL, tileZ);
      this.helper.setUniformFloatVec4(Uniforms$1.RENDER_EXTENT, extent);
      this.helper.setUniformFloatValue(Uniforms$1.GLOBAL_ALPHA, 1);
      this.helper.bindBuffer(
        /** @type {TileGeometry} */ (tileRepresentation).maskVertices,
      );
      this.helper.bindBuffer(this.tileMaskIndices_);
      this.helper.enableAttributes(this.tileMaskAttributes_);
      const renderCount = this.tileMaskIndices_.getSize();
      this.helper.drawElements(0, renderCount);
    }

    /**
     * @param {number} alpha Alpha value of the tile
     * @param {import("../../extent.js").Extent} renderExtent Which extent to restrict drawing to
     * @param {import("../../transform.js").Transform} batchInvertTransform Inverse of the transformation in which tile geometries are expressed
     * @param {number} tileZ Tile zoom level
     * @param {number} depth Depth of the tile
     * @private
     */
    applyUniforms_(alpha, renderExtent, batchInvertTransform, tileZ, depth) {
      // world to screen matrix
      setFromArray(this.tmpTransform_, this.currentFrameStateTransform_);
      multiply(this.tmpTransform_, batchInvertTransform);
      this.helper.setUniformMatrixValue(
        Uniforms$1.PROJECTION_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );

      // screen to world matrix
      makeInverse(this.tmpTransform_, this.currentFrameStateTransform_);
      this.helper.setUniformMatrixValue(
        Uniforms$1.SCREEN_TO_WORLD_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );

      this.helper.setUniformFloatValue(Uniforms$1.GLOBAL_ALPHA, alpha);
      this.helper.setUniformFloatValue(Uniforms$1.DEPTH, depth);
      this.helper.setUniformFloatValue(Uniforms$1.TILE_ZOOM_LEVEL, tileZ);
      this.helper.setUniformFloatVec4(Uniforms$1.RENDER_EXTENT, renderExtent);
    }

    /**
     * @override
     */
    renderTile(
      tileRepresentation,
      tileTransform,
      frameState,
      renderExtent,
      tileResolution,
      tileSize,
      tileOrigin,
      tileExtent,
      depth,
      gutter,
      alpha,
    ) {
      const gutterExtent = getIntersection(tileExtent, renderExtent, tileExtent);
      const tileZ = tileRepresentation.tile.getTileCoord()[0];
      for (let i = 0, ii = this.styleRenderers_.length; i < ii; i++) {
        const renderer = this.styleRenderers_[i];
        const buffers = tileRepresentation.buffers[i];
        if (!buffers) {
          continue;
        }
        renderer.render(buffers, frameState, () => {
          this.applyUniforms_(
            alpha,
            gutterExtent,
            buffers.invertVerticesTransform,
            tileZ,
            depth,
          );
        });
      }
    }

    /**
     * Render declutter items for this layer
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     */
    renderDeclutter(frameState) {}

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      super.disposeInternal();
    }
  }

  /**
   * @module ol/layer/TileProperty
   */

  /**
   * @enum {string}
   */
  var TileProperty = {
    PRELOAD: 'preload',
    USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError',
  };

  /**
   * @module ol/layer/BaseTile
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("./Base").BaseLayerObjectEventTypes|
   *     import("./Layer.js").LayerEventType|'change:preload'|'change:useInterimTilesOnError', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("../render/EventType").LayerRenderEventTypes, import("../render/Event").default, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("./Base").BaseLayerObjectEventTypes|
   *   import("./Layer.js").LayerEventType|'change:preload'|'change:useInterimTilesOnError'|import("../render/EventType").LayerRenderEventTypes, Return>} BaseTileLayerOnSignature
   */

  /**
   * @template {import("../source/Tile.js").default} TileSourceType
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
   * means no preloading.
   * @property {TileSourceType} [source] Source for this layer.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use {@link import("../Map.js").default#addLayer map.addLayer()}.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * @property {boolean} [useInterimTilesOnError=true] Deprecated.  Use interim tiles on error.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   * @property {number} [cacheSize=512] The internal tile cache size.  This needs to be large enough to render
   * two zoom levels worth of tiles.
   */

  /**
   * @classdesc
   * For layer sources that provide pre-rendered, tiled images in grids that are
   * organized by zoom levels for specific resolutions.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Tile.js").default} TileSourceType
   * @template {import("../renderer/Layer.js").default} RendererType
   * @extends {Layer<TileSourceType, RendererType>}
   * @api
   */
  class BaseTileLayer extends Layer {
    /**
     * @param {Options<TileSourceType>} [options] Tile layer options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign({}, options);

      const cacheSize = options.cacheSize;
      delete options.cacheSize;

      delete baseOptions.preload;
      delete baseOptions.useInterimTilesOnError;
      super(baseOptions);

      /***
       * @type {BaseTileLayerOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {BaseTileLayerOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {BaseTileLayerOnSignature<void>}
       */
      this.un;

      /**
       * @type {number|undefined}
       * @private
       */
      this.cacheSize_ = cacheSize;

      this.setPreload(options.preload !== undefined ? options.preload : 0);
      this.setUseInterimTilesOnError(
        options.useInterimTilesOnError !== undefined
          ? options.useInterimTilesOnError
          : true,
      );
    }

    /**
     * @return {number|undefined} The suggested cache size
     * @protected
     */
    getCacheSize() {
      return this.cacheSize_;
    }

    /**
     * Return the level as number to which we will preload tiles up to.
     * @return {number} The level to preload tiles up to.
     * @observable
     * @api
     */
    getPreload() {
      return /** @type {number} */ (this.get(TileProperty.PRELOAD));
    }

    /**
     * Set the level as number to which we will preload tiles up to.
     * @param {number} preload The level to preload tiles up to.
     * @observable
     * @api
     */
    setPreload(preload) {
      this.set(TileProperty.PRELOAD, preload);
    }

    /**
     * Deprecated.  Whether we use interim tiles on error.
     * @return {boolean} Use interim tiles on error.
     * @observable
     * @api
     */
    getUseInterimTilesOnError() {
      return /** @type {boolean} */ (
        this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)
      );
    }

    /**
     * Deprecated.  Set whether we use interim tiles on error.
     * @param {boolean} useInterimTilesOnError Use interim tiles on error.
     * @observable
     * @api
     */
    setUseInterimTilesOnError(useInterimTilesOnError) {
      this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);
    }

    /**
     * Get data for a pixel location.  The return type depends on the source data.  For image tiles,
     * a four element RGBA array will be returned.  For data tiles, the array length will match the
     * number of bands in the dataset.  For requests outside the layer extent, `null` will be returned.
     * Data for a image tiles can only be retrieved if the source's `crossOrigin` property is set.
     *
     * ```js
     * // display layer data on every pointer move
     * map.on('pointermove', (event) => {
     *   console.log(layer.getData(event.pixel));
     * });
     * ```
     * @param {import("../pixel").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.
     * @api
     * @override
     */
    getData(pixel) {
      return super.getData(pixel);
    }
  }

  /**
   * @module ol/layer/WebGLVectorTile
   */

  /***
   * @template T
   * @typedef {T extends import("../source/Vector.js").default<infer U extends import("../Feature.js").FeatureLike> ? U : never} ExtractedFeatureType
   */

  /**
   * @template {import("../source/VectorTile.js").default<FeatureType>} [VectorTileSourceType=import("../source/VectorTile.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=ExtractedFeatureType<VectorTileSourceType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * FIXME: not supported yet
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {VectorTileSourceType} [source] Source.
   * @property {import('../style/flat.js').FlatStyleLike} style Layer style.
   * @property {import('../style/flat.js').StyleVariables} [variables] Style variables. Each variable must hold a literal value (not
   * an expression). These variables can be used as {@link import("../expr/expression.js").ExpressionValue expressions} in the styles properties
   * using the `['var', 'varName']` operator.
   * To update style variables, use the {@link import("./WebGLVector.js").default#updateStyleVariables} method.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * FIXME: not supported yet
   * @property {boolean} [disableHitDetection=false] Setting this to true will provide a slight performance boost, but will
   * prevent all hit detection on the layer.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Layer optimized for rendering large vector datasets.
   *
   * **Important: a `WebGLVector` layer must be manually disposed when removed, otherwise the underlying WebGL context
   * will not be garbage collected.**
   *
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/VectorTile.js").default<FeatureType>} [VectorTileSourceType=import("../source/VectorTile.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=ExtractedFeatureType<VectorTileSourceType>]
   * @extends {BaseTileLayer<VectorTileSourceType, WebGLVectorTileLayerRenderer>}
   */
  class WebGLVectorTileLayer extends BaseTileLayer {
    /**
     * @param {Options<VectorTileSourceType, FeatureType>} [options] Options.
     */
    constructor(options) {
      const baseOptions = Object.assign({}, options);

      super(baseOptions);

      /**
       * @type {import('../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = options.variables || {};

      /**
       * @private
       */
      this.style_ = options.style;

      /**
       * @private
       */
      this.hitDetectionDisabled_ = !!options.disableHitDetection;
    }

    /**
     * @override
     */
    createRenderer() {
      return new WebGLVectorTileLayerRenderer(this, {
        style: this.style_,
        variables: this.styleVariables_,
        disableHitDetection: this.hitDetectionDisabled_,
      });
    }

    /**
     * Update any variables used by the layer style and trigger a re-render.
     * @param {import('../style/flat.js').StyleVariables} variables Variables to update.
     */
    updateStyleVariables(variables) {
      Object.assign(this.styleVariables_, variables);
      this.changed();
    }

    /**
     * Set the layer style.
     * @param {import('../style/flat.js').FlatStyleLike} style Layer style.
     */
    setStyle(style) {
      this.style_ = style;
      this.clearRenderer();
      this.changed();
    }
  }

  /**
   * @module ol/VectorRenderTile
   */

  /**
   * @typedef {Object} ReplayState
   * @property {boolean} dirty Dirty.
   * @property {null|import("./render.js").OrderFunction} renderedRenderOrder RenderedRenderOrder.
   * @property {number} renderedTileRevision RenderedTileRevision.
   * @property {number} renderedResolution RenderedResolution.
   * @property {number} renderedRevision RenderedRevision.
   * @property {number} renderedTileResolution RenderedTileResolution.
   * @property {number} renderedTileZ RenderedTileZ.
   */

  /**
   * @type {Array<HTMLCanvasElement>}
   */
  const canvasPool = [];

  class VectorRenderTile extends Tile {
    /**
     * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("./TileState.js").default} state State.
     * @param {import("./tilecoord.js").TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
     * @param {function(VectorRenderTile):Array<import("./VectorTile").default>} getSourceTiles Function.
     * @param {function(VectorRenderTile):void} removeSourceTiles Function.
     */
    constructor(
      tileCoord,
      state,
      urlTileCoord,
      getSourceTiles,
      removeSourceTiles,
    ) {
      super(tileCoord, state, {transition: 0});

      /**
       * @private
       * @type {CanvasRenderingContext2D|null}
       */
      this.context_ = null;

      /**
       * Executor groups. Read/written by the renderer.
       * @type {Object<string, Array<import("./render/canvas/ExecutorGroup.js").default>>}
       */
      this.executorGroups = {};

      /**
       * Number of loading source tiles. Read/written by the source.
       * @type {number}
       */
      this.loadingSourceTiles = 0;

      /**
       * @type {Object<string, ImageData>}
       */
      this.hitDetectionImageData = {};

      /**
       * @private
       * @type {!Object<string, ReplayState>}
       */
      this.replayState_ = {};

      /**
       * @type {Array<import("./VectorTile.js").default>}
       */
      this.sourceTiles = [];

      /**
       * @type {Object<string, boolean>}
       */
      this.errorTileKeys = {};

      /**
       * @type {number}
       */
      this.wantedResolution;

      /**
       * @type {!function():Array<import("./VectorTile.js").default>}
       */
      this.getSourceTiles = getSourceTiles.bind(undefined, this);

      /**
       * @type {!function(VectorRenderTile):void}
       * @private
       */
      this.removeSourceTiles_ = removeSourceTiles;

      /**
       * @type {import("./tilecoord.js").TileCoord}
       */
      this.wrappedTileCoord = urlTileCoord;
    }

    /**
     * @return {CanvasRenderingContext2D} The rendering context.
     */
    getContext() {
      if (!this.context_) {
        this.context_ = createCanvasContext2D(1, 1, canvasPool);
      }
      return this.context_;
    }

    /**
     * @return {boolean} Tile has a rendering context.
     */
    hasContext() {
      return !!this.context_;
    }

    /**
     * Get the Canvas for this tile.
     * @return {HTMLCanvasElement} Canvas.
     */
    getImage() {
      return this.hasContext() ? this.getContext().canvas : null;
    }

    /**
     * @param {import("./layer/Layer.js").default} layer Layer.
     * @return {ReplayState} The replay state.
     */
    getReplayState(layer) {
      const key = getUid(layer);
      if (!(key in this.replayState_)) {
        this.replayState_[key] = {
          dirty: false,
          renderedRenderOrder: null,
          renderedResolution: NaN,
          renderedRevision: -1,
          renderedTileResolution: NaN,
          renderedTileRevision: -1,
          renderedTileZ: -1,
        };
      }
      return this.replayState_[key];
    }

    /**
     * Load the tile.
     * @override
     */
    load() {
      this.getSourceTiles();
    }

    /**
     * Remove from the cache due to expiry
     * @override
     */
    release() {
      if (this.context_) {
        releaseCanvas$1(this.context_);
        canvasPool.push(this.context_.canvas);
        this.context_ = null;
      }
      this.removeSourceTiles_(this);
      this.sourceTiles.length = 0;
      super.release();
    }
  }

  /**
   * @module ol/VectorTile
   */

  /**
   * @template {import('./Feature.js').FeatureLike} FeatureType
   */
  let VectorTile$1 = class VectorTile extends Tile {
    /**
     * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("./TileState.js").default} state State.
     * @param {string} src Data source url.
     * @param {import("./format/Feature.js").default<FeatureType>} format Feature format.
     * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function.
     * @param {import("./Tile.js").Options} [options] Tile options.
     */
    constructor(tileCoord, state, src, format, tileLoadFunction, options) {
      super(tileCoord, state, options);

      /**
       * Extent of this tile; set by the source.
       * @type {import("./extent.js").Extent}
       */
      this.extent = null;

      /**
       * @private
       * @type {import("./format/Feature.js").default<FeatureType>}
       */
      this.format_ = format;

      /**
       * @private
       * @type {Array<FeatureType>}
       */
      this.features_ = null;

      /**
       * @private
       * @type {import("./featureloader.js").FeatureLoader}
       */
      this.loader_;

      /**
       * Feature projection of this tile; set by the source.
       * @type {import("./proj/Projection.js").default}
       */
      this.projection = null;

      /**
       * Resolution of this tile; set by the source.
       * @type {number}
       */
      this.resolution;

      /**
       * @private
       * @type {import("./Tile.js").LoadFunction}
       */
      this.tileLoadFunction_ = tileLoadFunction;

      /**
       * @private
       * @type {string}
       */
      this.url_ = src;

      this.key = src;
    }

    /**
     * @return {string} Tile url.
     */
    getTileUrl() {
      return this.url_;
    }

    /**
     * Get the feature format assigned for reading this tile's features.
     * @return {import("./format/Feature.js").default<FeatureType>} Feature format.
     * @api
     */
    getFormat() {
      return this.format_;
    }

    /**
     * Get the features for this tile. Geometries will be in the view projection.
     * @return {Array<FeatureType>} Features.
     * @api
     */
    getFeatures() {
      return this.features_;
    }

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {
      if (this.state == TileState.IDLE) {
        this.setState(TileState.LOADING);
        this.tileLoadFunction_(this, this.url_);
        if (this.loader_) {
          this.loader_(this.extent, this.resolution, this.projection);
        }
      }
    }

    /**
     * Handler for successful tile load.
     * @param {Array<FeatureType>} features The loaded features.
     * @param {import("./proj/Projection.js").default} dataProjection Data projection.
     */
    onLoad(features, dataProjection) {
      this.setFeatures(features);
    }

    /**
     * Handler for tile load errors.
     */
    onError() {
      this.setState(TileState.ERROR);
    }

    /**
     * Function for use in a {@link module:ol/source/VectorTile~VectorTile}'s `tileLoadFunction`.
     * Sets the features for the tile.
     * @param {Array<FeatureType>} features Features.
     * @api
     */
    setFeatures(features) {
      this.features_ = features;
      this.setState(TileState.LOADED);
    }

    /**
     * Set the feature loader for reading this tile's features.
     * @param {import("./featureloader.js").FeatureLoader<FeatureType>} loader Feature loader.
     * @api
     */
    setLoader(loader) {
      this.loader_ = loader;
    }
  };

  var $version = 8;
  var $root = {
  	version: {
  		required: true,
  		type: "enum",
  		values: [
  			8
  		]
  	},
  	name: {
  		type: "string"
  	},
  	metadata: {
  		type: "*"
  	},
  	center: {
  		type: "array",
  		value: "number"
  	},
  	centerAltitude: {
  		type: "number"
  	},
  	zoom: {
  		type: "number"
  	},
  	bearing: {
  		type: "number",
  		"default": 0,
  		period: 360,
  		units: "degrees"
  	},
  	pitch: {
  		type: "number",
  		"default": 0,
  		units: "degrees"
  	},
  	roll: {
  		type: "number",
  		"default": 0,
  		units: "degrees"
  	},
  	state: {
  		type: "state",
  		"default": {
  		}
  	},
  	light: {
  		type: "light"
  	},
  	sky: {
  		type: "sky"
  	},
  	projection: {
  		type: "projection"
  	},
  	terrain: {
  		type: "terrain"
  	},
  	sources: {
  		required: true,
  		type: "sources"
  	},
  	sprite: {
  		type: "sprite"
  	},
  	glyphs: {
  		type: "string"
  	},
  	transition: {
  		type: "transition"
  	},
  	layers: {
  		required: true,
  		type: "array",
  		value: "layer"
  	}
  };
  var sources = {
  	"*": {
  		type: "source"
  	}
  };
  var source = [
  	"source_vector",
  	"source_raster",
  	"source_raster_dem",
  	"source_geojson",
  	"source_video",
  	"source_image"
  ];
  var source_vector = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			vector: {
  			}
  		}
  	},
  	url: {
  		type: "string"
  	},
  	tiles: {
  		type: "array",
  		value: "string"
  	},
  	bounds: {
  		type: "array",
  		value: "number",
  		length: 4,
  		"default": [
  			-180,
  			-85.051129,
  			180,
  			85.051129
  		]
  	},
  	scheme: {
  		type: "enum",
  		values: {
  			xyz: {
  			},
  			tms: {
  			}
  		},
  		"default": "xyz"
  	},
  	minzoom: {
  		type: "number",
  		"default": 0
  	},
  	maxzoom: {
  		type: "number",
  		"default": 22
  	},
  	attribution: {
  		type: "string"
  	},
  	promoteId: {
  		type: "promoteId"
  	},
  	volatile: {
  		type: "boolean",
  		"default": false
  	},
  	"*": {
  		type: "*"
  	}
  };
  var source_raster = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			raster: {
  			}
  		}
  	},
  	url: {
  		type: "string"
  	},
  	tiles: {
  		type: "array",
  		value: "string"
  	},
  	bounds: {
  		type: "array",
  		value: "number",
  		length: 4,
  		"default": [
  			-180,
  			-85.051129,
  			180,
  			85.051129
  		]
  	},
  	minzoom: {
  		type: "number",
  		"default": 0
  	},
  	maxzoom: {
  		type: "number",
  		"default": 22
  	},
  	tileSize: {
  		type: "number",
  		"default": 512,
  		units: "pixels"
  	},
  	scheme: {
  		type: "enum",
  		values: {
  			xyz: {
  			},
  			tms: {
  			}
  		},
  		"default": "xyz"
  	},
  	attribution: {
  		type: "string"
  	},
  	volatile: {
  		type: "boolean",
  		"default": false
  	},
  	"*": {
  		type: "*"
  	}
  };
  var source_raster_dem = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			"raster-dem": {
  			}
  		}
  	},
  	url: {
  		type: "string"
  	},
  	tiles: {
  		type: "array",
  		value: "string"
  	},
  	bounds: {
  		type: "array",
  		value: "number",
  		length: 4,
  		"default": [
  			-180,
  			-85.051129,
  			180,
  			85.051129
  		]
  	},
  	minzoom: {
  		type: "number",
  		"default": 0
  	},
  	maxzoom: {
  		type: "number",
  		"default": 22
  	},
  	tileSize: {
  		type: "number",
  		"default": 512,
  		units: "pixels"
  	},
  	attribution: {
  		type: "string"
  	},
  	encoding: {
  		type: "enum",
  		values: {
  			terrarium: {
  			},
  			mapbox: {
  			},
  			custom: {
  			}
  		},
  		"default": "mapbox"
  	},
  	redFactor: {
  		type: "number",
  		"default": 1
  	},
  	blueFactor: {
  		type: "number",
  		"default": 1
  	},
  	greenFactor: {
  		type: "number",
  		"default": 1
  	},
  	baseShift: {
  		type: "number",
  		"default": 0
  	},
  	volatile: {
  		type: "boolean",
  		"default": false
  	},
  	"*": {
  		type: "*"
  	}
  };
  var source_geojson = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			geojson: {
  			}
  		}
  	},
  	data: {
  		required: true,
  		type: "*"
  	},
  	maxzoom: {
  		type: "number",
  		"default": 18
  	},
  	attribution: {
  		type: "string"
  	},
  	buffer: {
  		type: "number",
  		"default": 128,
  		maximum: 512,
  		minimum: 0
  	},
  	filter: {
  		type: "*"
  	},
  	tolerance: {
  		type: "number",
  		"default": 0.375
  	},
  	cluster: {
  		type: "boolean",
  		"default": false
  	},
  	clusterRadius: {
  		type: "number",
  		"default": 50,
  		minimum: 0
  	},
  	clusterMaxZoom: {
  		type: "number"
  	},
  	clusterMinPoints: {
  		type: "number"
  	},
  	clusterProperties: {
  		type: "*"
  	},
  	lineMetrics: {
  		type: "boolean",
  		"default": false
  	},
  	generateId: {
  		type: "boolean",
  		"default": false
  	},
  	promoteId: {
  		type: "promoteId"
  	}
  };
  var source_video = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			video: {
  			}
  		}
  	},
  	urls: {
  		required: true,
  		type: "array",
  		value: "string"
  	},
  	coordinates: {
  		required: true,
  		type: "array",
  		length: 4,
  		value: {
  			type: "array",
  			length: 2,
  			value: "number"
  		}
  	}
  };
  var source_image = {
  	type: {
  		required: true,
  		type: "enum",
  		values: {
  			image: {
  			}
  		}
  	},
  	url: {
  		required: true,
  		type: "string"
  	},
  	coordinates: {
  		required: true,
  		type: "array",
  		length: 4,
  		value: {
  			type: "array",
  			length: 2,
  			value: "number"
  		}
  	}
  };
  var layer = {
  	id: {
  		type: "string",
  		required: true
  	},
  	type: {
  		type: "enum",
  		values: {
  			fill: {
  			},
  			line: {
  			},
  			symbol: {
  			},
  			circle: {
  			},
  			heatmap: {
  			},
  			"fill-extrusion": {
  			},
  			raster: {
  			},
  			hillshade: {
  			},
  			"color-relief": {
  			},
  			background: {
  			}
  		},
  		required: true
  	},
  	metadata: {
  		type: "*"
  	},
  	source: {
  		type: "string"
  	},
  	"source-layer": {
  		type: "string"
  	},
  	minzoom: {
  		type: "number",
  		minimum: 0,
  		maximum: 24
  	},
  	maxzoom: {
  		type: "number",
  		minimum: 0,
  		maximum: 24
  	},
  	filter: {
  		type: "filter"
  	},
  	layout: {
  		type: "layout"
  	},
  	paint: {
  		type: "paint"
  	}
  };
  var layout = [
  	"layout_fill",
  	"layout_line",
  	"layout_circle",
  	"layout_heatmap",
  	"layout_fill-extrusion",
  	"layout_symbol",
  	"layout_raster",
  	"layout_hillshade",
  	"layout_color-relief",
  	"layout_background"
  ];
  var layout_background = {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_fill = {
  	"fill-sort-key": {
  		type: "number",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_circle = {
  	"circle-sort-key": {
  		type: "number",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_heatmap = {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_line = {
  	"line-cap": {
  		type: "enum",
  		values: {
  			butt: {
  			},
  			round: {
  			},
  			square: {
  			}
  		},
  		"default": "butt",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"line-join": {
  		type: "enum",
  		values: {
  			bevel: {
  			},
  			round: {
  			},
  			miter: {
  			}
  		},
  		"default": "miter",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-miter-limit": {
  		type: "number",
  		"default": 2,
  		requires: [
  			{
  				"line-join": "miter"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"line-round-limit": {
  		type: "number",
  		"default": 1.05,
  		requires: [
  			{
  				"line-join": "round"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"line-sort-key": {
  		type: "number",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_symbol = {
  	"symbol-placement": {
  		type: "enum",
  		values: {
  			point: {
  			},
  			line: {
  			},
  			"line-center": {
  			}
  		},
  		"default": "point",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"symbol-spacing": {
  		type: "number",
  		"default": 250,
  		minimum: 1,
  		units: "pixels",
  		requires: [
  			{
  				"symbol-placement": "line"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"symbol-avoid-edges": {
  		type: "boolean",
  		"default": false,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"symbol-sort-key": {
  		type: "number",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"symbol-z-order": {
  		type: "enum",
  		values: {
  			auto: {
  			},
  			"viewport-y": {
  			},
  			source: {
  			}
  		},
  		"default": "auto",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-allow-overlap": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"icon-image",
  			{
  				"!": "icon-overlap"
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-overlap": {
  		type: "enum",
  		values: {
  			never: {
  			},
  			always: {
  			},
  			cooperative: {
  			}
  		},
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-ignore-placement": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-optional": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"icon-image",
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-rotation-alignment": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			},
  			auto: {
  			}
  		},
  		"default": "auto",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-size": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		units: "factor of the original icon size",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-text-fit": {
  		type: "enum",
  		values: {
  			none: {
  			},
  			width: {
  			},
  			height: {
  			},
  			both: {
  			}
  		},
  		"default": "none",
  		requires: [
  			"icon-image",
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-text-fit-padding": {
  		type: "array",
  		value: "number",
  		length: 4,
  		"default": [
  			0,
  			0,
  			0,
  			0
  		],
  		units: "pixels",
  		requires: [
  			"icon-image",
  			"text-field",
  			{
  				"icon-text-fit": [
  					"both",
  					"width",
  					"height"
  				]
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-image": {
  		type: "resolvedImage",
  		tokens: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-rotate": {
  		type: "number",
  		"default": 0,
  		period: 360,
  		units: "degrees",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-padding": {
  		type: "padding",
  		"default": [
  			2
  		],
  		units: "pixels",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-keep-upright": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"icon-image",
  			{
  				"icon-rotation-alignment": "map"
  			},
  			{
  				"symbol-placement": [
  					"line",
  					"line-center"
  				]
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-offset": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-anchor": {
  		type: "enum",
  		values: {
  			center: {
  			},
  			left: {
  			},
  			right: {
  			},
  			top: {
  			},
  			bottom: {
  			},
  			"top-left": {
  			},
  			"top-right": {
  			},
  			"bottom-left": {
  			},
  			"bottom-right": {
  			}
  		},
  		"default": "center",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-pitch-alignment": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			},
  			auto: {
  			}
  		},
  		"default": "auto",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-pitch-alignment": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			},
  			auto: {
  			}
  		},
  		"default": "auto",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-rotation-alignment": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			},
  			"viewport-glyph": {
  			},
  			auto: {
  			}
  		},
  		"default": "auto",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-field": {
  		type: "formatted",
  		"default": "",
  		tokens: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-font": {
  		type: "array",
  		value: "string",
  		"default": [
  			"Open Sans Regular",
  			"Arial Unicode MS Regular"
  		],
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-size": {
  		type: "number",
  		"default": 16,
  		minimum: 0,
  		units: "pixels",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-max-width": {
  		type: "number",
  		"default": 10,
  		minimum: 0,
  		units: "ems",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-line-height": {
  		type: "number",
  		"default": 1.2,
  		units: "ems",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-letter-spacing": {
  		type: "number",
  		"default": 0,
  		units: "ems",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-justify": {
  		type: "enum",
  		values: {
  			auto: {
  			},
  			left: {
  			},
  			center: {
  			},
  			right: {
  			}
  		},
  		"default": "center",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-radial-offset": {
  		type: "number",
  		units: "ems",
  		"default": 0,
  		requires: [
  			"text-field"
  		],
  		"property-type": "data-driven",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		}
  	},
  	"text-variable-anchor": {
  		type: "array",
  		value: "enum",
  		values: {
  			center: {
  			},
  			left: {
  			},
  			right: {
  			},
  			top: {
  			},
  			bottom: {
  			},
  			"top-left": {
  			},
  			"top-right": {
  			},
  			"bottom-left": {
  			},
  			"bottom-right": {
  			}
  		},
  		requires: [
  			"text-field",
  			{
  				"symbol-placement": [
  					"point"
  				]
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-variable-anchor-offset": {
  		type: "variableAnchorOffsetCollection",
  		requires: [
  			"text-field",
  			{
  				"symbol-placement": [
  					"point"
  				]
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-anchor": {
  		type: "enum",
  		values: {
  			center: {
  			},
  			left: {
  			},
  			right: {
  			},
  			top: {
  			},
  			bottom: {
  			},
  			"top-left": {
  			},
  			"top-right": {
  			},
  			"bottom-left": {
  			},
  			"bottom-right": {
  			}
  		},
  		"default": "center",
  		requires: [
  			"text-field",
  			{
  				"!": "text-variable-anchor"
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-max-angle": {
  		type: "number",
  		"default": 45,
  		units: "degrees",
  		requires: [
  			"text-field",
  			{
  				"symbol-placement": [
  					"line",
  					"line-center"
  				]
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-writing-mode": {
  		type: "array",
  		value: "enum",
  		values: {
  			horizontal: {
  			},
  			vertical: {
  			}
  		},
  		requires: [
  			"text-field",
  			{
  				"symbol-placement": [
  					"point"
  				]
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-rotate": {
  		type: "number",
  		"default": 0,
  		period: 360,
  		units: "degrees",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-padding": {
  		type: "number",
  		"default": 2,
  		minimum: 0,
  		units: "pixels",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-keep-upright": {
  		type: "boolean",
  		"default": true,
  		requires: [
  			"text-field",
  			{
  				"text-rotation-alignment": "map"
  			},
  			{
  				"symbol-placement": [
  					"line",
  					"line-center"
  				]
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-transform": {
  		type: "enum",
  		values: {
  			none: {
  			},
  			uppercase: {
  			},
  			lowercase: {
  			}
  		},
  		"default": "none",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-offset": {
  		type: "array",
  		value: "number",
  		units: "ems",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		requires: [
  			"text-field",
  			{
  				"!": "text-radial-offset"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-allow-overlap": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"text-field",
  			{
  				"!": "text-overlap"
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-overlap": {
  		type: "enum",
  		values: {
  			never: {
  			},
  			always: {
  			},
  			cooperative: {
  			}
  		},
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-ignore-placement": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-optional": {
  		type: "boolean",
  		"default": false,
  		requires: [
  			"text-field",
  			"icon-image"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_raster = {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var layout_hillshade = {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  };
  var filter = {
  	type: "array",
  	value: "*"
  };
  var filter_operator = {
  	type: "enum",
  	values: {
  		"==": {
  		},
  		"!=": {
  		},
  		">": {
  		},
  		">=": {
  		},
  		"<": {
  		},
  		"<=": {
  		},
  		"in": {
  		},
  		"!in": {
  		},
  		all: {
  		},
  		any: {
  		},
  		none: {
  		},
  		has: {
  		},
  		"!has": {
  		}
  	}
  };
  var geometry_type = {
  	type: "enum",
  	values: {
  		Point: {
  		},
  		LineString: {
  		},
  		Polygon: {
  		}
  	}
  };
  var function_stop = {
  	type: "array",
  	minimum: 0,
  	maximum: 24,
  	value: [
  		"number",
  		"color"
  	],
  	length: 2
  };
  var expression$1 = {
  	type: "array",
  	value: "*",
  	minimum: 1
  };
  var light = {
  	anchor: {
  		type: "enum",
  		"default": "viewport",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"property-type": "data-constant",
  		transition: false,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		}
  	},
  	position: {
  		type: "array",
  		"default": [
  			1.15,
  			210,
  			30
  		],
  		length: 3,
  		value: "number",
  		"property-type": "data-constant",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		}
  	},
  	color: {
  		type: "color",
  		"property-type": "data-constant",
  		"default": "#ffffff",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	intensity: {
  		type: "number",
  		"property-type": "data-constant",
  		"default": 0.5,
  		minimum: 0,
  		maximum: 1,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	}
  };
  var sky = {
  	"sky-color": {
  		type: "color",
  		"property-type": "data-constant",
  		"default": "#88C6FC",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"horizon-color": {
  		type: "color",
  		"property-type": "data-constant",
  		"default": "#ffffff",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"fog-color": {
  		type: "color",
  		"property-type": "data-constant",
  		"default": "#ffffff",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"fog-ground-blend": {
  		type: "number",
  		"property-type": "data-constant",
  		"default": 0.5,
  		minimum: 0,
  		maximum: 1,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"horizon-fog-blend": {
  		type: "number",
  		"property-type": "data-constant",
  		"default": 0.8,
  		minimum: 0,
  		maximum: 1,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"sky-horizon-blend": {
  		type: "number",
  		"property-type": "data-constant",
  		"default": 0.8,
  		minimum: 0,
  		maximum: 1,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	},
  	"atmosphere-blend": {
  		type: "number",
  		"property-type": "data-constant",
  		"default": 0.8,
  		minimum: 0,
  		maximum: 1,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		transition: true
  	}
  };
  var terrain = {
  	source: {
  		type: "string",
  		required: true
  	},
  	exaggeration: {
  		type: "number",
  		minimum: 0,
  		"default": 1
  	}
  };
  var projection = {
  	type: {
  		type: "projectionDefinition",
  		"default": "mercator",
  		"property-type": "data-constant",
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		}
  	}
  };
  var paint = [
  	"paint_fill",
  	"paint_line",
  	"paint_circle",
  	"paint_heatmap",
  	"paint_fill-extrusion",
  	"paint_symbol",
  	"paint_raster",
  	"paint_hillshade",
  	"paint_color-relief",
  	"paint_background"
  ];
  var paint_fill = {
  	"fill-antialias": {
  		type: "boolean",
  		"default": true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		requires: [
  			{
  				"!": "fill-pattern"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-outline-color": {
  		type: "color",
  		transition: true,
  		requires: [
  			{
  				"!": "fill-pattern"
  			},
  			{
  				"fill-antialias": true
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"fill-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-pattern": {
  		type: "resolvedImage",
  		transition: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "cross-faded-data-driven"
  	}
  };
  var paint_line = {
  	"line-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		requires: [
  			{
  				"!": "line-pattern"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"line-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"line-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"line-width": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-gap-width": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-offset": {
  		type: "number",
  		"default": 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-blur": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"line-dasharray": {
  		type: "array",
  		value: "number",
  		minimum: 0,
  		transition: true,
  		units: "line widths",
  		requires: [
  			{
  				"!": "line-pattern"
  			}
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "cross-faded"
  	},
  	"line-pattern": {
  		type: "resolvedImage",
  		transition: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "cross-faded-data-driven"
  	},
  	"line-gradient": {
  		type: "color",
  		transition: false,
  		requires: [
  			{
  				"!": "line-dasharray"
  			},
  			{
  				"!": "line-pattern"
  			},
  			{
  				source: "geojson",
  				has: {
  					lineMetrics: true
  				}
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"line-progress"
  			]
  		},
  		"property-type": "color-ramp"
  	}
  };
  var paint_circle = {
  	"circle-radius": {
  		type: "number",
  		"default": 5,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-blur": {
  		type: "number",
  		"default": 0,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"circle-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"circle-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"circle-pitch-scale": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"circle-pitch-alignment": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "viewport",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"circle-stroke-width": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-stroke-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"circle-stroke-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	}
  };
  var paint_heatmap = {
  	"heatmap-radius": {
  		type: "number",
  		"default": 30,
  		minimum: 1,
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"heatmap-weight": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"heatmap-intensity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"heatmap-color": {
  		type: "color",
  		"default": [
  			"interpolate",
  			[
  				"linear"
  			],
  			[
  				"heatmap-density"
  			],
  			0,
  			"rgba(0, 0, 255, 0)",
  			0.1,
  			"royalblue",
  			0.3,
  			"cyan",
  			0.5,
  			"lime",
  			0.7,
  			"yellow",
  			1,
  			"red"
  		],
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"heatmap-density"
  			]
  		},
  		"property-type": "color-ramp"
  	},
  	"heatmap-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  };
  var paint_symbol = {
  	"icon-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-halo-color": {
  		type: "color",
  		"default": "rgba(0, 0, 0, 0)",
  		transition: true,
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-halo-width": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-halo-blur": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"icon-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		requires: [
  			"icon-image"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"icon-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"icon-image",
  			"icon-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		overridable: true,
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-halo-color": {
  		type: "color",
  		"default": "rgba(0, 0, 0, 0)",
  		transition: true,
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-halo-width": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-halo-blur": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		transition: true,
  		units: "pixels",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"text-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		requires: [
  			"text-field"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"text-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"text-field",
  			"text-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  };
  var paint_raster = {
  	"raster-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-hue-rotate": {
  		type: "number",
  		"default": 0,
  		period: 360,
  		transition: true,
  		units: "degrees",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-brightness-min": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-brightness-max": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-saturation": {
  		type: "number",
  		"default": 0,
  		minimum: -1,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-contrast": {
  		type: "number",
  		"default": 0,
  		minimum: -1,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-resampling": {
  		type: "enum",
  		values: {
  			linear: {
  			},
  			nearest: {
  			}
  		},
  		"default": "linear",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"raster-fade-duration": {
  		type: "number",
  		"default": 300,
  		minimum: 0,
  		transition: false,
  		units: "milliseconds",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  };
  var paint_hillshade = {
  	"hillshade-illumination-direction": {
  		type: "numberArray",
  		"default": 335,
  		minimum: 0,
  		maximum: 359,
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-illumination-altitude": {
  		type: "numberArray",
  		"default": 45,
  		minimum: 0,
  		maximum: 90,
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-illumination-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "viewport",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-exaggeration": {
  		type: "number",
  		"default": 0.5,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-shadow-color": {
  		type: "colorArray",
  		"default": "#000000",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-highlight-color": {
  		type: "colorArray",
  		"default": "#FFFFFF",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-accent-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"hillshade-method": {
  		type: "enum",
  		values: {
  			standard: {
  			},
  			basic: {
  			},
  			combined: {
  			},
  			igor: {
  			},
  			multidirectional: {
  			}
  		},
  		"default": "standard",
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  };
  var paint_background = {
  	"background-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		requires: [
  			{
  				"!": "background-pattern"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"background-pattern": {
  		type: "resolvedImage",
  		transition: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "cross-faded"
  	},
  	"background-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  };
  var transition = {
  	duration: {
  		type: "number",
  		"default": 300,
  		minimum: 0,
  		units: "milliseconds"
  	},
  	delay: {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		units: "milliseconds"
  	}
  };
  var promoteId = {
  	"*": {
  		type: "string"
  	}
  };
  var v8Spec = {
  	$version: $version,
  	$root: $root,
  	sources: sources,
  	source: source,
  	source_vector: source_vector,
  	source_raster: source_raster,
  	source_raster_dem: source_raster_dem,
  	source_geojson: source_geojson,
  	source_video: source_video,
  	source_image: source_image,
  	layer: layer,
  	layout: layout,
  	layout_background: layout_background,
  	layout_fill: layout_fill,
  	layout_circle: layout_circle,
  	layout_heatmap: layout_heatmap,
  	"layout_fill-extrusion": {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  },
  	layout_line: layout_line,
  	layout_symbol: layout_symbol,
  	layout_raster: layout_raster,
  	layout_hillshade: layout_hillshade,
  	"layout_color-relief": {
  	visibility: {
  		type: "enum",
  		values: {
  			visible: {
  			},
  			none: {
  			}
  		},
  		"default": "visible",
  		"property-type": "constant"
  	}
  },
  	filter: filter,
  	filter_operator: filter_operator,
  	geometry_type: geometry_type,
  	"function": {
  	expression: {
  		type: "expression"
  	},
  	stops: {
  		type: "array",
  		value: "function_stop"
  	},
  	base: {
  		type: "number",
  		"default": 1,
  		minimum: 0
  	},
  	property: {
  		type: "string",
  		"default": "$zoom"
  	},
  	type: {
  		type: "enum",
  		values: {
  			identity: {
  			},
  			exponential: {
  			},
  			interval: {
  			},
  			categorical: {
  			}
  		},
  		"default": "exponential"
  	},
  	colorSpace: {
  		type: "enum",
  		values: {
  			rgb: {
  			},
  			lab: {
  			},
  			hcl: {
  			}
  		},
  		"default": "rgb"
  	},
  	"default": {
  		type: "*",
  		required: false
  	}
  },
  	function_stop: function_stop,
  	expression: expression$1,
  	light: light,
  	sky: sky,
  	terrain: terrain,
  	projection: projection,
  	paint: paint,
  	paint_fill: paint_fill,
  	"paint_fill-extrusion": {
  	"fill-extrusion-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-extrusion-color": {
  		type: "color",
  		"default": "#000000",
  		transition: true,
  		requires: [
  			{
  				"!": "fill-extrusion-pattern"
  			}
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-extrusion-translate": {
  		type: "array",
  		value: "number",
  		length: 2,
  		"default": [
  			0,
  			0
  		],
  		transition: true,
  		units: "pixels",
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-extrusion-translate-anchor": {
  		type: "enum",
  		values: {
  			map: {
  			},
  			viewport: {
  			}
  		},
  		"default": "map",
  		requires: [
  			"fill-extrusion-translate"
  		],
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"fill-extrusion-pattern": {
  		type: "resolvedImage",
  		transition: true,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom",
  				"feature"
  			]
  		},
  		"property-type": "cross-faded-data-driven"
  	},
  	"fill-extrusion-height": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		units: "meters",
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-extrusion-base": {
  		type: "number",
  		"default": 0,
  		minimum: 0,
  		units: "meters",
  		transition: true,
  		requires: [
  			"fill-extrusion-height"
  		],
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom",
  				"feature",
  				"feature-state"
  			]
  		},
  		"property-type": "data-driven"
  	},
  	"fill-extrusion-vertical-gradient": {
  		type: "boolean",
  		"default": true,
  		transition: false,
  		expression: {
  			interpolated: false,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	}
  },
  	paint_line: paint_line,
  	paint_circle: paint_circle,
  	paint_heatmap: paint_heatmap,
  	paint_symbol: paint_symbol,
  	paint_raster: paint_raster,
  	paint_hillshade: paint_hillshade,
  	"paint_color-relief": {
  	"color-relief-opacity": {
  		type: "number",
  		"default": 1,
  		minimum: 0,
  		maximum: 1,
  		transition: true,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"zoom"
  			]
  		},
  		"property-type": "data-constant"
  	},
  	"color-relief-color": {
  		type: "color",
  		transition: false,
  		expression: {
  			interpolated: true,
  			parameters: [
  				"elevation"
  			]
  		},
  		"property-type": "color-ramp"
  	}
  },
  	paint_background: paint_background,
  	transition: transition,
  	"property-type": {
  	"data-driven": {
  		type: "property-type"
  	},
  	"cross-faded": {
  		type: "property-type"
  	},
  	"cross-faded-data-driven": {
  		type: "property-type"
  	},
  	"color-ramp": {
  		type: "property-type"
  	},
  	"data-constant": {
  		type: "property-type"
  	},
  	constant: {
  		type: "property-type"
  	}
  },
  	promoteId: promoteId
  };

  const refProperties = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];

  function deref(layer, parent) {
      const result = {};
      for (const k in layer) {
          if (k !== 'ref') {
              result[k] = layer[k];
          }
      }
      refProperties.forEach((k) => {
          if (k in parent) {
              result[k] = parent[k];
          }
      });
      return result;
  }
  /**
   * Given an array of layers, some of which may contain `ref` properties
   * whose value is the `id` of another property, return a new array where
   * such layers have been augmented with the 'type', 'source', etc. properties
   * from the parent layer, and the `ref` property has been removed.
   *
   * The input is not modified. The output may contain references to portions
   * of the input.
   *
   * @private
   * @param {Array<Layer>} layers
   * @returns {Array<Layer>}
   */
  function derefLayers(layers) {
      layers = layers.slice();
      const map = Object.create(null);
      for (let i = 0; i < layers.length; i++) {
          map[layers[i].id] = layers[i];
      }
      for (let i = 0; i < layers.length; i++) {
          if ('ref' in layers[i]) {
              layers[i] = deref(layers[i], map[layers[i].ref]);
          }
      }
      return layers;
  }

  class ExpressionParsingError extends Error {
      constructor(key, message) {
          super(message);
          this.message = message;
          this.key = key;
      }
  }

  /**
   * Tracks `let` bindings during expression parsing.
   * @private
   */
  class Scope {
      constructor(parent, bindings = []) {
          this.parent = parent;
          this.bindings = {};
          for (const [name, expression] of bindings) {
              this.bindings[name] = expression;
          }
      }
      concat(bindings) {
          return new Scope(this, bindings);
      }
      get(name) {
          if (this.bindings[name]) {
              return this.bindings[name];
          }
          if (this.parent) {
              return this.parent.get(name);
          }
          throw new Error(`${name} not found in scope.`);
      }
      has(name) {
          if (this.bindings[name])
              return true;
          return this.parent ? this.parent.has(name) : false;
      }
  }

  const NullType = { kind: 'null' };
  const NumberType = { kind: 'number' };
  const StringType = { kind: 'string' };
  const BooleanType = { kind: 'boolean' };
  const ColorType = { kind: 'color' };
  const ProjectionDefinitionType = { kind: 'projectionDefinition' };
  const ObjectType = { kind: 'object' };
  const ValueType = { kind: 'value' };
  const ErrorType = { kind: 'error' };
  const CollatorType = { kind: 'collator' };
  const FormattedType = { kind: 'formatted' };
  const PaddingType = { kind: 'padding' };
  const ColorArrayType = { kind: 'colorArray' };
  const NumberArrayType = { kind: 'numberArray' };
  const ResolvedImageType = { kind: 'resolvedImage' };
  const VariableAnchorOffsetCollectionType = { kind: 'variableAnchorOffsetCollection' };
  function array(itemType, N) {
      return {
          kind: 'array',
          itemType,
          N
      };
  }
  function typeToString(type) {
      if (type.kind === 'array') {
          const itemType = typeToString(type.itemType);
          return typeof type.N === 'number' ?
              `array<${itemType}, ${type.N}>` :
              type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;
      }
      else {
          return type.kind;
      }
  }
  const valueMemberTypes = [
      NullType,
      NumberType,
      StringType,
      BooleanType,
      ColorType,
      ProjectionDefinitionType,
      FormattedType,
      ObjectType,
      array(ValueType),
      PaddingType,
      NumberArrayType,
      ColorArrayType,
      ResolvedImageType,
      VariableAnchorOffsetCollectionType
  ];
  /**
   * Returns null if `t` is a subtype of `expected`; otherwise returns an
   * error message.
   * @private
   */
  function checkSubtype(expected, t) {
      if (t.kind === 'error') {
          // Error is a subtype of every type
          return null;
      }
      else if (expected.kind === 'array') {
          if (t.kind === 'array' &&
              ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) &&
              (typeof expected.N !== 'number' || expected.N === t.N)) {
              return null;
          }
      }
      else if (expected.kind === t.kind) {
          return null;
      }
      else if (expected.kind === 'value') {
          for (const memberType of valueMemberTypes) {
              if (!checkSubtype(memberType, t)) {
                  return null;
              }
          }
      }
      return `Expected ${typeToString(expected)} but found ${typeToString(t)} instead.`;
  }
  function isValidType(provided, allowedTypes) {
      return allowedTypes.some(t => t.kind === provided.kind);
  }
  function isValidNativeType(provided, allowedTypes) {
      return allowedTypes.some(t => {
          if (t === 'null') {
              return provided === null;
          }
          else if (t === 'array') {
              return Array.isArray(provided);
          }
          else if (t === 'object') {
              return provided && !Array.isArray(provided) && typeof provided === 'object';
          }
          else {
              return t === typeof provided;
          }
      });
  }
  /**
   * Verify whether the specified type is of the same type as the specified sample.
   *
   * @param provided Type to verify
   * @param sample Sample type to reference
   * @returns `true` if both objects are of the same type, `false` otherwise
   * @example basic types
   * if (verifyType(outputType, ValueType)) {
   *     // type narrowed to:
   *     outputType.kind; // 'value'
   * }
   * @example array types
   * if (verifyType(outputType, array(NumberType))) {
   *     // type narrowed to:
   *     outputType.kind; // 'array'
   *     outputType.itemType; // NumberTypeT
   *     outputType.itemType.kind; // 'number'
   * }
   */
  function verifyType(provided, sample) {
      if (provided.kind === 'array' && sample.kind === 'array') {
          return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number';
      }
      return provided.kind === sample.kind;
  }

  // See https://observablehq.com/@mbostock/lab-and-rgb
  const Xn$1 = 0.96422, Yn$1 = 1, Zn$1 = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad$1 = Math.PI / 180, rad2deg = 180 / Math.PI;
  function constrainAngle(angle) {
      angle = angle % 360;
      if (angle < 0) {
          angle += 360;
      }
      return angle;
  }
  function rgbToLab([r, g, b, alpha]) {
      r = rgb2xyz(r);
      g = rgb2xyz(g);
      b = rgb2xyz(b);
      let x, z;
      const y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn$1);
      if (r === g && g === b) {
          x = z = y;
      }
      else {
          x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn$1);
          z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn$1);
      }
      const l = 116 * y - 16;
      return [(l < 0) ? 0 : l, 500 * (x - y), 200 * (y - z), alpha];
  }
  function rgb2xyz(x) {
      return (x <= 0.04045) ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
  }
  function xyz2lab(t) {
      return (t > t3) ? Math.pow(t, 1 / 3) : t / t2 + t0;
  }
  function labToRgb([l, a, b, alpha]) {
      let y = (l + 16) / 116, x = isNaN(a) ? y : y + a / 500, z = isNaN(b) ? y : y - b / 200;
      y = Yn$1 * lab2xyz(y);
      x = Xn$1 * lab2xyz(x);
      z = Zn$1 * lab2xyz(z);
      return [
          xyz2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), // D50 -> sRGB
          xyz2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
          xyz2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
          alpha,
      ];
  }
  function xyz2rgb(x) {
      x = (x <= 0.00304) ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055;
      return (x < 0) ? 0 : (x > 1) ? 1 : x; // clip to 0..1 range
  }
  function lab2xyz(t) {
      return (t > t1) ? t * t * t : t2 * (t - t0);
  }
  function rgbToHcl(rgbColor) {
      const [l, a, b, alpha] = rgbToLab(rgbColor);
      const c = Math.sqrt(a * a + b * b);
      const h = Math.round(c * 10000) ? constrainAngle(Math.atan2(b, a) * rad2deg) : NaN;
      return [h, c, l, alpha];
  }
  function hclToRgb([h, c, l, alpha]) {
      h = isNaN(h) ? 0 : h * deg2rad$1;
      return labToRgb([l, Math.cos(h) * c, Math.sin(h) * c, alpha]);
  }
  // https://drafts.csswg.org/css-color-4/#hsl-to-rgb
  function hslToRgb([h, s, l, alpha]) {
      h = constrainAngle(h);
      s /= 100;
      l /= 100;
      function f(n) {
          const k = (n + h / 30) % 12;
          const a = s * Math.min(l, 1 - l);
          return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
      }
      return [f(0), f(8), f(4), alpha];
  }

  // polyfill for Object.hasOwn
  const hasOwnProperty = Object.hasOwn ||
      function hasOwnProperty(object, key) {
          return Object.prototype.hasOwnProperty.call(object, key);
      };
  function getOwn(object, key) {
      return hasOwnProperty(object, key) ? object[key] : undefined;
  }

  /**
   * CSS color parser compliant with CSS Color 4 Specification.
   * Supports: named colors, `transparent` keyword, all rgb hex notations,
   * rgb(), rgba(), hsl() and hsla() functions.
   * Does not round the parsed values to integers from the range 0..255.
   *
   * Syntax:
   *
   * <alpha-value> = <number> | <percentage>
   *         <hue> = <number> | <angle>
   *
   *         rgb() = rgb( <percentage>{3} [ / <alpha-value> ]? ) | rgb( <number>{3} [ / <alpha-value> ]? )
   *         rgb() = rgb( <percentage>#{3} , <alpha-value>? )    | rgb( <number>#{3} , <alpha-value>? )
   *
   *         hsl() = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? )
   *         hsl() = hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )
   *
   * Caveats:
   *   - <angle> - <number> with optional `deg` suffix; `grad`, `rad`, `turn` are not supported
   *   - `none` keyword is not supported
   *   - comments inside rgb()/hsl() are not supported
   *   - legacy color syntax rgba() is supported with an identical grammar and behavior to rgb()
   *   - legacy color syntax hsla() is supported with an identical grammar and behavior to hsl()
   *
   * @param input CSS color string to parse.
   * @returns Color in sRGB color space, with `red`, `green`, `blue`
   * and `alpha` channels normalized to the range 0..1,
   * or `undefined` if the input is not a valid color string.
   */
  function parseCssColor(input) {
      input = input.toLowerCase().trim();
      if (input === 'transparent') {
          return [0, 0, 0, 0];
      }
      // 'white', 'black', 'blue'
      const namedColorsMatch = getOwn(namedColors, input);
      if (namedColorsMatch) {
          const [r, g, b] = namedColorsMatch;
          return [r / 255, g / 255, b / 255, 1];
      }
      // #f0c, #f0cf, #ff00cc, #ff00ccff
      if (input.startsWith('#')) {
          const hexRegexp = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;
          if (hexRegexp.test(input)) {
              const step = input.length < 6 ? 1 : 2;
              let i = 1;
              return [
                  parseHex(input.slice(i, i += step)),
                  parseHex(input.slice(i, i += step)),
                  parseHex(input.slice(i, i += step)),
                  parseHex(input.slice(i, i + step) || 'ff'),
              ];
          }
      }
      // rgb(128 0 0), rgb(50% 0% 0%), rgba(255,0,255,0.6), rgb(255 0 255 / 60%), rgb(100% 0% 100% /.6)
      if (input.startsWith('rgb')) {
          const rgbRegExp = /^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/;
          const rgbMatch = input.match(rgbRegExp);
          if (rgbMatch) {
              const [_, // eslint-disable-line @typescript-eslint/no-unused-vars
              r, // <numeric>
              rp, // %         (optional)
              f1, // ,         (optional)
              g, // <numeric>
              gp, // %         (optional)
              f2, // ,         (optional)
              b, // <numeric>
              bp, // %         (optional)
              f3, // ,|/       (optional)
              a, // <numeric> (optional)
              ap, // %         (optional)
              ] = rgbMatch;
              const argFormat = [f1 || ' ', f2 || ' ', f3].join('');
              if (argFormat === '  ' ||
                  argFormat === '  /' ||
                  argFormat === ',,' ||
                  argFormat === ',,,') {
                  const valFormat = [rp, gp, bp].join('');
                  const maxValue = (valFormat === '%%%') ? 100 :
                      (valFormat === '') ? 255 : 0;
                  if (maxValue) {
                      const rgba = [
                          clamp(+r / maxValue, 0, 1),
                          clamp(+g / maxValue, 0, 1),
                          clamp(+b / maxValue, 0, 1),
                          a ? parseAlpha(+a, ap) : 1,
                      ];
                      if (validateNumbers(rgba)) {
                          return rgba;
                      }
                      // invalid numbers
                  }
                  // values must be all numbers or all percentages
              }
              return; // comma optional syntax requires no commas at all
          }
      }
      // hsl(120 50% 80%), hsla(120deg,50%,80%,.9), hsl(12e1 50% 80% / 90%)
      const hslRegExp = /^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/;
      const hslMatch = input.match(hslRegExp);
      if (hslMatch) {
          const [_, // eslint-disable-line @typescript-eslint/no-unused-vars
          h, // <numeric>
          f1, // ,         (optional)
          s, // <numeric>
          f2, // ,         (optional)
          l, // <numeric>
          f3, // ,|/       (optional)
          a, // <numeric> (optional)
          ap, // %         (optional)
          ] = hslMatch;
          const argFormat = [f1 || ' ', f2 || ' ', f3].join('');
          if (argFormat === '  ' ||
              argFormat === '  /' ||
              argFormat === ',,' ||
              argFormat === ',,,') {
              const hsla = [
                  +h,
                  clamp(+s, 0, 100),
                  clamp(+l, 0, 100),
                  a ? parseAlpha(+a, ap) : 1,
              ];
              if (validateNumbers(hsla)) {
                  return hslToRgb(hsla);
              }
              // invalid numbers
          }
          // comma optional syntax requires no commas at all
      }
  }
  function parseHex(hex) {
      return parseInt(hex.padEnd(2, hex), 16) / 255;
  }
  function parseAlpha(a, asPercentage) {
      return clamp(asPercentage ? (a / 100) : a, 0, 1);
  }
  function clamp(n, min, max) {
      return Math.min(Math.max(min, n), max);
  }
  /**
   * The regular expression for numeric values is not super specific, and it may
   * happen that it will accept a value that is not a valid number. In order to
   * detect and eliminate such values this function exists.
   *
   * @param array Array of uncertain numbers.
   * @returns `true` if the specified array contains only valid numbers, `false` otherwise.
   */
  function validateNumbers(array) {
      return !array.some(Number.isNaN);
  }
  /**
   * To generate:
   * - visit {@link https://www.w3.org/TR/css-color-4/#named-colors}
   * - run in the console:
   * @example
   * copy(`{\n${[...document.querySelector('.named-color-table tbody').children].map((tr) => `${tr.cells[2].textContent.trim()}: [${tr.cells[4].textContent.trim().split(/\s+/).join(', ')}],`).join('\n')}\n}`);
   */
  const namedColors = {
      aliceblue: [240, 248, 255],
      antiquewhite: [250, 235, 215],
      aqua: [0, 255, 255],
      aquamarine: [127, 255, 212],
      azure: [240, 255, 255],
      beige: [245, 245, 220],
      bisque: [255, 228, 196],
      black: [0, 0, 0],
      blanchedalmond: [255, 235, 205],
      blue: [0, 0, 255],
      blueviolet: [138, 43, 226],
      brown: [165, 42, 42],
      burlywood: [222, 184, 135],
      cadetblue: [95, 158, 160],
      chartreuse: [127, 255, 0],
      chocolate: [210, 105, 30],
      coral: [255, 127, 80],
      cornflowerblue: [100, 149, 237],
      cornsilk: [255, 248, 220],
      crimson: [220, 20, 60],
      cyan: [0, 255, 255],
      darkblue: [0, 0, 139],
      darkcyan: [0, 139, 139],
      darkgoldenrod: [184, 134, 11],
      darkgray: [169, 169, 169],
      darkgreen: [0, 100, 0],
      darkgrey: [169, 169, 169],
      darkkhaki: [189, 183, 107],
      darkmagenta: [139, 0, 139],
      darkolivegreen: [85, 107, 47],
      darkorange: [255, 140, 0],
      darkorchid: [153, 50, 204],
      darkred: [139, 0, 0],
      darksalmon: [233, 150, 122],
      darkseagreen: [143, 188, 143],
      darkslateblue: [72, 61, 139],
      darkslategray: [47, 79, 79],
      darkslategrey: [47, 79, 79],
      darkturquoise: [0, 206, 209],
      darkviolet: [148, 0, 211],
      deeppink: [255, 20, 147],
      deepskyblue: [0, 191, 255],
      dimgray: [105, 105, 105],
      dimgrey: [105, 105, 105],
      dodgerblue: [30, 144, 255],
      firebrick: [178, 34, 34],
      floralwhite: [255, 250, 240],
      forestgreen: [34, 139, 34],
      fuchsia: [255, 0, 255],
      gainsboro: [220, 220, 220],
      ghostwhite: [248, 248, 255],
      gold: [255, 215, 0],
      goldenrod: [218, 165, 32],
      gray: [128, 128, 128],
      green: [0, 128, 0],
      greenyellow: [173, 255, 47],
      grey: [128, 128, 128],
      honeydew: [240, 255, 240],
      hotpink: [255, 105, 180],
      indianred: [205, 92, 92],
      indigo: [75, 0, 130],
      ivory: [255, 255, 240],
      khaki: [240, 230, 140],
      lavender: [230, 230, 250],
      lavenderblush: [255, 240, 245],
      lawngreen: [124, 252, 0],
      lemonchiffon: [255, 250, 205],
      lightblue: [173, 216, 230],
      lightcoral: [240, 128, 128],
      lightcyan: [224, 255, 255],
      lightgoldenrodyellow: [250, 250, 210],
      lightgray: [211, 211, 211],
      lightgreen: [144, 238, 144],
      lightgrey: [211, 211, 211],
      lightpink: [255, 182, 193],
      lightsalmon: [255, 160, 122],
      lightseagreen: [32, 178, 170],
      lightskyblue: [135, 206, 250],
      lightslategray: [119, 136, 153],
      lightslategrey: [119, 136, 153],
      lightsteelblue: [176, 196, 222],
      lightyellow: [255, 255, 224],
      lime: [0, 255, 0],
      limegreen: [50, 205, 50],
      linen: [250, 240, 230],
      magenta: [255, 0, 255],
      maroon: [128, 0, 0],
      mediumaquamarine: [102, 205, 170],
      mediumblue: [0, 0, 205],
      mediumorchid: [186, 85, 211],
      mediumpurple: [147, 112, 219],
      mediumseagreen: [60, 179, 113],
      mediumslateblue: [123, 104, 238],
      mediumspringgreen: [0, 250, 154],
      mediumturquoise: [72, 209, 204],
      mediumvioletred: [199, 21, 133],
      midnightblue: [25, 25, 112],
      mintcream: [245, 255, 250],
      mistyrose: [255, 228, 225],
      moccasin: [255, 228, 181],
      navajowhite: [255, 222, 173],
      navy: [0, 0, 128],
      oldlace: [253, 245, 230],
      olive: [128, 128, 0],
      olivedrab: [107, 142, 35],
      orange: [255, 165, 0],
      orangered: [255, 69, 0],
      orchid: [218, 112, 214],
      palegoldenrod: [238, 232, 170],
      palegreen: [152, 251, 152],
      paleturquoise: [175, 238, 238],
      palevioletred: [219, 112, 147],
      papayawhip: [255, 239, 213],
      peachpuff: [255, 218, 185],
      peru: [205, 133, 63],
      pink: [255, 192, 203],
      plum: [221, 160, 221],
      powderblue: [176, 224, 230],
      purple: [128, 0, 128],
      rebeccapurple: [102, 51, 153],
      red: [255, 0, 0],
      rosybrown: [188, 143, 143],
      royalblue: [65, 105, 225],
      saddlebrown: [139, 69, 19],
      salmon: [250, 128, 114],
      sandybrown: [244, 164, 96],
      seagreen: [46, 139, 87],
      seashell: [255, 245, 238],
      sienna: [160, 82, 45],
      silver: [192, 192, 192],
      skyblue: [135, 206, 235],
      slateblue: [106, 90, 205],
      slategray: [112, 128, 144],
      slategrey: [112, 128, 144],
      snow: [255, 250, 250],
      springgreen: [0, 255, 127],
      steelblue: [70, 130, 180],
      tan: [210, 180, 140],
      teal: [0, 128, 128],
      thistle: [216, 191, 216],
      tomato: [255, 99, 71],
      turquoise: [64, 224, 208],
      violet: [238, 130, 238],
      wheat: [245, 222, 179],
      white: [255, 255, 255],
      whitesmoke: [245, 245, 245],
      yellow: [255, 255, 0],
      yellowgreen: [154, 205, 50],
  };

  function interpolateNumber(from, to, t) {
      return from + t * (to - from);
  }
  function interpolateArray(from, to, t) {
      return from.map((d, i) => {
          return interpolateNumber(d, to[i], t);
      });
  }
  /**
   * Color representation used by WebGL.
   * Defined in sRGB color space and pre-blended with alpha.
   * @private
   */
  class Color {
      /**
       * @param r Red component premultiplied by `alpha` 0..1
       * @param g Green component premultiplied by `alpha` 0..1
       * @param b Blue component premultiplied by `alpha` 0..1
       * @param [alpha=1] Alpha component 0..1
       * @param [premultiplied=true] Whether the `r`, `g` and `b` values have already
       * been multiplied by alpha. If `true` nothing happens if `false` then they will
       * be multiplied automatically.
       */
      constructor(r, g, b, alpha = 1, premultiplied = true) {
          this.r = r;
          this.g = g;
          this.b = b;
          this.a = alpha;
          if (!premultiplied) {
              this.r *= alpha;
              this.g *= alpha;
              this.b *= alpha;
              if (!alpha) {
                  // alpha = 0 erases completely rgb channels. This behavior is not desirable
                  // if this particular color is later used in color interpolation.
                  // Because of that, a reference to original color is saved.
                  this.overwriteGetter('rgb', [r, g, b, alpha]);
              }
          }
      }
      /**
       * Parses CSS color strings and converts colors to sRGB color space if needed.
       * Officially supported color formats:
       * - keyword, e.g. 'aquamarine' or 'steelblue'
       * - hex (with 3, 4, 6 or 8 digits), e.g. '#f0f' or '#e9bebea9'
       * - rgb and rgba, e.g. 'rgb(0,240,120)' or 'rgba(0%,94%,47%,0.1)' or 'rgb(0 240 120 / .3)'
       * - hsl and hsla, e.g. 'hsl(0,0%,83%)' or 'hsla(0,0%,83%,.5)' or 'hsl(0 0% 83% / 20%)'
       *
       * @param input CSS color string to parse.
       * @returns A `Color` instance, or `undefined` if the input is not a valid color string.
       */
      static parse(input) {
          // in zoom-and-property function input could be an instance of Color class
          if (input instanceof Color) {
              return input;
          }
          if (typeof input !== 'string') {
              return;
          }
          const rgba = parseCssColor(input);
          if (rgba) {
              return new Color(...rgba, false);
          }
      }
      /**
       * Used in color interpolation and by 'to-rgba' expression.
       *
       * @returns Gien color, with reversed alpha blending, in sRGB color space.
       */
      get rgb() {
          const { r, g, b, a } = this;
          const f = a || Infinity; // reverse alpha blending factor
          return this.overwriteGetter('rgb', [r / f, g / f, b / f, a]);
      }
      /**
       * Used in color interpolation.
       *
       * @returns Gien color, with reversed alpha blending, in HCL color space.
       */
      get hcl() {
          return this.overwriteGetter('hcl', rgbToHcl(this.rgb));
      }
      /**
       * Used in color interpolation.
       *
       * @returns Gien color, with reversed alpha blending, in LAB color space.
       */
      get lab() {
          return this.overwriteGetter('lab', rgbToLab(this.rgb));
      }
      /**
       * Lazy getter pattern. When getter is called for the first time lazy value
       * is calculated and then overwrites getter function in given object instance.
       *
       * @example:
       * const redColor = Color.parse('red');
       * let x = redColor.hcl; // this will invoke `get hcl()`, which will calculate
       * // the value of red in HCL space and invoke this `overwriteGetter` function
       * // which in turn will set a field with a key 'hcl' in the `redColor` object.
       * // In other words it will override `get hcl()` from its `Color` prototype
       * // with its own property: hcl = [calculated red value in hcl].
       * let y = redColor.hcl; // next call will no longer invoke getter but simply
       * // return the previously calculated value
       * x === y; // true - `x` is exactly the same object as `y`
       *
       * @param getterKey Getter key
       * @param lazyValue Lazily calculated value to be memoized by current instance
       * @private
       */
      overwriteGetter(getterKey, lazyValue) {
          Object.defineProperty(this, getterKey, { value: lazyValue });
          return lazyValue;
      }
      /**
       * Used by 'to-string' expression.
       *
       * @returns Serialized color in format `rgba(r,g,b,a)`
       * where r,g,b are numbers within 0..255 and alpha is number within 1..0
       *
       * @example
       * var purple = new Color.parse('purple');
       * purple.toString; // = "rgba(128,0,128,1)"
       * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');
       * translucentGreen.toString(); // = "rgba(26,207,26,0.73)"
       */
      toString() {
          const [r, g, b, a] = this.rgb;
          return `rgba(${[r, g, b].map(n => Math.round(n * 255)).join(',')},${a})`;
      }
      static interpolate(from, to, t, spaceKey = 'rgb') {
          switch (spaceKey) {
              case 'rgb': {
                  const [r, g, b, alpha] = interpolateArray(from.rgb, to.rgb, t);
                  return new Color(r, g, b, alpha, false);
              }
              case 'hcl': {
                  const [hue0, chroma0, light0, alphaF] = from.hcl;
                  const [hue1, chroma1, light1, alphaT] = to.hcl;
                  // https://github.com/gka/chroma.js/blob/cd1b3c0926c7a85cbdc3b1453b3a94006de91a92/src/interpolator/_hsx.js
                  let hue, chroma;
                  if (!isNaN(hue0) && !isNaN(hue1)) {
                      let dh = hue1 - hue0;
                      if (hue1 > hue0 && dh > 180) {
                          dh -= 360;
                      }
                      else if (hue1 < hue0 && hue0 - hue1 > 180) {
                          dh += 360;
                      }
                      hue = hue0 + t * dh;
                  }
                  else if (!isNaN(hue0)) {
                      hue = hue0;
                      if (light1 === 1 || light1 === 0)
                          chroma = chroma0;
                  }
                  else if (!isNaN(hue1)) {
                      hue = hue1;
                      if (light0 === 1 || light0 === 0)
                          chroma = chroma1;
                  }
                  else {
                      hue = NaN;
                  }
                  const [r, g, b, alpha] = hclToRgb([
                      hue,
                      chroma !== null && chroma !== void 0 ? chroma : interpolateNumber(chroma0, chroma1, t),
                      interpolateNumber(light0, light1, t),
                      interpolateNumber(alphaF, alphaT, t),
                  ]);
                  return new Color(r, g, b, alpha, false);
              }
              case 'lab': {
                  const [r, g, b, alpha] = labToRgb(interpolateArray(from.lab, to.lab, t));
                  return new Color(r, g, b, alpha, false);
              }
          }
      }
  }
  Color.black = new Color(0, 0, 0, 1);
  Color.white = new Color(1, 1, 1, 1);
  Color.transparent = new Color(0, 0, 0, 0);
  Color.red = new Color(1, 0, 0, 1);

  // Flow type declarations for Intl cribbed from
  // https://github.com/facebook/flow/issues/1270
  class Collator {
      constructor(caseSensitive, diacriticSensitive, locale) {
          if (caseSensitive)
              this.sensitivity = diacriticSensitive ? 'variant' : 'case';
          else
              this.sensitivity = diacriticSensitive ? 'accent' : 'base';
          this.locale = locale;
          this.collator = new Intl.Collator(this.locale ? this.locale : [], { sensitivity: this.sensitivity, usage: 'search' });
      }
      compare(lhs, rhs) {
          return this.collator.compare(lhs, rhs);
      }
      resolvedLocale() {
          // We create a Collator without "usage: search" because we don't want
          // the search options encoded in our result (e.g. "en-u-co-search")
          return new Intl.Collator(this.locale ? this.locale : [])
              .resolvedOptions().locale;
      }
  }

  const VERTICAL_ALIGN_OPTIONS = ['bottom', 'center', 'top'];
  class FormattedSection {
      constructor(text, image, scale, fontStack, textColor, verticalAlign) {
          this.text = text;
          this.image = image;
          this.scale = scale;
          this.fontStack = fontStack;
          this.textColor = textColor;
          this.verticalAlign = verticalAlign;
      }
  }
  class Formatted {
      constructor(sections) {
          this.sections = sections;
      }
      static fromString(unformatted) {
          return new Formatted([new FormattedSection(unformatted, null, null, null, null, null)]);
      }
      isEmpty() {
          if (this.sections.length === 0)
              return true;
          return !this.sections.some(section => section.text.length !== 0 ||
              (section.image && section.image.name.length !== 0));
      }
      static factory(text) {
          if (text instanceof Formatted) {
              return text;
          }
          else {
              return Formatted.fromString(text);
          }
      }
      toString() {
          if (this.sections.length === 0)
              return '';
          return this.sections.map(section => section.text).join('');
      }
  }

  /**
   * A set of four numbers representing padding around a box. Create instances from
   * bare arrays or numeric values using the static method `Padding.parse`.
   * @private
   */
  class Padding {
      constructor(values) {
          this.values = values.slice();
      }
      /**
       * Numeric padding values
       * @param input A padding value
       * @returns A `Padding` instance, or `undefined` if the input is not a valid padding value.
       */
      static parse(input) {
          if (input instanceof Padding) {
              return input;
          }
          // Backwards compatibility: bare number is treated the same as array with single value.
          // Padding applies to all four sides.
          if (typeof input === 'number') {
              return new Padding([input, input, input, input]);
          }
          if (!Array.isArray(input)) {
              return undefined;
          }
          if (input.length < 1 || input.length > 4) {
              return undefined;
          }
          for (const val of input) {
              if (typeof val !== 'number') {
                  return undefined;
              }
          }
          // Expand shortcut properties into explicit 4-sided values
          switch (input.length) {
              case 1:
                  input = [input[0], input[0], input[0], input[0]];
                  break;
              case 2:
                  input = [input[0], input[1], input[0], input[1]];
                  break;
              case 3:
                  input = [input[0], input[1], input[2], input[1]];
                  break;
          }
          return new Padding(input);
      }
      toString() {
          return JSON.stringify(this.values);
      }
      static interpolate(from, to, t) {
          return new Padding(interpolateArray(from.values, to.values, t));
      }
  }

  /**
   * An array of numbers. Create instances from
   * bare arrays or numeric values using the static method `NumberArray.parse`.
   * @private
   */
  class NumberArray {
      constructor(values) {
          this.values = values.slice();
      }
      /**
       * Numeric NumberArray values
       * @param input A NumberArray value
       * @returns A `NumberArray` instance, or `undefined` if the input is not a valid NumberArray value.
       */
      static parse(input) {
          if (input instanceof NumberArray) {
              return input;
          }
          // Backwards compatibility (e.g. hillshade-illumination-direction): bare number is treated the same as array with single value.
          if (typeof input === 'number') {
              return new NumberArray([input]);
          }
          if (!Array.isArray(input)) {
              return undefined;
          }
          for (const val of input) {
              if (typeof val !== 'number') {
                  return undefined;
              }
          }
          return new NumberArray(input);
      }
      toString() {
          return JSON.stringify(this.values);
      }
      static interpolate(from, to, t) {
          return new NumberArray(interpolateArray(from.values, to.values, t));
      }
  }

  /**
   * An array of colors. Create instances from
   * bare arrays or strings using the static method `ColorArray.parse`.
   * @private
   */
  class ColorArray {
      constructor(values) {
          this.values = values.slice();
      }
      /**
       * ColorArray values
       * @param input A ColorArray value
       * @returns A `ColorArray` instance, or `undefined` if the input is not a valid ColorArray value.
       */
      static parse(input) {
          if (input instanceof ColorArray) {
              return input;
          }
          // Backwards compatibility (e.g. hillshade-shadow-color): bare Color is treated the same as array with single value.
          if (typeof input === 'string') {
              const parsed_val = Color.parse(input);
              if (!parsed_val) {
                  return undefined;
              }
              return new ColorArray([parsed_val]);
          }
          if (!Array.isArray(input)) {
              return undefined;
          }
          const colors = [];
          for (const val of input) {
              if (typeof val !== 'string') {
                  return undefined;
              }
              const parsed_val = Color.parse(val);
              if (!parsed_val) {
                  return undefined;
              }
              colors.push(parsed_val);
          }
          return new ColorArray(colors);
      }
      toString() {
          return JSON.stringify(this.values);
      }
      static interpolate(from, to, t, spaceKey = 'rgb') {
          const colors = [];
          if (from.values.length != to.values.length) {
              throw new Error(`colorArray: Arrays have mismatched length (${from.values.length} vs. ${to.values.length}), cannot interpolate.`);
          }
          for (let i = 0; i < from.values.length; i++) {
              colors.push(Color.interpolate(from.values[i], to.values[i], t, spaceKey));
          }
          return new ColorArray(colors);
      }
  }

  class RuntimeError extends Error {
      constructor(message) {
          super(message);
          this.name = 'RuntimeError';
      }
      toJSON() {
          return this.message;
      }
  }

  /** Set of valid anchor positions, as a set for validation */
  const anchors = new Set(['center', 'left', 'right', 'top', 'bottom', 'top-left', 'top-right', 'bottom-left', 'bottom-right']);
  /**
   * Utility class to assist managing values for text-variable-anchor-offset property. Create instances from
   * bare arrays using the static method `VariableAnchorOffsetCollection.parse`.
   * @private
   */
  class VariableAnchorOffsetCollection {
      constructor(values) {
          this.values = values.slice();
      }
      static parse(input) {
          if (input instanceof VariableAnchorOffsetCollection) {
              return input;
          }
          if (!Array.isArray(input) ||
              input.length < 1 ||
              input.length % 2 !== 0) {
              return undefined;
          }
          for (let i = 0; i < input.length; i += 2) {
              // Elements in even positions should be anchor positions; Elements in odd positions should be offset values
              const anchorValue = input[i];
              const offsetValue = input[i + 1];
              if (typeof anchorValue !== 'string' || !anchors.has(anchorValue)) {
                  return undefined;
              }
              if (!Array.isArray(offsetValue) || offsetValue.length !== 2 || typeof offsetValue[0] !== 'number' || typeof offsetValue[1] !== 'number') {
                  return undefined;
              }
          }
          return new VariableAnchorOffsetCollection(input);
      }
      toString() {
          return JSON.stringify(this.values);
      }
      static interpolate(from, to, t) {
          const fromValues = from.values;
          const toValues = to.values;
          if (fromValues.length !== toValues.length) {
              throw new RuntimeError(`Cannot interpolate values of different length. from: ${from.toString()}, to: ${to.toString()}`);
          }
          const output = [];
          for (let i = 0; i < fromValues.length; i += 2) {
              // Anchor entries must match
              if (fromValues[i] !== toValues[i]) {
                  throw new RuntimeError(`Cannot interpolate values containing mismatched anchors. from[${i}]: ${fromValues[i]}, to[${i}]: ${toValues[i]}`);
              }
              output.push(fromValues[i]);
              // Interpolate the offset values for each anchor
              const [fx, fy] = fromValues[i + 1];
              const [tx, ty] = toValues[i + 1];
              output.push([interpolateNumber(fx, tx, t), interpolateNumber(fy, ty, t)]);
          }
          return new VariableAnchorOffsetCollection(output);
      }
  }

  class ResolvedImage {
      constructor(options) {
          this.name = options.name;
          this.available = options.available;
      }
      toString() {
          return this.name;
      }
      static fromString(name) {
          if (!name)
              return null; // treat empty values as no image
          return new ResolvedImage({ name, available: false });
      }
  }

  class ProjectionDefinition {
      constructor(from, to, transition) {
          this.from = from;
          this.to = to;
          this.transition = transition;
      }
      static interpolate(from, to, t) {
          return new ProjectionDefinition(from, to, t);
      }
      static parse(input) {
          if (input instanceof ProjectionDefinition) {
              return input;
          }
          if (Array.isArray(input) && input.length === 3 && typeof input[0] === 'string' && typeof input[1] === 'string' && typeof input[2] === 'number') {
              return new ProjectionDefinition(input[0], input[1], input[2]);
          }
          if (typeof input === 'object' && typeof input.from === 'string' && typeof input.to === 'string' && typeof input.transition === 'number') {
              return new ProjectionDefinition(input.from, input.to, input.transition);
          }
          if (typeof input === 'string') {
              return new ProjectionDefinition(input, input, 1);
          }
          return undefined;
      }
  }

  function validateRGBA(r, g, b, a) {
      if (!(typeof r === 'number' && r >= 0 && r <= 255 &&
          typeof g === 'number' && g >= 0 && g <= 255 &&
          typeof b === 'number' && b >= 0 && b <= 255)) {
          const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b];
          return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`;
      }
      if (!(typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1))) {
          return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;
      }
      return null;
  }
  function isValue(mixed) {
      if (mixed === null ||
          typeof mixed === 'string' ||
          typeof mixed === 'boolean' ||
          typeof mixed === 'number' ||
          mixed instanceof ProjectionDefinition ||
          mixed instanceof Color ||
          mixed instanceof Collator ||
          mixed instanceof Formatted ||
          mixed instanceof Padding ||
          mixed instanceof NumberArray ||
          mixed instanceof ColorArray ||
          mixed instanceof VariableAnchorOffsetCollection ||
          mixed instanceof ResolvedImage) {
          return true;
      }
      else if (Array.isArray(mixed)) {
          for (const item of mixed) {
              if (!isValue(item)) {
                  return false;
              }
          }
          return true;
      }
      else if (typeof mixed === 'object') {
          for (const key in mixed) {
              if (!isValue(mixed[key])) {
                  return false;
              }
          }
          return true;
      }
      else {
          return false;
      }
  }
  function typeOf(value) {
      if (value === null) {
          return NullType;
      }
      else if (typeof value === 'string') {
          return StringType;
      }
      else if (typeof value === 'boolean') {
          return BooleanType;
      }
      else if (typeof value === 'number') {
          return NumberType;
      }
      else if (value instanceof Color) {
          return ColorType;
      }
      else if (value instanceof ProjectionDefinition) {
          return ProjectionDefinitionType;
      }
      else if (value instanceof Collator) {
          return CollatorType;
      }
      else if (value instanceof Formatted) {
          return FormattedType;
      }
      else if (value instanceof Padding) {
          return PaddingType;
      }
      else if (value instanceof NumberArray) {
          return NumberArrayType;
      }
      else if (value instanceof ColorArray) {
          return ColorArrayType;
      }
      else if (value instanceof VariableAnchorOffsetCollection) {
          return VariableAnchorOffsetCollectionType;
      }
      else if (value instanceof ResolvedImage) {
          return ResolvedImageType;
      }
      else if (Array.isArray(value)) {
          const length = value.length;
          let itemType;
          for (const item of value) {
              const t = typeOf(item);
              if (!itemType) {
                  itemType = t;
              }
              else if (itemType === t) {
                  continue;
              }
              else {
                  itemType = ValueType;
                  break;
              }
          }
          return array(itemType || ValueType, length);
      }
      else {
          return ObjectType;
      }
  }
  function valueToString(value) {
      const type = typeof value;
      if (value === null) {
          return '';
      }
      else if (type === 'string' || type === 'number' || type === 'boolean') {
          return String(value);
      }
      else if (value instanceof Color || value instanceof ProjectionDefinition || value instanceof Formatted || value instanceof Padding || value instanceof NumberArray || value instanceof ColorArray || value instanceof VariableAnchorOffsetCollection || value instanceof ResolvedImage) {
          return value.toString();
      }
      else {
          return JSON.stringify(value);
      }
  }

  class Literal {
      constructor(type, value) {
          this.type = type;
          this.value = value;
      }
      static parse(args, context) {
          if (args.length !== 2)
              return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);
          if (!isValue(args[1]))
              return context.error('invalid value');
          const value = args[1];
          let type = typeOf(value);
          // special case: infer the item type if possible for zero-length arrays
          const expected = context.expectedType;
          if (type.kind === 'array' &&
              type.N === 0 &&
              expected &&
              expected.kind === 'array' &&
              (typeof expected.N !== 'number' || expected.N === 0)) {
              type = expected;
          }
          return new Literal(type, value);
      }
      evaluate() {
          return this.value;
      }
      eachChild() { }
      outputDefined() {
          return true;
      }
  }

  const types$1 = {
      string: StringType,
      number: NumberType,
      boolean: BooleanType,
      object: ObjectType
  };
  class Assertion {
      constructor(type, args) {
          this.type = type;
          this.args = args;
      }
      static parse(args, context) {
          if (args.length < 2)
              return context.error('Expected at least one argument.');
          let i = 1;
          let type;
          const name = args[0];
          if (name === 'array') {
              let itemType;
              if (args.length > 2) {
                  const type = args[1];
                  if (typeof type !== 'string' || !(type in types$1) || type === 'object')
                      return context.error('The item type argument of "array" must be one of string, number, boolean', 1);
                  itemType = types$1[type];
                  i++;
              }
              else {
                  itemType = ValueType;
              }
              let N;
              if (args.length > 3) {
                  if (args[2] !== null &&
                      (typeof args[2] !== 'number' ||
                          args[2] < 0 ||
                          args[2] !== Math.floor(args[2]))) {
                      return context.error('The length argument to "array" must be a positive integer literal', 2);
                  }
                  N = args[2];
                  i++;
              }
              type = array(itemType, N);
          }
          else {
              if (!types$1[name])
                  throw new Error(`Types doesn't contain name = ${name}`);
              type = types$1[name];
          }
          const parsed = [];
          for (; i < args.length; i++) {
              const input = context.parse(args[i], i, ValueType);
              if (!input)
                  return null;
              parsed.push(input);
          }
          return new Assertion(type, parsed);
      }
      evaluate(ctx) {
          for (let i = 0; i < this.args.length; i++) {
              const value = this.args[i].evaluate(ctx);
              const error = checkSubtype(this.type, typeOf(value));
              if (!error) {
                  return value;
              }
              else if (i === this.args.length - 1) {
                  throw new RuntimeError(`Expected value to be of type ${typeToString(this.type)}, but found ${typeToString(typeOf(value))} instead.`);
              }
          }
          throw new Error();
      }
      eachChild(fn) {
          this.args.forEach(fn);
      }
      outputDefined() {
          return this.args.every(arg => arg.outputDefined());
      }
  }

  const types$2 = {
      'to-boolean': BooleanType,
      'to-color': ColorType,
      'to-number': NumberType,
      'to-string': StringType
  };
  /**
   * Special form for error-coalescing coercion expressions "to-number",
   * "to-color".  Since these coercions can fail at runtime, they accept multiple
   * arguments, only evaluating one at a time until one succeeds.
   *
   * @private
   */
  class Coercion {
      constructor(type, args) {
          this.type = type;
          this.args = args;
      }
      static parse(args, context) {
          if (args.length < 2)
              return context.error('Expected at least one argument.');
          const name = args[0];
          if (!types$2[name])
              throw new Error(`Can't parse ${name} as it is not part of the known types`);
          if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)
              return context.error('Expected one argument.');
          const type = types$2[name];
          const parsed = [];
          for (let i = 1; i < args.length; i++) {
              const input = context.parse(args[i], i, ValueType);
              if (!input)
                  return null;
              parsed.push(input);
          }
          return new Coercion(type, parsed);
      }
      evaluate(ctx) {
          switch (this.type.kind) {
              case 'boolean':
                  return Boolean(this.args[0].evaluate(ctx));
              case 'color': {
                  let input;
                  let error;
                  for (const arg of this.args) {
                      input = arg.evaluate(ctx);
                      error = null;
                      if (input instanceof Color) {
                          return input;
                      }
                      else if (typeof input === 'string') {
                          const c = ctx.parseColor(input);
                          if (c)
                              return c;
                      }
                      else if (Array.isArray(input)) {
                          if (input.length < 3 || input.length > 4) {
                              error = `Invalid rgba value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;
                          }
                          else {
                              error = validateRGBA(input[0], input[1], input[2], input[3]);
                          }
                          if (!error) {
                              return new Color(input[0] / 255, input[1] / 255, input[2] / 255, input[3]);
                          }
                      }
                  }
                  throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
              }
              case 'padding': {
                  let input;
                  for (const arg of this.args) {
                      input = arg.evaluate(ctx);
                      const pad = Padding.parse(input);
                      if (pad) {
                          return pad;
                      }
                  }
                  throw new RuntimeError(`Could not parse padding from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
              }
              case 'numberArray': {
                  let input;
                  for (const arg of this.args) {
                      input = arg.evaluate(ctx);
                      const val = NumberArray.parse(input);
                      if (val) {
                          return val;
                      }
                  }
                  throw new RuntimeError(`Could not parse numberArray from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
              }
              case 'colorArray': {
                  let input;
                  for (const arg of this.args) {
                      input = arg.evaluate(ctx);
                      const val = ColorArray.parse(input);
                      if (val) {
                          return val;
                      }
                  }
                  throw new RuntimeError(`Could not parse colorArray from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
              }
              case 'variableAnchorOffsetCollection': {
                  let input;
                  for (const arg of this.args) {
                      input = arg.evaluate(ctx);
                      const coll = VariableAnchorOffsetCollection.parse(input);
                      if (coll) {
                          return coll;
                      }
                  }
                  throw new RuntimeError(`Could not parse variableAnchorOffsetCollection from value '${typeof input === 'string' ? input : JSON.stringify(input)}'`);
              }
              case 'number': {
                  let value = null;
                  for (const arg of this.args) {
                      value = arg.evaluate(ctx);
                      if (value === null)
                          return 0;
                      const num = Number(value);
                      if (isNaN(num))
                          continue;
                      return num;
                  }
                  throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);
              }
              case 'formatted':
                  // There is no explicit 'to-formatted' but this coercion can be implicitly
                  // created by properties that expect the 'formatted' type.
                  return Formatted.fromString(valueToString(this.args[0].evaluate(ctx)));
              case 'resolvedImage':
                  return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));
              case 'projectionDefinition':
                  return this.args[0].evaluate(ctx);
              default:
                  return valueToString(this.args[0].evaluate(ctx));
          }
      }
      eachChild(fn) {
          this.args.forEach(fn);
      }
      outputDefined() {
          return this.args.every(arg => arg.outputDefined());
      }
  }

  const geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];
  class EvaluationContext {
      constructor() {
          this.globals = null;
          this.feature = null;
          this.featureState = null;
          this.formattedSection = null;
          this._parseColorCache = new Map();
          this.availableImages = null;
          this.canonical = null;
      }
      id() {
          return this.feature && 'id' in this.feature ? this.feature.id : null;
      }
      geometryType() {
          return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;
      }
      geometry() {
          return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;
      }
      canonicalID() {
          return this.canonical;
      }
      properties() {
          return this.feature && this.feature.properties || {};
      }
      parseColor(input) {
          let cached = this._parseColorCache.get(input);
          if (!cached) {
              cached = Color.parse(input);
              this._parseColorCache.set(input, cached);
          }
          return cached;
      }
  }

  /**
   * State associated parsing at a given point in an expression tree.
   * @private
   */
  class ParsingContext {
      constructor(registry, isConstantFunc, path = [], expectedType, scope = new Scope(), errors = []) {
          this.registry = registry;
          this.path = path;
          this.key = path.map(part => `[${part}]`).join('');
          this.scope = scope;
          this.errors = errors;
          this.expectedType = expectedType;
          this._isConstant = isConstantFunc;
      }
      /**
       * @param expr the JSON expression to parse
       * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed
       * @param options
       * @param options.omitTypeAnnotations set true to omit inferred type annotations.  Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.
       * @private
       */
      parse(expr, index, expectedType, bindings, options = {}) {
          if (index) {
              return this.concat(index, expectedType, bindings)._parse(expr, options);
          }
          return this._parse(expr, options);
      }
      _parse(expr, options) {
          if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {
              expr = ['literal', expr];
          }
          function annotate(parsed, type, typeAnnotation) {
              if (typeAnnotation === 'assert') {
                  return new Assertion(type, [parsed]);
              }
              else if (typeAnnotation === 'coerce') {
                  return new Coercion(type, [parsed]);
              }
              else {
                  return parsed;
              }
          }
          if (Array.isArray(expr)) {
              if (expr.length === 0) {
                  return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');
              }
              const op = expr[0];
              if (typeof op !== 'string') {
                  this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use ["literal", [...]].`, 0);
                  return null;
              }
              const Expr = this.registry[op];
              if (Expr) {
                  let parsed = Expr.parse(expr, this);
                  if (!parsed)
                      return null;
                  if (this.expectedType) {
                      const expected = this.expectedType;
                      const actual = parsed.type;
                      // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.
                      // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.
                      // Otherwise, we do static type-checking.
                      //
                      // These behaviors are overridable for:
                      //   * The "coalesce" operator, which needs to omit type annotations.
                      //   * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.
                      //
                      if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {
                          parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');
                      }
                      else if (('projectionDefinition' === expected.kind && ['string', 'array'].includes(actual.kind)) ||
                          ((['color', 'formatted', 'resolvedImage'].includes(expected.kind)) && ['value', 'string'].includes(actual.kind)) ||
                          ((['padding', 'numberArray'].includes(expected.kind)) && ['value', 'number', 'array'].includes(actual.kind)) ||
                          ('colorArray' === expected.kind && ['value', 'string', 'array'].includes(actual.kind)) ||
                          ('variableAnchorOffsetCollection' === expected.kind && ['value', 'array'].includes(actual.kind))) {
                          parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');
                      }
                      else if (this.checkSubtype(expected, actual)) {
                          return null;
                      }
                  }
                  // If an expression's arguments are all literals, we can evaluate
                  // it immediately and replace it with a literal value in the
                  // parsed/compiled result. Expressions that expect an image should
                  // not be resolved here so we can later get the available images.
                  if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && this._isConstant(parsed)) {
                      const ec = new EvaluationContext();
                      try {
                          parsed = new Literal(parsed.type, parsed.evaluate(ec));
                      }
                      catch (e) {
                          this.error(e.message);
                          return null;
                      }
                  }
                  return parsed;
              }
              return this.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0);
          }
          else if (typeof expr === 'undefined') {
              return this.error('\'undefined\' value invalid. Use null instead.');
          }
          else if (typeof expr === 'object') {
              return this.error('Bare objects invalid. Use ["literal", {...}] instead.');
          }
          else {
              return this.error(`Expected an array, but found ${typeof expr} instead.`);
          }
      }
      /**
       * Returns a copy of this context suitable for parsing the subexpression at
       * index `index`, optionally appending to 'let' binding map.
       *
       * Note that `errors` property, intended for collecting errors while
       * parsing, is copied by reference rather than cloned.
       * @private
       */
      concat(index, expectedType, bindings) {
          const path = typeof index === 'number' ? this.path.concat(index) : this.path;
          const scope = bindings ? this.scope.concat(bindings) : this.scope;
          return new ParsingContext(this.registry, this._isConstant, path, expectedType || null, scope, this.errors);
      }
      /**
       * Push a parsing (or type checking) error into the `this.errors`
       * @param error The message
       * @param keys Optionally specify the source of the error at a child
       * of the current expression at `this.key`.
       * @private
       */
      error(error, ...keys) {
          const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;
          this.errors.push(new ExpressionParsingError(key, error));
      }
      /**
       * Returns null if `t` is a subtype of `expected`; otherwise returns an
       * error message and also pushes it to `this.errors`.
       * @param expected The expected type
       * @param t The actual type
       * @returns null if `t` is a subtype of `expected`; otherwise returns an error message
       */
      checkSubtype(expected, t) {
          const error = checkSubtype(expected, t);
          if (error)
              this.error(error);
          return error;
      }
  }

  class Let {
      constructor(bindings, result) {
          this.type = result.type;
          this.bindings = [].concat(bindings);
          this.result = result;
      }
      evaluate(ctx) {
          return this.result.evaluate(ctx);
      }
      eachChild(fn) {
          for (const binding of this.bindings) {
              fn(binding[1]);
          }
          fn(this.result);
      }
      static parse(args, context) {
          if (args.length < 4)
              return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);
          const bindings = [];
          for (let i = 1; i < args.length - 1; i += 2) {
              const name = args[i];
              if (typeof name !== 'string') {
                  return context.error(`Expected string, but found ${typeof name} instead.`, i);
              }
              if (/[^a-zA-Z0-9_]/.test(name)) {
                  return context.error('Variable names must contain only alphanumeric characters or \'_\'.', i);
              }
              const value = context.parse(args[i + 1], i + 1);
              if (!value)
                  return null;
              bindings.push([name, value]);
          }
          const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);
          if (!result)
              return null;
          return new Let(bindings, result);
      }
      outputDefined() {
          return this.result.outputDefined();
      }
  }

  class Var {
      constructor(name, boundExpression) {
          this.type = boundExpression.type;
          this.name = name;
          this.boundExpression = boundExpression;
      }
      static parse(args, context) {
          if (args.length !== 2 || typeof args[1] !== 'string')
              return context.error('\'var\' expression requires exactly one string literal argument.');
          const name = args[1];
          if (!context.scope.has(name)) {
              return context.error(`Unknown variable "${name}". Make sure "${name}" has been bound in an enclosing "let" expression before using it.`, 1);
          }
          return new Var(name, context.scope.get(name));
      }
      evaluate(ctx) {
          return this.boundExpression.evaluate(ctx);
      }
      eachChild() { }
      outputDefined() {
          return false;
      }
  }

  class At {
      constructor(type, index, input) {
          this.type = type;
          this.index = index;
          this.input = input;
      }
      static parse(args, context) {
          if (args.length !== 3)
              return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);
          const index = context.parse(args[1], 1, NumberType);
          const input = context.parse(args[2], 2, array(context.expectedType || ValueType));
          if (!index || !input)
              return null;
          const t = input.type;
          return new At(t.itemType, index, input);
      }
      evaluate(ctx) {
          const index = this.index.evaluate(ctx);
          const array = this.input.evaluate(ctx);
          if (index < 0) {
              throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);
          }
          if (index >= array.length) {
              throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);
          }
          if (index !== Math.floor(index)) {
              throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);
          }
          return array[index];
      }
      eachChild(fn) {
          fn(this.index);
          fn(this.input);
      }
      outputDefined() {
          return false;
      }
  }

  class In {
      constructor(needle, haystack) {
          this.type = BooleanType;
          this.needle = needle;
          this.haystack = haystack;
      }
      static parse(args, context) {
          if (args.length !== 3) {
              return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);
          }
          const needle = context.parse(args[1], 1, ValueType);
          const haystack = context.parse(args[2], 2, ValueType);
          if (!needle || !haystack)
              return null;
          if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {
              return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`);
          }
          return new In(needle, haystack);
      }
      evaluate(ctx) {
          const needle = this.needle.evaluate(ctx);
          const haystack = this.haystack.evaluate(ctx);
          if (!haystack)
              return false;
          if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {
              throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`);
          }
          if (!isValidNativeType(haystack, ['string', 'array'])) {
              throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`);
          }
          return haystack.indexOf(needle) >= 0;
      }
      eachChild(fn) {
          fn(this.needle);
          fn(this.haystack);
      }
      outputDefined() {
          return true;
      }
  }

  class IndexOf {
      constructor(needle, haystack, fromIndex) {
          this.type = NumberType;
          this.needle = needle;
          this.haystack = haystack;
          this.fromIndex = fromIndex;
      }
      static parse(args, context) {
          if (args.length <= 2 || args.length >= 5) {
              return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);
          }
          const needle = context.parse(args[1], 1, ValueType);
          const haystack = context.parse(args[2], 2, ValueType);
          if (!needle || !haystack)
              return null;
          if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {
              return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(needle.type)} instead`);
          }
          if (args.length === 4) {
              const fromIndex = context.parse(args[3], 3, NumberType);
              if (!fromIndex)
                  return null;
              return new IndexOf(needle, haystack, fromIndex);
          }
          else {
              return new IndexOf(needle, haystack);
          }
      }
      evaluate(ctx) {
          const needle = this.needle.evaluate(ctx);
          const haystack = this.haystack.evaluate(ctx);
          if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {
              throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${typeToString(typeOf(needle))} instead.`);
          }
          let fromIndex;
          if (this.fromIndex) {
              fromIndex = this.fromIndex.evaluate(ctx);
          }
          if (isValidNativeType(haystack, ['string'])) {
              const rawIndex = haystack.indexOf(needle, fromIndex);
              if (rawIndex === -1) {
                  return -1;
              }
              else {
                  // The index may be affected by surrogate pairs, so get the length of the preceding substring.
                  return [...haystack.slice(0, rawIndex)].length;
              }
          }
          else if (isValidNativeType(haystack, ['array'])) {
              return haystack.indexOf(needle, fromIndex);
          }
          else {
              throw new RuntimeError(`Expected second argument to be of type array or string, but found ${typeToString(typeOf(haystack))} instead.`);
          }
      }
      eachChild(fn) {
          fn(this.needle);
          fn(this.haystack);
          if (this.fromIndex) {
              fn(this.fromIndex);
          }
      }
      outputDefined() {
          return false;
      }
  }

  class Match {
      constructor(inputType, outputType, input, cases, outputs, otherwise) {
          this.inputType = inputType;
          this.type = outputType;
          this.input = input;
          this.cases = cases;
          this.outputs = outputs;
          this.otherwise = otherwise;
      }
      static parse(args, context) {
          if (args.length < 5)
              return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);
          if (args.length % 2 !== 1)
              return context.error('Expected an even number of arguments.');
          let inputType;
          let outputType;
          if (context.expectedType && context.expectedType.kind !== 'value') {
              outputType = context.expectedType;
          }
          const cases = {};
          const outputs = [];
          for (let i = 2; i < args.length - 1; i += 2) {
              let labels = args[i];
              const value = args[i + 1];
              if (!Array.isArray(labels)) {
                  labels = [labels];
              }
              const labelContext = context.concat(i);
              if (labels.length === 0) {
                  return labelContext.error('Expected at least one branch label.');
              }
              for (const label of labels) {
                  if (typeof label !== 'number' && typeof label !== 'string') {
                      return labelContext.error('Branch labels must be numbers or strings.');
                  }
                  else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {
                      return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);
                  }
                  else if (typeof label === 'number' && Math.floor(label) !== label) {
                      return labelContext.error('Numeric branch labels must be integer values.');
                  }
                  else if (!inputType) {
                      inputType = typeOf(label);
                  }
                  else if (labelContext.checkSubtype(inputType, typeOf(label))) {
                      return null;
                  }
                  if (typeof cases[String(label)] !== 'undefined') {
                      return labelContext.error('Branch labels must be unique.');
                  }
                  cases[String(label)] = outputs.length;
              }
              const result = context.parse(value, i, outputType);
              if (!result)
                  return null;
              outputType = outputType || result.type;
              outputs.push(result);
          }
          const input = context.parse(args[1], 1, ValueType);
          if (!input)
              return null;
          const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
          if (!otherwise)
              return null;
          if (input.type.kind !== 'value' && context.concat(1).checkSubtype(inputType, input.type)) {
              return null;
          }
          return new Match(inputType, outputType, input, cases, outputs, otherwise);
      }
      evaluate(ctx) {
          const input = this.input.evaluate(ctx);
          const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;
          return output.evaluate(ctx);
      }
      eachChild(fn) {
          fn(this.input);
          this.outputs.forEach(fn);
          fn(this.otherwise);
      }
      outputDefined() {
          return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();
      }
  }

  class Case {
      constructor(type, branches, otherwise) {
          this.type = type;
          this.branches = branches;
          this.otherwise = otherwise;
      }
      static parse(args, context) {
          if (args.length < 4)
              return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);
          if (args.length % 2 !== 0)
              return context.error('Expected an odd number of arguments.');
          let outputType;
          if (context.expectedType && context.expectedType.kind !== 'value') {
              outputType = context.expectedType;
          }
          const branches = [];
          for (let i = 1; i < args.length - 1; i += 2) {
              const test = context.parse(args[i], i, BooleanType);
              if (!test)
                  return null;
              const result = context.parse(args[i + 1], i + 1, outputType);
              if (!result)
                  return null;
              branches.push([test, result]);
              outputType = outputType || result.type;
          }
          const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);
          if (!otherwise)
              return null;
          if (!outputType)
              throw new Error('Can\'t infer output type');
          return new Case(outputType, branches, otherwise);
      }
      evaluate(ctx) {
          for (const [test, expression] of this.branches) {
              if (test.evaluate(ctx)) {
                  return expression.evaluate(ctx);
              }
          }
          return this.otherwise.evaluate(ctx);
      }
      eachChild(fn) {
          for (const [test, expression] of this.branches) {
              fn(test);
              fn(expression);
          }
          fn(this.otherwise);
      }
      outputDefined() {
          return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();
      }
  }

  class Slice {
      constructor(type, input, beginIndex, endIndex) {
          this.type = type;
          this.input = input;
          this.beginIndex = beginIndex;
          this.endIndex = endIndex;
      }
      static parse(args, context) {
          if (args.length <= 2 || args.length >= 5) {
              return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);
          }
          const input = context.parse(args[1], 1, ValueType);
          const beginIndex = context.parse(args[2], 2, NumberType);
          if (!input || !beginIndex)
              return null;
          if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) {
              return context.error(`Expected first argument to be of type array or string, but found ${typeToString(input.type)} instead`);
          }
          if (args.length === 4) {
              const endIndex = context.parse(args[3], 3, NumberType);
              if (!endIndex)
                  return null;
              return new Slice(input.type, input, beginIndex, endIndex);
          }
          else {
              return new Slice(input.type, input, beginIndex);
          }
      }
      evaluate(ctx) {
          const input = this.input.evaluate(ctx);
          const beginIndex = this.beginIndex.evaluate(ctx);
          let endIndex;
          if (this.endIndex) {
              endIndex = this.endIndex.evaluate(ctx);
          }
          if (isValidNativeType(input, ['string'])) {
              // Indices may be affected by surrogate pairs.
              return [...input].slice(beginIndex, endIndex).join('');
          }
          else if (isValidNativeType(input, ['array'])) {
              return input.slice(beginIndex, endIndex);
          }
          else {
              throw new RuntimeError(`Expected first argument to be of type array or string, but found ${typeToString(typeOf(input))} instead.`);
          }
      }
      eachChild(fn) {
          fn(this.input);
          fn(this.beginIndex);
          if (this.endIndex) {
              fn(this.endIndex);
          }
      }
      outputDefined() {
          return false;
      }
  }

  /**
   * Returns the index of the last stop <= input, or 0 if it doesn't exist.
   * @private
   */
  function findStopLessThanOrEqualTo(stops, input) {
      const lastIndex = stops.length - 1;
      let lowerIndex = 0;
      let upperIndex = lastIndex;
      let currentIndex = 0;
      let currentValue, nextValue;
      while (lowerIndex <= upperIndex) {
          currentIndex = Math.floor((lowerIndex + upperIndex) / 2);
          currentValue = stops[currentIndex];
          nextValue = stops[currentIndex + 1];
          if (currentValue <= input) {
              if (currentIndex === lastIndex || input < nextValue) { // Search complete
                  return currentIndex;
              }
              lowerIndex = currentIndex + 1;
          }
          else if (currentValue > input) {
              upperIndex = currentIndex - 1;
          }
          else {
              throw new RuntimeError('Input is not a number.');
          }
      }
      return 0;
  }

  class Step {
      constructor(type, input, stops) {
          this.type = type;
          this.input = input;
          this.labels = [];
          this.outputs = [];
          for (const [label, expression] of stops) {
              this.labels.push(label);
              this.outputs.push(expression);
          }
      }
      static parse(args, context) {
          if (args.length - 1 < 4) {
              return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);
          }
          if ((args.length - 1) % 2 !== 0) {
              return context.error('Expected an even number of arguments.');
          }
          const input = context.parse(args[1], 1, NumberType);
          if (!input)
              return null;
          const stops = [];
          let outputType = null;
          if (context.expectedType && context.expectedType.kind !== 'value') {
              outputType = context.expectedType;
          }
          for (let i = 1; i < args.length; i += 2) {
              const label = i === 1 ? -Infinity : args[i];
              const value = args[i + 1];
              const labelKey = i;
              const valueKey = i + 1;
              if (typeof label !== 'number') {
                  return context.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
              }
              if (stops.length && stops[stops.length - 1][0] >= label) {
                  return context.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', labelKey);
              }
              const parsed = context.parse(value, valueKey, outputType);
              if (!parsed)
                  return null;
              outputType = outputType || parsed.type;
              stops.push([label, parsed]);
          }
          return new Step(outputType, input, stops);
      }
      evaluate(ctx) {
          const labels = this.labels;
          const outputs = this.outputs;
          if (labels.length === 1) {
              return outputs[0].evaluate(ctx);
          }
          const value = this.input.evaluate(ctx);
          if (value <= labels[0]) {
              return outputs[0].evaluate(ctx);
          }
          const stopCount = labels.length;
          if (value >= labels[stopCount - 1]) {
              return outputs[stopCount - 1].evaluate(ctx);
          }
          const index = findStopLessThanOrEqualTo(labels, value);
          return outputs[index].evaluate(ctx);
      }
      eachChild(fn) {
          fn(this.input);
          for (const expression of this.outputs) {
              fn(expression);
          }
      }
      outputDefined() {
          return this.outputs.every(out => out.outputDefined());
      }
  }

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

  var unitbezier;
  var hasRequiredUnitbezier;

  function requireUnitbezier () {
  	if (hasRequiredUnitbezier) return unitbezier;
  	hasRequiredUnitbezier = 1;

  	unitbezier = UnitBezier;

  	function UnitBezier(p1x, p1y, p2x, p2y) {
  	    // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
  	    this.cx = 3.0 * p1x;
  	    this.bx = 3.0 * (p2x - p1x) - this.cx;
  	    this.ax = 1.0 - this.cx - this.bx;

  	    this.cy = 3.0 * p1y;
  	    this.by = 3.0 * (p2y - p1y) - this.cy;
  	    this.ay = 1.0 - this.cy - this.by;

  	    this.p1x = p1x;
  	    this.p1y = p1y;
  	    this.p2x = p2x;
  	    this.p2y = p2y;
  	}

  	UnitBezier.prototype = {
  	    sampleCurveX: function (t) {
  	        // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
  	        return ((this.ax * t + this.bx) * t + this.cx) * t;
  	    },

  	    sampleCurveY: function (t) {
  	        return ((this.ay * t + this.by) * t + this.cy) * t;
  	    },

  	    sampleCurveDerivativeX: function (t) {
  	        return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
  	    },

  	    solveCurveX: function (x, epsilon) {
  	        if (epsilon === undefined) epsilon = 1e-6;

  	        if (x < 0.0) return 0.0;
  	        if (x > 1.0) return 1.0;

  	        var t = x;

  	        // First try a few iterations of Newton's method - normally very fast.
  	        for (var i = 0; i < 8; i++) {
  	            var x2 = this.sampleCurveX(t) - x;
  	            if (Math.abs(x2) < epsilon) return t;

  	            var d2 = this.sampleCurveDerivativeX(t);
  	            if (Math.abs(d2) < 1e-6) break;

  	            t = t - x2 / d2;
  	        }

  	        // Fall back to the bisection method for reliability.
  	        var t0 = 0.0;
  	        var t1 = 1.0;
  	        t = x;

  	        for (i = 0; i < 20; i++) {
  	            x2 = this.sampleCurveX(t);
  	            if (Math.abs(x2 - x) < epsilon) break;

  	            if (x > x2) {
  	                t0 = t;
  	            } else {
  	                t1 = t;
  	            }

  	            t = (t1 - t0) * 0.5 + t0;
  	        }

  	        return t;
  	    },

  	    solve: function (x, epsilon) {
  	        return this.sampleCurveY(this.solveCurveX(x, epsilon));
  	    }
  	};
  	return unitbezier;
  }

  var unitbezierExports = requireUnitbezier();
  var UnitBezier = /*@__PURE__*/getDefaultExportFromCjs$1(unitbezierExports);

  class Interpolate {
      constructor(type, operator, interpolation, input, stops) {
          this.type = type;
          this.operator = operator;
          this.interpolation = interpolation;
          this.input = input;
          this.labels = [];
          this.outputs = [];
          for (const [label, expression] of stops) {
              this.labels.push(label);
              this.outputs.push(expression);
          }
      }
      static interpolationFactor(interpolation, input, lower, upper) {
          let t = 0;
          if (interpolation.name === 'exponential') {
              t = exponentialInterpolation(input, interpolation.base, lower, upper);
          }
          else if (interpolation.name === 'linear') {
              t = exponentialInterpolation(input, 1, lower, upper);
          }
          else if (interpolation.name === 'cubic-bezier') {
              const c = interpolation.controlPoints;
              const ub = new UnitBezier(c[0], c[1], c[2], c[3]);
              t = ub.solve(exponentialInterpolation(input, 1, lower, upper));
          }
          return t;
      }
      static parse(args, context) {
          let [operator, interpolation, input, ...rest] = args;
          if (!Array.isArray(interpolation) || interpolation.length === 0) {
              return context.error('Expected an interpolation type expression.', 1);
          }
          if (interpolation[0] === 'linear') {
              interpolation = { name: 'linear' };
          }
          else if (interpolation[0] === 'exponential') {
              const base = interpolation[1];
              if (typeof base !== 'number')
                  return context.error('Exponential interpolation requires a numeric base.', 1, 1);
              interpolation = {
                  name: 'exponential',
                  base
              };
          }
          else if (interpolation[0] === 'cubic-bezier') {
              const controlPoints = interpolation.slice(1);
              if (controlPoints.length !== 4 ||
                  controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)) {
                  return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);
              }
              interpolation = {
                  name: 'cubic-bezier',
                  controlPoints: controlPoints
              };
          }
          else {
              return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);
          }
          if (args.length - 1 < 4) {
              return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);
          }
          if ((args.length - 1) % 2 !== 0) {
              return context.error('Expected an even number of arguments.');
          }
          input = context.parse(input, 2, NumberType);
          if (!input)
              return null;
          const stops = [];
          let outputType = null;
          if ((operator === 'interpolate-hcl' || operator === 'interpolate-lab') && context.expectedType != ColorArrayType) {
              outputType = ColorType;
          }
          else if (context.expectedType && context.expectedType.kind !== 'value') {
              outputType = context.expectedType;
          }
          for (let i = 0; i < rest.length; i += 2) {
              const label = rest[i];
              const value = rest[i + 1];
              const labelKey = i + 3;
              const valueKey = i + 4;
              if (typeof label !== 'number') {
                  return context.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);
              }
              if (stops.length && stops[stops.length - 1][0] >= label) {
                  return context.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', labelKey);
              }
              const parsed = context.parse(value, valueKey, outputType);
              if (!parsed)
                  return null;
              outputType = outputType || parsed.type;
              stops.push([label, parsed]);
          }
          if (!verifyType(outputType, NumberType) &&
              !verifyType(outputType, ProjectionDefinitionType) &&
              !verifyType(outputType, ColorType) &&
              !verifyType(outputType, PaddingType) &&
              !verifyType(outputType, NumberArrayType) &&
              !verifyType(outputType, ColorArrayType) &&
              !verifyType(outputType, VariableAnchorOffsetCollectionType) &&
              !verifyType(outputType, array(NumberType))) {
              return context.error(`Type ${typeToString(outputType)} is not interpolatable.`);
          }
          return new Interpolate(outputType, operator, interpolation, input, stops);
      }
      evaluate(ctx) {
          const labels = this.labels;
          const outputs = this.outputs;
          if (labels.length === 1) {
              return outputs[0].evaluate(ctx);
          }
          const value = this.input.evaluate(ctx);
          if (value <= labels[0]) {
              return outputs[0].evaluate(ctx);
          }
          const stopCount = labels.length;
          if (value >= labels[stopCount - 1]) {
              return outputs[stopCount - 1].evaluate(ctx);
          }
          const index = findStopLessThanOrEqualTo(labels, value);
          const lower = labels[index];
          const upper = labels[index + 1];
          const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);
          const outputLower = outputs[index].evaluate(ctx);
          const outputUpper = outputs[index + 1].evaluate(ctx);
          switch (this.operator) {
              case 'interpolate':
                  switch (this.type.kind) {
                      case 'number':
                          return interpolateNumber(outputLower, outputUpper, t);
                      case 'color':
                          return Color.interpolate(outputLower, outputUpper, t);
                      case 'padding':
                          return Padding.interpolate(outputLower, outputUpper, t);
                      case 'colorArray':
                          return ColorArray.interpolate(outputLower, outputUpper, t);
                      case 'numberArray':
                          return NumberArray.interpolate(outputLower, outputUpper, t);
                      case 'variableAnchorOffsetCollection':
                          return VariableAnchorOffsetCollection.interpolate(outputLower, outputUpper, t);
                      case 'array':
                          return interpolateArray(outputLower, outputUpper, t);
                      case 'projectionDefinition':
                          return ProjectionDefinition.interpolate(outputLower, outputUpper, t);
                  }
              case 'interpolate-hcl':
                  switch (this.type.kind) {
                      case 'color':
                          return Color.interpolate(outputLower, outputUpper, t, 'hcl');
                      case 'colorArray':
                          return ColorArray.interpolate(outputLower, outputUpper, t, 'hcl');
                  }
              case 'interpolate-lab':
                  switch (this.type.kind) {
                      case 'color':
                          return Color.interpolate(outputLower, outputUpper, t, 'lab');
                      case 'colorArray':
                          return ColorArray.interpolate(outputLower, outputUpper, t, 'lab');
                  }
          }
      }
      eachChild(fn) {
          fn(this.input);
          for (const expression of this.outputs) {
              fn(expression);
          }
      }
      outputDefined() {
          return this.outputs.every(out => out.outputDefined());
      }
  }
  /**
   * Returns a ratio that can be used to interpolate between exponential function
   * stops.
   * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,
   * and `a` and `b` are constants affording sufficient degrees of freedom to fit
   * the function to the given stops.
   *
   * Here's a bit of algebra that lets us compute `f(x)` directly from the stop
   * values without explicitly solving for `a` and `b`:
   *
   * First stop value: `f(x0) = y0 = a * base^x0 + b`
   * Second stop value: `f(x1) = y1 = a * base^x1 + b`
   * => `y1 - y0 = a(base^x1 - base^x0)`
   * => `a = (y1 - y0)/(base^x1 - base^x0)`
   *
   * Desired value: `f(x) = y = a * base^x + b`
   * => `f(x) = y0 + a * (base^x - base^x0)`
   *
   * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a
   * little algebra:
   * ```
   * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)
   *                     = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)
   * ```
   *
   * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have
   * `f(x) = y0 + (y1 - y0) * ratio`.  In other words, `ratio` may be treated as
   * an interpolation factor between the two stops' output values.
   *
   * (Note: a slightly different form for `ratio`,
   * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer
   * expensive `Math.pow()` operations.)
   *
   * @private
  */
  function exponentialInterpolation(input, base, lowerValue, upperValue) {
      const difference = upperValue - lowerValue;
      const progress = input - lowerValue;
      if (difference === 0) {
          return 0;
      }
      else if (base === 1) {
          return progress / difference;
      }
      else {
          return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);
      }
  }

  class Coalesce {
      constructor(type, args) {
          this.type = type;
          this.args = args;
      }
      static parse(args, context) {
          if (args.length < 2) {
              return context.error('Expected at least one argument.');
          }
          let outputType = null;
          const expectedType = context.expectedType;
          if (expectedType && expectedType.kind !== 'value') {
              outputType = expectedType;
          }
          const parsedArgs = [];
          for (const arg of args.slice(1)) {
              const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, { typeAnnotation: 'omit' });
              if (!parsed)
                  return null;
              outputType = outputType || parsed.type;
              parsedArgs.push(parsed);
          }
          if (!outputType)
              throw new Error('No output type');
          // Above, we parse arguments without inferred type annotation so that
          // they don't produce a runtime error for `null` input, which would
          // preempt the desired null-coalescing behavior.
          // Thus, if any of our arguments would have needed an annotation, we
          // need to wrap the enclosing coalesce expression with it instead.
          const needsAnnotation = expectedType &&
              parsedArgs.some(arg => checkSubtype(expectedType, arg.type));
          return needsAnnotation ?
              new Coalesce(ValueType, parsedArgs) :
              new Coalesce(outputType, parsedArgs);
      }
      evaluate(ctx) {
          let result = null;
          let argCount = 0;
          let requestedImageName;
          for (const arg of this.args) {
              argCount++;
              result = arg.evaluate(ctx);
              // we need to keep track of the first requested image in a coalesce statement
              // if coalesce can't find a valid image, we return the first image name so styleimagemissing can fire
              if (result && result instanceof ResolvedImage && !result.available) {
                  if (!requestedImageName) {
                      requestedImageName = result.name;
                  }
                  result = null;
                  if (argCount === this.args.length) {
                      result = requestedImageName;
                  }
              }
              if (result !== null)
                  break;
          }
          return result;
      }
      eachChild(fn) {
          this.args.forEach(fn);
      }
      outputDefined() {
          return this.args.every(arg => arg.outputDefined());
      }
  }

  function isComparableType(op, type) {
      if (op === '==' || op === '!=') {
          // equality operator
          return type.kind === 'boolean' ||
              type.kind === 'string' ||
              type.kind === 'number' ||
              type.kind === 'null' ||
              type.kind === 'value';
      }
      else {
          // ordering operator
          return type.kind === 'string' ||
              type.kind === 'number' ||
              type.kind === 'value';
      }
  }
  function eq(ctx, a, b) { return a === b; }
  function neq(ctx, a, b) { return a !== b; }
  function lt(ctx, a, b) { return a < b; }
  function gt(ctx, a, b) { return a > b; }
  function lteq(ctx, a, b) { return a <= b; }
  function gteq(ctx, a, b) { return a >= b; }
  function eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; }
  function neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); }
  function ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; }
  function gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; }
  function lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; }
  function gteqCollate(ctx, a, b, c) { return c.compare(a, b) >= 0; }
  /**
   * Special form for comparison operators, implementing the signatures:
   * - (T, T, ?Collator) => boolean
   * - (T, value, ?Collator) => boolean
   * - (value, T, ?Collator) => boolean
   *
   * For inequalities, T must be either value, string, or number. For ==/!=, it
   * can also be boolean or null.
   *
   * Equality semantics are equivalent to Javascript's strict equality (===/!==)
   * -- i.e., when the arguments' types don't match, == evaluates to false, != to
   * true.
   *
   * When types don't match in an ordering comparison, a runtime error is thrown.
   *
   * @private
   */
  function makeComparison(op, compareBasic, compareWithCollator) {
      const isOrderComparison = op !== '==' && op !== '!=';
      return class Comparison {
          constructor(lhs, rhs, collator) {
              this.type = BooleanType;
              this.lhs = lhs;
              this.rhs = rhs;
              this.collator = collator;
              this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';
          }
          static parse(args, context) {
              if (args.length !== 3 && args.length !== 4)
                  return context.error('Expected two or three arguments.');
              const op = args[0];
              let lhs = context.parse(args[1], 1, ValueType);
              if (!lhs)
                  return null;
              if (!isComparableType(op, lhs.type)) {
                  return context.concat(1).error(`"${op}" comparisons are not supported for type '${typeToString(lhs.type)}'.`);
              }
              let rhs = context.parse(args[2], 2, ValueType);
              if (!rhs)
                  return null;
              if (!isComparableType(op, rhs.type)) {
                  return context.concat(2).error(`"${op}" comparisons are not supported for type '${typeToString(rhs.type)}'.`);
              }
              if (lhs.type.kind !== rhs.type.kind &&
                  lhs.type.kind !== 'value' &&
                  rhs.type.kind !== 'value') {
                  return context.error(`Cannot compare types '${typeToString(lhs.type)}' and '${typeToString(rhs.type)}'.`);
              }
              if (isOrderComparison) {
                  // typing rules specific to less/greater than operators
                  if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {
                      // (value, T)
                      lhs = new Assertion(rhs.type, [lhs]);
                  }
                  else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {
                      // (T, value)
                      rhs = new Assertion(lhs.type, [rhs]);
                  }
              }
              let collator = null;
              if (args.length === 4) {
                  if (lhs.type.kind !== 'string' &&
                      rhs.type.kind !== 'string' &&
                      lhs.type.kind !== 'value' &&
                      rhs.type.kind !== 'value') {
                      return context.error('Cannot use collator to compare non-string types.');
                  }
                  collator = context.parse(args[3], 3, CollatorType);
                  if (!collator)
                      return null;
              }
              return new Comparison(lhs, rhs, collator);
          }
          evaluate(ctx) {
              const lhs = this.lhs.evaluate(ctx);
              const rhs = this.rhs.evaluate(ctx);
              if (isOrderComparison && this.hasUntypedArgument) {
                  const lt = typeOf(lhs);
                  const rt = typeOf(rhs);
                  // check that type is string or number, and equal
                  if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {
                      throw new RuntimeError(`Expected arguments for "${op}" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`);
                  }
              }
              if (this.collator && !isOrderComparison && this.hasUntypedArgument) {
                  const lt = typeOf(lhs);
                  const rt = typeOf(rhs);
                  if (lt.kind !== 'string' || rt.kind !== 'string') {
                      return compareBasic(ctx, lhs, rhs);
                  }
              }
              return this.collator ?
                  compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :
                  compareBasic(ctx, lhs, rhs);
          }
          eachChild(fn) {
              fn(this.lhs);
              fn(this.rhs);
              if (this.collator) {
                  fn(this.collator);
              }
          }
          outputDefined() {
              return true;
          }
      };
  }
  const Equals = makeComparison('==', eq, eqCollate);
  const NotEquals = makeComparison('!=', neq, neqCollate);
  const LessThan$1 = makeComparison('<', lt, ltCollate);
  const GreaterThan$1 = makeComparison('>', gt, gtCollate);
  const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);
  const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);

  class CollatorExpression {
      constructor(caseSensitive, diacriticSensitive, locale) {
          this.type = CollatorType;
          this.locale = locale;
          this.caseSensitive = caseSensitive;
          this.diacriticSensitive = diacriticSensitive;
      }
      static parse(args, context) {
          if (args.length !== 2)
              return context.error('Expected one argument.');
          const options = args[1];
          if (typeof options !== 'object' || Array.isArray(options))
              return context.error('Collator options argument must be an object.');
          const caseSensitive = context.parse(options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);
          if (!caseSensitive)
              return null;
          const diacriticSensitive = context.parse(options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);
          if (!diacriticSensitive)
              return null;
          let locale = null;
          if (options['locale']) {
              locale = context.parse(options['locale'], 1, StringType);
              if (!locale)
                  return null;
          }
          return new CollatorExpression(caseSensitive, diacriticSensitive, locale);
      }
      evaluate(ctx) {
          return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);
      }
      eachChild(fn) {
          fn(this.caseSensitive);
          fn(this.diacriticSensitive);
          if (this.locale) {
              fn(this.locale);
          }
      }
      outputDefined() {
          // Technically the set of possible outputs is the combinatoric set of Collators produced
          // by all possible outputs of locale/caseSensitive/diacriticSensitive
          // But for the primary use of Collators in comparison operators, we ignore the Collator's
          // possible outputs anyway, so we can get away with leaving this false for now.
          return false;
      }
  }

  class NumberFormat {
      constructor(number, locale, currency, minFractionDigits, maxFractionDigits) {
          this.type = StringType;
          this.number = number;
          this.locale = locale;
          this.currency = currency;
          this.minFractionDigits = minFractionDigits;
          this.maxFractionDigits = maxFractionDigits;
      }
      static parse(args, context) {
          if (args.length !== 3)
              return context.error('Expected two arguments.');
          const number = context.parse(args[1], 1, NumberType);
          if (!number)
              return null;
          const options = args[2];
          if (typeof options !== 'object' || Array.isArray(options))
              return context.error('NumberFormat options argument must be an object.');
          let locale = null;
          if (options['locale']) {
              locale = context.parse(options['locale'], 1, StringType);
              if (!locale)
                  return null;
          }
          let currency = null;
          if (options['currency']) {
              currency = context.parse(options['currency'], 1, StringType);
              if (!currency)
                  return null;
          }
          let minFractionDigits = null;
          if (options['min-fraction-digits']) {
              minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);
              if (!minFractionDigits)
                  return null;
          }
          let maxFractionDigits = null;
          if (options['max-fraction-digits']) {
              maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);
              if (!maxFractionDigits)
                  return null;
          }
          return new NumberFormat(number, locale, currency, minFractionDigits, maxFractionDigits);
      }
      evaluate(ctx) {
          return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [], {
              style: this.currency ? 'currency' : 'decimal',
              currency: this.currency ? this.currency.evaluate(ctx) : undefined,
              minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,
              maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined,
          }).format(this.number.evaluate(ctx));
      }
      eachChild(fn) {
          fn(this.number);
          if (this.locale) {
              fn(this.locale);
          }
          if (this.currency) {
              fn(this.currency);
          }
          if (this.minFractionDigits) {
              fn(this.minFractionDigits);
          }
          if (this.maxFractionDigits) {
              fn(this.maxFractionDigits);
          }
      }
      outputDefined() {
          return false;
      }
  }

  class FormatExpression {
      constructor(sections) {
          this.type = FormattedType;
          this.sections = sections;
      }
      static parse(args, context) {
          if (args.length < 2) {
              return context.error('Expected at least one argument.');
          }
          const firstArg = args[1];
          if (!Array.isArray(firstArg) && typeof firstArg === 'object') {
              return context.error('First argument must be an image or text section.');
          }
          const sections = [];
          let nextTokenMayBeObject = false;
          for (let i = 1; i <= args.length - 1; ++i) {
              const arg = args[i];
              if (nextTokenMayBeObject && typeof arg === 'object' && !Array.isArray(arg)) {
                  nextTokenMayBeObject = false;
                  let scale = null;
                  if (arg['font-scale']) {
                      scale = context.parse(arg['font-scale'], 1, NumberType);
                      if (!scale)
                          return null;
                  }
                  let font = null;
                  if (arg['text-font']) {
                      font = context.parse(arg['text-font'], 1, array(StringType));
                      if (!font)
                          return null;
                  }
                  let textColor = null;
                  if (arg['text-color']) {
                      textColor = context.parse(arg['text-color'], 1, ColorType);
                      if (!textColor)
                          return null;
                  }
                  let verticalAlign = null;
                  if (arg['vertical-align']) {
                      if (typeof arg['vertical-align'] === 'string' && !VERTICAL_ALIGN_OPTIONS.includes(arg['vertical-align'])) {
                          return context.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${arg['vertical-align']}' instead.`);
                      }
                      verticalAlign = context.parse(arg['vertical-align'], 1, StringType);
                      if (!verticalAlign)
                          return null;
                  }
                  const lastExpression = sections[sections.length - 1];
                  lastExpression.scale = scale;
                  lastExpression.font = font;
                  lastExpression.textColor = textColor;
                  lastExpression.verticalAlign = verticalAlign;
              }
              else {
                  const content = context.parse(args[i], 1, ValueType);
                  if (!content)
                      return null;
                  const kind = content.type.kind;
                  if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')
                      return context.error('Formatted text type must be \'string\', \'value\', \'image\' or \'null\'.');
                  nextTokenMayBeObject = true;
                  sections.push({ content, scale: null, font: null, textColor: null, verticalAlign: null });
              }
          }
          return new FormatExpression(sections);
      }
      evaluate(ctx) {
          const evaluateSection = section => {
              const evaluatedContent = section.content.evaluate(ctx);
              if (typeOf(evaluatedContent) === ResolvedImageType) {
                  return new FormattedSection('', evaluatedContent, null, null, null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null);
              }
              return new FormattedSection(valueToString(evaluatedContent), null, section.scale ? section.scale.evaluate(ctx) : null, section.font ? section.font.evaluate(ctx).join(',') : null, section.textColor ? section.textColor.evaluate(ctx) : null, section.verticalAlign ? section.verticalAlign.evaluate(ctx) : null);
          };
          return new Formatted(this.sections.map(evaluateSection));
      }
      eachChild(fn) {
          for (const section of this.sections) {
              fn(section.content);
              if (section.scale) {
                  fn(section.scale);
              }
              if (section.font) {
                  fn(section.font);
              }
              if (section.textColor) {
                  fn(section.textColor);
              }
              if (section.verticalAlign) {
                  fn(section.verticalAlign);
              }
          }
      }
      outputDefined() {
          // Technically the combinatoric set of all children
          // Usually, this.text will be undefined anyway
          return false;
      }
  }

  class ImageExpression {
      constructor(input) {
          this.type = ResolvedImageType;
          this.input = input;
      }
      static parse(args, context) {
          if (args.length !== 2) {
              return context.error('Expected two arguments.');
          }
          const name = context.parse(args[1], 1, StringType);
          if (!name)
              return context.error('No image name provided.');
          return new ImageExpression(name);
      }
      evaluate(ctx) {
          const evaluatedImageName = this.input.evaluate(ctx);
          const value = ResolvedImage.fromString(evaluatedImageName);
          if (value && ctx.availableImages)
              value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;
          return value;
      }
      eachChild(fn) {
          fn(this.input);
      }
      outputDefined() {
          // The output of image is determined by the list of available images in the evaluation context
          return false;
      }
  }

  class Length {
      constructor(input) {
          this.type = NumberType;
          this.input = input;
      }
      static parse(args, context) {
          if (args.length !== 2)
              return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);
          const input = context.parse(args[1], 1);
          if (!input)
              return null;
          if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')
              return context.error(`Expected argument of type string or array, but found ${typeToString(input.type)} instead.`);
          return new Length(input);
      }
      evaluate(ctx) {
          const input = this.input.evaluate(ctx);
          if (typeof input === 'string') {
              // The length may be affected by surrogate pairs.
              return [...input].length;
          }
          else if (Array.isArray(input)) {
              return input.length;
          }
          else {
              throw new RuntimeError(`Expected value to be of type string or array, but found ${typeToString(typeOf(input))} instead.`);
          }
      }
      eachChild(fn) {
          fn(this.input);
      }
      outputDefined() {
          return false;
      }
  }

  const EXTENT = 8192;
  function getTileCoordinates(p, canonical) {
      const x = mercatorXfromLng(p[0]);
      const y = mercatorYfromLat(p[1]);
      const tilesAtZoom = Math.pow(2, canonical.z);
      return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];
  }
  function getLngLatFromTileCoord(coord, canonical) {
      const tilesAtZoom = Math.pow(2, canonical.z);
      const x = (coord[0] / EXTENT + canonical.x) / tilesAtZoom;
      const y = (coord[1] / EXTENT + canonical.y) / tilesAtZoom;
      return [lngFromMercatorXfromLng(x), latFromMercatorY(y)];
  }
  function mercatorXfromLng(lng) {
      return (180 + lng) / 360;
  }
  function lngFromMercatorXfromLng(mercatorX) {
      return mercatorX * 360 - 180;
  }
  function mercatorYfromLat(lat) {
      return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;
  }
  function latFromMercatorY(mercatorY) {
      return 360 / Math.PI * Math.atan(Math.exp((180 - mercatorY * 360) * Math.PI / 180)) - 90;
  }
  function updateBBox(bbox, coord) {
      bbox[0] = Math.min(bbox[0], coord[0]);
      bbox[1] = Math.min(bbox[1], coord[1]);
      bbox[2] = Math.max(bbox[2], coord[0]);
      bbox[3] = Math.max(bbox[3], coord[1]);
  }
  function boxWithinBox(bbox1, bbox2) {
      if (bbox1[0] <= bbox2[0])
          return false;
      if (bbox1[2] >= bbox2[2])
          return false;
      if (bbox1[1] <= bbox2[1])
          return false;
      if (bbox1[3] >= bbox2[3])
          return false;
      return true;
  }
  function rayIntersect(p, p1, p2) {
      return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);
  }
  function pointOnBoundary(p, p1, p2) {
      const x1 = p[0] - p1[0];
      const y1 = p[1] - p1[1];
      const x2 = p[0] - p2[0];
      const y2 = p[1] - p2[1];
      return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);
  }
  // a, b are end points for line segment1, c and d are end points for line segment2
  function segmentIntersectSegment(a, b, c, d) {
      // check if two segments are parallel or not
      // precondition is end point a, b is inside polygon, if line a->b is
      // parallel to polygon edge c->d, then a->b won't intersect with c->d
      const vectorP = [b[0] - a[0], b[1] - a[1]];
      const vectorQ = [d[0] - c[0], d[1] - c[1]];
      if (perp(vectorQ, vectorP) === 0)
          return false;
      // If lines are intersecting with each other, the relative location should be:
      // a and b lie in different sides of segment c->d
      // c and d lie in different sides of segment a->b
      if (twoSided(a, b, c, d) && twoSided(c, d, a, b))
          return true;
      return false;
  }
  function lineIntersectPolygon(p1, p2, polygon) {
      for (const ring of polygon) {
          // loop through every edge of the ring
          for (let j = 0; j < ring.length - 1; ++j) {
              if (segmentIntersectSegment(p1, p2, ring[j], ring[j + 1])) {
                  return true;
              }
          }
      }
      return false;
  }
  // ray casting algorithm for detecting if point is in polygon
  function pointWithinPolygon(point, rings, trueIfOnBoundary = false) {
      let inside = false;
      for (const ring of rings) {
          for (let j = 0; j < ring.length - 1; j++) {
              if (pointOnBoundary(point, ring[j], ring[j + 1]))
                  return trueIfOnBoundary;
              if (rayIntersect(point, ring[j], ring[j + 1]))
                  inside = !inside;
          }
      }
      return inside;
  }
  function pointWithinPolygons(point, polygons) {
      for (const polygon of polygons) {
          if (pointWithinPolygon(point, polygon))
              return true;
      }
      return false;
  }
  function lineStringWithinPolygon(line, polygon) {
      // First, check if geometry points of line segments are all inside polygon
      for (const point of line) {
          if (!pointWithinPolygon(point, polygon)) {
              return false;
          }
      }
      // Second, check if there is line segment intersecting polygon edge
      for (let i = 0; i < line.length - 1; ++i) {
          if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {
              return false;
          }
      }
      return true;
  }
  function lineStringWithinPolygons(line, polygons) {
      for (const polygon of polygons) {
          if (lineStringWithinPolygon(line, polygon))
              return true;
      }
      return false;
  }
  function perp(v1, v2) {
      return (v1[0] * v2[1] - v1[1] * v2[0]);
  }
  // check if p1 and p2 are in different sides of line segment q1->q2
  function twoSided(p1, p2, q1, q2) {
      // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)
      const x1 = p1[0] - q1[0];
      const y1 = p1[1] - q1[1];
      const x2 = p2[0] - q1[0];
      const y2 = p2[1] - q1[1];
      const x3 = q2[0] - q1[0];
      const y3 = q2[1] - q1[1];
      const det1 = (x1 * y3 - x3 * y1);
      const det2 = (x2 * y3 - x3 * y2);
      if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0))
          return true;
      return false;
  }

  function getTilePolygon(coordinates, bbox, canonical) {
      const polygon = [];
      for (let i = 0; i < coordinates.length; i++) {
          const ring = [];
          for (let j = 0; j < coordinates[i].length; j++) {
              const coord = getTileCoordinates(coordinates[i][j], canonical);
              updateBBox(bbox, coord);
              ring.push(coord);
          }
          polygon.push(ring);
      }
      return polygon;
  }
  function getTilePolygons(coordinates, bbox, canonical) {
      const polygons = [];
      for (let i = 0; i < coordinates.length; i++) {
          const polygon = getTilePolygon(coordinates[i], bbox, canonical);
          polygons.push(polygon);
      }
      return polygons;
  }
  function updatePoint(p, bbox, polyBBox, worldSize) {
      if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {
          const halfWorldSize = worldSize * 0.5;
          let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;
          if (shift === 0) {
              shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;
          }
          p[0] += shift;
      }
      updateBBox(bbox, p);
  }
  function resetBBox(bbox) {
      bbox[0] = bbox[1] = Infinity;
      bbox[2] = bbox[3] = -Infinity;
  }
  function getTilePoints(geometry, pointBBox, polyBBox, canonical) {
      const worldSize = Math.pow(2, canonical.z) * EXTENT;
      const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
      const tilePoints = [];
      for (const points of geometry) {
          for (const point of points) {
              const p = [point.x + shifts[0], point.y + shifts[1]];
              updatePoint(p, pointBBox, polyBBox, worldSize);
              tilePoints.push(p);
          }
      }
      return tilePoints;
  }
  function getTileLines(geometry, lineBBox, polyBBox, canonical) {
      const worldSize = Math.pow(2, canonical.z) * EXTENT;
      const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];
      const tileLines = [];
      for (const line of geometry) {
          const tileLine = [];
          for (const point of line) {
              const p = [point.x + shifts[0], point.y + shifts[1]];
              updateBBox(lineBBox, p);
              tileLine.push(p);
          }
          tileLines.push(tileLine);
      }
      if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {
          resetBBox(lineBBox);
          for (const line of tileLines) {
              for (const p of line) {
                  updatePoint(p, lineBBox, polyBBox, worldSize);
              }
          }
      }
      return tileLines;
  }
  function pointsWithinPolygons(ctx, polygonGeometry) {
      const pointBBox = [Infinity, Infinity, -Infinity, -Infinity];
      const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];
      const canonical = ctx.canonicalID();
      if (polygonGeometry.type === 'Polygon') {
          const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
          const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
          if (!boxWithinBox(pointBBox, polyBBox))
              return false;
          for (const point of tilePoints) {
              if (!pointWithinPolygon(point, tilePolygon))
                  return false;
          }
      }
      if (polygonGeometry.type === 'MultiPolygon') {
          const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
          const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);
          if (!boxWithinBox(pointBBox, polyBBox))
              return false;
          for (const point of tilePoints) {
              if (!pointWithinPolygons(point, tilePolygons))
                  return false;
          }
      }
      return true;
  }
  function linesWithinPolygons(ctx, polygonGeometry) {
      const lineBBox = [Infinity, Infinity, -Infinity, -Infinity];
      const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];
      const canonical = ctx.canonicalID();
      if (polygonGeometry.type === 'Polygon') {
          const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);
          const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
          if (!boxWithinBox(lineBBox, polyBBox))
              return false;
          for (const line of tileLines) {
              if (!lineStringWithinPolygon(line, tilePolygon))
                  return false;
          }
      }
      if (polygonGeometry.type === 'MultiPolygon') {
          const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);
          const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);
          if (!boxWithinBox(lineBBox, polyBBox))
              return false;
          for (const line of tileLines) {
              if (!lineStringWithinPolygons(line, tilePolygons))
                  return false;
          }
      }
      return true;
  }
  let Within$1 = class Within {
      constructor(geojson, geometries) {
          this.type = BooleanType;
          this.geojson = geojson;
          this.geometries = geometries;
      }
      static parse(args, context) {
          if (args.length !== 2)
              return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);
          if (isValue(args[1])) {
              const geojson = args[1];
              if (geojson.type === 'FeatureCollection') {
                  const polygonsCoords = [];
                  for (const polygon of geojson.features) {
                      const { type, coordinates } = polygon.geometry;
                      if (type === 'Polygon') {
                          polygonsCoords.push(coordinates);
                      }
                      if (type === 'MultiPolygon') {
                          polygonsCoords.push(...coordinates);
                      }
                  }
                  if (polygonsCoords.length) {
                      const multipolygonWrapper = {
                          type: 'MultiPolygon',
                          coordinates: polygonsCoords
                      };
                      return new Within(geojson, multipolygonWrapper);
                  }
              }
              else if (geojson.type === 'Feature') {
                  const type = geojson.geometry.type;
                  if (type === 'Polygon' || type === 'MultiPolygon') {
                      return new Within(geojson, geojson.geometry);
                  }
              }
              else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {
                  return new Within(geojson, geojson);
              }
          }
          return context.error('\'within\' expression requires valid geojson object that contains polygon geometry type.');
      }
      evaluate(ctx) {
          if (ctx.geometry() != null && ctx.canonicalID() != null) {
              if (ctx.geometryType() === 'Point') {
                  return pointsWithinPolygons(ctx, this.geometries);
              }
              else if (ctx.geometryType() === 'LineString') {
                  return linesWithinPolygons(ctx, this.geometries);
              }
          }
          return false;
      }
      eachChild() { }
      outputDefined() {
          return true;
      }
  };

  class TinyQueue {
      constructor(data = [], compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
          this.data = data;
          this.length = this.data.length;
          this.compare = compare;

          if (this.length > 0) {
              for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);
          }
      }

      push(item) {
          this.data.push(item);
          this._up(this.length++);
      }

      pop() {
          if (this.length === 0) return undefined;

          const top = this.data[0];
          const bottom = this.data.pop();

          if (--this.length > 0) {
              this.data[0] = bottom;
              this._down(0);
          }

          return top;
      }

      peek() {
          return this.data[0];
      }

      _up(pos) {
          const {data, compare} = this;
          const item = data[pos];

          while (pos > 0) {
              const parent = (pos - 1) >> 1;
              const current = data[parent];
              if (compare(item, current) >= 0) break;
              data[pos] = current;
              pos = parent;
          }

          data[pos] = item;
      }

      _down(pos) {
          const {data, compare} = this;
          const halfLength = this.length >> 1;
          const item = data[pos];

          while (pos < halfLength) {
              let bestChild = (pos << 1) + 1; // initially it is the left child
              const right = bestChild + 1;

              if (right < this.length && compare(data[right], data[bestChild]) < 0) {
                  bestChild = right;
              }
              if (compare(data[bestChild], item) >= 0) break;

              data[pos] = data[bestChild];
              pos = bestChild;
          }

          data[pos] = item;
      }
  }

  /**
   * Classifies an array of rings into polygons with outer rings and holes
   * @param rings - the rings to classify
   * @param maxRings - the maximum number of rings to include in a polygon, use 0 to include all rings
   * @returns an array of polygons with internal rings as holes
   */
  function classifyRings(rings, maxRings) {
      const len = rings.length;
      if (len <= 1)
          return [rings];
      const polygons = [];
      let polygon;
      let ccw;
      for (const ring of rings) {
          const area = calculateSignedArea(ring);
          if (area === 0)
              continue;
          ring.area = Math.abs(area);
          if (ccw === undefined)
              ccw = area < 0;
          if (ccw === area < 0) {
              if (polygon)
                  polygons.push(polygon);
              polygon = [ring];
          }
          else {
              polygon.push(ring);
          }
      }
      if (polygon)
          polygons.push(polygon);
      return polygons;
  }
  /**
   * Returns the signed area for the polygon ring.  Positive areas are exterior rings and
   * have a clockwise winding.  Negative areas are interior rings and have a counter clockwise
   * ordering.
   *
   * @param ring - Exterior or interior ring
   * @returns Signed area
   */
  function calculateSignedArea(ring) {
      let sum = 0;
      for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {
          p1 = ring[i];
          p2 = ring[j];
          sum += (p2.x - p1.x) * (p1.y + p2.y);
      }
      return sum;
  }

  // This is taken from https://github.com/mapbox/cheap-ruler/ in order to take only the relevant parts
  // Values that define WGS84 ellipsoid model of the Earth
  const RE = 6378.137; // equatorial radius
  const FE = 1 / 298.257223563; // flattening
  const E2 = FE * (2 - FE);
  const RAD = Math.PI / 180;
  class CheapRuler {
      constructor(lat) {
          // Curvature formulas from https://en.wikipedia.org/wiki/Earth_radius#Meridional
          const m = RAD * RE * 1000;
          const coslat = Math.cos(lat * RAD);
          const w2 = 1 / (1 - E2 * (1 - coslat * coslat));
          const w = Math.sqrt(w2);
          // multipliers for converting longitude and latitude degrees into distance
          this.kx = m * w * coslat; // based on normal radius of curvature
          this.ky = m * w * w2 * (1 - E2); // based on meridional radius of curvature
      }
      /**
       * Given two points of the form [longitude, latitude], returns the distance.
       *
       * @param a - point [longitude, latitude]
       * @param b - point [longitude, latitude]
       * @returns distance
       * @example
       * const distance = ruler.distance([30.5, 50.5], [30.51, 50.49]);
       * //=distance
       */
      distance(a, b) {
          const dx = this.wrap(a[0] - b[0]) * this.kx;
          const dy = (a[1] - b[1]) * this.ky;
          return Math.sqrt(dx * dx + dy * dy);
      }
      /**
       * Returns an object of the form {point, index, t}, where point is closest point on the line
       * from the given point, index is the start index of the segment with the closest point,
       * and t is a parameter from 0 to 1 that indicates where the closest point is on that segment.
       *
       * @param line - an array of points that form the line
       * @param p - point [longitude, latitude]
       * @returns the nearest point, its index in the array and the proportion along the line
       * @example
       * const point = ruler.pointOnLine(line, [-67.04, 50.5]).point;
       * //=point
       */
      pointOnLine(line, p) {
          let minDist = Infinity;
          let minX, minY, minI, minT;
          for (let i = 0; i < line.length - 1; i++) {
              let x = line[i][0];
              let y = line[i][1];
              let dx = this.wrap(line[i + 1][0] - x) * this.kx;
              let dy = (line[i + 1][1] - y) * this.ky;
              let t = 0;
              if (dx !== 0 || dy !== 0) {
                  t = (this.wrap(p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy);
                  if (t > 1) {
                      x = line[i + 1][0];
                      y = line[i + 1][1];
                  }
                  else if (t > 0) {
                      x += (dx / this.kx) * t;
                      y += (dy / this.ky) * t;
                  }
              }
              dx = this.wrap(p[0] - x) * this.kx;
              dy = (p[1] - y) * this.ky;
              const sqDist = dx * dx + dy * dy;
              if (sqDist < minDist) {
                  minDist = sqDist;
                  minX = x;
                  minY = y;
                  minI = i;
                  minT = t;
              }
          }
          return {
              point: [minX, minY],
              index: minI,
              t: Math.max(0, Math.min(1, minT))
          };
      }
      wrap(deg) {
          while (deg < -180)
              deg += 360;
          while (deg > 180)
              deg -= 360;
          return deg;
      }
  }

  const MinPointsSize = 100;
  const MinLinePointsSize = 50;
  function compareDistPair(a, b) {
      return b[0] - a[0];
  }
  function getRangeSize(range) {
      return range[1] - range[0] + 1;
  }
  function isRangeSafe(range, threshold) {
      return range[1] >= range[0] && range[1] < threshold;
  }
  function splitRange(range, isLine) {
      if (range[0] > range[1]) {
          return [null, null];
      }
      const size = getRangeSize(range);
      if (isLine) {
          if (size === 2) {
              return [range, null];
          }
          const size1 = Math.floor(size / 2);
          return [[range[0], range[0] + size1],
              [range[0] + size1, range[1]]];
      }
      if (size === 1) {
          return [range, null];
      }
      const size1 = Math.floor(size / 2) - 1;
      return [[range[0], range[0] + size1],
          [range[0] + size1 + 1, range[1]]];
  }
  function getBBox(coords, range) {
      if (!isRangeSafe(range, coords.length)) {
          return [Infinity, Infinity, -Infinity, -Infinity];
      }
      const bbox = [Infinity, Infinity, -Infinity, -Infinity];
      for (let i = range[0]; i <= range[1]; ++i) {
          updateBBox(bbox, coords[i]);
      }
      return bbox;
  }
  function getPolygonBBox(polygon) {
      const bbox = [Infinity, Infinity, -Infinity, -Infinity];
      for (const ring of polygon) {
          for (const coord of ring) {
              updateBBox(bbox, coord);
          }
      }
      return bbox;
  }
  function isValidBBox(bbox) {
      return bbox[0] !== -Infinity && bbox[1] !== -Infinity && bbox[2] !== Infinity && bbox[3] !== Infinity;
  }
  // Calculate the distance between two bounding boxes.
  // Calculate the delta in x and y direction, and use two fake points {0.0, 0.0}
  // and {dx, dy} to calculate the distance. Distance will be 0.0 if bounding box are overlapping.
  function bboxToBBoxDistance(bbox1, bbox2, ruler) {
      if (!isValidBBox(bbox1) || !isValidBBox(bbox2)) {
          return NaN;
      }
      let dx = 0.0;
      let dy = 0.0;
      // bbox1 in left side
      if (bbox1[2] < bbox2[0]) {
          dx = bbox2[0] - bbox1[2];
      }
      // bbox1 in right side
      if (bbox1[0] > bbox2[2]) {
          dx = bbox1[0] - bbox2[2];
      }
      // bbox1 in above side
      if (bbox1[1] > bbox2[3]) {
          dy = bbox1[1] - bbox2[3];
      }
      // bbox1 in down side
      if (bbox1[3] < bbox2[1]) {
          dy = bbox2[1] - bbox1[3];
      }
      return ruler.distance([0.0, 0.0], [dx, dy]);
  }
  function pointToLineDistance(point, line, ruler) {
      const nearestPoint = ruler.pointOnLine(line, point);
      return ruler.distance(point, nearestPoint.point);
  }
  function segmentToSegmentDistance(p1, p2, q1, q2, ruler) {
      const dist1 = Math.min(pointToLineDistance(p1, [q1, q2], ruler), pointToLineDistance(p2, [q1, q2], ruler));
      const dist2 = Math.min(pointToLineDistance(q1, [p1, p2], ruler), pointToLineDistance(q2, [p1, p2], ruler));
      return Math.min(dist1, dist2);
  }
  function lineToLineDistance(line1, range1, line2, range2, ruler) {
      const rangeSafe = isRangeSafe(range1, line1.length) && isRangeSafe(range2, line2.length);
      if (!rangeSafe) {
          return Infinity;
      }
      let dist = Infinity;
      for (let i = range1[0]; i < range1[1]; ++i) {
          const p1 = line1[i];
          const p2 = line1[i + 1];
          for (let j = range2[0]; j < range2[1]; ++j) {
              const q1 = line2[j];
              const q2 = line2[j + 1];
              if (segmentIntersectSegment(p1, p2, q1, q2)) {
                  return 0.0;
              }
              dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));
          }
      }
      return dist;
  }
  function pointsToPointsDistance(points1, range1, points2, range2, ruler) {
      const rangeSafe = isRangeSafe(range1, points1.length) && isRangeSafe(range2, points2.length);
      if (!rangeSafe) {
          return NaN;
      }
      let dist = Infinity;
      for (let i = range1[0]; i <= range1[1]; ++i) {
          for (let j = range2[0]; j <= range2[1]; ++j) {
              dist = Math.min(dist, ruler.distance(points1[i], points2[j]));
              if (dist === 0.0) {
                  return dist;
              }
          }
      }
      return dist;
  }
  function pointToPolygonDistance(point, polygon, ruler) {
      if (pointWithinPolygon(point, polygon, true)) {
          return 0.0;
      }
      let dist = Infinity;
      for (const ring of polygon) {
          const front = ring[0];
          const back = ring[ring.length - 1];
          if (front !== back) {
              dist = Math.min(dist, pointToLineDistance(point, [back, front], ruler));
              if (dist === 0.0) {
                  return dist;
              }
          }
          const nearestPoint = ruler.pointOnLine(ring, point);
          dist = Math.min(dist, ruler.distance(point, nearestPoint.point));
          if (dist === 0.0) {
              return dist;
          }
      }
      return dist;
  }
  function lineToPolygonDistance(line, range, polygon, ruler) {
      if (!isRangeSafe(range, line.length)) {
          return NaN;
      }
      for (let i = range[0]; i <= range[1]; ++i) {
          if (pointWithinPolygon(line[i], polygon, true)) {
              return 0.0;
          }
      }
      let dist = Infinity;
      for (let i = range[0]; i < range[1]; ++i) {
          const p1 = line[i];
          const p2 = line[i + 1];
          for (const ring of polygon) {
              for (let j = 0, len = ring.length, k = len - 1; j < len; k = j++) {
                  const q1 = ring[k];
                  const q2 = ring[j];
                  if (segmentIntersectSegment(p1, p2, q1, q2)) {
                      return 0.0;
                  }
                  dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));
              }
          }
      }
      return dist;
  }
  function polygonIntersect(poly1, poly2) {
      for (const ring of poly1) {
          for (const point of ring) {
              if (pointWithinPolygon(point, poly2, true)) {
                  return true;
              }
          }
      }
      return false;
  }
  function polygonToPolygonDistance(polygon1, polygon2, ruler, currentMiniDist = Infinity) {
      const bbox1 = getPolygonBBox(polygon1);
      const bbox2 = getPolygonBBox(polygon2);
      if (currentMiniDist !== Infinity && bboxToBBoxDistance(bbox1, bbox2, ruler) >= currentMiniDist) {
          return currentMiniDist;
      }
      if (boxWithinBox(bbox1, bbox2)) {
          if (polygonIntersect(polygon1, polygon2)) {
              return 0.0;
          }
      }
      else if (polygonIntersect(polygon2, polygon1)) {
          return 0.0;
      }
      let dist = Infinity;
      for (const ring1 of polygon1) {
          for (let i = 0, len1 = ring1.length, l = len1 - 1; i < len1; l = i++) {
              const p1 = ring1[l];
              const p2 = ring1[i];
              for (const ring2 of polygon2) {
                  for (let j = 0, len2 = ring2.length, k = len2 - 1; j < len2; k = j++) {
                      const q1 = ring2[k];
                      const q2 = ring2[j];
                      if (segmentIntersectSegment(p1, p2, q1, q2)) {
                          return 0.0;
                      }
                      dist = Math.min(dist, segmentToSegmentDistance(p1, p2, q1, q2, ruler));
                  }
              }
          }
      }
      return dist;
  }
  function updateQueue(distQueue, miniDist, ruler, points, polyBBox, rangeA) {
      if (!rangeA) {
          return;
      }
      const tempDist = bboxToBBoxDistance(getBBox(points, rangeA), polyBBox, ruler);
      // Insert new pair to the queue if the bbox distance is less than
      // miniDist, The pair with biggest distance will be at the top
      if (tempDist < miniDist) {
          distQueue.push([tempDist, rangeA, [0, 0]]);
      }
  }
  function updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, range1, range2) {
      if (!range1 || !range2) {
          return;
      }
      const tempDist = bboxToBBoxDistance(getBBox(pointSet1, range1), getBBox(pointSet2, range2), ruler);
      // Insert new pair to the queue if the bbox distance is less than
      // miniDist, The pair with biggest distance will be at the top
      if (tempDist < miniDist) {
          distQueue.push([tempDist, range1, range2]);
      }
  }
  // Divide and conquer, the time complexity is O(n*lgn), faster than Brute force
  // O(n*n) Most of the time, use index for in-place processing.
  function pointsToPolygonDistance(points, isLine, polygon, ruler, currentMiniDist = Infinity) {
      let miniDist = Math.min(ruler.distance(points[0], polygon[0][0]), currentMiniDist);
      if (miniDist === 0.0) {
          return miniDist;
      }
      const distQueue = new TinyQueue([[0, [0, points.length - 1], [0, 0]]], compareDistPair);
      const polyBBox = getPolygonBBox(polygon);
      while (distQueue.length > 0) {
          const distPair = distQueue.pop();
          if (distPair[0] >= miniDist) {
              continue;
          }
          const range = distPair[1];
          // In case the set size are relatively small, we could use brute-force directly
          const threshold = isLine ? MinLinePointsSize : MinPointsSize;
          if (getRangeSize(range) <= threshold) {
              if (!isRangeSafe(range, points.length)) {
                  return NaN;
              }
              if (isLine) {
                  const tempDist = lineToPolygonDistance(points, range, polygon, ruler);
                  if (isNaN(tempDist) || tempDist === 0.0) {
                      return tempDist;
                  }
                  miniDist = Math.min(miniDist, tempDist);
              }
              else {
                  for (let i = range[0]; i <= range[1]; ++i) {
                      const tempDist = pointToPolygonDistance(points[i], polygon, ruler);
                      miniDist = Math.min(miniDist, tempDist);
                      if (miniDist === 0.0) {
                          return 0.0;
                      }
                  }
              }
          }
          else {
              const newRangesA = splitRange(range, isLine);
              updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[0]);
              updateQueue(distQueue, miniDist, ruler, points, polyBBox, newRangesA[1]);
          }
      }
      return miniDist;
  }
  function pointSetToPointSetDistance(pointSet1, isLine1, pointSet2, isLine2, ruler, currentMiniDist = Infinity) {
      let miniDist = Math.min(currentMiniDist, ruler.distance(pointSet1[0], pointSet2[0]));
      if (miniDist === 0.0) {
          return miniDist;
      }
      const distQueue = new TinyQueue([[0, [0, pointSet1.length - 1], [0, pointSet2.length - 1]]], compareDistPair);
      while (distQueue.length > 0) {
          const distPair = distQueue.pop();
          if (distPair[0] >= miniDist) {
              continue;
          }
          const rangeA = distPair[1];
          const rangeB = distPair[2];
          const threshold1 = isLine1 ? MinLinePointsSize : MinPointsSize;
          const threshold2 = isLine2 ? MinLinePointsSize : MinPointsSize;
          // In case the set size are relatively small, we could use brute-force directly
          if (getRangeSize(rangeA) <= threshold1 && getRangeSize(rangeB) <= threshold2) {
              if (!isRangeSafe(rangeA, pointSet1.length) && isRangeSafe(rangeB, pointSet2.length)) {
                  return NaN;
              }
              let tempDist;
              if (isLine1 && isLine2) {
                  tempDist = lineToLineDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);
                  miniDist = Math.min(miniDist, tempDist);
              }
              else if (isLine1 && !isLine2) {
                  const sublibe = pointSet1.slice(rangeA[0], rangeA[1] + 1);
                  for (let i = rangeB[0]; i <= rangeB[1]; ++i) {
                      tempDist = pointToLineDistance(pointSet2[i], sublibe, ruler);
                      miniDist = Math.min(miniDist, tempDist);
                      if (miniDist === 0.0) {
                          return miniDist;
                      }
                  }
              }
              else if (!isLine1 && isLine2) {
                  const sublibe = pointSet2.slice(rangeB[0], rangeB[1] + 1);
                  for (let i = rangeA[0]; i <= rangeA[1]; ++i) {
                      tempDist = pointToLineDistance(pointSet1[i], sublibe, ruler);
                      miniDist = Math.min(miniDist, tempDist);
                      if (miniDist === 0.0) {
                          return miniDist;
                      }
                  }
              }
              else {
                  tempDist = pointsToPointsDistance(pointSet1, rangeA, pointSet2, rangeB, ruler);
                  miniDist = Math.min(miniDist, tempDist);
              }
          }
          else {
              const newRangesA = splitRange(rangeA, isLine1);
              const newRangesB = splitRange(rangeB, isLine2);
              updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[0]);
              updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[0], newRangesB[1]);
              updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[0]);
              updateQueueTwoSets(distQueue, miniDist, ruler, pointSet1, pointSet2, newRangesA[1], newRangesB[1]);
          }
      }
      return miniDist;
  }
  function pointToGeometryDistance(ctx, geometries) {
      const tilePoints = ctx.geometry();
      const pointPosition = tilePoints.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));
      if (tilePoints.length === 0) {
          return NaN;
      }
      const ruler = new CheapRuler(pointPosition[0][1]);
      let dist = Infinity;
      for (const geometry of geometries) {
          switch (geometry.type) {
              case 'Point':
                  dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, [geometry.coordinates], false, ruler, dist));
                  break;
              case 'LineString':
                  dist = Math.min(dist, pointSetToPointSetDistance(pointPosition, false, geometry.coordinates, true, ruler, dist));
                  break;
              case 'Polygon':
                  dist = Math.min(dist, pointsToPolygonDistance(pointPosition, false, geometry.coordinates, ruler, dist));
                  break;
          }
          if (dist === 0.0) {
              return dist;
          }
      }
      return dist;
  }
  function lineStringToGeometryDistance(ctx, geometries) {
      const tileLine = ctx.geometry();
      const linePositions = tileLine.flat().map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));
      if (tileLine.length === 0) {
          return NaN;
      }
      const ruler = new CheapRuler(linePositions[0][1]);
      let dist = Infinity;
      for (const geometry of geometries) {
          switch (geometry.type) {
              case 'Point':
                  dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, [geometry.coordinates], false, ruler, dist));
                  break;
              case 'LineString':
                  dist = Math.min(dist, pointSetToPointSetDistance(linePositions, true, geometry.coordinates, true, ruler, dist));
                  break;
              case 'Polygon':
                  dist = Math.min(dist, pointsToPolygonDistance(linePositions, true, geometry.coordinates, ruler, dist));
                  break;
          }
          if (dist === 0.0) {
              return dist;
          }
      }
      return dist;
  }
  function polygonToGeometryDistance(ctx, geometries) {
      const tilePolygon = ctx.geometry();
      if (tilePolygon.length === 0 || tilePolygon[0].length === 0) {
          return NaN;
      }
      const polygons = classifyRings(tilePolygon).map(polygon => {
          return polygon.map(ring => {
              return ring.map(p => getLngLatFromTileCoord([p.x, p.y], ctx.canonical));
          });
      });
      const ruler = new CheapRuler(polygons[0][0][0][1]);
      let dist = Infinity;
      for (const geometry of geometries) {
          for (const polygon of polygons) {
              switch (geometry.type) {
                  case 'Point':
                      dist = Math.min(dist, pointsToPolygonDistance([geometry.coordinates], false, polygon, ruler, dist));
                      break;
                  case 'LineString':
                      dist = Math.min(dist, pointsToPolygonDistance(geometry.coordinates, true, polygon, ruler, dist));
                      break;
                  case 'Polygon':
                      dist = Math.min(dist, polygonToPolygonDistance(polygon, geometry.coordinates, ruler, dist));
                      break;
              }
              if (dist === 0.0) {
                  return dist;
              }
          }
      }
      return dist;
  }
  function toSimpleGeometry(geometry) {
      if (geometry.type === 'MultiPolygon') {
          return geometry.coordinates.map(polygon => {
              return {
                  type: 'Polygon',
                  coordinates: polygon
              };
          });
      }
      if (geometry.type === 'MultiLineString') {
          return geometry.coordinates.map(lineString => {
              return {
                  type: 'LineString',
                  coordinates: lineString
              };
          });
      }
      if (geometry.type === 'MultiPoint') {
          return geometry.coordinates.map(point => {
              return {
                  type: 'Point',
                  coordinates: point
              };
          });
      }
      return [geometry];
  }
  class Distance {
      constructor(geojson, geometries) {
          this.type = NumberType;
          this.geojson = geojson;
          this.geometries = geometries;
      }
      static parse(args, context) {
          if (args.length !== 2)
              return context.error(`'distance' expression requires exactly one argument, but found ${args.length - 1} instead.`);
          if (isValue(args[1])) {
              const geojson = args[1];
              if (geojson.type === 'FeatureCollection') {
                  return new Distance(geojson, geojson.features.map(feature => toSimpleGeometry(feature.geometry)).flat());
              }
              else if (geojson.type === 'Feature') {
                  return new Distance(geojson, toSimpleGeometry(geojson.geometry));
              }
              else if ('type' in geojson && 'coordinates' in geojson) {
                  return new Distance(geojson, toSimpleGeometry(geojson));
              }
          }
          return context.error('\'distance\' expression requires valid geojson object that contains polygon geometry type.');
      }
      evaluate(ctx) {
          if (ctx.geometry() != null && ctx.canonicalID() != null) {
              if (ctx.geometryType() === 'Point') {
                  return pointToGeometryDistance(ctx, this.geometries);
              }
              else if (ctx.geometryType() === 'LineString') {
                  return lineStringToGeometryDistance(ctx, this.geometries);
              }
              else if (ctx.geometryType() === 'Polygon') {
                  return polygonToGeometryDistance(ctx, this.geometries);
              }
          }
          return NaN;
      }
      eachChild() { }
      outputDefined() {
          return true;
      }
  }

  class GlobalState {
      constructor(key) {
          this.type = ValueType;
          this.key = key;
      }
      static parse(args, context) {
          if (args.length !== 2) {
              return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);
          }
          const key = args[1];
          if (key === undefined || key === null) {
              return context.error('Global state property must be defined.');
          }
          if (typeof key !== 'string') {
              return context.error(`Global state property must be string, but found ${typeof args[1]} instead.`);
          }
          return new GlobalState(key);
      }
      evaluate(ctx) {
          var _a;
          const globalState = (_a = ctx.globals) === null || _a === void 0 ? void 0 : _a.globalState;
          if (!globalState || Object.keys(globalState).length === 0)
              return null;
          return getOwn(globalState, this.key);
      }
      eachChild() { }
      outputDefined() {
          return false;
      }
  }

  const expressions$1 = {
      // special forms
      '==': Equals,
      '!=': NotEquals,
      '>': GreaterThan$1,
      '<': LessThan$1,
      '>=': GreaterThanOrEqual,
      '<=': LessThanOrEqual,
      'array': Assertion,
      'at': At,
      'boolean': Assertion,
      'case': Case,
      'coalesce': Coalesce,
      'collator': CollatorExpression,
      'format': FormatExpression,
      'image': ImageExpression,
      'in': In,
      'index-of': IndexOf,
      'interpolate': Interpolate,
      'interpolate-hcl': Interpolate,
      'interpolate-lab': Interpolate,
      'length': Length,
      'let': Let,
      'literal': Literal,
      'match': Match,
      'number': Assertion,
      'number-format': NumberFormat,
      'object': Assertion,
      'slice': Slice,
      'step': Step,
      'string': Assertion,
      'to-boolean': Coercion,
      'to-color': Coercion,
      'to-number': Coercion,
      'to-string': Coercion,
      'var': Var,
      'within': Within$1,
      'distance': Distance,
      'global-state': GlobalState
  };

  class CompoundExpression {
      constructor(name, type, evaluate, args) {
          this.name = name;
          this.type = type;
          this._evaluate = evaluate;
          this.args = args;
      }
      evaluate(ctx) {
          return this._evaluate(ctx, this.args);
      }
      eachChild(fn) {
          this.args.forEach(fn);
      }
      outputDefined() {
          return false;
      }
      static parse(args, context) {
          const op = args[0];
          const definition = CompoundExpression.definitions[op];
          if (!definition) {
              return context.error(`Unknown expression "${op}". If you wanted a literal array, use ["literal", [...]].`, 0);
          }
          // Now check argument types against each signature
          const type = Array.isArray(definition) ?
              definition[0] : definition.type;
          const availableOverloads = Array.isArray(definition) ?
              [[definition[1], definition[2]]] :
              definition.overloads;
          const overloads = availableOverloads.filter(([signature]) => (!Array.isArray(signature) || // varags
              signature.length === args.length - 1 // correct param count
          ));
          let signatureContext = null;
          for (const [params, evaluate] of overloads) {
              // Use a fresh context for each attempted signature so that, if
              // we eventually succeed, we haven't polluted `context.errors`.
              signatureContext = new ParsingContext(context.registry, isExpressionConstant, context.path, null, context.scope);
              // First parse all the args, potentially coercing to the
              // types expected by this overload.
              const parsedArgs = [];
              let argParseFailed = false;
              for (let i = 1; i < args.length; i++) {
                  const arg = args[i];
                  const expectedType = Array.isArray(params) ?
                      params[i - 1] :
                      params.type;
                  const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);
                  if (!parsed) {
                      argParseFailed = true;
                      break;
                  }
                  parsedArgs.push(parsed);
              }
              if (argParseFailed) {
                  // Couldn't coerce args of this overload to expected type, move
                  // on to next one.
                  continue;
              }
              if (Array.isArray(params)) {
                  if (params.length !== parsedArgs.length) {
                      signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);
                      continue;
                  }
              }
              for (let i = 0; i < parsedArgs.length; i++) {
                  const expected = Array.isArray(params) ? params[i] : params.type;
                  const arg = parsedArgs[i];
                  signatureContext.concat(i + 1).checkSubtype(expected, arg.type);
              }
              if (signatureContext.errors.length === 0) {
                  return new CompoundExpression(op, type, evaluate, parsedArgs);
              }
          }
          if (overloads.length === 1) {
              context.errors.push(...signatureContext.errors);
          }
          else {
              const expected = overloads.length ? overloads : availableOverloads;
              const signatures = expected
                  .map(([params]) => stringifySignature(params))
                  .join(' | ');
              const actualTypes = [];
              // For error message, re-parse arguments without trying to
              // apply any coercions
              for (let i = 1; i < args.length; i++) {
                  const parsed = context.parse(args[i], 1 + actualTypes.length);
                  if (!parsed)
                      return null;
                  actualTypes.push(typeToString(parsed.type));
              }
              context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);
          }
          return null;
      }
      static register(registry, definitions) {
          CompoundExpression.definitions = definitions;
          for (const name in definitions) {
              registry[name] = CompoundExpression;
          }
      }
  }
  function rgba(ctx, [r, g, b, a]) {
      r = r.evaluate(ctx);
      g = g.evaluate(ctx);
      b = b.evaluate(ctx);
      const alpha = a ? a.evaluate(ctx) : 1;
      const error = validateRGBA(r, g, b, alpha);
      if (error)
          throw new RuntimeError(error);
      return new Color(r / 255, g / 255, b / 255, alpha, false);
  }
  function has(key, obj) {
      return key in obj;
  }
  function get(key, obj) {
      const v = obj[key];
      return typeof v === 'undefined' ? null : v;
  }
  function binarySearch(v, a, i, j) {
      while (i <= j) {
          const m = (i + j) >> 1;
          if (a[m] === v)
              return true;
          if (a[m] > v)
              j = m - 1;
          else
              i = m + 1;
      }
      return false;
  }
  function varargs(type) {
      return { type };
  }
  CompoundExpression.register(expressions$1, {
      'error': [
          ErrorType,
          [StringType],
          (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }
      ],
      'typeof': [
          StringType,
          [ValueType],
          (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))
      ],
      'to-rgba': [
          array(NumberType, 4),
          [ColorType],
          (ctx, [v]) => {
              const [r, g, b, a] = v.evaluate(ctx).rgb;
              return [r * 255, g * 255, b * 255, a];
          },
      ],
      'rgb': [
          ColorType,
          [NumberType, NumberType, NumberType],
          rgba
      ],
      'rgba': [
          ColorType,
          [NumberType, NumberType, NumberType, NumberType],
          rgba
      ],
      'has': {
          type: BooleanType,
          overloads: [
              [
                  [StringType],
                  (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())
              ], [
                  [StringType, ObjectType],
                  (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))
              ]
          ]
      },
      'get': {
          type: ValueType,
          overloads: [
              [
                  [StringType],
                  (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())
              ], [
                  [StringType, ObjectType],
                  (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))
              ]
          ]
      },
      'feature-state': [
          ValueType,
          [StringType],
          (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})
      ],
      'properties': [
          ObjectType,
          [],
          (ctx) => ctx.properties()
      ],
      'geometry-type': [
          StringType,
          [],
          (ctx) => ctx.geometryType()
      ],
      'id': [
          ValueType,
          [],
          (ctx) => ctx.id()
      ],
      'zoom': [
          NumberType,
          [],
          (ctx) => ctx.globals.zoom
      ],
      'heatmap-density': [
          NumberType,
          [],
          (ctx) => ctx.globals.heatmapDensity || 0
      ],
      'elevation': [
          NumberType,
          [],
          (ctx) => ctx.globals.elevation || 0
      ],
      'line-progress': [
          NumberType,
          [],
          (ctx) => ctx.globals.lineProgress || 0
      ],
      'accumulated': [
          ValueType,
          [],
          (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated
      ],
      '+': [
          NumberType,
          varargs(NumberType),
          (ctx, args) => {
              let result = 0;
              for (const arg of args) {
                  result += arg.evaluate(ctx);
              }
              return result;
          }
      ],
      '*': [
          NumberType,
          varargs(NumberType),
          (ctx, args) => {
              let result = 1;
              for (const arg of args) {
                  result *= arg.evaluate(ctx);
              }
              return result;
          }
      ],
      '-': {
          type: NumberType,
          overloads: [
              [
                  [NumberType, NumberType],
                  (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)
              ], [
                  [NumberType],
                  (ctx, [a]) => -a.evaluate(ctx)
              ]
          ]
      },
      '/': [
          NumberType,
          [NumberType, NumberType],
          (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)
      ],
      '%': [
          NumberType,
          [NumberType, NumberType],
          (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)
      ],
      'ln2': [
          NumberType,
          [],
          () => Math.LN2
      ],
      'pi': [
          NumberType,
          [],
          () => Math.PI
      ],
      'e': [
          NumberType,
          [],
          () => Math.E
      ],
      '^': [
          NumberType,
          [NumberType, NumberType],
          (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))
      ],
      'sqrt': [
          NumberType,
          [NumberType],
          (ctx, [x]) => Math.sqrt(x.evaluate(ctx))
      ],
      'log10': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10
      ],
      'ln': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.log(n.evaluate(ctx))
      ],
      'log2': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2
      ],
      'sin': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.sin(n.evaluate(ctx))
      ],
      'cos': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.cos(n.evaluate(ctx))
      ],
      'tan': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.tan(n.evaluate(ctx))
      ],
      'asin': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.asin(n.evaluate(ctx))
      ],
      'acos': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.acos(n.evaluate(ctx))
      ],
      'atan': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.atan(n.evaluate(ctx))
      ],
      'min': [
          NumberType,
          varargs(NumberType),
          (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))
      ],
      'max': [
          NumberType,
          varargs(NumberType),
          (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))
      ],
      'abs': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.abs(n.evaluate(ctx))
      ],
      'round': [
          NumberType,
          [NumberType],
          (ctx, [n]) => {
              const v = n.evaluate(ctx);
              // Javascript's Math.round() rounds towards +Infinity for halfway
              // values, even when they're negative. It's more common to round
              // away from 0 (e.g., this is what python and C++ do)
              return v < 0 ? -Math.round(-v) : Math.round(v);
          }
      ],
      'floor': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.floor(n.evaluate(ctx))
      ],
      'ceil': [
          NumberType,
          [NumberType],
          (ctx, [n]) => Math.ceil(n.evaluate(ctx))
      ],
      'filter-==': [
          BooleanType,
          [StringType, ValueType],
          (ctx, [k, v]) => ctx.properties()[k.value] === v.value
      ],
      'filter-id-==': [
          BooleanType,
          [ValueType],
          (ctx, [v]) => ctx.id() === v.value
      ],
      'filter-type-==': [
          BooleanType,
          [StringType],
          (ctx, [v]) => ctx.geometryType() === v.value
      ],
      'filter-<': [
          BooleanType,
          [StringType, ValueType],
          (ctx, [k, v]) => {
              const a = ctx.properties()[k.value];
              const b = v.value;
              return typeof a === typeof b && a < b;
          }
      ],
      'filter-id-<': [
          BooleanType,
          [ValueType],
          (ctx, [v]) => {
              const a = ctx.id();
              const b = v.value;
              return typeof a === typeof b && a < b;
          }
      ],
      'filter->': [
          BooleanType,
          [StringType, ValueType],
          (ctx, [k, v]) => {
              const a = ctx.properties()[k.value];
              const b = v.value;
              return typeof a === typeof b && a > b;
          }
      ],
      'filter-id->': [
          BooleanType,
          [ValueType],
          (ctx, [v]) => {
              const a = ctx.id();
              const b = v.value;
              return typeof a === typeof b && a > b;
          }
      ],
      'filter-<=': [
          BooleanType,
          [StringType, ValueType],
          (ctx, [k, v]) => {
              const a = ctx.properties()[k.value];
              const b = v.value;
              return typeof a === typeof b && a <= b;
          }
      ],
      'filter-id-<=': [
          BooleanType,
          [ValueType],
          (ctx, [v]) => {
              const a = ctx.id();
              const b = v.value;
              return typeof a === typeof b && a <= b;
          }
      ],
      'filter->=': [
          BooleanType,
          [StringType, ValueType],
          (ctx, [k, v]) => {
              const a = ctx.properties()[k.value];
              const b = v.value;
              return typeof a === typeof b && a >= b;
          }
      ],
      'filter-id->=': [
          BooleanType,
          [ValueType],
          (ctx, [v]) => {
              const a = ctx.id();
              const b = v.value;
              return typeof a === typeof b && a >= b;
          }
      ],
      'filter-has': [
          BooleanType,
          [ValueType],
          (ctx, [k]) => k.value in ctx.properties()
      ],
      'filter-has-id': [
          BooleanType,
          [],
          (ctx) => (ctx.id() !== null && ctx.id() !== undefined)
      ],
      'filter-type-in': [
          BooleanType,
          [array(StringType)],
          (ctx, [v]) => v.value.indexOf(ctx.geometryType()) >= 0
      ],
      'filter-id-in': [
          BooleanType,
          [array(ValueType)],
          (ctx, [v]) => v.value.indexOf(ctx.id()) >= 0
      ],
      'filter-in-small': [
          BooleanType,
          [StringType, array(ValueType)],
          // assumes v is an array literal
          (ctx, [k, v]) => v.value.indexOf(ctx.properties()[k.value]) >= 0
      ],
      'filter-in-large': [
          BooleanType,
          [StringType, array(ValueType)],
          // assumes v is a array literal with values sorted in ascending order and of a single type
          (ctx, [k, v]) => binarySearch(ctx.properties()[k.value], v.value, 0, v.value.length - 1)
      ],
      'all': {
          type: BooleanType,
          overloads: [
              [
                  [BooleanType, BooleanType],
                  (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)
              ],
              [
                  varargs(BooleanType),
                  (ctx, args) => {
                      for (const arg of args) {
                          if (!arg.evaluate(ctx))
                              return false;
                      }
                      return true;
                  }
              ]
          ]
      },
      'any': {
          type: BooleanType,
          overloads: [
              [
                  [BooleanType, BooleanType],
                  (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)
              ],
              [
                  varargs(BooleanType),
                  (ctx, args) => {
                      for (const arg of args) {
                          if (arg.evaluate(ctx))
                              return true;
                      }
                      return false;
                  }
              ]
          ]
      },
      '!': [
          BooleanType,
          [BooleanType],
          (ctx, [b]) => !b.evaluate(ctx)
      ],
      'is-supported-script': [
          BooleanType,
          [StringType],
          // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant
          (ctx, [s]) => {
              const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;
              if (isSupportedScript) {
                  return isSupportedScript(s.evaluate(ctx));
              }
              return true;
          }
      ],
      'upcase': [
          StringType,
          [StringType],
          (ctx, [s]) => s.evaluate(ctx).toUpperCase()
      ],
      'downcase': [
          StringType,
          [StringType],
          (ctx, [s]) => s.evaluate(ctx).toLowerCase()
      ],
      'concat': [
          StringType,
          varargs(ValueType),
          (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')
      ],
      'resolved-locale': [
          StringType,
          [CollatorType],
          (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()
      ]
  });
  function stringifySignature(signature) {
      if (Array.isArray(signature)) {
          return `(${signature.map(typeToString).join(', ')})`;
      }
      else {
          return `(${typeToString(signature.type)}...)`;
      }
  }
  function isExpressionConstant(expression) {
      if (expression instanceof Var) {
          return isExpressionConstant(expression.boundExpression);
      }
      else if (expression instanceof CompoundExpression && expression.name === 'error') {
          return false;
      }
      else if (expression instanceof CollatorExpression) {
          // Although the results of a Collator expression with fixed arguments
          // generally shouldn't change between executions, we can't serialize them
          // as constant expressions because results change based on environment.
          return false;
      }
      else if (expression instanceof Within$1) {
          return false;
      }
      else if (expression instanceof Distance) {
          return false;
      }
      else if (expression instanceof GlobalState) {
          return false;
      }
      const isTypeAnnotation = expression instanceof Coercion ||
          expression instanceof Assertion;
      let childrenConstant = true;
      expression.eachChild(child => {
          // We can _almost_ assume that if `expressions` children are constant,
          // they would already have been evaluated to Literal values when they
          // were parsed.  Type annotations are the exception, because they might
          // have been inferred and added after a child was parsed.
          // So we recurse into isConstant() for the children of type annotations,
          // but otherwise simply check whether they are Literals.
          if (isTypeAnnotation) {
              childrenConstant = childrenConstant && isExpressionConstant(child);
          }
          else {
              childrenConstant = childrenConstant && child instanceof Literal;
          }
      });
      if (!childrenConstant) {
          return false;
      }
      return isFeatureConstant(expression) &&
          isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'elevation', 'line-progress', 'accumulated', 'is-supported-script']);
  }
  function isFeatureConstant(e) {
      if (e instanceof CompoundExpression) {
          if (e.name === 'get' && e.args.length === 1) {
              return false;
          }
          else if (e.name === 'feature-state') {
              return false;
          }
          else if (e.name === 'has' && e.args.length === 1) {
              return false;
          }
          else if (e.name === 'properties' ||
              e.name === 'geometry-type' ||
              e.name === 'id') {
              return false;
          }
          else if (/^filter-/.test(e.name)) {
              return false;
          }
      }
      if (e instanceof Within$1) {
          return false;
      }
      if (e instanceof Distance) {
          return false;
      }
      let result = true;
      e.eachChild(arg => {
          if (result && !isFeatureConstant(arg)) {
              result = false;
          }
      });
      return result;
  }
  function isStateConstant(e) {
      if (e instanceof CompoundExpression) {
          if (e.name === 'feature-state') {
              return false;
          }
      }
      let result = true;
      e.eachChild(arg => {
          if (result && !isStateConstant(arg)) {
              result = false;
          }
      });
      return result;
  }
  function isGlobalPropertyConstant(e, properties) {
      if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) {
          return false;
      }
      let result = true;
      e.eachChild((arg) => {
          if (result && !isGlobalPropertyConstant(arg, properties)) {
              result = false;
          }
      });
      return result;
  }

  function success(value) {
      return { result: 'success', value };
  }
  function error(value) {
      return { result: 'error', value };
  }

  function supportsPropertyExpression(spec) {
      return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-data-driven';
  }
  function supportsZoomExpression(spec) {
      return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;
  }
  function supportsInterpolation(spec) {
      return !!spec.expression && spec.expression.interpolated;
  }

  function isFunction$1(value) {
      return typeof value === 'object' && value !== null && !Array.isArray(value) && typeOf(value) === ObjectType;
  }

  class StyleExpression {
      constructor(expression, propertySpec) {
          this.expression = expression;
          this._warningHistory = {};
          this._evaluator = new EvaluationContext();
          this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;
          this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;
      }
      evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
          this._evaluator.globals = globals;
          this._evaluator.feature = feature;
          this._evaluator.featureState = featureState;
          this._evaluator.canonical = canonical;
          this._evaluator.availableImages = availableImages || null;
          this._evaluator.formattedSection = formattedSection;
          return this.expression.evaluate(this._evaluator);
      }
      evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
          this._evaluator.globals = globals;
          this._evaluator.feature = feature || null;
          this._evaluator.featureState = featureState || null;
          this._evaluator.canonical = canonical;
          this._evaluator.availableImages = availableImages || null;
          this._evaluator.formattedSection = formattedSection || null;
          try {
              const val = this.expression.evaluate(this._evaluator);
              if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {
                  return this._defaultValue;
              }
              if (this._enumValues && !(val in this._enumValues)) {
                  throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);
              }
              return val;
          }
          catch (e) {
              if (!this._warningHistory[e.message]) {
                  this._warningHistory[e.message] = true;
                  if (typeof console !== 'undefined') {
                      console.warn(e.message);
                  }
              }
              return this._defaultValue;
          }
      }
  }
  function isExpression(expression) {
      return Array.isArray(expression) && expression.length > 0 &&
          typeof expression[0] === 'string' && expression[0] in expressions$1;
  }
  /**
   * Parse and typecheck the given style spec JSON expression.  If
   * options.defaultValue is provided, then the resulting StyleExpression's
   * `evaluate()` method will handle errors by logging a warning (once per
   * message) and returning the default value.  Otherwise, it will throw
   * evaluation errors.
   *
   * @private
   */
  function createExpression(expression, propertySpec) {
      const parser = new ParsingContext(expressions$1, isExpressionConstant, [], propertySpec ? getExpectedType(propertySpec) : undefined);
      // For string-valued properties, coerce to string at the top level rather than asserting.
      const parsed = parser.parse(expression, undefined, undefined, undefined, propertySpec && propertySpec.type === 'string' ? { typeAnnotation: 'coerce' } : undefined);
      if (!parsed) {
          return error(parser.errors);
      }
      return success(new StyleExpression(parsed, propertySpec));
  }
  class ZoomConstantExpression {
      constructor(kind, expression) {
          this.kind = kind;
          this._styleExpression = expression;
          this.isStateDependent = kind !== 'constant' && !isStateConstant(expression.expression);
          this.globalStateRefs = findGlobalStateRefs(expression.expression);
      }
      evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
          return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
      }
      evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
          return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
      }
  }
  class ZoomDependentExpression {
      constructor(kind, expression, zoomStops, interpolationType) {
          this.kind = kind;
          this.zoomStops = zoomStops;
          this._styleExpression = expression;
          this.isStateDependent = kind !== 'camera' && !isStateConstant(expression.expression);
          this.globalStateRefs = findGlobalStateRefs(expression.expression);
          this.interpolationType = interpolationType;
      }
      evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection) {
          return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);
      }
      evaluate(globals, feature, featureState, canonical, availableImages, formattedSection) {
          return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);
      }
      interpolationFactor(input, lower, upper) {
          if (this.interpolationType) {
              return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);
          }
          else {
              return 0;
          }
      }
  }
  function createPropertyExpression(expressionInput, propertySpec) {
      const expression = createExpression(expressionInput, propertySpec);
      if (expression.result === 'error') {
          return expression;
      }
      const parsed = expression.value.expression;
      const isFeatureConstantResult = isFeatureConstant(parsed);
      if (!isFeatureConstantResult && !supportsPropertyExpression(propertySpec)) {
          return error([new ExpressionParsingError('', 'data expressions not supported')]);
      }
      const isZoomConstant = isGlobalPropertyConstant(parsed, ['zoom']);
      if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {
          return error([new ExpressionParsingError('', 'zoom expressions not supported')]);
      }
      const zoomCurve = findZoomCurve(parsed);
      if (!zoomCurve && !isZoomConstant) {
          return error([new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
      }
      else if (zoomCurve instanceof ExpressionParsingError) {
          return error([zoomCurve]);
      }
      else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {
          return error([new ExpressionParsingError('', '"interpolate" expressions cannot be used with this property')]);
      }
      if (!zoomCurve) {
          return success(isFeatureConstantResult ?
              new ZoomConstantExpression('constant', expression.value) :
              new ZoomConstantExpression('source', expression.value));
      }
      const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;
      return success(isFeatureConstantResult ?
          new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType) :
          new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType));
  }
  // Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate"
  // expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or
  // "coalesce" expressions.
  function findZoomCurve(expression) {
      let result = null;
      if (expression instanceof Let) {
          result = findZoomCurve(expression.result);
      }
      else if (expression instanceof Coalesce) {
          for (const arg of expression.args) {
              result = findZoomCurve(arg);
              if (result) {
                  break;
              }
          }
      }
      else if ((expression instanceof Step || expression instanceof Interpolate) &&
          expression.input instanceof CompoundExpression &&
          expression.input.name === 'zoom') {
          result = expression;
      }
      if (result instanceof ExpressionParsingError) {
          return result;
      }
      expression.eachChild((child) => {
          const childResult = findZoomCurve(child);
          if (childResult instanceof ExpressionParsingError) {
              result = childResult;
          }
          else if (!result && childResult) {
              result = new ExpressionParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.');
          }
          else if (result && childResult && result !== childResult) {
              result = new ExpressionParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.');
          }
      });
      return result;
  }
  function findGlobalStateRefs(expression, results = new Set()) {
      if (expression instanceof GlobalState) {
          results.add(expression.key);
      }
      expression.eachChild(childExpression => {
          findGlobalStateRefs(childExpression, results);
      });
      return results;
  }
  function getExpectedType(spec) {
      const types = {
          color: ColorType,
          string: StringType,
          number: NumberType,
          enum: StringType,
          boolean: BooleanType,
          formatted: FormattedType,
          padding: PaddingType,
          numberArray: NumberArrayType,
          colorArray: ColorArrayType,
          projectionDefinition: ProjectionDefinitionType,
          resolvedImage: ResolvedImageType,
          variableAnchorOffsetCollection: VariableAnchorOffsetCollectionType
      };
      if (spec.type === 'array') {
          return array(types[spec.value] || ValueType, spec.length);
      }
      return types[spec.type];
  }
  function getDefaultValue(spec) {
      if (spec.type === 'color' && isFunction$1(spec.default)) {
          // Special case for heatmap-color: it uses the 'default:' to define a
          // default color ramp, but createExpression expects a simple value to fall
          // back to in case of runtime errors
          return new Color(0, 0, 0, 0);
      }
      switch (spec.type) {
          case 'color':
              return Color.parse(spec.default) || null;
          case 'padding':
              return Padding.parse(spec.default) || null;
          case 'numberArray':
              return NumberArray.parse(spec.default) || null;
          case 'colorArray':
              return ColorArray.parse(spec.default) || null;
          case 'variableAnchorOffsetCollection':
              return VariableAnchorOffsetCollection.parse(spec.default) || null;
          case 'projectionDefinition':
              return ProjectionDefinition.parse(spec.default) || null;
          default:
              return (spec.default === undefined ? null : spec.default);
      }
  }

  function isExpressionFilter(filter) {
      if (filter === true || filter === false) {
          return true;
      }
      if (!Array.isArray(filter) || filter.length === 0) {
          return false;
      }
      switch (filter[0]) {
          case 'has':
              return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';
          case 'in':
              return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));
          case '!in':
          case '!has':
          case 'none':
              return false;
          case '==':
          case '!=':
          case '>':
          case '>=':
          case '<':
          case '<=':
              return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));
          case 'any':
          case 'all':
              for (const f of filter.slice(1)) {
                  if (!isExpressionFilter(f) && typeof f !== 'boolean') {
                      return false;
                  }
              }
              return true;
          default:
              return true;
      }
  }
  const filterSpec = {
      'type': 'boolean',
      'default': false,
      'transition': false,
      'property-type': 'data-driven',
      'expression': {
          'interpolated': false,
          'parameters': ['zoom', 'feature']
      }
  };
  /**
   * Given a filter expressed as nested arrays, return a new function
   * that evaluates whether a given feature (with a .properties or .tags property)
   * passes its test.
   *
   * @private
   * @param {Array} filter MapLibre filter
   * @returns {Function} filter-evaluating function
   */
  function featureFilter(filter) {
      if (filter === null || filter === undefined) {
          return { filter: () => true, needGeometry: false, getGlobalStateRefs: () => new Set() };
      }
      if (!isExpressionFilter(filter)) {
          filter = convertFilter$1(filter);
      }
      const compiled = createExpression(filter, filterSpec);
      if (compiled.result === 'error') {
          throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));
      }
      else {
          const needGeometry = geometryNeeded(filter);
          return {
              filter: (globalProperties, feature, canonical) => compiled.value.evaluate(globalProperties, feature, {}, canonical),
              needGeometry,
              getGlobalStateRefs: () => findGlobalStateRefs(compiled.value.expression)
          };
      }
  }
  // Comparison function to sort numbers and strings
  function compare(a, b) {
      return a < b ? -1 : a > b ? 1 : 0;
  }
  function geometryNeeded(filter) {
      if (!Array.isArray(filter))
          return false;
      if (filter[0] === 'within' || filter[0] === 'distance')
          return true;
      for (let index = 1; index < filter.length; index++) {
          if (geometryNeeded(filter[index]))
              return true;
      }
      return false;
  }
  function convertFilter$1(filter) {
      if (!filter)
          return true;
      const op = filter[0];
      if (filter.length <= 1)
          return (op !== 'any');
      const converted = op === '==' ? convertComparisonOp$1(filter[1], filter[2], '==') :
          op === '!=' ? convertNegation(convertComparisonOp$1(filter[1], filter[2], '==')) :
              op === '<' ||
                  op === '>' ||
                  op === '<=' ||
                  op === '>=' ? convertComparisonOp$1(filter[1], filter[2], op) :
                  op === 'any' ? convertDisjunctionOp(filter.slice(1)) :
                      op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter$1)) :
                          op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter$1).map(convertNegation)) :
                              op === 'in' ? convertInOp$1(filter[1], filter.slice(2)) :
                                  op === '!in' ? convertNegation(convertInOp$1(filter[1], filter.slice(2))) :
                                      op === 'has' ? convertHasOp$1(filter[1]) :
                                          op === '!has' ? convertNegation(convertHasOp$1(filter[1])) :
                                              true;
      return converted;
  }
  function convertComparisonOp$1(property, value, op) {
      switch (property) {
          case '$type':
              return [`filter-type-${op}`, value];
          case '$id':
              return [`filter-id-${op}`, value];
          default:
              return [`filter-${op}`, property, value];
      }
  }
  function convertDisjunctionOp(filters) {
      return ['any'].concat(filters.map(convertFilter$1));
  }
  function convertInOp$1(property, values) {
      if (values.length === 0) {
          return false;
      }
      switch (property) {
          case '$type':
              return ['filter-type-in', ['literal', values]];
          case '$id':
              return ['filter-id-in', ['literal', values]];
          default:
              if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {
                  return ['filter-in-large', property, ['literal', values.sort(compare)]];
              }
              else {
                  return ['filter-in-small', property, ['literal', values]];
              }
      }
  }
  function convertHasOp$1(property) {
      switch (property) {
          case '$type':
              return true;
          case '$id':
              return ['filter-has-id'];
          default:
              return ['filter-has', property];
      }
  }
  function convertNegation(filter) {
      return ['!', filter];
  }

  function convertLiteral(value) {
      return typeof value === 'object' ? ['literal', value] : value;
  }
  function convertFunction(parameters, propertySpec) {
      let stops = parameters.stops;
      if (!stops) {
          // identity function
          return convertIdentityFunction(parameters, propertySpec);
      }
      const zoomAndFeatureDependent = stops && typeof stops[0][0] === 'object';
      const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;
      const zoomDependent = zoomAndFeatureDependent || !featureDependent;
      stops = stops.map((stop) => {
          if (!featureDependent && propertySpec.tokens && typeof stop[1] === 'string') {
              return [stop[0], convertTokenString(stop[1])];
          }
          return [stop[0], convertLiteral(stop[1])];
      });
      if (zoomAndFeatureDependent) {
          return convertZoomAndPropertyFunction(parameters, propertySpec, stops);
      }
      else if (zoomDependent) {
          return convertZoomFunction(parameters, propertySpec, stops);
      }
      else {
          return convertPropertyFunction(parameters, propertySpec, stops);
      }
  }
  function convertIdentityFunction(parameters, propertySpec) {
      const get = ['get', parameters.property];
      if (parameters.default === undefined) {
          // By default, expressions for string-valued properties get coerced. To preserve
          // legacy function semantics, insert an explicit assertion instead.
          return propertySpec.type === 'string' ? ['string', get] : get;
      }
      else if (propertySpec.type === 'enum') {
          return [
              'match',
              get,
              Object.keys(propertySpec.values),
              get,
              parameters.default
          ];
      }
      else {
          const expression = [propertySpec.type === 'color' ? 'to-color' : propertySpec.type, get, convertLiteral(parameters.default)];
          if (propertySpec.type === 'array') {
              expression.splice(1, 0, propertySpec.value, propertySpec.length || null);
          }
          return expression;
      }
  }
  function getInterpolateOperator(parameters) {
      switch (parameters.colorSpace) {
          case 'hcl': return 'interpolate-hcl';
          case 'lab': return 'interpolate-lab';
          default: return 'interpolate';
      }
  }
  function convertZoomAndPropertyFunction(parameters, propertySpec, stops) {
      const featureFunctionParameters = {};
      const featureFunctionStops = {};
      const zoomStops = [];
      for (let s = 0; s < stops.length; s++) {
          const stop = stops[s];
          const zoom = stop[0].zoom;
          if (featureFunctionParameters[zoom] === undefined) {
              featureFunctionParameters[zoom] = {
                  zoom,
                  type: parameters.type,
                  property: parameters.property,
                  default: parameters.default,
              };
              featureFunctionStops[zoom] = [];
              zoomStops.push(zoom);
          }
          featureFunctionStops[zoom].push([stop[0].value, stop[1]]);
      }
      // the interpolation type for the zoom dimension of a zoom-and-property
      // function is determined directly from the style property specification
      // for which it's being used: linear for interpolatable properties, step
      // otherwise.
      const functionType = getFunctionType({}, propertySpec);
      if (functionType === 'exponential') {
          const expression = [getInterpolateOperator(parameters), ['linear'], ['zoom']];
          for (const z of zoomStops) {
              const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);
              appendStopPair(expression, z, output, false);
          }
          return expression;
      }
      else {
          const expression = ['step', ['zoom']];
          for (const z of zoomStops) {
              const output = convertPropertyFunction(featureFunctionParameters[z], propertySpec, featureFunctionStops[z]);
              appendStopPair(expression, z, output, true);
          }
          fixupDegenerateStepCurve(expression);
          return expression;
      }
  }
  function coalesce(a, b) {
      if (a !== undefined)
          return a;
      if (b !== undefined)
          return b;
  }
  function getFallback(parameters, propertySpec) {
      const defaultValue = convertLiteral(coalesce(parameters.default, propertySpec.default));
      /*
       * Some fields with type: resolvedImage have an undefined default.
       * Because undefined is an invalid value for resolvedImage, set fallback to
       * an empty string instead of undefined to ensure output
       * passes validation.
       */
      if (defaultValue === undefined && propertySpec.type === 'resolvedImage') {
          return '';
      }
      return defaultValue;
  }
  function convertPropertyFunction(parameters, propertySpec, stops) {
      const type = getFunctionType(parameters, propertySpec);
      const get = ['get', parameters.property];
      if (type === 'categorical' && typeof stops[0][0] === 'boolean') {
          const expression = ['case'];
          for (const stop of stops) {
              expression.push(['==', get, stop[0]], stop[1]);
          }
          expression.push(getFallback(parameters, propertySpec));
          return expression;
      }
      else if (type === 'categorical') {
          const expression = ['match', get];
          for (const stop of stops) {
              appendStopPair(expression, stop[0], stop[1], false);
          }
          expression.push(getFallback(parameters, propertySpec));
          return expression;
      }
      else if (type === 'interval') {
          const expression = ['step', ['number', get]];
          for (const stop of stops) {
              appendStopPair(expression, stop[0], stop[1], true);
          }
          fixupDegenerateStepCurve(expression);
          return parameters.default === undefined ? expression : [
              'case',
              ['==', ['typeof', get], 'number'],
              expression,
              convertLiteral(parameters.default)
          ];
      }
      else if (type === 'exponential') {
          const base = parameters.base !== undefined ? parameters.base : 1;
          const expression = [
              getInterpolateOperator(parameters),
              base === 1 ? ['linear'] : ['exponential', base],
              ['number', get]
          ];
          for (const stop of stops) {
              appendStopPair(expression, stop[0], stop[1], false);
          }
          return parameters.default === undefined ? expression : [
              'case',
              ['==', ['typeof', get], 'number'],
              expression,
              convertLiteral(parameters.default)
          ];
      }
      else {
          throw new Error(`Unknown property function type ${type}`);
      }
  }
  function convertZoomFunction(parameters, propertySpec, stops, input = ['zoom']) {
      const type = getFunctionType(parameters, propertySpec);
      let expression;
      let isStep = false;
      if (type === 'interval') {
          expression = ['step', input];
          isStep = true;
      }
      else if (type === 'exponential') {
          const base = parameters.base !== undefined ? parameters.base : 1;
          expression = [getInterpolateOperator(parameters), base === 1 ? ['linear'] : ['exponential', base], input];
      }
      else {
          throw new Error(`Unknown zoom function type "${type}"`);
      }
      for (const stop of stops) {
          appendStopPair(expression, stop[0], stop[1], isStep);
      }
      fixupDegenerateStepCurve(expression);
      return expression;
  }
  function fixupDegenerateStepCurve(expression) {
      // degenerate step curve (i.e. a constant function): add a noop stop
      if (expression[0] === 'step' && expression.length === 3) {
          expression.push(0);
          expression.push(expression[3]);
      }
  }
  function appendStopPair(curve, input, output, isStep) {
      // Skip duplicate stop values. They were not validated for functions, but they are for expressions.
      // https://github.com/mapbox/mapbox-gl-js/issues/4107
      if (curve.length > 3 && input === curve[curve.length - 2]) {
          return;
      }
      // step curves don't get the first input value, as it is redundant.
      if (!(isStep && curve.length === 2)) {
          curve.push(input);
      }
      curve.push(output);
  }
  function getFunctionType(parameters, propertySpec) {
      if (parameters.type) {
          return parameters.type;
      }
      else {
          return propertySpec.expression.interpolated ? 'exponential' : 'interval';
      }
  }
  // "String with {name} token" => ["concat", "String with ", ["get", "name"], " token"]
  function convertTokenString(s) {
      const result = ['concat'];
      const re = /{([^{}]+)}/g;
      let pos = 0;
      for (let match = re.exec(s); match !== null; match = re.exec(s)) {
          const literal = s.slice(pos, re.lastIndex - match[0].length);
          pos = re.lastIndex;
          if (literal.length > 0)
              result.push(literal);
          result.push(['get', match[1]]);
      }
      if (result.length === 1) {
          return s;
      }
      if (pos < s.length) {
          result.push(s.slice(pos));
      }
      else if (result.length === 2) {
          return ['to-string', result[1]];
      }
      return result;
  }

  const v8 = v8Spec;

  var fontWeights = {
    thin: 100,
    hairline: 100,
    'ultra-light': 200,
    'extra-light': 200,
    light: 300,
    book: 300,
    regular: 400,
    normal: 400,
    plain: 400,
    roman: 400,
    standard: 400,
    medium: 500,
    'semi-bold': 600,
    'demi-bold': 600,
    bold: 700,
    'extra-bold': 800,
    'ultra-bold': 800,
    heavy: 900,
    black: 900,
    'heavy-black': 900,
    fat: 900,
    poster: 900,
    'ultra-black': 950,
    'extra-black': 950
  };
  var sp = ' ';
  var italicRE = /(italic|oblique)$/i;

  var fontCache = {};

  /**
   * @param {string|Array<string>} fonts Mapbox GL Style fontstack or single font, e.g. `['Open Sans Regular', 'Arial Unicode MS Regular']` or `'Open Sans Regular'`.
   * @param {number} size Font size in pixels.
   * @param {string|number} [lineHeight] Line height as css line-height.
   * @returns {string} CSS font definition, e.g. `'normal 400 16px/1.2 "Open Sans"'`.
   */
  function mb2css(fonts, size, lineHeight) {
    var cssData = fontCache[fonts];
    if (!cssData) {
      if (!Array.isArray(fonts)) {
        fonts = [fonts];
      }
      var weight = 400;
      var style = 'normal';
      var fontFamilies = [];
      var haveWeight, haveStyle;
      for (var i = 0, ii = fonts.length; i < ii; ++i) {
        var font = fonts[i];
        var parts = font.split(' ');
        var maybeWeight = parts[parts.length - 1].toLowerCase();
        if (maybeWeight == 'normal' || maybeWeight == 'italic' || maybeWeight == 'oblique') {
          style = haveStyle ? style : maybeWeight;
          haveStyle = true;
          parts.pop();
          maybeWeight = parts[parts.length - 1].toLowerCase();
        } else if (italicRE.test(maybeWeight)) {
          maybeWeight = maybeWeight.replace(italicRE, '');
          style = haveStyle ? style : parts[parts.length - 1].replace(maybeWeight, '');
          haveStyle = true;
        }
        for (var w in fontWeights) {
          var previousPart = parts.length > 1 ? parts[parts.length - 2].toLowerCase() : '';
          if (maybeWeight == w || maybeWeight == w.replace('-', '') || previousPart + '-' + maybeWeight == w) {
            weight = haveWeight ? weight : fontWeights[w];
            parts.pop();
            if (previousPart && w.startsWith(previousPart)) {
              parts.pop();
            }
            break;
          }
        }
        if (!haveWeight && typeof maybeWeight == 'number') {
          weight = maybeWeight;
          haveWeight = true;
        }
        var fontFamily = parts.join(sp)
          .replace('Klokantech Noto Sans', 'Noto Sans')
          .replace('DIN Pro', 'Barlow')
          .replace('Arial Unicode MS', 'Arial');
        if (fontFamily.indexOf(sp) !== -1) {
          fontFamily = '"' + fontFamily + '"';
        }
        fontFamilies.push(fontFamily);
      }
      // CSS font property: font-style font-weight font-size/line-height font-family
      cssData = fontCache[fonts] = [style, weight, fontFamilies];
    }
    return cssData[0] + sp + cssData[1] + sp + size + 'px' + (lineHeight ? '/' + lineHeight : '') + sp + cssData[2];
  }

  const mapboxBaseUrl = 'https://api.mapbox.com';

  /**
   * @typedef {Object} Sprite
   * @property {string} id Id of the sprite source.
   * @property {string} url URL to the sprite source.
   */

  /**
   * Gets the path from a mapbox:// URL.
   * @param {string} url The Mapbox URL.
   * @return {string} The path.
   * @private
   */
  function getMapboxPath(url) {
    const startsWith = 'mapbox://';
    if (url.indexOf(startsWith) !== 0) {
      return '';
    }
    return url.slice(startsWith.length);
  }

  /**
   * Normalizes legacy string-based or new-style array based sprite definitions into array-based.
   * @param {string|Array<Sprite>} sprite the sprite source.
   * @param {string} token The access token.
   * @param {string} styleUrl The style URL.
   * @return {Array<Sprite>} An array of sprite definitions with normalized URLs.
   * @private
   */
  function normalizeSpriteDefinition(sprite, token, styleUrl) {
    if (typeof sprite === 'string') {
      return [
        {
          'id': 'default',
          'url': normalizeSpriteUrl(sprite, token, styleUrl),
        },
      ];
    }

    for (const spriteObj of sprite) {
      spriteObj.url = normalizeSpriteUrl(spriteObj.url, token, styleUrl);
    }

    return sprite;
  }

  /**
   * Turns mapbox:// sprite URLs into resolvable URLs.
   * @param {string} url The sprite URL.
   * @param {string} token The access token.
   * @param {string} styleUrl The style URL.
   * @return {string} A resolvable URL.
   * @private
   */
  function normalizeSpriteUrl(url, token, styleUrl) {
    const mapboxPath = getMapboxPath(url);
    if (!mapboxPath) {
      return decodeURI(new URL(url, styleUrl).href);
    }
    const startsWith = 'sprites/';
    if (mapboxPath.indexOf(startsWith) !== 0) {
      throw new Error(`unexpected sprites url: ${url}`);
    }
    const sprite = mapboxPath.slice(startsWith.length);

    return `${mapboxBaseUrl}/styles/v1/${sprite}/sprite?access_token=${token}`;
  }

  /**
   * Turns mapbox:// style URLs into resolvable URLs.
   * @param {string} url The style URL.
   * @param {string} token The access token.
   * @return {string} A resolvable URL.
   * @private
   */
  function normalizeStyleUrl(url, token) {
    const mapboxPath = getMapboxPath(url);
    if (!mapboxPath) {
      return decodeURI(new URL(url, location.href).href);
    }
    const startsWith = 'styles/';
    if (mapboxPath.indexOf(startsWith) !== 0) {
      throw new Error(`unexpected style url: ${url}`);
    }
    const style = mapboxPath.slice(startsWith.length);

    return `${mapboxBaseUrl}/styles/v1/${style}?&access_token=${token}`;
  }

  const mapboxSubdomains = ['a', 'b', 'c', 'd'];

  /**
   * Turns mapbox:// source URLs into vector tile URL templates.
   * @param {string} url The source URL.
   * @param {string} token The access token.
   * @param {string} tokenParam The access token key.
   * @param {string} styleUrl The style URL.
   * @return {Array<string>} A vector tile template.
   * @private
   */
  function normalizeSourceUrl(url, token, tokenParam, styleUrl) {
    const urlObject = new URL(url, styleUrl || location.href);
    const mapboxPath = getMapboxPath(url);
    if (!mapboxPath) {
      if (!token) {
        return [decodeURI(urlObject.href)];
      }
      if (!urlObject.searchParams.has(tokenParam)) {
        urlObject.searchParams.set(tokenParam, token);
      }
      return [decodeURI(urlObject.href)];
    }

    if (mapboxPath === 'mapbox.satellite') {
      const sizeFactor = window.devicePixelRatio >= 1.5 ? '@2x' : '';
      return [
        `https://api.mapbox.com/v4/${mapboxPath}/{z}/{x}/{y}${sizeFactor}.webp?access_token=${token}`,
      ];
    }
    return mapboxSubdomains.map(
      (sub) =>
        `https://${sub}.tiles.mapbox.com/v4/${mapboxPath}/{z}/{x}/{y}.vector.pbf?access_token=${token}`,
    );
  }

  /** @typedef {'Style'|'Source'|'Sprite'|'SpriteImage'|'Tiles'|'GeoJSON'} ResourceType */

  /** @typedef {import("ol").Map} Map */
  /** @typedef {import("ol/layer").Layer} Layer */
  /** @typedef {import("ol/layer").Group} LayerGroup */
  /** @typedef {import("ol/layer").Vector} VectorLayer */
  /** @typedef {import("ol/layer").VectorTile} VectorTileLayer */
  /** @typedef {import("ol/source").Source} Source */

  const emptyObj = Object.freeze({});

  const functionCacheByStyleId = {};
  const filterCacheByStyleId = {};

  let styleId = 0;
  function getStyleId(glStyle) {
    if (!glStyle.id) {
      glStyle.id = styleId++;
    }
    return glStyle.id;
  }

  function getStyleFunctionKey(glStyle, olLayer) {
    return getStyleId(glStyle) + '.' + getUid(olLayer);
  }

  /**
   * @param {Object} glStyle Mapboox style object.
   * @return {Object} Function cache.
   */
  function getFunctionCache(glStyle) {
    let functionCache = functionCacheByStyleId[glStyle.id];
    if (!functionCache) {
      functionCache = {};
      functionCacheByStyleId[getStyleId(glStyle)] = functionCache;
    }
    return functionCache;
  }

  /**
   * @param {Object} glStyle Mapboox style object.
   * @return {Object} Filter cache.
   */
  function getFilterCache(glStyle) {
    let filterCache = filterCacheByStyleId[glStyle.id];
    if (!filterCache) {
      filterCache = {};
      filterCacheByStyleId[getStyleId(glStyle)] = filterCache;
    }
    return filterCache;
  }

  function deg2rad(degrees) {
    return (degrees * Math.PI) / 180;
  }

  const defaultResolutions = (function () {
    const resolutions = [];
    for (let res = 78271.51696402048; resolutions.length <= 24; res /= 2) {
      resolutions.push(res);
    }
    return resolutions;
  })();

  /**
   * @param {number} width Width of the canvas.
   * @param {number} height Height of the canvas.
   * @return {HTMLCanvasElement} Canvas.
   */
  function createCanvas(width, height) {
    if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && typeof OffscreenCanvas !== 'undefined') { // eslint-disable-line
      return /** @type {?} */ (new OffscreenCanvas(width, height));
    }
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }

  function getZoomForResolution(resolution, resolutions) {
    let i = 0;
    const ii = resolutions.length;
    for (; i < ii; ++i) {
      const candidate = resolutions[i];
      if (candidate < resolution && i + 1 < ii) {
        const zoomFactor = resolutions[i] / resolutions[i + 1];
        return i + Math.log(resolutions[i] / resolution) / Math.log(zoomFactor);
      }
    }
    return ii - 1;
  }

  function getResolutionForZoom(zoom, resolutions) {
    const base = Math.floor(zoom);
    const factor = Math.pow(2, zoom - base);
    return resolutions[base] / factor;
  }

  const pendingRequests = {};
  /**
   * @param {ResourceType} resourceType Type of resource to load.
   * @param {string} url Url of the resource.
   * @param {Options} [options] Options.
   * @param {{url?: string}} [metadata] Object to be filled with the request.
   * @return {Promise<Object|Response>} Promise that resolves with the loaded resource
   * or rejects with the Response object.
   * @private
   */
  function fetchResource(resourceType, url, options = {}, metadata) {
    if (url in pendingRequests) {
      if (metadata) {
        metadata.url = pendingRequests[url][0].url;
      }
      return pendingRequests[url][1];
    }
    const transformedRequest = options.transformRequest
      ? options.transformRequest(url, resourceType) || url
      : url;
    const handleError = function (error) {
      delete pendingRequests[url];
      return Promise.reject(new Error('Error fetching source ' + url));
    };
    const handleResponse = function (response) {
      delete pendingRequests[url];
      return response.ok
        ? response.json()
        : Promise.reject(new Error('Error fetching source ' + url));
    };
    const pendingRequest = toPromise(() => transformedRequest)
      .then((transformedRequest) => {
        if (transformedRequest instanceof Response) {
          if (metadata) {
            metadata.url = transformedRequest.url;
          }
          return handleResponse(transformedRequest);
        }
        if (!(transformedRequest instanceof Request)) {
          transformedRequest = new Request(transformedRequest);
        }
        if (!transformedRequest.headers.get('Accept')) {
          transformedRequest.headers.set('Accept', 'application/json');
        }
        if (metadata) {
          metadata.url = transformedRequest.url;
        }
        return fetch(transformedRequest).then(handleResponse).catch(handleError);
      })
      .catch(handleError);
    pendingRequests[url] = [transformedRequest, pendingRequest];
    return pendingRequest;
  }

  function getGlStyle(glStyleOrUrl, options) {
    if (typeof glStyleOrUrl === 'string') {
      if (glStyleOrUrl.trim().startsWith('{')) {
        try {
          const glStyle = JSON.parse(glStyleOrUrl);
          return Promise.resolve(glStyle);
        } catch (error) {
          return Promise.reject(error);
        }
      } else {
        glStyleOrUrl = normalizeStyleUrl(glStyleOrUrl, options.accessToken);
        return fetchResource('Style', glStyleOrUrl, options);
      }
    } else {
      return Promise.resolve(glStyleOrUrl);
    }
  }

  const tilejsonCache = {};
  /**
   * @param {Object} glSource glStyle source object.
   * @param {string} styleUrl Style URL.
   * @param {Options} options Options.
   * @return {Promise<{tileJson: Object, tileLoadFunction: import('ol/Tile.js').LoadFunction}?>} TileJson and load function
   */
  function getTileJson(glSource, styleUrl, options = {}) {
    const cacheKey = [styleUrl, JSON.stringify(glSource)].toString();
    let promise = tilejsonCache[cacheKey];
    if (!promise || options.transformRequest) {
      let tileLoadFunction;
      if (options.transformRequest) {
        tileLoadFunction = (tile, src) => {
          const transformedRequest = options.transformRequest
            ? options.transformRequest(src, 'Tiles') || src
            : src;
          if (tile instanceof VectorTile$1) {
            tile.setLoader((extent, resolution, projection) => {
              const handleResponse = function (response) {
                response.arrayBuffer().then((data) => {
                  const format = tile.getFormat();
                  const features = format.readFeatures(data, {
                    extent: extent,
                    featureProjection: projection,
                  });
                  // @ts-ignore
                  tile.setFeatures(features);
                });
              };
              toPromise(() => transformedRequest)
                .then((transformedRequest) => {
                  if (transformedRequest instanceof Response) {
                    return handleResponse(transformedRequest);
                  }
                  fetch(transformedRequest)
                    .then(handleResponse)
                    .catch((e) => tile.setState(TileState.ERROR));
                })
                .catch((e) => tile.setState(TileState.ERROR));
            });
          } else {
            const img = tile.getImage();
            toPromise(() => transformedRequest)
              .then((transformedRequest) => {
                if (typeof transformedRequest === 'string') {
                  img.src = transformedRequest;
                  return;
                }
                const handleResponse = (response) =>
                  response.blob().then((blob) => {
                    const url = URL.createObjectURL(blob);
                    img.addEventListener('load', () => URL.revokeObjectURL(url));
                    img.addEventListener('error', () => URL.revokeObjectURL(url));
                    img.src = url;
                  });
                if (transformedRequest instanceof Response) {
                  return handleResponse(transformedRequest);
                }
                fetch(transformedRequest)
                  .then(handleResponse)
                  .catch((e) => tile.setState(TileState.ERROR));
              })
              .catch((e) => tile.setState(TileState.ERROR));
          }
        };
      }
      const url = glSource.url;
      if (url && !glSource.tiles) {
        const normalizedSourceUrl = normalizeSourceUrl(
          url,
          options.accessToken,
          options.accessTokenParam || 'access_token',
          styleUrl || location.href,
        );
        if (url.startsWith('mapbox://')) {
          promise = Promise.resolve({
            tileJson: Object.assign({}, glSource, {
              url: undefined,
              tiles: normalizedSourceUrl,
            }),
            tileLoadFunction,
          });
        } else {
          const metadata = {};
          promise = fetchResource(
            'Source',
            normalizedSourceUrl[0],
            options,
            metadata,
          ).then(function (tileJson) {
            tileJson.tiles = tileJson.tiles.map(function (tileUrl) {
              if (tileJson.scheme === 'tms') {
                tileUrl = tileUrl.replace('{y}', '{-y}');
              }
              return normalizeSourceUrl(
                tileUrl,
                options.accessToken,
                options.accessTokenParam || 'access_token',
                metadata.url,
              )[0];
            });
            return Promise.resolve({tileJson, tileLoadFunction});
          });
        }
      } else if (glSource.tiles) {
        glSource = Object.assign({}, glSource, {
          tiles: glSource.tiles.map(function (tileUrl) {
            if (glSource.scheme === 'tms') {
              tileUrl = tileUrl.replace('{y}', '{-y}');
            }
            return normalizeSourceUrl(
              tileUrl,
              options.accessToken,
              options.accessTokenParam || 'access_token',
              styleUrl || location.href,
            )[0];
          }),
        });
        promise = Promise.resolve({
          tileJson: Object.assign({}, glSource),
          tileLoadFunction,
        });
      } else {
        promise = Promise.reject(new Error('source has no `tiles` nor `url`'));
      }
      tilejsonCache[cacheKey] = promise;
    }
    return promise;
  }

  /**
   * @param {HTMLImageElement|HTMLCanvasElement} spriteImage Sprite image id.
   * @param {{x: number, y: number, width: number, height: number, pixelRatio: number}} spriteImageData Sprite image data.
   * @param {number} haloWidth Halo width.
   * @param {{r: number, g: number, b: number, a: number}} haloColor Halo color.
   * @return {HTMLCanvasElement} Canvas element with the halo.
   */
  function drawIconHalo(
    spriteImage,
    spriteImageData,
    haloWidth,
    haloColor,
  ) {
    const imgSize = [
      2 * haloWidth * spriteImageData.pixelRatio + spriteImageData.width,
      2 * haloWidth * spriteImageData.pixelRatio + spriteImageData.height,
    ];
    const imageCanvas = createCanvas(imgSize[0], imgSize[1]);
    const imageContext = imageCanvas.getContext('2d');
    imageContext.drawImage(
      spriteImage,
      spriteImageData.x,
      spriteImageData.y,
      spriteImageData.width,
      spriteImageData.height,
      haloWidth * spriteImageData.pixelRatio,
      haloWidth * spriteImageData.pixelRatio,
      spriteImageData.width,
      spriteImageData.height,
    );
    const imageData = imageContext.getImageData(0, 0, imgSize[0], imgSize[1]);
    imageContext.globalCompositeOperation = 'destination-over';
    imageContext.fillStyle = `rgba(${haloColor.r * 255},${haloColor.g * 255},${
    haloColor.b * 255
  },${haloColor.a})`;
    const data = imageData.data;
    for (let i = 0, ii = imageData.width; i < ii; ++i) {
      for (let j = 0, jj = imageData.height; j < jj; ++j) {
        const index = (j * ii + i) * 4;
        const alpha = data[index + 3];
        if (alpha > 0) {
          imageContext.arc(
            i,
            j,
            haloWidth * spriteImageData.pixelRatio,
            0,
            2 * Math.PI,
          );
        }
      }
    }
    imageContext.fill();
    return imageCanvas;
  }

  function smoothstep(min, max, value) {
    const x = Math.max(0, Math.min(1, (value - min) / (max - min)));
    return x * x * (3 - 2 * x);
  }

  /**
   * @param {HTMLImageElement|HTMLCanvasElement} image SDF image
   * @param {{x: number, y: number, width: number, height: number}} area Area to unSDF
   * @param {{r: number, g: number, b: number, a: number}} color Color to use
   * @return {HTMLCanvasElement} Regular image
   */
  function drawSDF(image, area, color) {
    const imageCanvas = createCanvas(area.width, area.height);
    const imageContext = imageCanvas.getContext('2d');
    imageContext.drawImage(
      image,
      area.x,
      area.y,
      area.width,
      area.height,
      0,
      0,
      area.width,
      area.height,
    );
    const imageData = imageContext.getImageData(0, 0, area.width, area.height);
    const data = imageData.data;
    for (let i = 0, ii = imageData.width; i < ii; ++i) {
      for (let j = 0, jj = imageData.height; j < jj; ++j) {
        const index = (j * ii + i) * 4;
        const dist = data[index + 3] / 255;

        const buffer = 0.75;
        const gamma = 0.1;

        const alpha = smoothstep(buffer - gamma, buffer + gamma, dist);
        if (alpha > 0) {
          data[index + 0] = Math.round(255 * color.r * alpha);
          data[index + 1] = Math.round(255 * color.g * alpha);
          data[index + 2] = Math.round(255 * color.b * alpha);
          data[index + 3] = Math.round(255 * alpha);
        } else {
          data[index + 3] = 0;
        }
      }
    }
    imageContext.putImageData(imageData, 0, 0);
    return imageCanvas;
  }

  /**
   * @typedef {import("./apply.js").Options} Options
   * @private
   */

  const hairSpacePool = Array(256).join('\u200A');
  function applyLetterSpacing(text, letterSpacing) {
    if (letterSpacing >= 0.05) {
      let textWithLetterSpacing = '';
      const lines = text.split('\n');
      const joinSpaceString = hairSpacePool.slice(
        0,
        Math.round(letterSpacing / 0.1),
      );
      for (let l = 0, ll = lines.length; l < ll; ++l) {
        if (l > 0) {
          textWithLetterSpacing += '\n';
        }
        textWithLetterSpacing += lines[l].split('').join(joinSpaceString);
      }
      return textWithLetterSpacing;
    }
    return text;
  }

  let measureContext;
  function getMeasureContext() {
    if (!measureContext) {
      measureContext = createCanvas(1, 1).getContext('2d');
    }
    return measureContext;
  }

  function measureText(text, letterSpacing) {
    return (
      getMeasureContext().measureText(text).width +
      (text.length - 1) * letterSpacing
    );
  }

  const measureCache = {};
  checkedFonts.on('propertychange', () => {
    for (const key in measureCache) {
      delete measureCache[key];
    }
  });

  function wrapText(text, font, em, letterSpacing) {
    if (text.indexOf('\n') !== -1) {
      const hardLines = text.split('\n');
      const lines = [];
      for (let i = 0, ii = hardLines.length; i < ii; ++i) {
        lines.push(wrapText(hardLines[i], font, em, letterSpacing));
      }
      return lines.join('\n');
    }
    const key = em + ',' + font + ',' + text + ',' + letterSpacing;
    let wrappedText = measureCache[key];
    if (!wrappedText) {
      const words = text.split(' ');
      if (words.length > 1) {
        const ctx = getMeasureContext();
        ctx.font = font;
        const oneEm = ctx.measureText('M').width;
        const maxWidth = oneEm * em;
        let line = '';
        const lines = [];
        // Pass 1 - wrap lines to not exceed maxWidth
        for (let i = 0, ii = words.length; i < ii; ++i) {
          const word = words[i];
          const testLine = line + (line ? ' ' : '') + word;
          if (measureText(testLine, letterSpacing) <= maxWidth) {
            line = testLine;
          } else {
            if (line) {
              lines.push(line);
            }
            line = word;
          }
        }
        if (line) {
          lines.push(line);
        }
        // Pass 2 - add lines with a width of less than 30% of maxWidth to the previous or next line
        for (let i = 0, ii = lines.length; i < ii && ii > 1; ++i) {
          const line = lines[i];
          if (measureText(line, letterSpacing) < maxWidth * 0.35) {
            const prevWidth =
              i > 0 ? measureText(lines[i - 1], letterSpacing) : Infinity;
            const nextWidth =
              i < ii - 1 ? measureText(lines[i + 1], letterSpacing) : Infinity;
            lines.splice(i, 1);
            ii -= 1;
            if (prevWidth < nextWidth) {
              lines[i - 1] += ' ' + line;
              i -= 1;
            } else {
              lines[i] = line + ' ' + lines[i];
            }
          }
        }
        // Pass 3 - try to fill 80% of maxWidth for each line
        for (let i = 0, ii = lines.length - 1; i < ii; ++i) {
          const line = lines[i];
          const next = lines[i + 1];
          if (
            measureText(line, letterSpacing) > maxWidth * 0.7 &&
            measureText(next, letterSpacing) < maxWidth * 0.6
          ) {
            const lineWords = line.split(' ');
            const lastWord = lineWords.pop();
            if (measureText(lastWord, letterSpacing) < maxWidth * 0.2) {
              lines[i] = lineWords.join(' ');
              lines[i + 1] = lastWord + ' ' + next;
            }
            ii -= 1;
          }
        }
        wrappedText = lines.join('\n');
      } else {
        wrappedText = text;
      }
      wrappedText = applyLetterSpacing(wrappedText, letterSpacing);
      measureCache[key] = wrappedText;
    }
    return wrappedText;
  }

  const webSafeFonts = [
    'Arial',
    'Courier New',
    'Times New Roman',
    'Verdana',
    'sans-serif',
    'serif',
    'monospace',
    'cursive',
    'fantasy',
  ];

  const processedFontFamilies = {};

  /**
   * @param {Array} fonts Fonts.
   * @param {string} [templateUrl] Template URL.
   * @return {Array} Processed fonts.
   * @private
   */
  function getFonts(
    fonts,
    templateUrl = 'https://cdn.jsdelivr.net/npm/@fontsource/{font-family}/{fontweight}{-fontstyle}.css',
  ) {
    let fontDescriptions;
    for (let i = 0, ii = fonts.length; i < ii; ++i) {
      const font = fonts[i];
      if (font in processedFontFamilies) {
        continue;
      }
      processedFontFamilies[font] = true;
      const cssFont = mb2css(font, 16);
      const parts = cssFont.split(' ');
      if (!fontDescriptions) {
        fontDescriptions = [];
      }
      fontDescriptions.push([
        parts.slice(3).join(' ').replace(/"/g, ''),
        parts[1],
        parts[0],
      ]);
    }
    if (!fontDescriptions) {
      return fonts;
    }

    (async () => {
      await document.fonts.ready;
      for (let i = 0, ii = fontDescriptions.length; i < ii; ++i) {
        const fontDescription = fontDescriptions[i];
        const family = fontDescription[0];
        if (webSafeFonts.includes(family)) {
          continue;
        }
        const weight = fontDescription[1];
        const style = fontDescription[2];
        const loaded = await document.fonts.load(
          `${style} ${weight} 16px "${family}"`,
        );
        if (
          !loaded.some(
            (f) =>
              f.family.replace(/^['"]|['"]$/g, '').toLowerCase() ===
                family.toLowerCase() &&
              f.weight == weight &&
              f.style === style,
          )
        ) {
          const fontUrl = templateUrl
            .replace('{font-family}', family.replace(/ /g, '-').toLowerCase())
            .replace('{Font+Family}', family.replace(/ /g, '+'))
            .replace('{fontweight}', weight)
            .replace(
              '{-fontstyle}',
              style.replace('normal', '').replace(/(.+)/, '-$1'),
            )
            .replace('{fontstyle}', style);
          if (!document.querySelector('link[href="' + fontUrl + '"]')) {
            const markup = document.createElement('link');
            markup.href = fontUrl;
            markup.rel = 'stylesheet';
            document.head.appendChild(markup);
          }
        }
      }
    })();

    return fonts;
  }

  /*
  ol-mapbox-style - Use Mapbox/MapLibre Style objects with OpenLayers
  Copyright 2016-present ol-mapbox-style contributors
  License: https://raw.githubusercontent.com/openlayers/ol-mapbox-style/master/LICENSE
  */


  /**
   * @typedef {import("ol/layer/Vector").default} VectorLayer
   * @typedef {import("ol/layer/VectorTile").default} VectorTileLayer
   * @typedef {import("ol/style/Style").StyleFunction} StyleFunction
   * @typedef {import('./util.js').ResourceType} ResourceType
   */

  /** @typedef {string|Request|Response|Promise<string|Request|Response>|Object<string, string|Request|Response|Promise<string|Request|Response>>} SpriteImageUrl */

  /**
   * @typedef {Object} SpriteImage
   * @property {HTMLImageElement|HTMLCanvasElement} image Image
   * @property {Array<number>} size Size
   * @property {boolean} [unSDFed] Image has been unSDFed
   */

  /** @typedef {Object<string, SpriteImage>} SpriteImages */

  const types = {
    'Point': 1,
    'MultiPoint': 1,
    'LineString': 2,
    'MultiLineString': 2,
    'Polygon': 3,
    'MultiPolygon': 3,
  };
  const anchor = {
    'center': [0.5, 0.5],
    'left': [0, 0.5],
    'right': [1, 0.5],
    'top': [0.5, 0],
    'bottom': [0.5, 1],
    'top-left': [0, 0],
    'top-right': [1, 0],
    'bottom-left': [0, 1],
    'bottom-right': [1, 1],
  };

  const expressionData = function (rawExpression, propertySpec) {
    const compiledExpression = createPropertyExpression(
      rawExpression,
      propertySpec,
    );
    if (compiledExpression.result === 'error') {
      throw new Error(
        compiledExpression.value
          .map((err) => `${err.key}: ${err.message}`)
          .join(', '),
      );
    }
    return compiledExpression.value;
  };

  // Shared camera object for global expression evaluation context
  const cameraObj = {zoom: 0, distanceFromCenter: 0};

  // Add unsupported expressions to the MapLibre GL Style spec
  CompoundExpression.register(expressions$1, {
    ...CompoundExpression.definitions,
    'pitch': [{kind: 'number'}, [], (ctx) => cameraObj.pitch || 90],
    'distance-from-center': [
      {kind: 'number'},
      [],
      (ctx) => cameraObj.distanceFromCenter || 0,
    ],
  });

  let renderFeatureCoordinates, renderFeature;

  /**
   * @private
   * @param {Object} layer Gl object layer.
   * @param {string} layoutOrPaint 'layout' or 'paint'.
   * @param {string} property Feature property.
   * @param {Object} feature Gl feature.
   * @param {Object} [functionCache] Function cache.
   * @param {Object} [featureState] Feature state.
   * @return {?} Value.
   */
  function getValue(
    layer,
    layoutOrPaint,
    property,
    feature,
    functionCache,
    featureState,
  ) {
    const layerId = layer.id;
    if (!functionCache) {
      functionCache = {};
      console.warn('No functionCache provided to getValue()'); // eslint-disable-line no-console
    }
    if (!functionCache[layerId]) {
      functionCache[layerId] = {};
    }
    const functions = functionCache[layerId];
    if (!functions[property]) {
      let value = (layer[layoutOrPaint] || emptyObj)[property];
      const propertySpec = v8[`${layoutOrPaint}_${layer.type}`][property];
      if (value === undefined) {
        value = propertySpec.default;
      }
      let isExpr = isExpression(value);
      if (!isExpr && isFunction$1(value)) {
        value = convertFunction(value, propertySpec);
        isExpr = true;
      }
      if (isExpr) {
        const compiledExpression = expressionData(value, propertySpec);
        functions[property] =
          compiledExpression.evaluate.bind(compiledExpression);
      } else {
        if (propertySpec.type == 'color') {
          value = Color.parse(value);
        }
        functions[property] = function () {
          return value;
        };
      }
    }
    return functions[property](cameraObj, feature, featureState);
  }

  /**
   * @private
   * @param {Object} layer Gl object layer.
   * @param {Object} feature Gl feature.
   * @param {"icon"|"text"} prefix Style property prefix.
   * @param {Object} [functionCache] Function cache.
   * @return {"declutter"|"obstacle"|"none"} Value.
   */
  function getDeclutterMode(layer, feature, prefix, functionCache) {
    const allowOverlap = getValue(
      layer,
      'layout',
      `${prefix}-allow-overlap`,
      feature,
      functionCache,
    );
    if (!allowOverlap) {
      return 'declutter';
    }
    const ignorePlacement = getValue(
      layer,
      'layout',
      `${prefix}-ignore-placement`,
      feature,
      functionCache,
    );
    if (!ignorePlacement) {
      return 'obstacle';
    }
    return 'none';
  }

  /**
   * @private
   * @param {string} layerId Layer id.
   * @param {?} filter Filter.
   * @param {Object} feature Feature.
   * @param {Object} [filterCache] Filter cache.
   * @return {boolean} Filter result.
   */
  function evaluateFilter(layerId, filter, feature, filterCache) {
    if (!filterCache) {
      console.warn('No filterCache provided to evaluateFilter()'); // eslint-disable-line no-console
    }
    if (!(layerId in filterCache)) {
      try {
        filterCache[layerId] = featureFilter(filter).filter;
      } catch (e) {
        console.warn('Filter will evaluate to false: ' + e.message); // eslint-disable-line no-console
        filterCache[layerId] = function () {
          return false;
        };
      }
    }
    return filterCache[layerId](cameraObj, feature);
  }

  /**
   * @private
   * @param {?} color Color.
   * @param {number} [opacity] Opacity.
   * @return {string} Color.
   */
  function colorWithOpacity(color, opacity) {
    if (color) {
      if ((color.a === 0 || opacity === 0)) {
        return undefined;
      }
      const a = color.a;
      opacity = opacity === undefined ? 1 : opacity;
      return a === 0
        ? 'transparent'
        : 'rgba(' +
            Math.round((color.r * 255) / a) +
            ',' +
            Math.round((color.g * 255) / a) +
            ',' +
            Math.round((color.b * 255) / a) +
            ',' +
            a * opacity +
            ')';
    }
    return color;
  }

  const templateRegEx = /\{[^{}}]*\}/g;

  /**
   * @private
   * @param {string} text Text.
   * @param {Object} properties Properties.
   * @return {string} Text.
   */
  function fromTemplate(text, properties) {
    return text.replace(templateRegEx, function (match) {
      return properties[match.slice(1, -1)] || '';
    });
  }

  /**
   * @private
   * @param {string} icon Icon identifier (with prefix if not 'default')
   * @param {SpriteImages} spriteImages Sprite images.
   * @return {SpriteImage} Image.
   */
  function getSpriteImageForIcon(icon, spriteImages) {
    let prefix = icon.split(':')[0];
    if (prefix === icon) {
      prefix = 'default';
    }
    return spriteImages[prefix];
  }

  const styleFunctionArgs = {};

  /**
   * Creates a style function from the `glStyle` object for all layers that use
   * the specified `source`, which needs to be a `"type": "vector"` or
   * `"type": "geojson"` source and applies it to the specified OpenLayers layer.
   *
   * Two additional properties will be set on the provided layer:
   *
   *  * `mapbox-source`: The `id` of the Mapbox/MapLibre Style document's source that the
   *    OpenLayers layer was created from. Usually `apply()` creates one
   *    OpenLayers layer per Mapbox/MapLibre Style source, unless the layer stack has
   *    layers from different sources in between.
   *  * `mapbox-layers`: The `id`s of the Mapbox/MapLibre Style document's layers that are
   *    included in the OpenLayers layer.
   *
   * This function also works in a web worker. In worker mode, the main thread needs
   * to listen to messages from the worker and respond with another message to make
   * sure that sprite image loading works:
   *
   * ```js
   *  worker.addEventListener('message', event => {
   *   if (event.data.action === 'loadImage') {
   *     const image = new Image();
   *     image.crossOrigin = 'anonymous';
   *     image.addEventListener('load', function() {
   *       createImageBitmap(image, 0, 0, image.width, image.height).then(imageBitmap => {
   *         worker.postMessage({
   *           action: 'imageLoaded',
   *           image: imageBitmap,
   *           src: event.data.src
   *         }, [imageBitmap]);
   *       });
   *     });
   *     image.src = event.data.src;
   *   }
   * });
   * ```
   *
   * @param {VectorLayer|VectorTileLayer} olLayer OpenLayers layer to
   * apply the style to. In addition to the style, the layer will get two
   * properties: `mapbox-source` will be the `id` of the `glStyle`'s source used
   * for the layer, and `mapbox-layers` will be an array of the `id`s of the
   * `glStyle`'s layers.
   * @param {string|Object} glStyle Mapbox/MapLibre Style object.
   * @param {string|Array<string>} sourceOrLayers `source` key or an array of layer `id`s
   * from the Mapbox/MapLibre Style object. When a `source` key is provided, all layers for
   * the specified source will be included in the style function. When layer `id`s
   * are provided, they must be from layers that use the same source.
   * @param {Array<number>} resolutions
   * Resolutions for mapping resolution to zoom level.
   * @param {Object} spriteData Sprite data from the url specified in
   * the Mapbox/MapLibre Style object's `sprite` property. Only required if a `sprite`
   * property is specified in the Mapbox/MapLibre Style object.
   * @param {SpriteImageUrl} spriteImageUrl Sprite image url for the sprite
   * specified in the Mapbox/MapLibre Style object's `sprite` property. Only required if a
   * `sprite` property is specified in the Mapbox/MapLibre Style object. If multiple `sprite`s
   * are defined in the style object, this has to be an object with the sprite id as key and the
   * sprite image URL as value.
   * @param {function(Array<string>, string=):Array<string>} getFonts Function that
   * receives a font stack and the url template from the GL style's `metadata['ol:webfonts']`
   * property (if set) as arguments, and returns a (modified) font stack that
   * is available. Font names are the names used in the Mapbox/MapLibre Style object. If
   * not provided, the font stack will be used as-is. This function can also be
   * used for loading web fonts.
   * @param {function(VectorLayer|VectorTileLayer, string):HTMLImageElement|HTMLCanvasElement|string|undefined} [getImage]
   * Function that returns an image or a URL for an image name. If the result is an HTMLImageElement, it must already be
   * loaded. The layer can be used to call layer.changed() when the loading and processing of the image has finished.
   * This function can be used for icons not in the sprite or to override sprite icons.
   * @return {StyleFunction} Style function for use in
   * `ol.layer.Vector` or `ol.layer.VectorTile`.
   */
  function stylefunction(
    olLayer,
    glStyle,
    sourceOrLayers,
    resolutions = defaultResolutions,
    spriteData = undefined,
    spriteImageUrl = undefined,
    getFonts = undefined,
    getImage = undefined,
  ) {
    if (typeof glStyle == 'string') {
      glStyle = JSON.parse(glStyle);
    }
    if (glStyle.version != 8) {
      throw new Error('glStyle version 8 required.');
    }
    styleFunctionArgs[getStyleFunctionKey(glStyle, olLayer)] =
      Array.from(arguments);

    /** @type {SpriteImages} */
    const spriteImages = {};

    if (
      typeof spriteImageUrl === 'string' ||
      spriteImageUrl instanceof Request ||
      spriteImageUrl instanceof Response ||
      spriteImageUrl instanceof Promise
    ) {
      spriteImageUrl = {'default': spriteImageUrl};
    }

    for (const prefix in spriteImageUrl) {
      const imageUrl = spriteImageUrl[prefix];
      toPromise(() => imageUrl).then(async (imageUrl) => {
        let blobUrl;
        if (typeof Image !== 'undefined') {
          const img = new Image();
          if (typeof imageUrl === 'string') {
            img.crossOrigin = 'anonymous';
            img.src = imageUrl;
          } else {
            let response;
            if (imageUrl instanceof Request) {
              response = await fetch(imageUrl);
            } else if (imageUrl instanceof Response) {
              response = imageUrl;
            }
            const blob = await response.blob();
            blobUrl = URL.createObjectURL(blob);
            img.src = blobUrl;
          }
          img.addEventListener('load', function load() {
            img.removeEventListener('load', load);
            spriteImages[prefix] = {
              image: img,
              size: [img.width, img.height],
            };
            olLayer.changed();
            if (blobUrl) {
              URL.revokeObjectURL(blobUrl);
            }
          });
          img.addEventListener('error', function error() {
            URL.revokeObjectURL(blobUrl);
            img.removeEventListener('error', error);
          });
        } else if (
          typeof WorkerGlobalScope !== 'undefined' &&
          self instanceof WorkerGlobalScope // eslint-disable-line
        ) {
          const worker = /** @type {*} */ (self);
          // Main thread needs to handle 'loadImage' and dispatch 'imageLoaded'
          worker.postMessage({
            action: 'loadImage',
            src: imageUrl,
          });
          worker.addEventListener('message', function handler(event) {
            if (
              event.data.action === 'imageLoaded' &&
              event.data.src === imageUrl
            ) {
              spriteImages[prefix] = {
                image: event.data.image,
                size: [event.data.image.width, event.data.image.height],
              };
            }
          });
        }
      });
    }

    const allLayers = derefLayers(glStyle.layers);

    const layersBySourceLayer = {};
    const mapboxLayers = [];

    const iconImageCache = {};
    const patternCache = {};
    const functionCache = getFunctionCache(glStyle);
    const filterCache = getFilterCache(glStyle);

    let mapboxSource;
    for (let i = 0, ii = allLayers.length; i < ii; ++i) {
      const layer = allLayers[i];
      const layerId = layer.id;
      if (
        (typeof sourceOrLayers == 'string' && layer.source == sourceOrLayers) ||
        (Array.isArray(sourceOrLayers) && sourceOrLayers.indexOf(layerId) !== -1)
      ) {
        const sourceLayer = layer['source-layer'];
        if (!mapboxSource) {
          mapboxSource = layer.source;
          const source = glStyle.sources[mapboxSource];
          if (!source) {
            throw new Error(`Source "${mapboxSource}" is not defined`);
          }
          const type = source.type;
          if (type !== 'vector' && type !== 'geojson') {
            throw new Error(
              `Source "${mapboxSource}" is not of type "vector" or "geojson", but "${type}"`,
            );
          }
        } else if (layer.source !== mapboxSource) {
          throw new Error(
            `Layer "${layerId}" does not use source "${mapboxSource}`,
          );
        }
        let layers = layersBySourceLayer[sourceLayer];
        if (!layers) {
          layers = [];
          layersBySourceLayer[sourceLayer] = layers;
        }
        layers.push({
          layer: layer,
          index: i,
        });
        mapboxLayers.push(layerId);
      }
    }

    const textHalo = new Stroke();
    const textColor = new Fill();

    const styles = [];

    /**
     * @param {import("ol/Feature").default|import("ol/render/Feature").default} feature Feature.
     * @param {number} resolution Resolution.
     * @param {string} [onlyLayer] Calculate style for this layer only.
     * @return {Array<import("ol/style/Style").default>} Style.
     */
    const styleFunction = function (feature, resolution, onlyLayer) {
      const properties = feature.getProperties();
      const layers = layersBySourceLayer[properties['mvt:layer']];
      if (!layers) {
        return undefined;
      }
      let zoom = resolutions.indexOf(resolution);
      if (zoom == -1) {
        zoom = getZoomForResolution(resolution, resolutions);
      }
      cameraObj.zoom = zoom;
      cameraObj.distanceFromCenter = 0;
      const featureGeometry = feature.getGeometry();
      const type = types[featureGeometry.getType()];
      const map = olLayer.get('map');
      if (map && map instanceof Map$1 && type === 1) {
        const size = map.getSize();
        if (size) {
          const mapCenter = map.getView().getCenter();
          const featureCenter = getCenter(featureGeometry.getExtent());
          cameraObj.distanceFromCenter =
            distance(mapCenter, featureCenter) / resolution / size[1];
        }
      }
      const f = {
        id: feature.getId(),
        properties: properties,
        type: type,
      };
      const featureState = olLayer.get('mapbox-featurestate')[feature.getId()];
      let stylesLength = -1;
      for (let i = 0, ii = layers.length; i < ii; ++i) {
        const layerData = layers[i];
        const layer = layerData.layer;
        const layerId = layer.id;
        if (onlyLayer !== undefined && onlyLayer !== layerId) {
          continue;
        }

        const layout = layer.layout || emptyObj;
        const paint = layer.paint || emptyObj;
        if (
          layout.visibility === 'none' ||
          ('minzoom' in layer && zoom < layer.minzoom) ||
          ('maxzoom' in layer && zoom >= layer.maxzoom)
        ) {
          continue;
        }
        const filter = layer.filter;
        if (!filter || evaluateFilter(layerId, filter, f, filterCache)) {
          let color, opacity, fill, stroke, strokeColor, style;
          const index = layerData.index;
          if (
            type == 3 &&
            (layer.type == 'fill' || layer.type == 'fill-extrusion')
          ) {
            opacity = getValue(
              layer,
              'paint',
              layer.type + '-opacity',
              f,
              functionCache,
              featureState,
            );
            if (layer.type + '-pattern' in paint) {
              const fillIcon = getValue(
                layer,
                'paint',
                layer.type + '-pattern',
                f,
                functionCache,
                featureState,
              );
              if (fillIcon) {
                const icon =
                  typeof fillIcon === 'string'
                    ? fromTemplate(fillIcon, properties)
                    : fillIcon.toString();
                const spriteImage = getSpriteImageForIcon(icon, spriteImages);
                if (spriteData && spriteData[icon] && spriteImage) {
                  ++stylesLength;
                  style = styles[stylesLength];
                  if (
                    !style ||
                    !style.getFill() ||
                    style.getStroke() ||
                    style.getText()
                  ) {
                    style = new Style({
                      fill: new Fill(),
                    });
                    styles[stylesLength] = style;
                  }
                  fill = style.getFill();
                  style.setZIndex(index);
                  const icon_cache_key = icon + '.' + opacity;
                  let pattern = patternCache[icon_cache_key];
                  if (!pattern) {
                    const spriteImageData = spriteData[icon];
                    const canvas = createCanvas(
                      spriteImageData.width,
                      spriteImageData.height,
                    );
                    const ctx = /** @type {CanvasRenderingContext2D} */ (
                      canvas.getContext('2d')
                    );
                    ctx.globalAlpha = opacity;
                    ctx.drawImage(
                      spriteImage.image,
                      spriteImageData.x,
                      spriteImageData.y,
                      spriteImageData.width,
                      spriteImageData.height,
                      0,
                      0,
                      spriteImageData.width,
                      spriteImageData.height,
                    );
                    pattern = ctx.createPattern(canvas, 'repeat');
                    patternCache[icon_cache_key] = pattern;
                  }
                  fill.setColor(pattern);
                }
              }
            } else {
              color = colorWithOpacity(
                getValue(
                  layer,
                  'paint',
                  layer.type + '-color',
                  f,
                  functionCache,
                  featureState,
                ),
                opacity,
              );
              if (layer.type + '-outline-color' in paint) {
                strokeColor = colorWithOpacity(
                  getValue(
                    layer,
                    'paint',
                    layer.type + '-outline-color',
                    f,
                    functionCache,
                    featureState,
                  ),
                  opacity,
                );
              }
              if (!strokeColor) {
                strokeColor = color;
              }
              if (color || strokeColor) {
                ++stylesLength;
                style = styles[stylesLength];
                if (
                  !style ||
                  (color && !style.getFill()) ||
                  (!color && style.getFill()) ||
                  (strokeColor && !style.getStroke()) ||
                  (!strokeColor && style.getStroke()) ||
                  style.getText()
                ) {
                  style = new Style({
                    fill: color ? new Fill() : undefined,
                    stroke: strokeColor ? new Stroke() : undefined,
                  });
                  styles[stylesLength] = style;
                }
                if (color) {
                  fill = style.getFill();
                  fill.setColor(color);
                }
                if (strokeColor) {
                  stroke = style.getStroke();
                  stroke.setColor(strokeColor);
                  stroke.setWidth(0.5);
                }
                style.setZIndex(index);
              }
            }
          }
          if (type != 1 && layer.type == 'line') {
            if (!('line-pattern' in paint)) {
              color = colorWithOpacity(
                getValue(
                  layer,
                  'paint',
                  'line-color',
                  f,
                  functionCache,
                  featureState,
                ),
                getValue(
                  layer,
                  'paint',
                  'line-opacity',
                  f,
                  functionCache,
                  featureState,
                ),
              );
            } else {
              color = undefined;
            }
            const width = getValue(
              layer,
              'paint',
              'line-width',
              f,
              functionCache,
              featureState,
            );
            if (color && width > 0) {
              ++stylesLength;
              style = styles[stylesLength];
              if (
                !style ||
                !style.getStroke() ||
                style.getFill() ||
                style.getText()
              ) {
                style = new Style({
                  stroke: new Stroke(),
                });
                styles[stylesLength] = style;
              }
              stroke = style.getStroke();
              stroke.setLineCap(
                getValue(
                  layer,
                  'layout',
                  'line-cap',
                  f,
                  functionCache,
                  featureState,
                ),
              );
              stroke.setLineJoin(
                getValue(
                  layer,
                  'layout',
                  'line-join',
                  f,
                  functionCache,
                  featureState,
                ),
              );
              stroke.setMiterLimit(
                getValue(
                  layer,
                  'layout',
                  'line-miter-limit',
                  f,
                  functionCache,
                  featureState,
                ),
              );
              stroke.setColor(color);
              stroke.setWidth(width);
              stroke.setLineDash(
                paint['line-dasharray']
                  ? getValue(
                      layer,
                      'paint',
                      'line-dasharray',
                      f,
                      functionCache,
                      featureState,
                    ).map(function (x) {
                      return x * width;
                    })
                  : null,
              );
              style.setZIndex(index);
            }
          }

          let hasImage = false;
          let text = null;
          let placementAngle = 0;
          let icon, iconImg, skipLabel;
          if ((type == 1 || type == 2) && 'icon-image' in layout) {
            const iconImage = getValue(
              layer,
              'layout',
              'icon-image',
              f,
              functionCache,
              featureState,
            );
            if (iconImage) {
              icon =
                typeof iconImage === 'string'
                  ? fromTemplate(iconImage, properties)
                  : iconImage.toString();
              let styleGeom = undefined;
              const imageElement = getImage ? getImage(olLayer, icon) : undefined;
              const spriteImage = getSpriteImageForIcon(icon, spriteImages);
              if (
                (spriteData && spriteData[icon] && spriteImage) ||
                imageElement
              ) {
                const iconRotationAlignment = getValue(
                  layer,
                  'layout',
                  'icon-rotation-alignment',
                  f,
                  functionCache,
                  featureState,
                );
                if (type == 2) {
                  const geom = /** @type {*} */ (feature.getGeometry());
                  // ol package and ol-debug.js only
                  if (geom.getFlatMidpoint || geom.getFlatMidpoints) {
                    const extent = geom.getExtent();
                    const size = Math.sqrt(
                      Math.max(
                        Math.pow((extent[2] - extent[0]) / resolution, 2),
                        Math.pow((extent[3] - extent[1]) / resolution, 2),
                      ),
                    );
                    if (size > 150) {
                      //FIXME Do not hard-code a size of 150
                      const midpoint =
                        geom.getType() === 'MultiLineString'
                          ? geom.getFlatMidpoints()
                          : geom.getFlatMidpoint();
                      if (!renderFeature) {
                        renderFeatureCoordinates = [NaN, NaN];
                        renderFeature = new RenderFeature(
                          'Point',
                          renderFeatureCoordinates,
                          [],
                          2,
                          {},
                          undefined,
                        );
                      }
                      styleGeom = renderFeature;
                      renderFeatureCoordinates[0] = midpoint[0];
                      renderFeatureCoordinates[1] = midpoint[1];
                      const placement = getValue(
                        layer,
                        'layout',
                        'symbol-placement',
                        f,
                        functionCache,
                        featureState,
                      );
                      if (
                        placement === 'line' &&
                        iconRotationAlignment === 'map'
                      ) {
                        const stride = geom.getStride();
                        const coordinates = geom.getFlatCoordinates();
                        for (
                          let i = 0, ii = coordinates.length - stride;
                          i < ii;
                          i += stride
                        ) {
                          const x1 = coordinates[i];
                          const y1 = coordinates[i + 1];
                          const x2 = coordinates[i + stride];
                          const y2 = coordinates[i + stride + 1];
                          const minX = Math.min(x1, x2);
                          const maxX = Math.max(x1, x2);
                          const xM = midpoint[0];
                          const yM = midpoint[1];
                          const dotProduct =
                            (y2 - y1) * (xM - x1) - (x2 - x1) * (yM - y1);
                          if (
                            Math.abs(dotProduct) < 0.001 && //midpoint is aligned with the segment
                            xM <= maxX &&
                            xM >= minX //midpoint is on the segment and not outside it
                          ) {
                            placementAngle = Math.atan2(y1 - y2, x2 - x1);
                            break;
                          }
                        }
                      }
                    }
                  }
                }
                if (type !== 2 || styleGeom) {
                  const iconSize = getValue(
                    layer,
                    'layout',
                    'icon-size',
                    f,
                    functionCache,
                    featureState,
                  );
                  const iconColor =
                    paint['icon-color'] !== undefined
                      ? getValue(
                          layer,
                          'paint',
                          'icon-color',
                          f,
                          functionCache,
                          featureState,
                        )
                      : null;
                  if (!iconColor || iconColor.a !== 0) {
                    const haloColor = getValue(
                      layer,
                      'paint',
                      'icon-halo-color',
                      f,
                      functionCache,
                      featureState,
                    );
                    const haloWidth = getValue(
                      layer,
                      'paint',
                      'icon-halo-width',
                      f,
                      functionCache,
                      featureState,
                    );
                    let iconCacheKey = `${icon}.${iconSize}.${haloWidth}.${haloColor}`;
                    if (iconColor !== null) {
                      iconCacheKey += `.${iconColor}`;
                    }
                    iconImg = iconImageCache[iconCacheKey];
                    if (!iconImg) {
                      const declutterMode = getDeclutterMode(
                        layer,
                        f,
                        'icon',
                        functionCache,
                      );
                      let displacement;
                      if ('icon-offset' in layout) {
                        displacement = getValue(
                          layer,
                          'layout',
                          'icon-offset',
                          f,
                          functionCache,
                          featureState,
                        ).slice(0);
                        displacement[0] *= iconSize;
                        displacement[1] *= -iconSize;
                      }
                      let color = iconColor
                        ? [
                            iconColor.r * 255,
                            iconColor.g * 255,
                            iconColor.b * 255,
                            iconColor.a,
                          ]
                        : undefined;
                      if (imageElement) {
                        const iconOptions = {
                          color: color,
                          rotateWithView: iconRotationAlignment === 'map',
                          displacement: displacement,
                          declutterMode: declutterMode,
                          scale: iconSize,
                        };
                        if (typeof imageElement === 'string') {
                          // it is a src URL
                          iconOptions.src = imageElement;
                        } else {
                          iconOptions.img = imageElement;
                          iconOptions.imgSize = [
                            imageElement.width,
                            imageElement.height,
                          ];
                        }
                        iconImg = new Icon(iconOptions);
                      } else {
                        const spriteImageData = spriteData[icon];
                        let img, size, offset;
                        if (haloWidth) {
                          if (spriteImageData.sdf) {
                            img = drawIconHalo(
                              drawSDF(
                                spriteImage.image,
                                spriteImageData,
                                iconColor || [0, 0, 0, 1],
                              ),
                              {
                                x: 0,
                                y: 0,
                                width: spriteImageData.width,
                                height: spriteImageData.height,
                                pixelRatio: spriteImageData.pixelRatio,
                              },
                              haloWidth,
                              haloColor,
                            );
                            color = undefined; // do not tint haloed icons
                          } else {
                            img = drawIconHalo(
                              spriteImage.image,
                              spriteImageData,
                              haloWidth,
                              haloColor,
                            );
                          }
                        } else {
                          if (spriteImageData.sdf) {
                            if (!spriteImage.unSDFed) {
                              const spriteImageUnSDFed = drawSDF(
                                spriteImage.image,
                                {
                                  x: 0,
                                  y: 0,
                                  width: spriteImage.size[0],
                                  height: spriteImage.size[1],
                                },
                                {r: 1, g: 1, b: 1},
                              );
                              spriteImage.image = spriteImageUnSDFed;
                              spriteImage.unSDFed = true;
                            }
                          }
                          img = spriteImage.image;
                          size = [spriteImageData.width, spriteImageData.height];
                          offset = [spriteImageData.x, spriteImageData.y];
                        }
                        iconImg = new Icon({
                          color: color,
                          img: img,
                          // @ts-ignore
                          imgSize: spriteImage.size,
                          size: size,
                          offset: offset,
                          rotateWithView: iconRotationAlignment === 'map',
                          scale: iconSize / spriteImageData.pixelRatio,
                          displacement: displacement,
                          declutterMode: declutterMode,
                        });
                      }
                      iconImageCache[iconCacheKey] = iconImg;
                    }
                  }
                  if (iconImg) {
                    ++stylesLength;
                    style = styles[stylesLength];
                    if (
                      !style ||
                      !style.getImage() ||
                      style.getFill() ||
                      style.getStroke()
                    ) {
                      style = new Style();
                      styles[stylesLength] = style;
                    }
                    style.setGeometry(styleGeom);
                    iconImg.setRotation(
                      placementAngle +
                        deg2rad(
                          getValue(
                            layer,
                            'layout',
                            'icon-rotate',
                            f,
                            functionCache,
                            featureState,
                          ),
                        ),
                    );
                    iconImg.setOpacity(
                      getValue(
                        layer,
                        'paint',
                        'icon-opacity',
                        f,
                        functionCache,
                        featureState,
                      ),
                    );
                    iconImg.setAnchor(
                      anchor[
                        getValue(
                          layer,
                          'layout',
                          'icon-anchor',
                          f,
                          functionCache,
                          featureState,
                        )
                      ],
                    );
                    style.setImage(iconImg);
                    text = style.getText();
                    style.setText(undefined);
                    style.setZIndex(index);
                    hasImage = true;
                    skipLabel = false;
                  }
                } else {
                  skipLabel = true;
                }
              }
            }
          }

          if (type == 1 && layer.type === 'circle') {
            ++stylesLength;
            style = styles[stylesLength];
            if (
              !style ||
              !style.getImage() ||
              style.getFill() ||
              style.getStroke()
            ) {
              style = new Style();
              styles[stylesLength] = style;
            }
            const circleRadius =
              'circle-radius' in paint
                ? getValue(
                    layer,
                    'paint',
                    'circle-radius',
                    f,
                    functionCache,
                    featureState,
                  )
                : 5;
            const circleStrokeColor = colorWithOpacity(
              getValue(
                layer,
                'paint',
                'circle-stroke-color',
                f,
                functionCache,
                featureState,
              ),
              getValue(
                layer,
                'paint',
                'circle-stroke-opacity',
                f,
                functionCache,
                featureState,
              ),
            );

            const circleTranslate = getValue(
              layer,
              'paint',
              'circle-translate',
              f,
              functionCache,
              featureState,
            );
            const circleColor = colorWithOpacity(
              getValue(
                layer,
                'paint',
                'circle-color',
                f,
                functionCache,
                featureState,
              ),
              getValue(
                layer,
                'paint',
                'circle-opacity',
                f,
                functionCache,
                featureState,
              ),
            );
            const circleStrokeWidth = getValue(
              layer,
              'paint',
              'circle-stroke-width',
              f,
              functionCache,
              featureState,
            );
            const cache_key =
              circleRadius +
              '.' +
              circleStrokeColor +
              '.' +
              circleColor +
              '.' +
              circleStrokeWidth +
              '.' +
              circleTranslate[0] +
              '.' +
              circleTranslate[1];

            iconImg = iconImageCache[cache_key];
            if (!iconImg) {
              iconImg = new CircleStyle({
                radius: circleRadius,
                displacement: [circleTranslate[0], -circleTranslate[1]],
                stroke:
                  circleStrokeColor && circleStrokeWidth > 0
                    ? new Stroke({
                        width: circleStrokeWidth,
                        color: circleStrokeColor,
                      })
                    : undefined,
                fill: circleColor
                  ? new Fill({
                      color: circleColor,
                    })
                  : undefined,
                declutterMode: 'none',
              });
              iconImageCache[cache_key] = iconImg;
            }
            style.setImage(iconImg);
            text = style.getText();
            style.setText(undefined);
            style.setGeometry(undefined);
            style.setZIndex(index);
            hasImage = true;
          }

          let label, font, textLineHeight, textSize, letterSpacing, maxTextWidth;
          if ('text-field' in layout) {
            textSize = Math.round(
              getValue(
                layer,
                'layout',
                'text-size',
                f,
                functionCache,
                featureState,
              ),
            );
            const fontArray = getValue(
              layer,
              'layout',
              'text-font',
              f,
              functionCache,
              featureState,
            );
            textLineHeight = getValue(
              layer,
              'layout',
              'text-line-height',
              f,
              functionCache,
              featureState,
            );
            font = mb2css(
              getFonts
                ? getFonts(
                    fontArray,
                    glStyle.metadata
                      ? glStyle.metadata['ol:webfonts']
                      : undefined,
                  )
                : fontArray,
              textSize,
              textLineHeight,
            );
            if (!font.includes('sans-serif')) {
              font += ',sans-serif';
            }
            letterSpacing = getValue(
              layer,
              'layout',
              'text-letter-spacing',
              f,
              functionCache,
              featureState,
            );
            maxTextWidth = getValue(
              layer,
              'layout',
              'text-max-width',
              f,
              functionCache,
              featureState,
            );
            const textField = getValue(
              layer,
              'layout',
              'text-field',
              f,
              functionCache,
              featureState,
            );
            if (typeof textField === 'object' && textField.sections) {
              if (textField.sections.length === 1) {
                label = textField.toString();
              } else {
                label = textField.sections.reduce((acc, chunk, i) => {
                  const fonts = chunk.fontStack
                    ? chunk.fontStack.split(',')
                    : fontArray;
                  const chunkFont = mb2css(
                    getFonts ? getFonts(fonts) : fonts,
                    textSize * (chunk.scale || 1),
                    textLineHeight,
                  );
                  let text = chunk.text;
                  if (text === '\n') {
                    acc.push('\n', '');
                    return acc;
                  }
                  if (type == 2) {
                    acc.push(applyLetterSpacing(text, letterSpacing), chunkFont);
                    return acc;
                  }
                  text = wrapText(
                    text,
                    chunkFont,
                    maxTextWidth,
                    letterSpacing,
                  ).split('\n');
                  for (let i = 0, ii = text.length; i < ii; ++i) {
                    if (i > 0) {
                      acc.push('\n', '');
                    }
                    acc.push(text[i], chunkFont);
                  }
                  return acc;
                }, []);
              }
            } else {
              label = fromTemplate(textField, properties).trim();
            }
            opacity = getValue(
              layer,
              'paint',
              'text-opacity',
              f,
              functionCache,
              featureState,
            );
          }
          if (label && opacity && !skipLabel) {
            if (!hasImage) {
              ++stylesLength;
              style = styles[stylesLength];
              if (
                !style ||
                !style.getText() ||
                style.getFill() ||
                style.getStroke()
              ) {
                style = new Style();
                styles[stylesLength] = style;
              }
              style.setImage(undefined);
              style.setGeometry(undefined);
            }
            const declutterMode = getDeclutterMode(
              layer,
              f,
              'text',
              functionCache,
            );
            if (!style.getText()) {
              style.setText(text);
            }
            text = style.getText();
            if (
              !text ||
              ('getDeclutterMode' in text &&
                text.getDeclutterMode() !== declutterMode)
            ) {
              text = new Text({
                padding: [2, 2, 2, 2],
                // @ts-ignore
                declutterMode: declutterMode,
              });
              style.setText(text);
            }
            const textTransform = getValue(
              layer,
              'layout',
              'text-transform',
              f,
              functionCache,
              featureState,
            );
            if (textTransform == 'uppercase') {
              label = Array.isArray(label)
                ? label.map((t, i) => (i % 2 ? t : t.toUpperCase()))
                : label.toUpperCase();
            } else if (textTransform == 'lowercase') {
              label = Array.isArray(label)
                ? label.map((t, i) => (i % 2 ? t : t.toLowerCase()))
                : label.toLowerCase();
            }
            const wrappedLabel = Array.isArray(label)
              ? label
              : type == 2
                ? applyLetterSpacing(label, letterSpacing)
                : wrapText(label, font, maxTextWidth, letterSpacing);
            text.setText(wrappedLabel);
            text.setFont(font);
            text.setRotation(
              deg2rad(
                getValue(
                  layer,
                  'layout',
                  'text-rotate',
                  f,
                  functionCache,
                  featureState,
                ),
              ),
            );
            if (typeof text.setKeepUpright === 'function') {
              const keepUpright = getValue(
                layer,
                'layout',
                'text-keep-upright',
                f,
                functionCache,
                featureState,
              );
              text.setKeepUpright(keepUpright);
            }
            const textAnchor = getValue(
              layer,
              'layout',
              'text-anchor',
              f,
              functionCache,
              featureState,
            );
            const placement =
              hasImage || type == 1
                ? 'point'
                : getValue(
                    layer,
                    'layout',
                    'symbol-placement',
                    f,
                    functionCache,
                    featureState,
                  );
            let textAlign;
            if (placement === 'line-center') {
              text.setPlacement('line');
              textAlign = 'center';
            } else {
              text.setPlacement(placement);
            }
            if (placement === 'line' && typeof text.setRepeat === 'function') {
              const symbolSpacing = getValue(
                layer,
                'layout',
                'symbol-spacing',
                f,
                functionCache,
                featureState,
              );
              text.setRepeat(symbolSpacing * 2);
            }
            text.setOverflow(placement === 'point');
            let textHaloWidth = getValue(
              layer,
              'paint',
              'text-halo-width',
              f,
              functionCache,
              featureState,
            );
            const textOffset = getValue(
              layer,
              'layout',
              'text-offset',
              f,
              functionCache,
              featureState,
            );
            const textTranslate = getValue(
              layer,
              'paint',
              'text-translate',
              f,
              functionCache,
              featureState,
            );
            // Text offset has to take halo width and line height into account
            let vOffset = 0;
            let hOffset = 0;
            if (placement == 'point') {
              textAlign = 'center';
              if (textAnchor.indexOf('left') !== -1) {
                textAlign = 'left';
                hOffset = textHaloWidth;
              } else if (textAnchor.indexOf('right') !== -1) {
                textAlign = 'right';
                hOffset = -textHaloWidth;
              }
              const textRotationAlignment = getValue(
                layer,
                'layout',
                'text-rotation-alignment',
                f,
                functionCache,
                featureState,
              );
              text.setRotateWithView(textRotationAlignment == 'map');
            } else {
              text.setMaxAngle(
                (deg2rad(
                  getValue(
                    layer,
                    'layout',
                    'text-max-angle',
                    f,
                    functionCache,
                    featureState,
                  ),
                ) *
                  label.length) /
                  wrappedLabel.length,
              );
              text.setRotateWithView(false);
            }
            text.setTextAlign(textAlign);
            let textBaseline = 'middle';
            if (textAnchor.indexOf('bottom') == 0) {
              textBaseline = 'bottom';
              vOffset = -textHaloWidth - 0.5 * (textLineHeight - 1) * textSize;
            } else if (textAnchor.indexOf('top') == 0) {
              textBaseline = 'top';
              vOffset = textHaloWidth + 0.5 * (textLineHeight - 1) * textSize;
            }
            text.setTextBaseline(textBaseline);
            const textJustify = getValue(
              layer,
              'layout',
              'text-justify',
              f,
              functionCache,
              featureState,
            );
            text.setJustify(textJustify === 'auto' ? undefined : textJustify);
            text.setOffsetX(
              textOffset[0] * textSize + hOffset + textTranslate[0],
            );
            text.setOffsetY(
              textOffset[1] * textSize + vOffset + textTranslate[1],
            );
            textColor.setColor(
              colorWithOpacity(
                getValue(
                  layer,
                  'paint',
                  'text-color',
                  f,
                  functionCache,
                  featureState,
                ),
                opacity,
              ),
            );
            text.setFill(textColor);
            const haloColor = colorWithOpacity(
              getValue(
                layer,
                'paint',
                'text-halo-color',
                f,
                functionCache,
                featureState,
              ),
              opacity,
            );
            if (haloColor && textHaloWidth > 0) {
              textHalo.setColor(haloColor);
              // spec here : https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-symbol-text-halo-width
              // Halo width must be doubled because it is applied around the center of the text outline
              textHaloWidth *= 2;
              // 1/4 of text size (spec) x 2
              const halfTextSize = 0.5 * textSize;
              textHalo.setWidth(
                textHaloWidth <= halfTextSize ? textHaloWidth : halfTextSize,
              );
              text.setStroke(textHalo);
            } else {
              text.setStroke(undefined);
            }
            const textPadding = getValue(
              layer,
              'layout',
              'text-padding',
              f,
              functionCache,
              featureState,
            );
            const padding = text.getPadding();
            if (textPadding !== padding[0]) {
              padding[0] = textPadding;
              padding[1] = textPadding;
              padding[2] = textPadding;
              padding[3] = textPadding;
            }
            style.setZIndex(index);
          }
        }
      }

      if (stylesLength > -1) {
        styles.length = stylesLength + 1;
        return styles;
      }
      return undefined;
    };

    olLayer.setStyle(styleFunction);
    olLayer.set('mapbox-layers', mapboxLayers);
    olLayer.set('mapbox-source', mapboxSource);
    olLayer.set('mapbox-featurestate', olLayer.get('mapbox-featurestate') || {});
    return styleFunction;
  }

  /**
   * @module ol/format/Feature
   */

  /**
   * @typedef {Object} ReadOptions
   * @property {import("../proj.js").ProjectionLike} [dataProjection] Projection of the data we are reading.
   * If not provided, the projection will be derived from the data (where possible) or
   * the `dataProjection` of the format is assigned (where set). If the projection
   * can not be derived from the data and if no `dataProjection` is set for a format,
   * the features will not be reprojected.
   * @property {import("../extent.js").Extent} [extent] Tile extent in map units of the tile being read.
   * This is only required when reading data with tile pixels as geometry units. When configured,
   * a `dataProjection` with `TILE_PIXELS` as `units` and the tile's pixel extent as `extent` needs to be
   * provided.
   * @property {import("../proj.js").ProjectionLike} [featureProjection] Projection of the feature geometries
   * created by the format reader. If not provided, features will be returned in the
   * `dataProjection`.
   */

  /**
   * @typedef {Object} WriteOptions
   * @property {import("../proj.js").ProjectionLike} [dataProjection] Projection of the data we are writing.
   * If not provided, the `dataProjection` of the format is assigned (where set).
   * If no `dataProjection` is set for a format, the features will be returned
   * in the `featureProjection`.
   * @property {import("../proj.js").ProjectionLike} [featureProjection] Projection of the feature geometries
   * that will be serialized by the format writer. If not provided, geometries are assumed
   * to be in the `dataProjection` if that is set; in other words, they are not transformed.
   * @property {boolean} [rightHanded] When writing geometries, follow the right-hand
   * rule for linear ring orientation.  This means that polygons will have counter-clockwise
   * exterior rings and clockwise interior rings.  By default, coordinates are serialized
   * as they are provided at construction.  If `true`, the right-hand rule will
   * be applied.  If `false`, the left-hand rule will be applied (clockwise for
   * exterior and counter-clockwise for interior rings).  Note that not all
   * formats support this.  The GeoJSON format does use this property when writing
   * geometries.
   * @property {number} [decimals] Maximum number of decimal places for coordinates.
   * Coordinates are stored internally as floats, but floating-point arithmetic can create
   * coordinates with a large number of decimal places, not generally wanted on output.
   * Set a number here to round coordinates. Can also be used to ensure that
   * coordinates read in can be written back out with the same number of decimals.
   * Default is no rounding.
   */

  /**
   * @typedef {'arraybuffer' | 'json' | 'text' | 'xml'} Type
   */

  /**
   * @typedef {Object} SimpleGeometryObject
   * @property {import('../geom/Geometry.js').Type} type Type.
   * @property {Array<number>} flatCoordinates Flat coordinates.
   * @property {Array<number>|Array<Array<number>>} [ends] Ends or endss.
   * @property {import('../geom/Geometry.js').GeometryLayout} [layout] Layout.
   */

  /**
   * @typedef {Array<GeometryObject>} GeometryCollectionObject
   */

  /**
   * @typedef {SimpleGeometryObject|GeometryCollectionObject} GeometryObject
   */

  /**
   * @typedef {Object} FeatureObject
   * @property {string|number} [id] Id.
   * @property {GeometryObject} [geometry] Geometry.
   * @property {Object<string, *>} [properties] Properties.
   */

  /***
   * @template {import('../Feature.js').FeatureLike} T
   * @typedef {T extends RenderFeature ? typeof RenderFeature : typeof Feature} FeatureToFeatureClass
   */

  /***
   * @template {import("../Feature.js").FeatureClass} T
   * @typedef {T[keyof T] extends RenderFeature ? RenderFeature : Feature} FeatureClassToFeature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for feature formats.
   * {@link module:ol/format/Feature~FeatureFormat} subclasses provide the ability to decode and encode
   * {@link module:ol/Feature~Feature} objects from a variety of commonly used geospatial
   * file formats.  See the documentation for each format for more details.
   *
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("../Feature.js").default]
   * @abstract
   * @api
   */
  class FeatureFormat {
    constructor() {
      /**
       * @protected
       * @type {import("../proj/Projection.js").default|undefined}
       */
      this.dataProjection = undefined;

      /**
       * @protected
       * @type {import("../proj/Projection.js").default|undefined}
       */
      this.defaultFeatureProjection = undefined;

      /**
       * @protected
       * @type {FeatureToFeatureClass<FeatureType>}
       */
      this.featureClass = /** @type {FeatureToFeatureClass<FeatureType>} */ (
        Feature
      );

      /**
       * A list media types supported by the format in descending order of preference.
       * @type {Array<string>}
       */
      this.supportedMediaTypes = null;
    }

    /**
     * Adds the data projection to the read options.
     * @param {Document|Element|Object|string} source Source.
     * @param {ReadOptions} [options] Options.
     * @return {ReadOptions|undefined} Options.
     * @protected
     */
    getReadOptions(source, options) {
      if (options) {
        let dataProjection = options.dataProjection
          ? get$2(options.dataProjection)
          : this.readProjection(source);
        if (
          options.extent &&
          dataProjection &&
          dataProjection.getUnits() === 'tile-pixels'
        ) {
          dataProjection = get$2(dataProjection);
          dataProjection.setWorldExtent(options.extent);
        }
        options = {
          dataProjection: dataProjection,
          featureProjection: options.featureProjection,
        };
      }
      return this.adaptOptions(options);
    }

    /**
     * Sets the `dataProjection` on the options, if no `dataProjection`
     * is set.
     * @param {WriteOptions|ReadOptions|undefined} options
     *     Options.
     * @protected
     * @return {WriteOptions|ReadOptions|undefined}
     *     Updated options.
     */
    adaptOptions(options) {
      return Object.assign(
        {
          dataProjection: this.dataProjection,
          featureProjection: this.defaultFeatureProjection,
          featureClass: this.featureClass,
        },
        options,
      );
    }

    /**
     * @abstract
     * @return {Type} The format type.
     */
    getType() {
      return abstract();
    }

    /**
     * Read a single feature from a source.
     *
     * @abstract
     * @param {Document|Element|Object|string} source Source.
     * @param {ReadOptions} [options] Read options.
     * @return {FeatureType|Array<FeatureType>} Feature.
     */
    readFeature(source, options) {
      return abstract();
    }

    /**
     * Read all features from a source.
     *
     * @abstract
     * @param {Document|Element|ArrayBuffer|Object|string} source Source.
     * @param {ReadOptions} [options] Read options.
     * @return {Array<FeatureType>} Features.
     */
    readFeatures(source, options) {
      return abstract();
    }

    /**
     * Read a single geometry from a source.
     *
     * @abstract
     * @param {Document|Element|Object|string} source Source.
     * @param {ReadOptions} [options] Read options.
     * @return {import("../geom/Geometry.js").default} Geometry.
     */
    readGeometry(source, options) {
      return abstract();
    }

    /**
     * Read the projection from a source.
     *
     * @abstract
     * @param {Document|Element|Object|string} source Source.
     * @return {import("../proj/Projection.js").default|undefined} Projection.
     */
    readProjection(source) {
      return abstract();
    }

    /**
     * Encode a feature in this format.
     *
     * @abstract
     * @param {Feature} feature Feature.
     * @param {WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     */
    writeFeature(feature, options) {
      return abstract();
    }

    /**
     * Encode an array of features in this format.
     *
     * @abstract
     * @param {Array<Feature>} features Features.
     * @param {WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     */
    writeFeatures(features, options) {
      return abstract();
    }

    /**
     * Write a single geometry in this format.
     *
     * @abstract
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     */
    writeGeometry(geometry, options) {
      return abstract();
    }
  }

  /**
   * @template {import("../geom/Geometry.js").default|RenderFeature} T
   * @param {T} geometry Geometry.
   * @param {boolean} write Set to true for writing, false for reading.
   * @param {WriteOptions|ReadOptions} [options] Options.
   * @return {T} Transformed geometry.
   */
  function transformGeometryWithOptions(geometry, write, options) {
    const featureProjection = options
      ? get$2(options.featureProjection)
      : null;
    const dataProjection = options ? get$2(options.dataProjection) : null;

    let transformed = geometry;
    if (
      featureProjection &&
      dataProjection &&
      !equivalent$1(featureProjection, dataProjection)
    ) {
      if (write) {
        transformed = /** @type {T} */ (geometry.clone());
      }
      const fromProjection = write ? featureProjection : dataProjection;
      const toProjection = write ? dataProjection : featureProjection;
      if (fromProjection.getUnits() === 'tile-pixels') {
        transformed.transform(fromProjection, toProjection);
      } else {
        transformed.applyTransform(getTransform(fromProjection, toProjection));
      }
    }
    if (
      write &&
      options &&
      /** @type {WriteOptions} */ (options).decimals !== undefined
    ) {
      const power = Math.pow(10, /** @type {WriteOptions} */ (options).decimals);
      // if decimals option on write, round each coordinate appropriately
      /**
       * @param {Array<number>} coordinates Coordinates.
       * @return {Array<number>} Transformed coordinates.
       */
      const transform = function (coordinates) {
        for (let i = 0, ii = coordinates.length; i < ii; ++i) {
          coordinates[i] = Math.round(coordinates[i] * power) / power;
        }
        return coordinates;
      };
      if (transformed === geometry) {
        transformed = /** @type {T} */ (geometry.clone());
      }
      transformed.applyTransform(transform);
    }
    return transformed;
  }

  /**
   * @param {import("../extent.js").Extent} extent Extent.
   * @param {ReadOptions} [options] Read options.
   * @return {import("../extent.js").Extent} Transformed extent.
   */
  function transformExtentWithOptions(extent, options) {
    const featureProjection = options
      ? get$2(options.featureProjection)
      : null;
    const dataProjection = options ? get$2(options.dataProjection) : null;

    if (
      featureProjection &&
      dataProjection &&
      !equivalent$1(featureProjection, dataProjection)
    ) {
      return transformExtent(extent, dataProjection, featureProjection);
    }
    return extent;
  }

  const GeometryConstructor$1 = {
    Point: Point,
    LineString: LineString,
    Polygon: Polygon,
    MultiPoint: MultiPoint,
    MultiLineString: MultiLineString,
    MultiPolygon: MultiPolygon,
  };

  function orientFlatCoordinates(flatCoordinates, ends, stride) {
    if (Array.isArray(ends[0])) {
      // MultiPolagon
      if (!linearRingssAreOriented(flatCoordinates, 0, ends, stride)) {
        flatCoordinates = flatCoordinates.slice();
        orientLinearRingsArray(flatCoordinates, 0, ends, stride);
      }
      return flatCoordinates;
    }
    if (!linearRingsAreOriented(flatCoordinates, 0, ends, stride)) {
      flatCoordinates = flatCoordinates.slice();
      orientLinearRings(flatCoordinates, 0, ends, stride);
    }
    return flatCoordinates;
  }

  /**
   * @param {FeatureObject} object Feature object.
   * @param {WriteOptions|ReadOptions} [options] Options.
   * @return {RenderFeature|Array<RenderFeature>} Render feature.
   */
  function createRenderFeature(object, options) {
    const geometry = object.geometry;
    if (!geometry) {
      return [];
    }
    if (Array.isArray(geometry)) {
      return geometry
        .map((geometry) => createRenderFeature({...object, geometry}))
        .flat();
    }

    const geometryType =
      geometry.type === 'MultiPolygon' ? 'Polygon' : geometry.type;
    if (geometryType === 'GeometryCollection' || geometryType === 'Circle') {
      throw new Error('Unsupported geometry type: ' + geometryType);
    }

    const stride = geometry.layout.length;
    return transformGeometryWithOptions(
      new RenderFeature(
        geometryType,
        geometryType === 'Polygon'
          ? orientFlatCoordinates(geometry.flatCoordinates, geometry.ends, stride)
          : geometry.flatCoordinates,
        geometry.ends?.flat(),
        stride,
        object.properties || {},
        object.id,
      ).enableSimplifyTransformed(),
      false,
      options,
    );
  }

  /**
   * @param {GeometryObject|null} object Geometry object.
   * @param {WriteOptions|ReadOptions} [options] Options.
   * @return {import("../geom/Geometry.js").default} Geometry.
   */
  function createGeometry(object, options) {
    if (!object) {
      return null;
    }
    if (Array.isArray(object)) {
      const geometries = object.map((geometry) =>
        createGeometry(geometry, options),
      );
      return new GeometryCollection(geometries);
    }
    const Geometry = GeometryConstructor$1[object.type];
    return transformGeometryWithOptions(
      new Geometry(object.flatCoordinates, object.layout || 'XY', object.ends),
      false,
      options,
    );
  }

  /**
   * @module ol/format/JSONFeature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for JSON feature formats.
   *
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("../Feature.js").default]
   * @extends {FeatureFormat<FeatureType>}
   * @abstract
   */
  class JSONFeature extends FeatureFormat {
    constructor() {
      super();
    }

    /**
     * @return {import("./Feature.js").Type} Format.
     * @override
     */
    getType() {
      return 'json';
    }

    /**
     * Read a feature.  Only works for a single feature. Use `readFeatures` to
     * read a feature collection.
     *
     * @param {ArrayBuffer|Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {FeatureType|Array<FeatureType>} Feature.
     * @api
     * @override
     */
    readFeature(source, options) {
      return this.readFeatureFromObject(
        getObject(source),
        this.getReadOptions(source, options),
      );
    }

    /**
     * Read all features.  Works with both a single feature and a feature
     * collection.
     *
     * @param {ArrayBuffer|Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {Array<FeatureType>} Features.
     * @api
     * @override
     */
    readFeatures(source, options) {
      return this.readFeaturesFromObject(
        getObject(source),
        this.getReadOptions(source, options),
      );
    }

    /**
     * @abstract
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {FeatureType|Array<FeatureType>} Feature.
     */
    readFeatureFromObject(object, options) {
      return abstract();
    }

    /**
     * @abstract
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<FeatureType>} Features.
     */
    readFeaturesFromObject(object, options) {
      return abstract();
    }

    /**
     * Read a geometry.
     *
     * @param {ArrayBuffer|Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @api
     * @override
     */
    readGeometry(source, options) {
      return this.readGeometryFromObject(
        getObject(source),
        this.getReadOptions(source, options),
      );
    }

    /**
     * @abstract
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     */
    readGeometryFromObject(object, options) {
      return abstract();
    }

    /**
     * Read the projection.
     *
     * @param {ArrayBuffer|Document|Element|Object|string} source Source.
     * @return {import("../proj/Projection.js").default} Projection.
     * @api
     * @override
     */
    readProjection(source) {
      return this.readProjectionFromObject(getObject(source));
    }

    /**
     * @abstract
     * @param {Object} object Object.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     */
    readProjectionFromObject(object) {
      return abstract();
    }

    /**
     * Encode a feature as string.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded feature.
     * @api
     * @override
     */
    writeFeature(feature, options) {
      return JSON.stringify(this.writeFeatureObject(feature, options));
    }

    /**
     * @abstract
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {Object} Object.
     */
    writeFeatureObject(feature, options) {
      return abstract();
    }

    /**
     * Encode an array of features as string.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded features.
     * @api
     * @override
     */
    writeFeatures(features, options) {
      return JSON.stringify(this.writeFeaturesObject(features, options));
    }

    /**
     * @abstract
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {Object} Object.
     */
    writeFeaturesObject(features, options) {
      return abstract();
    }

    /**
     * Encode a geometry as string.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded geometry.
     * @api
     * @override
     */
    writeGeometry(geometry, options) {
      return JSON.stringify(this.writeGeometryObject(geometry, options));
    }

    /**
     * @abstract
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {Object} Object.
     */
    writeGeometryObject(geometry, options) {
      return abstract();
    }
  }

  /**
   * @param {Document|Element|Object|string} source Source.
   * @return {Object} Object.
   */
  function getObject(source) {
    if (typeof source === 'string') {
      const object = JSON.parse(source);
      return object ? /** @type {Object} */ (object) : null;
    }
    if (source !== null) {
      return source;
    }
    return null;
  }

  /**
   * @module ol/format/GeoJSON
   */


  /**
   * @typedef {import("geojson").GeoJSON} GeoJSONObject
   * @typedef {import("geojson").Feature} GeoJSONFeature
   * @typedef {import("geojson").FeatureCollection} GeoJSONFeatureCollection
   * @typedef {import("geojson").Geometry} GeoJSONGeometry
   * @typedef {import("geojson").Point} GeoJSONPoint
   * @typedef {import("geojson").LineString} GeoJSONLineString
   * @typedef {import("geojson").Polygon} GeoJSONPolygon
   * @typedef {import("geojson").MultiPoint} GeoJSONMultiPoint
   * @typedef {import("geojson").MultiLineString} GeoJSONMultiLineString
   * @typedef {import("geojson").MultiPolygon} GeoJSONMultiPolygon
   * @typedef {import("geojson").GeometryCollection} GeoJSONGeometryCollection
   */

  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @typedef {Object} Options
   *
   * @property {import("../proj.js").ProjectionLike} [dataProjection='EPSG:4326'] Default data projection.
   * @property {import("../proj.js").ProjectionLike} [featureProjection] Projection for features read or
   * written by the format.  Options passed to read or write methods will take precedence.
   * @property {string} [geometryName] Geometry name to use when creating features.
   * @property {boolean} [extractGeometryName=false] Certain GeoJSON providers include
   * the geometry_name field in the feature GeoJSON. If set to `true` the GeoJSON reader
   * will look for that field to set the geometry name. If both this field is set to `true`
   * and a `geometryName` is provided, the `geometryName` will take precedence.
   * @property {import('./Feature.js').FeatureToFeatureClass<FeatureType>} [featureClass] Feature class
   * to be used when reading features. The default is {@link module:ol/Feature~Feature}. If performance is
   * the primary concern, and features are not going to be modified or round-tripped through the format,
   * consider using {@link module:ol/render/Feature~RenderFeature}
   */

  /**
   * @classdesc
   * Feature format for reading and writing data in the GeoJSON format.
   *
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("../Feature.js").default]
   * @extends {JSONFeature<FeatureType>}
   * @api
   */
  class GeoJSON extends JSONFeature {
    /**
     * @param {Options<FeatureType>} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super();

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2(
        options.dataProjection ? options.dataProjection : 'EPSG:4326',
      );

      if (options.featureProjection) {
        /**
         * @type {import("../proj/Projection.js").default}
         */
        this.defaultFeatureProjection = get$2(options.featureProjection);
      }

      if (options.featureClass) {
        this.featureClass = options.featureClass;
      }

      /**
       * Name of the geometry attribute for features.
       * @type {string|undefined}
       * @private
       */
      this.geometryName_ = options.geometryName;

      /**
       * Look for the `geometry_name` in the feature GeoJSON
       * @type {boolean|undefined}
       * @private
       */
      this.extractGeometryName_ = options.extractGeometryName;

      this.supportedMediaTypes = [
        'application/geo+json',
        'application/vnd.geo+json',
      ];
    }

    /**
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {FeatureType|Array<FeatureType>} Feature.
     * @override
     */
    readFeatureFromObject(object, options) {
      /**
       * @type {GeoJSONFeature}
       */
      let geoJSONFeature = null;
      if (object['type'] === 'Feature') {
        geoJSONFeature = /** @type {GeoJSONFeature} */ (object);
      } else {
        geoJSONFeature = {
          'type': 'Feature',
          'geometry': /** @type {GeoJSONGeometry} */ (object),
          'properties': null,
        };
      }

      const geometry = readGeometryInternal(geoJSONFeature['geometry']);
      if (this.featureClass === RenderFeature) {
        return /** @type {FeatureType|Array<FeatureType>} */ (
          createRenderFeature(
            {
              geometry,
              id: geoJSONFeature['id'],
              properties: geoJSONFeature['properties'],
            },
            options,
          )
        );
      }

      const feature = new Feature();
      if (this.geometryName_) {
        feature.setGeometryName(this.geometryName_);
      } else if (this.extractGeometryName_ && geoJSONFeature['geometry_name']) {
        feature.setGeometryName(geoJSONFeature['geometry_name']);
      }
      feature.setGeometry(createGeometry(geometry, options));

      if ('id' in geoJSONFeature) {
        feature.setId(geoJSONFeature['id']);
      }

      if (geoJSONFeature['properties']) {
        feature.setProperties(geoJSONFeature['properties'], true);
      }
      return /** @type {FeatureType|Array<FeatureType>} */ (feature);
    }

    /**
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<FeatureType>} Features.
     * @override
     */
    readFeaturesFromObject(object, options) {
      const geoJSONObject = /** @type {GeoJSONObject} */ (object);
      let features = null;
      if (geoJSONObject['type'] === 'FeatureCollection') {
        const geoJSONFeatureCollection = /** @type {GeoJSONFeatureCollection} */ (
          object
        );
        features = [];
        const geoJSONFeatures = geoJSONFeatureCollection['features'];
        for (let i = 0, ii = geoJSONFeatures.length; i < ii; ++i) {
          const featureObject = this.readFeatureFromObject(
            geoJSONFeatures[i],
            options,
          );
          if (!featureObject) {
            continue;
          }
          features.push(featureObject);
        }
      } else {
        features = [this.readFeatureFromObject(object, options)];
      }
      return /** @type {Array<FeatureType>} */ (features.flat());
    }

    /**
     * @param {GeoJSONGeometry} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometryFromObject(object, options) {
      return readGeometry$1(object, options);
    }

    /**
     * @param {Object} object Object.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromObject(object) {
      const crs = object['crs'];
      let projection;
      if (crs) {
        if (crs['type'] == 'name') {
          projection = get$2(crs['properties']['name']);
        } else if (crs['type'] === 'EPSG') {
          projection = get$2('EPSG:' + crs['properties']['code']);
        } else {
          throw new Error('Unknown SRS type');
        }
      } else {
        projection = this.dataProjection;
      }
      return /** @type {import("../proj/Projection.js").default} */ (projection);
    }

    /**
     * Encode a feature as a GeoJSON Feature object.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {GeoJSONFeature} Object.
     * @api
     * @override
     */
    writeFeatureObject(feature, options) {
      options = this.adaptOptions(options);

      /** @type {GeoJSONFeature} */
      const object = {
        'type': 'Feature',
        geometry: null,
        properties: null,
      };

      const id = feature.getId();
      if (id !== undefined) {
        object.id = id;
      }

      if (!feature.hasProperties()) {
        return object;
      }

      const properties = feature.getProperties();
      const geometry = feature.getGeometry();
      if (geometry) {
        object.geometry = writeGeometry$1(geometry, options);

        delete properties[feature.getGeometryName()];
      }

      if (!isEmpty$1(properties)) {
        object.properties = properties;
      }

      return object;
    }

    /**
     * Encode an array of features as a GeoJSON object.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {GeoJSONFeatureCollection} GeoJSON Object.
     * @api
     * @override
     */
    writeFeaturesObject(features, options) {
      options = this.adaptOptions(options);
      const objects = [];
      for (let i = 0, ii = features.length; i < ii; ++i) {
        objects.push(this.writeFeatureObject(features[i], options));
      }
      return {
        type: 'FeatureCollection',
        features: objects,
      };
    }

    /**
     * Encode a geometry as a GeoJSON object.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {GeoJSONGeometry|GeoJSONGeometryCollection} Object.
     * @api
     * @override
     */
    writeGeometryObject(geometry, options) {
      return writeGeometry$1(geometry, this.adaptOptions(options));
    }
  }

  /**
   * @param {GeoJSONGeometry|GeoJSONGeometryCollection} object Object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {import("./Feature.js").GeometryObject} Geometry.
   */
  function readGeometryInternal(object, options) {
    if (!object) {
      return null;
    }

    /** @type {import("./Feature.js").GeometryObject} */
    let geometry;
    switch (object['type']) {
      case 'Point': {
        geometry = readPointGeometry$2(/** @type {GeoJSONPoint} */ (object));
        break;
      }
      case 'LineString': {
        geometry = readLineStringGeometry$2(
          /** @type {GeoJSONLineString} */ (object),
        );
        break;
      }
      case 'Polygon': {
        geometry = readPolygonGeometry$2(/** @type {GeoJSONPolygon} */ (object));
        break;
      }
      case 'MultiPoint': {
        geometry = readMultiPointGeometry$2(
          /** @type {GeoJSONMultiPoint} */ (object),
        );
        break;
      }
      case 'MultiLineString': {
        geometry = readMultiLineStringGeometry$2(
          /** @type {GeoJSONMultiLineString} */ (object),
        );
        break;
      }
      case 'MultiPolygon': {
        geometry = readMultiPolygonGeometry$2(
          /** @type {GeoJSONMultiPolygon} */ (object),
        );
        break;
      }
      case 'GeometryCollection': {
        geometry = readGeometryCollectionGeometry(
          /** @type {GeoJSONGeometryCollection} */ (object),
        );
        break;
      }
      default: {
        throw new Error('Unsupported GeoJSON type: ' + object['type']);
      }
    }
    return geometry;
  }

  /**
   * @param {GeoJSONGeometry|GeoJSONGeometryCollection} object Object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {import("../geom/Geometry.js").default} Geometry.
   */
  function readGeometry$1(object, options) {
    const geometryObject = readGeometryInternal(object);
    return createGeometry(geometryObject, options);
  }

  /**
   * @param {GeoJSONGeometryCollection} object Object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {import("./Feature.js").GeometryCollectionObject} Geometry collection.
   */
  function readGeometryCollectionGeometry(object, options) {
    const geometries = object['geometries'].map(
      /**
       * @param {GeoJSONGeometry} geometry Geometry.
       * @return {import("./Feature.js").GeometryObject} geometry Geometry.
       */
      function (geometry) {
        return readGeometryInternal(geometry);
      },
    );
    return geometries;
  }

  /**
   * @param {GeoJSONPoint} object Input object.
   * @return {import("./Feature.js").GeometryObject} Point geometry.
   */
  function readPointGeometry$2(object) {
    const flatCoordinates = object['coordinates'];
    return {
      type: 'Point',
      flatCoordinates,
      layout: getLayoutForStride(flatCoordinates.length),
    };
  }

  /**
   * @param {GeoJSONLineString} object Object.
   * @return {import("./Feature.js").GeometryObject} LineString geometry.
   */
  function readLineStringGeometry$2(object) {
    const coordinates = object['coordinates'];
    const flatCoordinates = coordinates.flat();
    return {
      type: 'LineString',
      flatCoordinates,
      ends: [flatCoordinates.length],
      layout: getLayoutForStride(coordinates[0]?.length || 2),
    };
  }

  /**
   * @param {GeoJSONMultiLineString} object Object.
   * @return {import("./Feature.js").GeometryObject} MultiLineString geometry.
   */
  function readMultiLineStringGeometry$2(object) {
    const coordinates = object['coordinates'];
    const stride = coordinates[0]?.[0]?.length || 2;
    const flatCoordinates = [];
    const ends = deflateCoordinatesArray(flatCoordinates, 0, coordinates, stride);
    return {
      type: 'MultiLineString',
      flatCoordinates,
      ends,
      layout: getLayoutForStride(stride),
    };
  }

  /**
   * @param {GeoJSONMultiPoint} object Object.
   * @return {import("./Feature.js").GeometryObject} MultiPoint geometry.
   */
  function readMultiPointGeometry$2(object) {
    const coordinates = object['coordinates'];
    return {
      type: 'MultiPoint',
      flatCoordinates: coordinates.flat(),
      layout: getLayoutForStride(coordinates[0]?.length || 2),
    };
  }

  /**
   * @param {GeoJSONMultiPolygon} object Object.
   * @return {import("./Feature.js").GeometryObject} MultiPolygon geometry.
   */
  function readMultiPolygonGeometry$2(object) {
    const coordinates = object['coordinates'];
    const flatCoordinates = [];
    const stride = coordinates[0]?.[0]?.[0].length || 2;
    const endss = deflateMultiCoordinatesArray(
      flatCoordinates,
      0,
      coordinates,
      stride,
    );
    return {
      type: 'MultiPolygon',
      flatCoordinates,
      ends: endss,
      layout: getLayoutForStride(stride),
    };
  }

  /**
   * @param {GeoJSONPolygon} object Object.
   * @return {import("./Feature.js").GeometryObject} Polygon.
   */
  function readPolygonGeometry$2(object) {
    const coordinates = object['coordinates'];
    const flatCoordinates = [];
    const stride = coordinates[0]?.[0]?.length;
    const ends = deflateCoordinatesArray(flatCoordinates, 0, coordinates, stride);
    return {
      type: 'Polygon',
      flatCoordinates,
      ends,
      layout: getLayoutForStride(stride),
    };
  }

  /**
   * @param {import("../geom/Geometry.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writeGeometry$1(geometry, options) {
    geometry = transformGeometryWithOptions(geometry, true, options);

    const type = geometry.getType();

    /** @type {GeoJSONGeometry} */
    let geoJSON;
    switch (type) {
      case 'Point': {
        geoJSON = writePointGeometry$1(
          /** @type {import("../geom/Point.js").default} */ (geometry));
        break;
      }
      case 'LineString': {
        geoJSON = writeLineStringGeometry$1(
          /** @type {import("../geom/LineString.js").default} */ (geometry));
        break;
      }
      case 'Polygon': {
        geoJSON = writePolygonGeometry$1(
          /** @type {import("../geom/Polygon.js").default} */ (geometry),
          options,
        );
        break;
      }
      case 'MultiPoint': {
        geoJSON = writeMultiPointGeometry$1(
          /** @type {import("../geom/MultiPoint.js").default} */ (geometry));
        break;
      }
      case 'MultiLineString': {
        geoJSON = writeMultiLineStringGeometry$1(
          /** @type {import("../geom/MultiLineString.js").default} */ (geometry));
        break;
      }
      case 'MultiPolygon': {
        geoJSON = writeMultiPolygonGeometry$1(
          /** @type {import("../geom/MultiPolygon.js").default} */ (geometry),
          options,
        );
        break;
      }
      case 'GeometryCollection': {
        geoJSON = writeGeometryCollectionGeometry(
          /** @type {import("../geom/GeometryCollection.js").default} */ (
            geometry
          ),
          options,
        );
        break;
      }
      case 'Circle': {
        geoJSON = {
          type: 'GeometryCollection',
          geometries: [],
        };
        break;
      }
      default: {
        throw new Error('Unsupported geometry type: ' + type);
      }
    }
    return geoJSON;
  }

  /**
   * @param {import("../geom/GeometryCollection.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometryCollection} GeoJSON geometry collection.
   */
  function writeGeometryCollectionGeometry(geometry, options) {
    options = Object.assign({}, options);
    delete options.featureProjection;
    const geometries = geometry.getGeometriesArray().map(function (geometry) {
      return writeGeometry$1(geometry, options);
    });
    return {
      type: 'GeometryCollection',
      geometries: geometries,
    };
  }

  /**
   * @param {import("../geom/LineString.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writeLineStringGeometry$1(geometry, options) {
    return {
      type: 'LineString',
      coordinates: geometry.getCoordinates(),
    };
  }

  /**
   * @param {import("../geom/MultiLineString.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writeMultiLineStringGeometry$1(geometry, options) {
    return {
      type: 'MultiLineString',
      coordinates: geometry.getCoordinates(),
    };
  }

  /**
   * @param {import("../geom/MultiPoint.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writeMultiPointGeometry$1(geometry, options) {
    return {
      type: 'MultiPoint',
      coordinates: geometry.getCoordinates(),
    };
  }

  /**
   * @param {import("../geom/MultiPolygon.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writeMultiPolygonGeometry$1(geometry, options) {
    let right;
    if (options) {
      right = options.rightHanded;
    }
    return {
      type: 'MultiPolygon',
      coordinates: geometry.getCoordinates(right),
    };
  }

  /**
   * @param {import("../geom/Point.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writePointGeometry$1(geometry, options) {
    return {
      type: 'Point',
      coordinates: geometry.getCoordinates(),
    };
  }

  /**
   * @param {import("../geom/Polygon.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {GeoJSONGeometry} GeoJSON geometry.
   */
  function writePolygonGeometry$1(geometry, options) {
    let right;
    if (options) {
      right = options.rightHanded;
    }
    return {
      type: 'Polygon',
      coordinates: geometry.getCoordinates(right),
    };
  }

  const SHIFT_LEFT_32 = (1 << 16) * (1 << 16);
  const SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;

  // Threshold chosen based on both benchmarking and knowledge about browser string
  // data structures (which currently switch structure types at 12 bytes or more)
  const TEXT_DECODER_MIN_LENGTH = 12;
  const utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8');

  const PBF_VARINT  = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum
  const PBF_FIXED64 = 1; // 64-bit: double, fixed64, sfixed64
  const PBF_BYTES   = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields
  const PBF_FIXED32 = 5; // 32-bit: float, fixed32, sfixed32

  class Pbf {
      /**
       * @param {Uint8Array | ArrayBuffer} [buf]
       */
      constructor(buf = new Uint8Array(16)) {
          this.buf = ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf);
          this.dataView = new DataView(this.buf.buffer);
          this.pos = 0;
          this.type = 0;
          this.length = this.buf.length;
      }

      // === READING =================================================================

      /**
       * @template T
       * @param {(tag: number, result: T, pbf: Pbf) => void} readField
       * @param {T} result
       * @param {number} [end]
       */
      readFields(readField, result, end = this.length) {
          while (this.pos < end) {
              const val = this.readVarint(),
                  tag = val >> 3,
                  startPos = this.pos;

              this.type = val & 0x7;
              readField(tag, result, this);

              if (this.pos === startPos) this.skip(val);
          }
          return result;
      }

      /**
       * @template T
       * @param {(tag: number, result: T, pbf: Pbf) => void} readField
       * @param {T} result
       */
      readMessage(readField, result) {
          return this.readFields(readField, result, this.readVarint() + this.pos);
      }

      readFixed32() {
          const val = this.dataView.getUint32(this.pos, true);
          this.pos += 4;
          return val;
      }

      readSFixed32() {
          const val = this.dataView.getInt32(this.pos, true);
          this.pos += 4;
          return val;
      }

      // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)

      readFixed64() {
          const val = this.dataView.getUint32(this.pos, true) + this.dataView.getUint32(this.pos + 4, true) * SHIFT_LEFT_32;
          this.pos += 8;
          return val;
      }

      readSFixed64() {
          const val = this.dataView.getUint32(this.pos, true) + this.dataView.getInt32(this.pos + 4, true) * SHIFT_LEFT_32;
          this.pos += 8;
          return val;
      }

      readFloat() {
          const val = this.dataView.getFloat32(this.pos, true);
          this.pos += 4;
          return val;
      }

      readDouble() {
          const val = this.dataView.getFloat64(this.pos, true);
          this.pos += 8;
          return val;
      }

      /**
       * @param {boolean} [isSigned]
       */
      readVarint(isSigned) {
          const buf = this.buf;
          let val, b;

          b = buf[this.pos++]; val  =  b & 0x7f;        if (b < 0x80) return val;
          b = buf[this.pos++]; val |= (b & 0x7f) << 7;  if (b < 0x80) return val;
          b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;
          b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;
          b = buf[this.pos];   val |= (b & 0x0f) << 28;

          return readVarintRemainder(val, isSigned, this);
      }

      readVarint64() { // for compatibility with v2.0.1
          return this.readVarint(true);
      }

      readSVarint() {
          const num = this.readVarint();
          return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding
      }

      readBoolean() {
          return Boolean(this.readVarint());
      }

      readString() {
          const end = this.readVarint() + this.pos;
          const pos = this.pos;
          this.pos = end;

          if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {
              // longer strings are fast with the built-in browser TextDecoder API
              return utf8TextDecoder.decode(this.buf.subarray(pos, end));
          }
          // short strings are fast with our custom implementation
          return readUtf8(this.buf, pos, end);
      }

      readBytes() {
          const end = this.readVarint() + this.pos,
              buffer = this.buf.subarray(this.pos, end);
          this.pos = end;
          return buffer;
      }

      // verbose for performance reasons; doesn't affect gzipped size

      /**
       * @param {number[]} [arr]
       * @param {boolean} [isSigned]
       */
      readPackedVarint(arr = [], isSigned) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readVarint(isSigned));
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedSVarint(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readSVarint());
          return arr;
      }
      /** @param {boolean[]} [arr] */
      readPackedBoolean(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readBoolean());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedFloat(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readFloat());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedDouble(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readDouble());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedFixed32(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readFixed32());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedSFixed32(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readSFixed32());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedFixed64(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readFixed64());
          return arr;
      }
      /** @param {number[]} [arr] */
      readPackedSFixed64(arr = []) {
          const end = this.readPackedEnd();
          while (this.pos < end) arr.push(this.readSFixed64());
          return arr;
      }
      readPackedEnd() {
          return this.type === PBF_BYTES ? this.readVarint() + this.pos : this.pos + 1;
      }

      /** @param {number} val */
      skip(val) {
          const type = val & 0x7;
          if (type === PBF_VARINT) while (this.buf[this.pos++] > 0x7f) {}
          else if (type === PBF_BYTES) this.pos = this.readVarint() + this.pos;
          else if (type === PBF_FIXED32) this.pos += 4;
          else if (type === PBF_FIXED64) this.pos += 8;
          else throw new Error(`Unimplemented type: ${type}`);
      }

      // === WRITING =================================================================

      /**
       * @param {number} tag
       * @param {number} type
       */
      writeTag(tag, type) {
          this.writeVarint((tag << 3) | type);
      }

      /** @param {number} min */
      realloc(min) {
          let length = this.length || 16;

          while (length < this.pos + min) length *= 2;

          if (length !== this.length) {
              const buf = new Uint8Array(length);
              buf.set(this.buf);
              this.buf = buf;
              this.dataView = new DataView(buf.buffer);
              this.length = length;
          }
      }

      finish() {
          this.length = this.pos;
          this.pos = 0;
          return this.buf.subarray(0, this.length);
      }

      /** @param {number} val */
      writeFixed32(val) {
          this.realloc(4);
          this.dataView.setInt32(this.pos, val, true);
          this.pos += 4;
      }

      /** @param {number} val */
      writeSFixed32(val) {
          this.realloc(4);
          this.dataView.setInt32(this.pos, val, true);
          this.pos += 4;
      }

      /** @param {number} val */
      writeFixed64(val) {
          this.realloc(8);
          this.dataView.setInt32(this.pos, val & -1, true);
          this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
          this.pos += 8;
      }

      /** @param {number} val */
      writeSFixed64(val) {
          this.realloc(8);
          this.dataView.setInt32(this.pos, val & -1, true);
          this.dataView.setInt32(this.pos + 4, Math.floor(val * SHIFT_RIGHT_32), true);
          this.pos += 8;
      }

      /** @param {number} val */
      writeVarint(val) {
          val = +val || 0;

          if (val > 0xfffffff || val < 0) {
              writeBigVarint(val, this);
              return;
          }

          this.realloc(4);

          this.buf[this.pos++] =           val & 0x7f  | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
          this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
          this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;
          this.buf[this.pos++] =   (val >>> 7) & 0x7f;
      }

      /** @param {number} val */
      writeSVarint(val) {
          this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);
      }

      /** @param {boolean} val */
      writeBoolean(val) {
          this.writeVarint(+val);
      }

      /** @param {string} str */
      writeString(str) {
          str = String(str);
          this.realloc(str.length * 4);

          this.pos++; // reserve 1 byte for short string length

          const startPos = this.pos;
          // write the string directly to the buffer and see how much was written
          this.pos = writeUtf8(this.buf, str, this.pos);
          const len = this.pos - startPos;

          if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);

          // finally, write the message length in the reserved place and restore the position
          this.pos = startPos - 1;
          this.writeVarint(len);
          this.pos += len;
      }

      /** @param {number} val */
      writeFloat(val) {
          this.realloc(4);
          this.dataView.setFloat32(this.pos, val, true);
          this.pos += 4;
      }

      /** @param {number} val */
      writeDouble(val) {
          this.realloc(8);
          this.dataView.setFloat64(this.pos, val, true);
          this.pos += 8;
      }

      /** @param {Uint8Array} buffer */
      writeBytes(buffer) {
          const len = buffer.length;
          this.writeVarint(len);
          this.realloc(len);
          for (let i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];
      }

      /**
       * @template T
       * @param {(obj: T, pbf: Pbf) => void} fn
       * @param {T} obj
       */
      writeRawMessage(fn, obj) {
          this.pos++; // reserve 1 byte for short message length

          // write the message directly to the buffer and see how much was written
          const startPos = this.pos;
          fn(obj, this);
          const len = this.pos - startPos;

          if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);

          // finally, write the message length in the reserved place and restore the position
          this.pos = startPos - 1;
          this.writeVarint(len);
          this.pos += len;
      }

      /**
       * @template T
       * @param {number} tag
       * @param {(obj: T, pbf: Pbf) => void} fn
       * @param {T} obj
       */
      writeMessage(tag, fn, obj) {
          this.writeTag(tag, PBF_BYTES);
          this.writeRawMessage(fn, obj);
      }

      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedVarint(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedVarint, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedSVarint(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedSVarint, arr);
      }
      /**
       * @param {number} tag
       * @param {boolean[]} arr
       */
      writePackedBoolean(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedBoolean, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedFloat(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedFloat, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedDouble(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedDouble, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedFixed32(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedFixed32, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedSFixed32(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedFixed64(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedFixed64, arr);
      }
      /**
       * @param {number} tag
       * @param {number[]} arr
       */
      writePackedSFixed64(tag, arr) {
          if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr);
      }

      /**
       * @param {number} tag
       * @param {Uint8Array} buffer
       */
      writeBytesField(tag, buffer) {
          this.writeTag(tag, PBF_BYTES);
          this.writeBytes(buffer);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeFixed32Field(tag, val) {
          this.writeTag(tag, PBF_FIXED32);
          this.writeFixed32(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeSFixed32Field(tag, val) {
          this.writeTag(tag, PBF_FIXED32);
          this.writeSFixed32(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeFixed64Field(tag, val) {
          this.writeTag(tag, PBF_FIXED64);
          this.writeFixed64(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeSFixed64Field(tag, val) {
          this.writeTag(tag, PBF_FIXED64);
          this.writeSFixed64(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeVarintField(tag, val) {
          this.writeTag(tag, PBF_VARINT);
          this.writeVarint(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeSVarintField(tag, val) {
          this.writeTag(tag, PBF_VARINT);
          this.writeSVarint(val);
      }
      /**
       * @param {number} tag
       * @param {string} str
       */
      writeStringField(tag, str) {
          this.writeTag(tag, PBF_BYTES);
          this.writeString(str);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeFloatField(tag, val) {
          this.writeTag(tag, PBF_FIXED32);
          this.writeFloat(val);
      }
      /**
       * @param {number} tag
       * @param {number} val
       */
      writeDoubleField(tag, val) {
          this.writeTag(tag, PBF_FIXED64);
          this.writeDouble(val);
      }
      /**
       * @param {number} tag
       * @param {boolean} val
       */
      writeBooleanField(tag, val) {
          this.writeVarintField(tag, +val);
      }
  }
  /**
   * @param {number} l
   * @param {boolean | undefined} s
   * @param {Pbf} p
   */
  function readVarintRemainder(l, s, p) {
      const buf = p.buf;
      let h, b;

      b = buf[p.pos++]; h  = (b & 0x70) >> 4;  if (b < 0x80) return toNum(l, h, s);
      b = buf[p.pos++]; h |= (b & 0x7f) << 3;  if (b < 0x80) return toNum(l, h, s);
      b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);
      b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);
      b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);
      b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);

      throw new Error('Expected varint not more than 10 bytes');
  }

  /**
   * @param {number} low
   * @param {number} high
   * @param {boolean} [isSigned]
   */
  function toNum(low, high, isSigned) {
      return isSigned ? high * 0x100000000 + (low >>> 0) : ((high >>> 0) * 0x100000000) + (low >>> 0);
  }

  /**
   * @param {number} val
   * @param {Pbf} pbf
   */
  function writeBigVarint(val, pbf) {
      let low, high;

      if (val >= 0) {
          low  = (val % 0x100000000) | 0;
          high = (val / 0x100000000) | 0;
      } else {
          low  = ~(-val % 0x100000000);
          high = ~(-val / 0x100000000);

          if (low ^ 0xffffffff) {
              low = (low + 1) | 0;
          } else {
              low = 0;
              high = (high + 1) | 0;
          }
      }

      if (val >= 0x10000000000000000 || val < -18446744073709552e3) {
          throw new Error('Given varint doesn\'t fit into 10 bytes');
      }

      pbf.realloc(10);

      writeBigVarintLow(low, high, pbf);
      writeBigVarintHigh(high, pbf);
  }

  /**
   * @param {number} high
   * @param {number} low
   * @param {Pbf} pbf
   */
  function writeBigVarintLow(low, high, pbf) {
      pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
      pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
      pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
      pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;
      pbf.buf[pbf.pos]   = low & 0x7f;
  }

  /**
   * @param {number} high
   * @param {Pbf} pbf
   */
  function writeBigVarintHigh(high, pbf) {
      const lsb = (high & 0x07) << 4;

      pbf.buf[pbf.pos++] |= lsb         | ((high >>>= 3) ? 0x80 : 0); if (!high) return;
      pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
      pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
      pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
      pbf.buf[pbf.pos++]  = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;
      pbf.buf[pbf.pos++]  = high & 0x7f;
  }

  /**
   * @param {number} startPos
   * @param {number} len
   * @param {Pbf} pbf
   */
  function makeRoomForExtraLength(startPos, len, pbf) {
      const extraLen =
          len <= 0x3fff ? 1 :
          len <= 0x1fffff ? 2 :
          len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));

      // if 1 byte isn't enough for encoding message length, shift the data to the right
      pbf.realloc(extraLen);
      for (let i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];
  }

  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedVarint(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedSVarint(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedFloat(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedDouble(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]);
  }
  /**
   * @param {boolean[]} arr
   * @param {Pbf} pbf
   */
  function writePackedBoolean(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedFixed32(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedSFixed32(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedFixed64(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]);
  }
  /**
   * @param {number[]} arr
   * @param {Pbf} pbf
   */
  function writePackedSFixed64(arr, pbf) {
      for (let i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]);
  }

  // Buffer code below from https://github.com/feross/buffer, MIT-licensed

  /**
   * @param {Uint8Array} buf
   * @param {number} pos
   * @param {number} end
   */
  function readUtf8(buf, pos, end) {
      let str = '';
      let i = pos;

      while (i < end) {
          const b0 = buf[i];
          let c = null; // codepoint
          let bytesPerSequence =
              b0 > 0xEF ? 4 :
              b0 > 0xDF ? 3 :
              b0 > 0xBF ? 2 : 1;

          if (i + bytesPerSequence > end) break;

          let b1, b2, b3;

          if (bytesPerSequence === 1) {
              if (b0 < 0x80) {
                  c = b0;
              }
          } else if (bytesPerSequence === 2) {
              b1 = buf[i + 1];
              if ((b1 & 0xC0) === 0x80) {
                  c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);
                  if (c <= 0x7F) {
                      c = null;
                  }
              }
          } else if (bytesPerSequence === 3) {
              b1 = buf[i + 1];
              b2 = buf[i + 2];
              if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {
                  c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);
                  if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {
                      c = null;
                  }
              }
          } else if (bytesPerSequence === 4) {
              b1 = buf[i + 1];
              b2 = buf[i + 2];
              b3 = buf[i + 3];
              if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
                  c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);
                  if (c <= 0xFFFF || c >= 0x110000) {
                      c = null;
                  }
              }
          }

          if (c === null) {
              c = 0xFFFD;
              bytesPerSequence = 1;

          } else if (c > 0xFFFF) {
              c -= 0x10000;
              str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);
              c = 0xDC00 | c & 0x3FF;
          }

          str += String.fromCharCode(c);
          i += bytesPerSequence;
      }

      return str;
  }

  /**
   * @param {Uint8Array} buf
   * @param {string} str
   * @param {number} pos
   */
  function writeUtf8(buf, str, pos) {
      for (let i = 0, c, lead; i < str.length; i++) {
          c = str.charCodeAt(i); // code point

          if (c > 0xD7FF && c < 0xE000) {
              if (lead) {
                  if (c < 0xDC00) {
                      buf[pos++] = 0xEF;
                      buf[pos++] = 0xBF;
                      buf[pos++] = 0xBD;
                      lead = c;
                      continue;
                  } else {
                      c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;
                      lead = null;
                  }
              } else {
                  if (c > 0xDBFF || (i + 1 === str.length)) {
                      buf[pos++] = 0xEF;
                      buf[pos++] = 0xBF;
                      buf[pos++] = 0xBD;
                  } else {
                      lead = c;
                  }
                  continue;
              }
          } else if (lead) {
              buf[pos++] = 0xEF;
              buf[pos++] = 0xBF;
              buf[pos++] = 0xBD;
              lead = null;
          }

          if (c < 0x80) {
              buf[pos++] = c;
          } else {
              if (c < 0x800) {
                  buf[pos++] = c >> 0x6 | 0xC0;
              } else {
                  if (c < 0x10000) {
                      buf[pos++] = c >> 0xC | 0xE0;
                  } else {
                      buf[pos++] = c >> 0x12 | 0xF0;
                      buf[pos++] = c >> 0xC & 0x3F | 0x80;
                  }
                  buf[pos++] = c >> 0x6 & 0x3F | 0x80;
              }
              buf[pos++] = c & 0x3F | 0x80;
          }
      }
      return pos;
  }

  /**
   * @module ol/format/MVT
   */
  //FIXME Implement projection handling


  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   * @typedef {Object} Options
   * @property {import('./Feature.js').FeatureToFeatureClass<FeatureType>} [featureClass] Class for features returned by
   * {@link module:ol/format/MVT~MVT#readFeatures}. Set to {@link module:ol/Feature~Feature} to get full editing and geometry
   * support at the cost of decreased rendering performance. The default is
   * {@link module:ol/render/Feature~RenderFeature}, which is optimized for rendering and hit detection.
   * @property {string} [geometryName='geometry'] Geometry name to use when creating features.
   * @property {string} [layerName='layer'] Name of the feature attribute that holds the layer name.
   * @property {Array<string>} [layers] Layers to read features from. If not provided, features will be read from all
   * @property {string} [idProperty] Optional property that will be assigned as the feature id and removed from the properties.
   * layers.
   */

  /**
   * @classdesc
   * Feature format for reading data in the Mapbox MVT format.
   *
   * @template {import('../Feature.js').FeatureLike} [FeatureType=RenderFeature]
   * @extends {FeatureFormat<FeatureType>}
   * @api
   */
  class MVT extends FeatureFormat {
    /**
     * @param {Options<FeatureType>} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @type {Projection}
       */
      this.dataProjection = new Projection({
        code: '',
        units: 'tile-pixels',
      });

      this.featureClass = options.featureClass
        ? options.featureClass
        : /** @type {import('./Feature.js').FeatureToFeatureClass<FeatureType>} */ (
            RenderFeature
          );

      /**
       * @private
       * @type {string|undefined}
       */
      this.geometryName_ = options.geometryName;

      /**
       * @private
       * @type {string}
       */
      this.layerName_ = options.layerName ? options.layerName : 'layer';

      /**
       * @private
       * @type {Array<string>|null}
       */
      this.layers_ = options.layers ? options.layers : null;

      /**
       * @private
       * @type {string}
       */
      this.idProperty_ = options.idProperty;

      this.supportedMediaTypes = [
        'application/vnd.mapbox-vector-tile',
        'application/x-protobuf',
      ];
    }

    /**
     * Read the raw geometry from the pbf offset stored in a raw feature's geometry
     * property.
     * @param {PBF} pbf PBF.
     * @param {Object} feature Raw feature.
     * @param {Array<number>} flatCoordinates Array to store flat coordinates in.
     * @param {Array<number>} ends Array to store ends in.
     * @private
     */
    readRawGeometry_(pbf, feature, flatCoordinates, ends) {
      pbf.pos = feature.geometry;

      const end = pbf.readVarint() + pbf.pos;
      let cmd = 1;
      let length = 0;
      let x = 0;
      let y = 0;
      let coordsLen = 0;
      let currentEnd = 0;

      while (pbf.pos < end) {
        if (!length) {
          const cmdLen = pbf.readVarint();
          cmd = cmdLen & 0x7;
          length = cmdLen >> 3;
        }

        length--;

        if (cmd === 1 || cmd === 2) {
          x += pbf.readSVarint();
          y += pbf.readSVarint();

          if (cmd === 1) {
            // moveTo
            if (coordsLen > currentEnd) {
              ends.push(coordsLen);
              currentEnd = coordsLen;
            }
          }

          flatCoordinates.push(x, y);
          coordsLen += 2;
        } else if (cmd === 7) {
          if (coordsLen > currentEnd) {
            // close polygon
            flatCoordinates.push(
              flatCoordinates[currentEnd],
              flatCoordinates[currentEnd + 1],
            );
            coordsLen += 2;
          }
        } else {
          throw new Error('Invalid command found in the PBF');
        }
      }

      if (coordsLen > currentEnd) {
        ends.push(coordsLen);
        currentEnd = coordsLen;
      }
    }

    /**
     * @private
     * @param {PBF} pbf PBF
     * @param {Object} rawFeature Raw Mapbox feature.
     * @param {import("./Feature.js").ReadOptions} options Read options.
     * @return {FeatureType|null} Feature.
     */
    createFeature_(pbf, rawFeature, options) {
      const type = rawFeature.type;
      if (type === 0) {
        return null;
      }

      let feature;
      const values = rawFeature.properties;

      let id;
      if (!this.idProperty_) {
        id = rawFeature.id;
      } else {
        id = values[this.idProperty_];
        delete values[this.idProperty_];
      }

      values[this.layerName_] = rawFeature.layer.name;

      const flatCoordinates = /** @type {Array<number>} */ ([]);
      const ends = /** @type {Array<number>} */ ([]);
      this.readRawGeometry_(pbf, rawFeature, flatCoordinates, ends);

      const geometryType = getGeometryType(type, ends.length);

      if (this.featureClass === RenderFeature) {
        feature =
          new /** @type {import('./Feature.js').FeatureToFeatureClass<RenderFeature>} */ (
            this.featureClass
          )(geometryType, flatCoordinates, ends, 2, values, id);
        feature.transform(options.dataProjection);
      } else {
        let geom;
        if (geometryType == 'Polygon') {
          const endss = inflateEnds(flatCoordinates, ends);
          geom =
            endss.length > 1
              ? new MultiPolygon(flatCoordinates, 'XY', endss)
              : new Polygon(flatCoordinates, 'XY', ends);
        } else {
          geom =
            geometryType === 'Point'
              ? new Point(flatCoordinates, 'XY')
              : geometryType === 'LineString'
                ? new LineString(flatCoordinates, 'XY')
                : geometryType === 'MultiPoint'
                  ? new MultiPoint(flatCoordinates, 'XY')
                  : geometryType === 'MultiLineString'
                    ? new MultiLineString(flatCoordinates, 'XY', ends)
                    : null;
        }
        const ctor = /** @type {typeof import("../Feature.js").default} */ (
          this.featureClass
        );
        feature = new ctor();
        if (this.geometryName_) {
          feature.setGeometryName(this.geometryName_);
        }
        const geometry = transformGeometryWithOptions(geom, false, options);
        feature.setGeometry(geometry);
        if (id !== undefined) {
          feature.setId(id);
        }
        feature.setProperties(values, true);
      }

      return /** @type {FeatureType} */ (feature);
    }

    /**
     * @return {import("./Feature.js").Type} Format.
     * @override
     */
    getType() {
      return 'arraybuffer';
    }

    /**
     * Read all features.
     *
     * @param {ArrayBuffer} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {Array<FeatureType>} Features.
     * @api
     * @override
     */
    readFeatures(source, options) {
      const layers = this.layers_;
      options = this.adaptOptions(options);
      const dataProjection = get$2(options.dataProjection);
      dataProjection.setWorldExtent(options.extent);
      options.dataProjection = dataProjection;

      const pbf = new Pbf(/** @type {ArrayBuffer} */ (source));
      const pbfLayers = pbf.readFields(layersPBFReader, {});
      const features = [];
      for (const name in pbfLayers) {
        if (layers && !layers.includes(name)) {
          continue;
        }
        const pbfLayer = pbfLayers[name];

        const extent = pbfLayer ? [0, 0, pbfLayer.extent, pbfLayer.extent] : null;
        dataProjection.setExtent(extent);

        for (let i = 0, ii = pbfLayer.length; i < ii; ++i) {
          const rawFeature = readRawFeature(pbf, pbfLayer, i);
          const feature = this.createFeature_(pbf, rawFeature, options);
          if (feature !== null) {
            features.push(feature);
          }
        }
      }

      return /** @type {Array<FeatureType>} */ (features);
    }

    /**
     * Read the projection from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {import("../proj/Projection.js").default} Projection.
     * @api
     * @override
     */
    readProjection(source) {
      return this.dataProjection;
    }

    /**
     * Sets the layers that features will be read from.
     * @param {Array<string>} layers Layers.
     * @api
     */
    setLayers(layers) {
      this.layers_ = layers;
    }
  }

  /**
   * Reader callback for parsing layers.
   * @param {number} tag The tag.
   * @param {Object} layers The layers object.
   * @param {PBF} pbf The PBF.
   */
  function layersPBFReader(tag, layers, pbf) {
    if (tag === 3) {
      const layer = {
        keys: [],
        values: [],
        features: [],
      };
      const end = pbf.readVarint() + pbf.pos;
      pbf.readFields(layerPBFReader, layer, end);
      layer.length = layer.features.length;
      if (layer.length) {
        layers[layer.name] = layer;
      }
    }
  }

  /**
   * Reader callback for parsing layer.
   * @param {number} tag The tag.
   * @param {Object} layer The layer object.
   * @param {PBF} pbf The PBF.
   */
  function layerPBFReader(tag, layer, pbf) {
    if (tag === 15) {
      layer.version = pbf.readVarint();
    } else if (tag === 1) {
      layer.name = pbf.readString();
    } else if (tag === 5) {
      layer.extent = pbf.readVarint();
    } else if (tag === 2) {
      layer.features.push(pbf.pos);
    } else if (tag === 3) {
      layer.keys.push(pbf.readString());
    } else if (tag === 4) {
      let value = null;
      const end = pbf.readVarint() + pbf.pos;
      while (pbf.pos < end) {
        tag = pbf.readVarint() >> 3;
        value =
          tag === 1
            ? pbf.readString()
            : tag === 2
              ? pbf.readFloat()
              : tag === 3
                ? pbf.readDouble()
                : tag === 4
                  ? pbf.readVarint64()
                  : tag === 5
                    ? pbf.readVarint()
                    : tag === 6
                      ? pbf.readSVarint()
                      : tag === 7
                        ? pbf.readBoolean()
                        : null;
      }
      layer.values.push(value);
    }
  }

  /**
   * Reader callback for parsing feature.
   * @param {number} tag The tag.
   * @param {Object} feature The feature object.
   * @param {PBF} pbf The PBF.
   */
  function featurePBFReader(tag, feature, pbf) {
    if (tag == 1) {
      feature.id = pbf.readVarint();
    } else if (tag == 2) {
      const end = pbf.readVarint() + pbf.pos;
      while (pbf.pos < end) {
        const key = feature.layer.keys[pbf.readVarint()];
        const value = feature.layer.values[pbf.readVarint()];
        feature.properties[key] = value;
      }
    } else if (tag == 3) {
      feature.type = pbf.readVarint();
    } else if (tag == 4) {
      feature.geometry = pbf.pos;
    }
  }

  /**
   * Read a raw feature from the pbf offset stored at index `i` in the raw layer.
   * @param {PBF} pbf PBF.
   * @param {Object} layer Raw layer.
   * @param {number} i Index of the feature in the raw layer's `features` array.
   * @return {Object} Raw feature.
   */
  function readRawFeature(pbf, layer, i) {
    pbf.pos = layer.features[i];
    const end = pbf.readVarint() + pbf.pos;

    const feature = {
      layer: layer,
      type: 0,
      properties: {},
    };
    pbf.readFields(featurePBFReader, feature, end);
    return feature;
  }

  /**
   * @param {number} type The raw feature's geometry type
   * @param {number} numEnds Number of ends of the flat coordinates of the
   * geometry.
   * @return {import("../render/Feature.js").Type} The geometry type.
   */
  function getGeometryType(type, numEnds) {
    /** @type {import("../render/Feature.js").Type} */
    let geometryType;
    if (type === 1) {
      geometryType = numEnds === 1 ? 'Point' : 'MultiPoint';
    } else if (type === 2) {
      geometryType = numEnds === 1 ? 'LineString' : 'MultiLineString';
    } else if (type === 3) {
      geometryType = 'Polygon';
      // MultiPolygon not relevant for rendering - winding order determines
      // outer rings of polygons.
    }
    return geometryType;
  }

  /**
   * @module ol/renderer/canvas/ImageLayer
   */

  /**
   * @classdesc
   * Canvas renderer for image layers.
   * @api
   */
  class CanvasImageLayerRenderer extends CanvasLayerRenderer {
    /**
     * @param {import("../../layer/Image.js").default} imageLayer Image layer.
     */
    constructor(imageLayer) {
      super(imageLayer);

      /**
       * @protected
       * @type {?import("../../Image.js").default}
       */
      this.image = null;
    }

    /**
     * @return {import('../../DataTile.js').ImageLike} Image.
     */
    getImage() {
      return !this.image ? null : this.image.getImage();
    }

    /**
     * Determine whether render should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      const layerState = frameState.layerStatesArray[frameState.layerIndex];
      const pixelRatio = frameState.pixelRatio;
      const viewState = frameState.viewState;
      const viewResolution = viewState.resolution;

      const imageSource = this.getLayer().getSource();

      const hints = frameState.viewHints;

      let renderedExtent = frameState.extent;
      if (layerState.extent !== undefined) {
        renderedExtent = getIntersection(
          renderedExtent,
          fromUserExtent(layerState.extent, viewState.projection),
        );
      }

      if (
        !hints[ViewHint.ANIMATING] &&
        !hints[ViewHint.INTERACTING] &&
        !isEmpty(renderedExtent)
      ) {
        if (imageSource) {
          const projection = viewState.projection;
          const image = imageSource.getImage(
            renderedExtent,
            viewResolution,
            pixelRatio,
            projection,
          );
          if (image) {
            if (this.loadImage(image)) {
              this.image = image;
            } else if (image.getState() === ImageState.EMPTY) {
              this.image = null;
            }
          }
        } else {
          this.image = null;
        }
      }

      return !!this.image;
    }

    /**
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray} Data at the pixel location.
     * @override
     */
    getData(pixel) {
      const frameState = this.frameState;
      if (!frameState) {
        return null;
      }

      const layer = this.getLayer();
      const coordinate = apply(
        frameState.pixelToCoordinateTransform,
        pixel.slice(),
      );

      const layerExtent = layer.getExtent();
      if (layerExtent) {
        if (!containsCoordinate(layerExtent, coordinate)) {
          return null;
        }
      }

      const imageExtent = this.image.getExtent();
      const img = this.image.getImage();

      const imageMapWidth = getWidth(imageExtent);
      const col = Math.floor(
        img.width * ((coordinate[0] - imageExtent[0]) / imageMapWidth),
      );
      if (col < 0 || col >= img.width) {
        return null;
      }

      const imageMapHeight = getHeight(imageExtent);
      const row = Math.floor(
        img.height * ((imageExtent[3] - coordinate[1]) / imageMapHeight),
      );
      if (row < 0 || row >= img.height) {
        return null;
      }

      return this.getImageData(img, col, row);
    }

    /**
     * Render the layer.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement} target Target that may be used to render content to.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState, target) {
      const image = this.image;
      const imageExtent = image.getExtent();
      const imageResolution = image.getResolution();
      const [imageResolutionX, imageResolutionY] = Array.isArray(imageResolution)
        ? imageResolution
        : [imageResolution, imageResolution];
      const imagePixelRatio = image.getPixelRatio();
      const layerState = frameState.layerStatesArray[frameState.layerIndex];
      const pixelRatio = frameState.pixelRatio;
      const viewState = frameState.viewState;
      const viewCenter = viewState.center;
      const viewResolution = viewState.resolution;
      const scaleX =
        (pixelRatio * imageResolutionX) / (viewResolution * imagePixelRatio);
      const scaleY =
        (pixelRatio * imageResolutionY) / (viewResolution * imagePixelRatio);

      this.prepareContainer(frameState, target);

      // desired dimensions of the canvas in pixels
      const width = this.context.canvas.width;
      const height = this.context.canvas.height;

      const context = this.getRenderContext(frameState);

      // clipped rendering if layer extent is set
      let clipped = false;
      let render = true;
      if (layerState.extent) {
        const layerExtent = fromUserExtent(
          layerState.extent,
          viewState.projection,
        );
        render = intersects$2(layerExtent, frameState.extent);
        clipped = render && !containsExtent(layerExtent, frameState.extent);
        if (clipped) {
          this.clipUnrotated(context, frameState, layerExtent);
        }
      }

      const img = image.getImage();

      const transform = compose(
        this.tempTransform,
        width / 2,
        height / 2,
        scaleX,
        scaleY,
        0,
        (imagePixelRatio * (imageExtent[0] - viewCenter[0])) / imageResolutionX,
        (imagePixelRatio * (viewCenter[1] - imageExtent[3])) / imageResolutionY,
      );

      this.renderedResolution = (imageResolutionY * pixelRatio) / imagePixelRatio;

      const dw = img.width * transform[0];
      const dh = img.height * transform[3];

      if (!this.getLayer().getSource().getInterpolate()) {
        context.imageSmoothingEnabled = false;
      }

      this.preRender(context, frameState);
      if (render && dw >= 0.5 && dh >= 0.5) {
        const dx = transform[4];
        const dy = transform[5];
        const opacity = layerState.opacity;
        if (opacity !== 1) {
          context.save();
          context.globalAlpha = opacity;
        }
        context.drawImage(img, 0, 0, +img.width, +img.height, dx, dy, dw, dh);
        if (opacity !== 1) {
          context.restore();
        }
      }
      this.postRender(this.context, frameState);

      if (clipped) {
        context.restore();
      }
      context.imageSmoothingEnabled = true;

      return this.container;
    }
  }

  /**
   * @module ol/layer/BaseImage
   */

  /**
   * @template {import("../source/Image.js").default} ImageSourceType
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use {@link import("../Map.js").default#addLayer map.addLayer()}.
   * @property {ImageSourceType} [source] Source for this layer.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Server-rendered images that are available for arbitrary extents and
   * resolutions.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Image.js").default} ImageSourceType
   * @template {import("../renderer/Layer.js").default} RendererType
   * @extends {Layer<ImageSourceType, RendererType>}
   * @api
   */
  class BaseImageLayer extends Layer {
    /**
     * @param {Options<ImageSourceType>} [options] Layer options.
     */
    constructor(options) {
      options = options ? options : {};
      super(options);
    }
  }

  /**
   * @module ol/layer/Image
   */

  /**
   * @classdesc
   * Server-rendered images that are available for arbitrary extents and
   * resolutions.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Image.js").default} ImageSourceType
   * @extends {BaseImageLayer<ImageSourceType, CanvasImageLayerRenderer>}
   * @api
   */
  class ImageLayer extends BaseImageLayer {
    /**
     * @param {import("./BaseImage.js").Options<ImageSourceType>} [options] Layer options.
     */
    constructor(options) {
      super(options);
    }

    /**
     * @override
     */
    createRenderer() {
      return new CanvasImageLayerRenderer(this);
    }

    /**
     * Get data for a pixel location.  A four element RGBA array will be returned.  For requests outside the
     * layer extent, `null` will be returned.  Data for an image can only be retrieved if the
     * source's `crossOrigin` property is set.
     *
     * ```js
     * // display layer data on every pointer move
     * map.on('pointermove', (event) => {
     *   console.log(layer.getData(event.pixel));
     * });
     * ```
     * @param {import("../pixel").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.
     * @api
     * @override
     */
    getData(pixel) {
      return super.getData(pixel);
    }
  }

  /**
   * @module ol/renderer/canvas/TileLayer
   */

  /**
   * @param {import("../../source/Tile.js").default} source The tile source.
   * @param {string} sourceKey The source key.
   * @param {number} z The tile z level.
   * @param {number} x The tile x level.
   * @param {number} y The tile y level.
   * @return {string} The cache key.
   */
  function getCacheKey(source, sourceKey, z, x, y) {
    return `${getUid(source)},${sourceKey},${getKeyZXY(z, x, y)}`;
  }

  /**
   * @typedef {Object<number, Set<import("../../Tile.js").default>>} TileLookup
   */

  /**
   * Add a tile to the lookup.
   * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.
   * @param {import("../../Tile.js").default} tile A tile.
   * @param {number} z The zoom level.
   * @return {boolean} The tile was added to the lookup.
   */
  function addTileToLookup(tilesByZ, tile, z) {
    if (!(z in tilesByZ)) {
      tilesByZ[z] = new Set([tile]);
      return true;
    }
    const set = tilesByZ[z];
    const existing = set.has(tile);
    if (!existing) {
      set.add(tile);
    }
    return !existing;
  }

  /**
   * Remove a tile from the lookup.
   * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.
   * @param {import("../../Tile.js").default} tile A tile.
   * @param {number} z The zoom level.
   * @return {boolean} The tile was removed from the lookup.
   */
  function removeTileFromLookup(tilesByZ, tile, z) {
    const set = tilesByZ[z];
    if (set) {
      return set.delete(tile);
    }
    return false;
  }

  /**
   * @param {import("../../Map.js").FrameState} frameState Frame state.
   * @param {import("../../extent.js").Extent} extent The frame extent.
   * @return {import("../../extent.js").Extent} Frame extent intersected with layer extents.
   */
  function getRenderExtent(frameState, extent) {
    const layerState = frameState.layerStatesArray[frameState.layerIndex];
    if (layerState.extent) {
      extent = getIntersection(
        extent,
        fromUserExtent(layerState.extent, frameState.viewState.projection),
      );
    }
    const source = /** @type {import("../../source/Tile.js").default} */ (
      layerState.layer.getRenderSource()
    );
    if (!source.getWrapX()) {
      const gridExtent = source
        .getTileGridForProjection(frameState.viewState.projection)
        .getExtent();
      if (gridExtent) {
        extent = getIntersection(extent, gridExtent);
      }
    }
    return extent;
  }

  /**
   * @typedef {Object} Options
   * @property {number} [cacheSize=512] The cache size.
   */

  /**
   * @classdesc
   * Canvas renderer for tile layers.
   * @api
   * @template {import("../../layer/Tile.js").default|import("../../layer/VectorTile.js").default} [LayerType=import("../../layer/Tile.js").default<import("../../source/Tile.js").default>|import("../../layer/VectorTile.js").default]
   * @extends {CanvasLayerRenderer<LayerType>}
   */
  class CanvasTileLayerRenderer extends CanvasLayerRenderer {
    /**
     * @param {LayerType} tileLayer Tile layer.
     * @param {Options} [options] Options.
     */
    constructor(tileLayer, options) {
      super(tileLayer);

      options = options || {};

      /**
       * Rendered extent has changed since the previous `renderFrame()` call
       * @type {boolean}
       */
      this.extentChanged = true;

      /**
       * The last call to `renderFrame` was completed with all tiles loaded
       * @type {boolean}
       */
      this.renderComplete = false;

      /**
       * @private
       * @type {?import("../../extent.js").Extent}
       */
      this.renderedExtent_ = null;

      /**
       * @protected
       * @type {number}
       */
      this.renderedPixelRatio;

      /**
       * @protected
       * @type {import("../../proj/Projection.js").default|null}
       */
      this.renderedProjection = null;

      /**
       * @protected
       * @type {!Array<import("../../Tile.js").default>}
       */
      this.renderedTiles = [];

      /**
       * @private
       * @type {string}
       */
      this.renderedSourceKey_;

      /**
       * @private
       * @type {number}
       */
      this.renderedSourceRevision_;

      /**
       * @protected
       * @type {import("../../extent.js").Extent}
       */
      this.tempExtent = createEmpty();

      /**
       * @private
       * @type {import("../../TileRange.js").default}
       */
      this.tempTileRange_ = new TileRange(0, 0, 0, 0);

      /**
       * @type {import("../../tilecoord.js").TileCoord}
       * @private
       */
      this.tempTileCoord_ = createOrUpdate(0, 0, 0);

      const cacheSize = options.cacheSize !== undefined ? options.cacheSize : 512;

      /**
       * @type {import("../../structs/LRUCache.js").default<import("../../Tile.js").default>}
       * @private
       */
      this.tileCache_ = new LRUCache(cacheSize);

      this.maxStaleKeys = cacheSize * 0.5;
    }

    /**
     * @return {LRUCache} Tile cache.
     */
    getTileCache() {
      return this.tileCache_;
    }

    /**
     * Get a tile from the cache or create one if needed.
     *
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {import("../../Tile.js").default|null} Tile (or null if outside source extent).
     * @protected
     */
    getOrCreateTile(z, x, y, frameState) {
      const tileCache = this.tileCache_;
      const tileLayer = this.getLayer();
      const tileSource = tileLayer.getSource();
      const cacheKey = getCacheKey(tileSource, tileSource.getKey(), z, x, y);

      /** @type {import("../../Tile.js").default} */
      let tile;

      if (tileCache.containsKey(cacheKey)) {
        tile = tileCache.get(cacheKey);
      } else {
        tile = tileSource.getTile(
          z,
          x,
          y,
          frameState.pixelRatio,
          frameState.viewState.projection,
        );
        if (!tile) {
          return null;
        }
        tileCache.set(cacheKey, tile);
      }
      return tile;
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {import("../../Tile.js").default|null} Tile (or null if outside source extent).
     * @protected
     */
    getTile(z, x, y, frameState) {
      const tile = this.getOrCreateTile(z, x, y, frameState);
      if (!tile) {
        return null;
      }
      return tile;
    }

    /**
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Uint8ClampedArray} Data at the pixel location.
     * @override
     */
    getData(pixel) {
      const frameState = this.frameState;
      if (!frameState) {
        return null;
      }

      const layer = this.getLayer();
      const coordinate = apply(
        frameState.pixelToCoordinateTransform,
        pixel.slice(),
      );

      const layerExtent = layer.getExtent();
      if (layerExtent) {
        if (!containsCoordinate(layerExtent, coordinate)) {
          return null;
        }
      }

      const viewState = frameState.viewState;
      const source = layer.getRenderSource();
      const tileGrid = source.getTileGridForProjection(viewState.projection);
      const tilePixelRatio = source.getTilePixelRatio(frameState.pixelRatio);

      for (
        let z = tileGrid.getZForResolution(viewState.resolution);
        z >= tileGrid.getMinZoom();
        --z
      ) {
        const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);
        const tile = this.getTile(z, tileCoord[1], tileCoord[2], frameState);
        if (!tile || tile.getState() !== TileState.LOADED) {
          continue;
        }

        const tileOrigin = tileGrid.getOrigin(z);
        const tileSize = toSize(tileGrid.getTileSize(z));
        const tileResolution = tileGrid.getResolution(z);

        /**
         * @type {import('../../DataTile.js').ImageLike}
         */
        let image;
        if (tile instanceof ImageTile || tile instanceof ReprojTile) {
          image = tile.getImage();
        } else if (tile instanceof DataTile) {
          image = asImageLike(tile.getData());
          if (!image) {
            continue;
          }
        } else {
          continue;
        }

        const col = Math.floor(
          tilePixelRatio *
            ((coordinate[0] - tileOrigin[0]) / tileResolution -
              tileCoord[1] * tileSize[0]),
        );

        const row = Math.floor(
          tilePixelRatio *
            ((tileOrigin[1] - coordinate[1]) / tileResolution -
              tileCoord[2] * tileSize[1]),
        );

        const gutter = Math.round(
          tilePixelRatio * source.getGutterForProjection(viewState.projection),
        );

        return this.getImageData(image, col + gutter, row + gutter);
      }

      return null;
    }

    /**
     * Determine whether render should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      if (!this.renderedProjection) {
        this.renderedProjection = frameState.viewState.projection;
      } else if (frameState.viewState.projection !== this.renderedProjection) {
        this.tileCache_.clear();
        this.renderedProjection = frameState.viewState.projection;
      }

      const source = this.getLayer().getSource();
      if (!source) {
        return false;
      }
      const sourceRevision = source.getRevision();
      if (!this.renderedSourceRevision_) {
        this.renderedSourceRevision_ = sourceRevision;
      } else if (this.renderedSourceRevision_ !== sourceRevision) {
        this.renderedSourceRevision_ = sourceRevision;
        if (this.renderedSourceKey_ === source.getKey()) {
          this.tileCache_.clear();
        }
      }
      return true;
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {import("../../extent.js").Extent} extent The extent to be rendered.
     * @param {number} initialZ The zoom level.
     * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.
     * @param {number} preload Number of additional levels to load.
     */
    enqueueTiles(frameState, extent, initialZ, tilesByZ, preload) {
      const viewState = frameState.viewState;
      const tileLayer = this.getLayer();
      const tileSource = tileLayer.getRenderSource();
      const tileGrid = tileSource.getTileGridForProjection(viewState.projection);

      const tileSourceKey = getUid(tileSource);
      if (!(tileSourceKey in frameState.wantedTiles)) {
        frameState.wantedTiles[tileSourceKey] = {};
      }

      const wantedTiles = frameState.wantedTiles[tileSourceKey];

      const map = tileLayer.getMapInternal();
      const minZ = Math.max(
        initialZ - preload,
        tileGrid.getMinZoom(),
        tileGrid.getZForResolution(
          Math.min(
            tileLayer.getMaxResolution(),
            map
              ? map
                  .getView()
                  .getResolutionForZoom(Math.max(tileLayer.getMinZoom(), 0))
              : tileGrid.getResolution(0),
          ),
          tileSource.zDirection,
        ),
      );
      const rotation = viewState.rotation;
      const viewport = rotation
        ? getRotatedViewport(
            viewState.center,
            viewState.resolution,
            rotation,
            frameState.size,
          )
        : undefined;
      for (let z = initialZ; z >= minZ; --z) {
        const tileRange = tileGrid.getTileRangeForExtentAndZ(
          extent,
          z,
          this.tempTileRange_,
        );

        const tileResolution = tileGrid.getResolution(z);

        for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {
          for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {
            if (
              rotation &&
              !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)
            ) {
              continue;
            }
            const tile = this.getTile(z, x, y, frameState);
            if (!tile) {
              continue;
            }
            const added = addTileToLookup(tilesByZ, tile, z);
            if (!added) {
              continue;
            }

            const tileQueueKey = tile.getKey();
            wantedTiles[tileQueueKey] = true;

            if (tile.getState() === TileState.IDLE) {
              if (!frameState.tileQueue.isKeyQueued(tileQueueKey)) {
                const tileCoord = createOrUpdate(z, x, y, this.tempTileCoord_);
                frameState.tileQueue.enqueue([
                  tile,
                  tileSourceKey,
                  tileGrid.getTileCoordCenter(tileCoord),
                  tileResolution,
                ]);
              }
            }
          }
        }
      }
    }

    /**
     * Look for tiles covering the provided tile coordinate at an alternate
     * zoom level.  Loaded tiles will be added to the provided tile texture lookup.
     * @param {import("../../tilecoord.js").TileCoord} tileCoord The target tile coordinate.
     * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.
     * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.
     * @private
     */
    findStaleTile_(tileCoord, tilesByZ) {
      const tileCache = this.tileCache_;
      const z = tileCoord[0];
      const x = tileCoord[1];
      const y = tileCoord[2];
      const staleKeys = this.getStaleKeys();
      for (let i = 0; i < staleKeys.length; ++i) {
        const cacheKey = getCacheKey(
          this.getLayer().getSource(),
          staleKeys[i],
          z,
          x,
          y,
        );
        if (tileCache.containsKey(cacheKey)) {
          const tile = tileCache.peek(cacheKey);
          if (tile.getState() === TileState.LOADED) {
            tile.endTransition(getUid(this));
            addTileToLookup(tilesByZ, tile, z);
            return true;
          }
        }
      }
      return false;
    }

    /**
     * Look for tiles covering the provided tile coordinate at an alternate
     * zoom level.  Loaded tiles will be added to the provided tile texture lookup.
     * @param {import("../../tilegrid/TileGrid.js").default} tileGrid The tile grid.
     * @param {import("../../tilecoord.js").TileCoord} tileCoord The target tile coordinate.
     * @param {number} altZ The alternate zoom level.
     * @param {TileLookup} tilesByZ Lookup of tiles by zoom level.
     * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.
     * @private
     */
    findAltTiles_(tileGrid, tileCoord, altZ, tilesByZ) {
      const tileRange = tileGrid.getTileRangeForTileCoordAndZ(
        tileCoord,
        altZ,
        this.tempTileRange_,
      );

      if (!tileRange) {
        return false;
      }

      let covered = true;
      const tileCache = this.tileCache_;
      const source = this.getLayer().getRenderSource();
      const sourceKey = source.getKey();
      for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {
        for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {
          const cacheKey = getCacheKey(source, sourceKey, altZ, x, y);
          let loaded = false;
          if (tileCache.containsKey(cacheKey)) {
            const tile = tileCache.peek(cacheKey);
            if (tile.getState() === TileState.LOADED) {
              addTileToLookup(tilesByZ, tile, altZ);
              loaded = true;
            }
          }
          if (!loaded) {
            covered = false;
          }
        }
      }
      return covered;
    }

    /**
     * Render the layer.
     *
     * The frame rendering logic has three parts:
     *
     *  1. Enqueue tiles
     *  2. Find alt tiles for those that are not yet loaded
     *  3. Render loaded tiles
     *
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement} target Target that may be used to render content to.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState, target) {
      this.renderComplete = true;

      /**
       * TODO:
       *  maybe skip transition when not fully opaque
       *  decide if this.renderComplete is useful
       */

      const layerState = frameState.layerStatesArray[frameState.layerIndex];
      const viewState = frameState.viewState;
      const projection = viewState.projection;
      const viewResolution = viewState.resolution;
      const viewCenter = viewState.center;
      const pixelRatio = frameState.pixelRatio;

      const tileLayer = this.getLayer();
      const tileSource = tileLayer.getSource();
      const tileGrid = tileSource.getTileGridForProjection(projection);
      const z = tileGrid.getZForResolution(viewResolution, tileSource.zDirection);
      const tileResolution = tileGrid.getResolution(z);

      const sourceKey = tileSource.getKey();
      if (!this.renderedSourceKey_) {
        this.renderedSourceKey_ = sourceKey;
      } else if (this.renderedSourceKey_ !== sourceKey) {
        this.prependStaleKey(this.renderedSourceKey_);
        this.renderedSourceKey_ = sourceKey;
      }

      let frameExtent = frameState.extent;
      const tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio);

      this.prepareContainer(frameState, target);

      // desired dimensions of the canvas in pixels
      const width = this.context.canvas.width;
      const height = this.context.canvas.height;

      const layerExtent =
        layerState.extent && fromUserExtent(layerState.extent, projection);
      if (layerExtent) {
        frameExtent = getIntersection(
          frameExtent,
          fromUserExtent(layerState.extent, projection),
        );
      }

      const dx = (tileResolution * width) / 2 / tilePixelRatio;
      const dy = (tileResolution * height) / 2 / tilePixelRatio;
      const canvasExtent = [
        viewCenter[0] - dx,
        viewCenter[1] - dy,
        viewCenter[0] + dx,
        viewCenter[1] + dy,
      ];

      /**
       * @type {TileLookup}
       */
      const tilesByZ = {};

      this.renderedTiles.length = 0;

      /**
       * Part 1: Enqueue tiles
       */

      const preload = tileLayer.getPreload();
      if (frameState.nextExtent) {
        const targetZ = tileGrid.getZForResolution(
          viewState.nextResolution,
          tileSource.zDirection,
        );
        const nextExtent = getRenderExtent(frameState, frameState.nextExtent);
        this.enqueueTiles(frameState, nextExtent, targetZ, tilesByZ, preload);
      }

      const renderExtent = getRenderExtent(frameState, frameExtent);
      this.enqueueTiles(frameState, renderExtent, z, tilesByZ, 0);
      if (preload > 0) {
        setTimeout(() => {
          this.enqueueTiles(
            frameState,
            renderExtent,
            z - 1,
            tilesByZ,
            preload - 1,
          );
        }, 0);
      }

      if (!(z in tilesByZ)) {
        return this.container;
      }

      /**
       * Part 2: Find alt tiles for those that are not yet loaded
       */

      const uid = getUid(this);
      const time = frameState.time;

      // look for cached tiles to use if a target tile is not ready
      for (const tile of tilesByZ[z]) {
        const tileState = tile.getState();
        if (tileState === TileState.EMPTY) {
          continue;
        }
        const tileCoord = tile.tileCoord;

        if (tileState === TileState.LOADED) {
          const alpha = tile.getAlpha(uid, time);
          if (alpha === 1) {
            // no need to look for alt tiles
            tile.endTransition(uid);
            continue;
          }
        }
        if (tileState !== TileState.ERROR) {
          this.renderComplete = false;
        }

        const hasStaleTile = this.findStaleTile_(tileCoord, tilesByZ);
        if (hasStaleTile) {
          // use the stale tile before the new tile's transition has completed
          removeTileFromLookup(tilesByZ, tile, z);
          frameState.animate = true;
          continue;
        }

        // first look for child tiles (at z + 1)
        const coveredByChildren = this.findAltTiles_(
          tileGrid,
          tileCoord,
          z + 1,
          tilesByZ,
        );

        if (coveredByChildren) {
          continue;
        }

        // next look for parent tiles
        const minZoom = tileGrid.getMinZoom();
        for (let parentZ = z - 1; parentZ >= minZoom; --parentZ) {
          const coveredByParent = this.findAltTiles_(
            tileGrid,
            tileCoord,
            parentZ,
            tilesByZ,
          );

          if (coveredByParent) {
            break;
          }
        }
      }

      /**
       * Part 3: Render loaded tiles
       */

      const canvasScale =
        ((tileResolution / viewResolution) * pixelRatio) / tilePixelRatio;

      const context = this.getRenderContext(frameState);

      // set scale transform for calculating tile positions on the canvas
      compose(
        this.tempTransform,
        width / 2,
        height / 2,
        canvasScale,
        canvasScale,
        0,
        -width / 2,
        -height / 2,
      );

      if (layerState.extent) {
        this.clipUnrotated(context, frameState, layerExtent);
      }

      if (!tileSource.getInterpolate()) {
        context.imageSmoothingEnabled = false;
      }

      this.preRender(context, frameState);

      /** @type {Array<number>} */
      const zs = Object.keys(tilesByZ).map(Number);
      zs.sort(ascending);

      let currentClip;
      const clips = [];
      const clipZs = [];
      for (let i = zs.length - 1; i >= 0; --i) {
        const currentZ = zs[i];
        const currentTilePixelSize = tileSource.getTilePixelSize(
          currentZ,
          pixelRatio,
          projection,
        );
        const currentResolution = tileGrid.getResolution(currentZ);
        const currentScale = currentResolution / tileResolution;
        const dx = currentTilePixelSize[0] * currentScale * canvasScale;
        const dy = currentTilePixelSize[1] * currentScale * canvasScale;
        const originTileCoord = tileGrid.getTileCoordForCoordAndZ(
          getTopLeft(canvasExtent),
          currentZ,
        );
        const originTileExtent = tileGrid.getTileCoordExtent(originTileCoord);
        const origin = apply(this.tempTransform, [
          (tilePixelRatio * (originTileExtent[0] - canvasExtent[0])) /
            tileResolution,
          (tilePixelRatio * (canvasExtent[3] - originTileExtent[3])) /
            tileResolution,
        ]);
        const tileGutter =
          tilePixelRatio * tileSource.getGutterForProjection(projection);
        for (const tile of tilesByZ[currentZ]) {
          if (tile.getState() !== TileState.LOADED) {
            continue;
          }
          const tileCoord = tile.tileCoord;

          // Calculate integer positions and sizes so that tiles align
          const xIndex = originTileCoord[1] - tileCoord[1];
          const nextX = Math.round(origin[0] - (xIndex - 1) * dx);
          const yIndex = originTileCoord[2] - tileCoord[2];
          const nextY = Math.round(origin[1] - (yIndex - 1) * dy);
          const x = Math.round(origin[0] - xIndex * dx);
          const y = Math.round(origin[1] - yIndex * dy);
          const w = nextX - x;
          const h = nextY - y;
          const transition = zs.length === 1;

          let contextSaved = false;

          // Clip mask for regions in this tile that already filled by a higher z tile
          currentClip = [x, y, x + w, y, x + w, y + h, x, y + h];
          for (let i = 0, ii = clips.length; i < ii; ++i) {
            if (!transition && currentZ < clipZs[i]) {
              const clip = clips[i];
              if (
                intersects$2(
                  [x, y, x + w, y + h],
                  [clip[0], clip[3], clip[4], clip[7]],
                )
              ) {
                if (!contextSaved) {
                  context.save();
                  contextSaved = true;
                }
                context.beginPath();
                // counter-clockwise (outer ring) for current tile
                context.moveTo(currentClip[0], currentClip[1]);
                context.lineTo(currentClip[2], currentClip[3]);
                context.lineTo(currentClip[4], currentClip[5]);
                context.lineTo(currentClip[6], currentClip[7]);
                // clockwise (inner ring) for higher z tile
                context.moveTo(clip[6], clip[7]);
                context.lineTo(clip[4], clip[5]);
                context.lineTo(clip[2], clip[3]);
                context.lineTo(clip[0], clip[1]);
                context.clip();
              }
            }
          }
          clips.push(currentClip);
          clipZs.push(currentZ);

          this.drawTile(tile, frameState, x, y, w, h, tileGutter, transition);
          if (contextSaved) {
            context.restore();
          }
          this.renderedTiles.unshift(tile);

          // TODO: decide if this is necessary
          this.updateUsedTiles(frameState.usedTiles, tileSource, tile);
        }
      }

      this.renderedResolution = tileResolution;
      this.extentChanged =
        !this.renderedExtent_ || !equals$1(this.renderedExtent_, canvasExtent);
      this.renderedExtent_ = canvasExtent;
      this.renderedPixelRatio = pixelRatio;

      this.postRender(this.context, frameState);

      if (layerState.extent) {
        context.restore();
      }
      context.imageSmoothingEnabled = true;

      if (this.renderComplete) {
        /**
         * @param {import("../../Map.js").default} map Map.
         * @param {import("../../Map.js").FrameState} frameState Frame state.
         */
        const postRenderFunction = (map, frameState) => {
          const tileSourceKey = getUid(tileSource);
          const wantedTiles = frameState.wantedTiles[tileSourceKey];
          const tilesCount = wantedTiles ? Object.keys(wantedTiles).length : 0;
          this.updateCacheSize(tilesCount);
          this.tileCache_.expireCache();
        };

        frameState.postRenderFunctions.push(postRenderFunction);
      }

      return this.container;
    }

    /**
     * Increases the cache size if needed
     * @param {number} tileCount Minimum number of tiles needed.
     */
    updateCacheSize(tileCount) {
      this.tileCache_.highWaterMark = Math.max(
        this.tileCache_.highWaterMark,
        tileCount * 2,
      );
    }

    /**
     * @param {import("../../Tile.js").default} tile Tile.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} x Left of the tile.
     * @param {number} y Top of the tile.
     * @param {number} w Width of the tile.
     * @param {number} h Height of the tile.
     * @param {number} gutter Tile gutter.
     * @param {boolean} transition Apply an alpha transition.
     * @protected
     */
    drawTile(tile, frameState, x, y, w, h, gutter, transition) {
      let image;
      if (tile instanceof DataTile) {
        image = asImageLike(tile.getData());
        if (!image) {
          throw new Error('Rendering array data is not yet supported');
        }
      } else {
        image = this.getTileImage(
          /** @type {import("../../ImageTile.js").default} */ (tile),
        );
      }
      if (!image) {
        return;
      }
      const context = this.getRenderContext(frameState);
      const uid = getUid(this);
      const layerState = frameState.layerStatesArray[frameState.layerIndex];
      const alpha =
        layerState.opacity *
        (transition ? tile.getAlpha(uid, frameState.time) : 1);
      const alphaChanged = alpha !== context.globalAlpha;
      if (alphaChanged) {
        context.save();
        context.globalAlpha = alpha;
      }
      context.drawImage(
        image,
        gutter,
        gutter,
        image.width - 2 * gutter,
        image.height - 2 * gutter,
        x,
        y,
        w,
        h,
      );

      if (alphaChanged) {
        context.restore();
      }
      if (alpha !== layerState.opacity) {
        frameState.animate = true;
      } else if (transition) {
        tile.endTransition(uid);
      }
    }

    /**
     * @return {HTMLCanvasElement} Image
     */
    getImage() {
      const context = this.context;
      return context ? context.canvas : null;
    }

    /**
     * Get the image from a tile.
     * @param {import("../../ImageTile.js").default} tile Tile.
     * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
     * @protected
     */
    getTileImage(tile) {
      return tile.getImage();
    }

    /**
     * @param {!Object<string, !Object<string, boolean>>} usedTiles Used tiles.
     * @param {import("../../source/Tile.js").default} tileSource Tile source.
     * @param {import('../../Tile.js').default} tile Tile.
     * @protected
     */
    updateUsedTiles(usedTiles, tileSource, tile) {
      // FIXME should we use tilesToDrawByZ instead?
      const tileSourceKey = getUid(tileSource);
      if (!(tileSourceKey in usedTiles)) {
        usedTiles[tileSourceKey] = {};
      }
      usedTiles[tileSourceKey][tile.getKey()] = true;
    }
  }

  /**
   * @module ol/layer/Tile
   */

  /**
   * @classdesc
   * For layer sources that provide pre-rendered, tiled images in grids that are
   * organized by zoom levels for specific resolutions.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Tile.js").default} [TileSourceType=import("../source/Tile.js").default]
   * @extends BaseTileLayer<TileSourceType, CanvasTileLayerRenderer>
   * @api
   */
  class TileLayer extends BaseTileLayer {
    /**
     * @param {import("./BaseTile.js").Options<TileSourceType>} [options] Tile layer options.
     */
    constructor(options) {
      super(options);
    }

    /**
     * @override
     */
    createRenderer() {
      return new CanvasTileLayerRenderer(this, {
        cacheSize: this.getCacheSize(),
      });
    }
  }

  /**
   * @module ol/renderer/canvas/VectorTileLayer
   */

  /**
   * @type {!Object<string, Array<import("../../render/canvas.js").BuilderType>>}
   */
  const IMAGE_REPLAYS = {
    'image': ['Polygon', 'Circle', 'LineString', 'Image', 'Text'],
    'hybrid': ['Polygon', 'LineString'],
    'vector': [],
  };

  /**
   * @type {!Object<string, Array<import("../../render/canvas.js").BuilderType>>}
   */
  const VECTOR_REPLAYS = {
    'hybrid': ['Image', 'Text', 'Default'],
    'vector': ['Polygon', 'Circle', 'LineString', 'Image', 'Text', 'Default'],
  };

  /**
   * @classdesc
   * Canvas renderer for vector tile layers.
   * @api
   * @extends {CanvasTileLayerRenderer<import("../../layer/VectorTile.js").default<import('../../source/VectorTile.js').default<import('../../Feature.js').FeatureLike>>>}
   */
  class CanvasVectorTileLayerRenderer extends CanvasTileLayerRenderer {
    /**
     * @param {import("../../layer/VectorTile.js").default} layer VectorTile layer.
     * @param {import("./TileLayer.js").Options} options Options.
     */
    constructor(layer, options) {
      super(layer, options);

      /** @private */
      this.boundHandleStyleImageChange_ = this.handleStyleImageChange_.bind(this);

      /**
       * @private
       * @type {number}
       */
      this.renderedLayerRevision_;

      /**
       * @private
       * @type {import("../../transform").Transform}
       */
      this.renderedPixelToCoordinateTransform_ = null;

      /**
       * @private
       * @type {number}
       */
      this.renderedRotation_;

      /**
       * @private
       * @type {number}
       */
      this.renderedOpacity_ = 1;

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.tmpTransform_ = create$3();

      /**
       * @private
       * @type {Array<ZIndexContext>}
       */
      this.tileClipContexts_ = null;
    }

    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} x Left of the tile.
     * @param {number} y Top of the tile.
     * @param {number} w Width of the tile.
     * @param {number} h Height of the tile.
     * @param {number} gutter Tile gutter.
     * @param {boolean} transition Apply an alpha transition.
     * @override
     */
    drawTile(tile, frameState, x, y, w, h, gutter, transition) {
      this.updateExecutorGroup_(
        tile,
        frameState.pixelRatio,
        frameState.viewState.projection,
      );
      if (this.tileImageNeedsRender_(tile)) {
        this.renderTileImage_(tile, frameState);
      }
      super.drawTile(tile, frameState, x, y, w, h, gutter, transition);
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {import("../../Tile.js").default|null} Tile (or null if outside source extent).
     * @override
     */
    getTile(z, x, y, frameState) {
      const tile = /** @type {import("../../VectorRenderTile.js").default} */ (
        this.getOrCreateTile(z, x, y, frameState)
      );
      if (!tile) {
        return null;
      }

      const viewState = frameState.viewState;
      const resolution = viewState.resolution;
      const viewHints = frameState.viewHints;
      const hifi = !(
        viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]
      );
      if (hifi || !tile.wantedResolution) {
        tile.wantedResolution = resolution;
      }
      return tile;
    }

    /**
     * Determine whether render should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      const layerRevision = this.getLayer().getRevision();
      if (this.renderedLayerRevision_ !== layerRevision) {
        this.renderedLayerRevision_ = layerRevision;
        this.renderedTiles.length = 0;
      }
      return super.prepareFrame(frameState);
    }

    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../../proj/Projection.js").default} projection Projection.
     * @private
     */
    updateExecutorGroup_(tile, pixelRatio, projection) {
      const layer = /** @type {import("../../layer/VectorTile.js").default} */ (
        this.getLayer()
      );
      const revision = layer.getRevision();
      const renderOrder = layer.getRenderOrder() || null;

      const resolution = tile.wantedResolution;
      const builderState = tile.getReplayState(layer);
      if (
        !builderState.dirty &&
        builderState.renderedResolution === resolution &&
        builderState.renderedRevision == revision &&
        builderState.renderedRenderOrder == renderOrder
      ) {
        return;
      }

      const source = layer.getSource();
      const declutter = !!layer.getDeclutter();
      const sourceTileGrid = source.getTileGrid();
      const tileGrid = source.getTileGridForProjection(projection);
      const tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);

      const sourceTiles = source.getSourceTiles(pixelRatio, projection, tile);
      const layerUid = getUid(layer);
      delete tile.hitDetectionImageData[layerUid];
      tile.executorGroups[layerUid] = [];
      builderState.dirty = false;
      for (let t = 0, tt = sourceTiles.length; t < tt; ++t) {
        const sourceTile = sourceTiles[t];
        if (sourceTile.getState() != TileState.LOADED) {
          continue;
        }
        const sourceTileCoord = sourceTile.tileCoord;
        const sourceTileExtent =
          sourceTileGrid.getTileCoordExtent(sourceTileCoord);
        const sharedExtent = getIntersection(tileExtent, sourceTileExtent);
        const builderExtent = buffer$1(
          sharedExtent,
          layer.getRenderBuffer() * resolution,
          this.tempExtent,
        );
        const bufferedExtent = equals$1(sourceTileExtent, sharedExtent)
          ? null
          : builderExtent;
        const builderGroup = new BuilderGroup(
          0,
          sharedExtent,
          resolution,
          pixelRatio,
        );
        const squaredTolerance = getSquaredTolerance(
          resolution,
          pixelRatio,
        );

        /**
         * @param {import("../../Feature.js").FeatureLike} feature Feature.
         * @param {number} [index] Render order index.
         * @this {CanvasVectorTileLayerRenderer}
         */
        const render = function (feature, index) {
          let styles;
          const styleFunction =
            feature.getStyleFunction() || layer.getStyleFunction();
          if (styleFunction) {
            styles = styleFunction(feature, resolution);
          }
          if (styles) {
            const dirty = this.renderFeature(
              feature,
              squaredTolerance,
              styles,
              builderGroup,
              declutter,
              index,
            );
            builderState.dirty = builderState.dirty || dirty;
          }
        };

        const features = sourceTile.getFeatures();
        if (renderOrder && renderOrder !== builderState.renderedRenderOrder) {
          features.sort(renderOrder);
        }
        for (let i = 0, ii = features.length; i < ii; ++i) {
          const feature = features[i];
          if (
            !bufferedExtent ||
            intersects$2(bufferedExtent, feature.getGeometry().getExtent())
          ) {
            render.call(this, feature, i);
          }
        }
        const executorGroupInstructions = builderGroup.finish();
        // no need to clip when the render tile is covered by a single source tile
        const replayExtent =
          layer.getRenderMode() !== 'vector' &&
          declutter &&
          sourceTiles.length === 1
            ? null
            : sharedExtent;
        const renderingReplayGroup = new ExecutorGroup(
          replayExtent,
          resolution,
          pixelRatio,
          source.getOverlaps(),
          executorGroupInstructions,
          layer.getRenderBuffer(),
          true,
        );
        tile.executorGroups[layerUid].push(renderingReplayGroup);
      }
      builderState.renderedRevision = revision;
      builderState.renderedRenderOrder = renderOrder;
      builderState.renderedResolution = resolution;
    }

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("../vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("../Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     * @override
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      const resolution = frameState.viewState.resolution;
      const rotation = frameState.viewState.rotation;
      hitTolerance = hitTolerance == undefined ? 0 : hitTolerance;
      const layer = this.getLayer();
      const source = layer.getSource();
      const tileGrid = source.getTileGridForProjection(
        frameState.viewState.projection,
      );

      const hitExtent = boundingExtent([coordinate]);
      buffer$1(hitExtent, resolution * hitTolerance, hitExtent);

      /** @type {!Object<string, import("../Map.js").HitMatch<T>|true>} */
      const features = {};

      /**
       * @param {import("../../Feature.js").FeatureLike} feature Feature.
       * @param {import("../../geom/SimpleGeometry.js").default} geometry Geometry.
       * @param {number} distanceSq The squared distance to the click position.
       * @return {T|undefined} Callback result.
       */
      const featureCallback = function (feature, geometry, distanceSq) {
        let key = feature.getId();
        if (key === undefined) {
          key = getUid(feature);
        }
        const match = features[key];
        if (!match) {
          if (distanceSq === 0) {
            features[key] = true;
            return callback(feature, layer, geometry);
          }
          matches.push(
            (features[key] = {
              feature: feature,
              layer: layer,
              geometry: geometry,
              distanceSq: distanceSq,
              callback: callback,
            }),
          );
        } else if (match !== true && distanceSq < match.distanceSq) {
          if (distanceSq === 0) {
            features[key] = true;
            matches.splice(matches.lastIndexOf(match), 1);
            return callback(feature, layer, geometry);
          }
          match.geometry = geometry;
          match.distanceSq = distanceSq;
        }
        return undefined;
      };

      const renderedTiles =
        /** @type {Array<import("../../VectorRenderTile.js").default>} */ (
          this.renderedTiles
        );
      const layerUid = getUid(layer);
      const declutter = layer.getDeclutter();
      const declutteredFeatures = declutter
        ? frameState.declutter?.[declutter]?.all().map((item) => item.value)
        : null;
      let found;
      foundFeature: for (let i = 0, ii = renderedTiles.length; i < ii; ++i) {
        const tile = renderedTiles[i];
        const tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
        if (!intersects$2(tileExtent, hitExtent)) {
          continue;
        }

        const executorGroups = tile.executorGroups[layerUid];
        for (let t = 0, tt = executorGroups.length; t < tt; ++t) {
          found = executorGroups[t].forEachFeatureAtCoordinate(
            coordinate,
            resolution,
            rotation,
            hitTolerance,
            featureCallback,
            declutteredFeatures,
          );
          if (found) {
            break foundFeature;
          }
        }
      }
      return found;
    }

    /**
     * Asynchronous layer level hit detection.
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../../Feature.js").FeatureLike>>} Promise that resolves with an array of features.
     * @override
     */
    getFeatures(pixel) {
      if (this.renderedTiles.length === 0) {
        return Promise.resolve([]);
      }
      return new Promise((resolve, reject) => {
        const layer = this.getLayer();
        const source = layer.getSource();
        const projection = this.renderedProjection;
        const projectionExtent = projection.getExtent();
        const resolution = this.renderedResolution;
        const tileGrid = source.getTileGridForProjection(projection);
        const coordinate = apply(
          this.renderedPixelToCoordinateTransform_,
          pixel.slice(),
        );
        const tileCoordString = tileGrid
          .getTileCoordForCoordAndResolution(coordinate, resolution)
          .toString();
        const tile =
          /** @type {Array<import("../../VectorRenderTile.js").default>} */ (
            this.renderedTiles
          ).find(
            (tile) =>
              tile.tileCoord.toString() === tileCoordString &&
              tile.getState() === TileState.LOADED,
          );
        if (!tile || tile.loadingSourceTiles > 0) {
          resolve([]);
          return;
        }
        if (
          source.getWrapX() &&
          projection.canWrapX() &&
          !containsExtent(
            projectionExtent,
            tileGrid.getTileCoordExtent(tile.tileCoord),
          )
        ) {
          wrapX$1(coordinate, projection);
        }
        const layerUid = getUid(layer);
        const extent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
        const corner = getTopLeft(extent);
        const tilePixel = [
          (coordinate[0] - corner[0]) / resolution,
          (corner[1] - coordinate[1]) / resolution,
        ];
        const features = tile
          .getSourceTiles()
          .reduce(
            (accumulator, sourceTile) =>
              accumulator.concat(sourceTile.getFeatures()),
            /** @type {Array<import("../../Feature.js").FeatureLike>} */ ([]),
          );
        let hitDetectionImageData = tile.hitDetectionImageData[layerUid];
        if (!hitDetectionImageData) {
          const tileSize = toSize(
            tileGrid.getTileSize(
              tileGrid.getZForResolution(resolution, source.zDirection),
            ),
          );
          const rotation = this.renderedRotation_;
          const transforms = [
            this.getRenderTransform(
              tileGrid.getTileCoordCenter(tile.wrappedTileCoord),
              resolution,
              0,
              HIT_DETECT_RESOLUTION,
              tileSize[0] * HIT_DETECT_RESOLUTION,
              tileSize[1] * HIT_DETECT_RESOLUTION,
              0,
            ),
          ];
          hitDetectionImageData = createHitDetectionImageData(
            tileSize,
            transforms,
            features,
            layer.getStyleFunction(),
            tileGrid.getTileCoordExtent(tile.wrappedTileCoord),
            tile.getReplayState(layer).renderedResolution,
            rotation,
          );
          tile.hitDetectionImageData[layerUid] = hitDetectionImageData;
        }
        resolve(hitDetect(tilePixel, features, hitDetectionImageData));
      });
    }

    /**
     * @param {import("../../extent.js").Extent} extent Extent.
     * @return {Array<import('../../Feature.js').FeatureLike>} Features.
     */
    getFeaturesInExtent(extent) {
      /** @type {Array<import('../../Feature.js').FeatureLike>} */
      const features = [];
      const tileCache = this.getTileCache();
      if (tileCache.getCount() === 0) {
        return features;
      }
      const source = this.getLayer().getSource();
      const tileGrid = source.getTileGridForProjection(
        this.frameState.viewState.projection,
      );
      const z = tileGrid.getZForResolution(this.renderedResolution);
      /** @type {Object<string, true>} */
      const visitedSourceTiles = {};
      tileCache.forEach((tile) => {
        if (tile.tileCoord[0] !== z || tile.getState() !== TileState.LOADED) {
          return;
        }
        const sourceTiles = tile.getSourceTiles();
        for (let i = 0, ii = sourceTiles.length; i < ii; ++i) {
          const sourceTile = sourceTiles[i];
          const key = sourceTile.getKey();
          if (key in visitedSourceTiles) {
            continue;
          }
          visitedSourceTiles[key] = true;
          const tileCoord = sourceTile.tileCoord;
          if (intersects$2(extent, tileGrid.getTileCoordExtent(tileCoord))) {
            const tileFeatures = sourceTile.getFeatures();
            if (tileFeatures) {
              for (let j = 0, jj = tileFeatures.length; j < jj; ++j) {
                const candidate = tileFeatures[j];
                const geometry = candidate.getGeometry();
                if (intersects$2(extent, geometry.getExtent())) {
                  features.push(candidate);
                }
              }
            }
          }
        }
      });
      return features;
    }

    /**
     * Perform action necessary to get the layer rendered after new fonts have loaded
     * @override
     */
    handleFontsChanged() {
      const layer = this.getLayer();
      if (layer.getVisible() && this.renderedLayerRevision_ !== undefined) {
        layer.changed();
      }
    }

    /**
     * Handle changes in image style state.
     * @param {import("../../events/Event.js").default} event Image style change event.
     * @private
     */
    handleStyleImageChange_(event) {
      this.renderIfReadyAndVisible();
    }

    /**
     * Render declutter items for this layer
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {import("../../layer/Layer.js").State} layerState Layer state.
     */
    renderDeclutter(frameState, layerState) {
      const context = this.context;
      const alpha = context.globalAlpha;
      context.globalAlpha = layerState.opacity;
      const viewHints = frameState.viewHints;
      const hifi = !(
        viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]
      );
      const scaledCanvasSize = [
        this.context.canvas.width,
        this.context.canvas.height,
      ];
      const declutter = this.getLayer().getDeclutter();
      const declutterTree = declutter
        ? frameState.declutter?.[declutter]
        : undefined;
      const layerUid = getUid(this.getLayer());
      const tiles =
        /** @type {Array<import("../../VectorRenderTile.js").default>} */ (
          this.renderedTiles
        );
      for (let i = 0, ii = tiles.length; i < ii; ++i) {
        const tile = tiles[i];
        const executorGroups = tile.executorGroups[layerUid];
        if (executorGroups) {
          for (let j = executorGroups.length - 1; j >= 0; --j) {
            executorGroups[j].execute(
              this.context,
              scaledCanvasSize,
              this.getTileRenderTransform(tile, frameState),
              frameState.viewState.rotation,
              hifi,
              DECLUTTER,
              declutterTree,
            );
          }
        }
      }
      context.globalAlpha = alpha;
    }

    /**
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @override
     */
    renderDeferredInternal(frameState) {
      const tiles =
        /** @type {Array<import("../../VectorRenderTile.js").default>} */ (
          this.renderedTiles
        );
      const layerUid = getUid(this.getLayer());
      const executorGroups = tiles.reduce((acc, tile, index) => {
        tile.executorGroups[layerUid].forEach((executorGroup) =>
          acc.push({
            executorGroup,
            index,
          }),
        );
        return acc;
      }, /** @type {Array<{executorGroup: CanvasExecutorGroup, index: number}>} */ ([]));

      const executorGroupZIndexContexts = executorGroups.map(({executorGroup}) =>
        executorGroup.getDeferredZIndexContexts(),
      );
      /** @type {Object<number, true>} */
      const usedZIndices = {};
      for (let i = 0, ii = executorGroups.length; i < ii; ++i) {
        const executorGroupZindexContext =
          executorGroups[i].executorGroup.getDeferredZIndexContexts();
        for (const key in executorGroupZindexContext) {
          usedZIndices[key] = true;
        }
      }
      const zIndexKeys = Object.keys(usedZIndices).map(Number).sort(ascending);
      zIndexKeys.forEach((zIndex) => {
        executorGroupZIndexContexts.forEach((zIndexContexts, i) => {
          if (!zIndexContexts[zIndex]) {
            return;
          }
          zIndexContexts[zIndex].forEach((zIndexContext) => {
            const {executorGroup, index} = executorGroups[i];
            const context = executorGroup.getRenderedContext();
            const alpha = context.globalAlpha;
            context.globalAlpha = this.renderedOpacity_;
            const tileClipContext = this.tileClipContexts_[index];
            if (tileClipContext) {
              tileClipContext.draw(context);
            }
            zIndexContext.draw(context);
            if (tileClipContext) {
              context.restore();
            }
            context.globalAlpha = alpha;
            zIndexContext.clear();
          });
          zIndexContexts[zIndex].length = 0;
        });
      });
    }

    /**
     * @param {import("../../VectorRenderTile.js").default} tile The tile
     * @param {import('../../Map.js').FrameState} frameState Current frame state
     * @return {import('../../transform.js').Transform} Transform to use to render this tile
     */
    getTileRenderTransform(tile, frameState) {
      const pixelRatio = frameState.pixelRatio;
      const viewState = frameState.viewState;
      const center = viewState.center;
      const resolution = viewState.resolution;
      const rotation = viewState.rotation;
      const size = frameState.size;
      const width = Math.round(size[0] * pixelRatio);
      const height = Math.round(size[1] * pixelRatio);

      const source = this.getLayer().getSource();
      const tileGrid = source.getTileGridForProjection(
        frameState.viewState.projection,
      );
      const tileCoord = tile.tileCoord;
      const tileExtent = tileGrid.getTileCoordExtent(tile.wrappedTileCoord);
      const worldOffset =
        tileGrid.getTileCoordExtent(tileCoord, this.tempExtent)[0] -
        tileExtent[0];
      const transform = multiply(
        scale$3(this.inversePixelTransform.slice(), 1 / pixelRatio, 1 / pixelRatio),
        this.getRenderTransform(
          center,
          resolution,
          rotation,
          pixelRatio,
          width,
          height,
          worldOffset,
        ),
      );
      return transform;
    }

    /**
     * Render the vectors for this layer.
     * @param {CanvasRenderingContext2D} context Target context.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @override
     */
    postRender(context, frameState) {
      const viewHints = frameState.viewHints;
      const hifi = !(
        viewHints[ViewHint.ANIMATING] || viewHints[ViewHint.INTERACTING]
      );

      this.renderedPixelToCoordinateTransform_ =
        frameState.pixelToCoordinateTransform.slice();
      this.renderedRotation_ = frameState.viewState.rotation;
      this.renderedOpacity_ =
        frameState.layerStatesArray[frameState.layerIndex].opacity;

      const layer = /** @type {import("../../layer/VectorTile.js").default} */ (
        this.getLayer()
      );
      const renderMode = layer.getRenderMode();
      const alpha = context.globalAlpha;
      context.globalAlpha = this.renderedOpacity_;
      const declutter = layer.getDeclutter();
      const replayTypes = declutter
        ? VECTOR_REPLAYS[renderMode].filter((type) => !DECLUTTER.includes(type))
        : VECTOR_REPLAYS[renderMode];
      const viewState = frameState.viewState;
      const rotation = viewState.rotation;
      const tileSource = layer.getSource();
      const tileGrid = tileSource.getTileGridForProjection(viewState.projection);
      const z = tileGrid.getZForResolution(
        viewState.resolution,
        tileSource.zDirection,
      );

      const tiles =
        /** @type {Array<import("../../VectorRenderTile.js").default>} */ (
          this.renderedTiles
        );
      const clips = [];
      const clipZs = [];
      const tileClipContexts = [];
      const layerUid = getUid(layer);
      let ready = true;
      for (let i = tiles.length - 1; i >= 0; --i) {
        const tile = tiles[i];
        ready = ready && !tile.getReplayState(layer).dirty;
        const executorGroups = tile.executorGroups[layerUid].filter((group) =>
          group.hasExecutors(replayTypes),
        );
        if (executorGroups.length === 0) {
          continue;
        }
        const transform = this.getTileRenderTransform(tile, frameState);
        const currentZ = tile.tileCoord[0];
        let contextSaved = false;
        // Clip mask for regions in this tile that already filled by a higher z tile
        const currentClip = executorGroups[0].getClipCoords(transform);
        let clipContext = context;
        let tileClipContext;
        if (currentClip) {
          tileClipContext = new ZIndexContext();
          clipContext = tileClipContext.getContext();
          for (let j = 0, jj = clips.length; j < jj; ++j) {
            if (z !== currentZ && currentZ < clipZs[j]) {
              const clip = clips[j];
              if (
                intersects$2(
                  [
                    currentClip[0],
                    currentClip[3],
                    currentClip[4],
                    currentClip[7],
                  ],
                  [clip[0], clip[3], clip[4], clip[7]],
                )
              ) {
                if (!contextSaved) {
                  clipContext.save();
                  contextSaved = true;
                }
                clipContext.beginPath();
                // counter-clockwise (outer ring) for current tile
                clipContext.moveTo(currentClip[0], currentClip[1]);
                clipContext.lineTo(currentClip[2], currentClip[3]);
                clipContext.lineTo(currentClip[4], currentClip[5]);
                clipContext.lineTo(currentClip[6], currentClip[7]);
                // clockwise (inner ring) for higher z tile
                clipContext.moveTo(clip[6], clip[7]);
                clipContext.lineTo(clip[4], clip[5]);
                clipContext.lineTo(clip[2], clip[3]);
                clipContext.lineTo(clip[0], clip[1]);
                clipContext.clip();
              }
            }
          }
          clips.push(currentClip);
          clipZs.push(currentZ);
        }
        for (let t = 0, tt = executorGroups.length; t < tt; ++t) {
          const executorGroup = executorGroups[t];
          executorGroup.execute(
            context,
            [context.canvas.width, context.canvas.height],
            transform,
            rotation,
            hifi,
            replayTypes,
            frameState.declutter?.[declutter],
          );
        }
        if (contextSaved) {
          if (clipContext === context) {
            clipContext.restore();
          } else {
            tileClipContexts[i] = tileClipContext;
          }
        }
      }
      context.globalAlpha = alpha;
      this.ready = ready;
      this.tileClipContexts_ = tileClipContexts;
      if (!frameState.declutter) {
        this.renderDeferredInternal(frameState);
      }

      super.postRender(context, frameState);
    }

    /**
     * @param {import("../../Feature.js").FeatureLike} feature Feature.
     * @param {number} squaredTolerance Squared tolerance.
     * @param {import("../../style/Style.js").default|Array<import("../../style/Style.js").default>} styles The style or array of styles.
     * @param {import("../../render/canvas/BuilderGroup.js").default} builderGroup Replay group.
     * @param {boolean} [declutter] Enable decluttering.
     * @param {number} [index] Render order index.
     * @return {boolean} `true` if an image is loading.
     */
    renderFeature(
      feature,
      squaredTolerance,
      styles,
      builderGroup,
      declutter,
      index,
    ) {
      if (!styles) {
        return false;
      }
      let loading = false;
      if (Array.isArray(styles)) {
        for (let i = 0, ii = styles.length; i < ii; ++i) {
          loading =
            renderFeature$1(
              builderGroup,
              feature,
              styles[i],
              squaredTolerance,
              this.boundHandleStyleImageChange_,
              undefined,
              declutter,
              index,
            ) || loading;
        }
      } else {
        loading = renderFeature$1(
          builderGroup,
          feature,
          styles,
          squaredTolerance,
          this.boundHandleStyleImageChange_,
          undefined,
          declutter,
          index,
        );
      }
      return loading;
    }

    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @return {boolean} A new tile image was rendered.
     * @private
     */
    tileImageNeedsRender_(tile) {
      const layer = /** @type {import("../../layer/VectorTile.js").default} */ (
        this.getLayer()
      );
      if (layer.getRenderMode() === 'vector') {
        return false;
      }
      const replayState = tile.getReplayState(layer);
      const revision = layer.getRevision();
      const resolution = tile.wantedResolution;
      return (
        replayState.renderedTileResolution !== resolution ||
        replayState.renderedTileRevision !== revision
      );
    }

    /**
     * @param {import("../../VectorRenderTile.js").default} tile Tile.
     * @param {import("../../Map").FrameState} frameState Frame state.
     * @private
     */
    renderTileImage_(tile, frameState) {
      const layer = /** @type {import("../../layer/VectorTile.js").default} */ (
        this.getLayer()
      );
      const replayState = tile.getReplayState(layer);
      const revision = layer.getRevision();
      const executorGroups = tile.executorGroups[getUid(layer)];
      replayState.renderedTileRevision = revision;

      const tileCoord = tile.wrappedTileCoord;
      const z = tileCoord[0];
      const source = layer.getSource();
      let pixelRatio = frameState.pixelRatio;
      const viewState = frameState.viewState;
      const projection = viewState.projection;
      const tileGrid = source.getTileGridForProjection(projection);
      const tileResolution = tileGrid.getResolution(tile.tileCoord[0]);
      const renderPixelRatio =
        (frameState.pixelRatio / tile.wantedResolution) * tileResolution;
      const resolution = tileGrid.getResolution(z);
      const context = tile.getContext();

      // Increase tile size when overzooming for low pixel ratio, to avoid blurry tiles
      pixelRatio = Math.round(
        Math.max(pixelRatio, renderPixelRatio / pixelRatio),
      );
      const size = source.getTilePixelSize(z, pixelRatio, projection);
      context.canvas.width = size[0];
      context.canvas.height = size[1];
      const renderScale = pixelRatio / renderPixelRatio;
      if (renderScale !== 1) {
        const canvasTransform = reset(this.tmpTransform_);
        scale$3(canvasTransform, renderScale, renderScale);
        context.setTransform.apply(context, canvasTransform);
      }
      const tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tempExtent);
      const pixelScale = renderPixelRatio / resolution;
      const transform = reset(this.tmpTransform_);
      scale$3(transform, pixelScale, -pixelScale);
      translate$2(transform, -tileExtent[0], -tileExtent[3]);
      for (let i = 0, ii = executorGroups.length; i < ii; ++i) {
        const executorGroup = executorGroups[i];
        executorGroup.execute(
          context,
          [
            context.canvas.width * renderScale,
            context.canvas.height * renderScale,
          ],
          transform,
          0,
          true,
          IMAGE_REPLAYS[layer.getRenderMode()],
          null,
        );
      }
      replayState.renderedTileResolution = tile.wantedResolution;
    }
  }

  /**
   * @module ol/layer/VectorTile
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("./Base").BaseLayerObjectEventTypes|
   *     import("./Layer.js").LayerEventType|'change:preload'|'change:useInterimTilesOnError', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("../render/EventType").LayerRenderEventTypes, import("../render/Event").default, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("./Base").BaseLayerObjectEventTypes|
   *     import("./Layer.js").LayerEventType|'change:preload'|'change:useInterimTilesOnError'|import("../render/EventType").LayerRenderEventTypes, Return>} VectorTileLayerOnSignature
   */

  /**
   * @typedef {'hybrid' | 'vector'} VectorTileRenderType
   */

  /***
   * @template T
   * @typedef {T extends import("../source/VectorTile.js").default<infer U extends import("../Feature.js").FeatureLike> ? U : never} ExtractedFeatureType
   */

  /**
   * @template {import("../source/VectorTile.js").default<FeatureType>} [VectorTileSourceType=import("../source/VectorTile.js").default<*>]
   * @template {import("../Feature").FeatureLike} [FeatureType=ExtractedFeatureType<VectorTileSourceType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
   * features before rendering. By default features are drawn in the order that they are created. Use
   * `null` to avoid the sort, but get an undefined draw order.
   * @property {number} [renderBuffer=100] The buffer in pixels around the tile extent used by the
   * renderer when getting features from the vector tile for the rendering or hit-detection.
   * Recommended value: Vector tiles are usually generated with a buffer, so this value should match
   * the largest possible buffer of the used tiles. It should be at least the size of the largest
   * point symbol or line width.
   * @property {VectorTileRenderType} [renderMode='hybrid'] Render mode for vector tiles:
   *  `'hybrid'`: Polygon and line elements are rendered as images, so pixels are scaled during zoom
   *    animations. Point symbols and texts are accurately rendered as vectors and can stay upright on
   *    rotated views, but get lifted above all polygon and line elements.
   *  `'vector'`: Everything is rendered as vectors and the original render order is maintained. Use
   *    this mode for improved performance and visual epxerience on vector tile layers with not too many
   *    rendered features (e.g. for highlighting a subset of features of another layer with the same
   *    source).
   * @property {VectorTileSourceType} [source] Source.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use [map.addLayer()]{@link import("../Map.js").default#addLayer}.
   * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable
   * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the
   * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the
   * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct
   * layers or groups of layers separately, use different truthy values for `declutter`.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer
   * style. When set to `null`, only
   * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style
   * which will be used if this is not set.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no
   * background will be rendered.
   * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will be
   * recreated during animations. This means that no vectors will be shown clipped, but the setting
   * will have a performance impact for large amounts of vector data. When set to `false`, batches
   * will be recreated when no animation is active.
   * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will be
   * recreated during interactions. See also `updateWhileAnimating`.
   * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
   * means no preloading.
   * @property {boolean} [useInterimTilesOnError=true] Deprecated.  Use interim tiles on error.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   * @property {number} [cacheSize=0] The internal tile cache size.  If too small, this will auto-grow to hold
   * two zoom levels worth of tiles.
   */

  /**
   * @classdesc
   * Layer for vector tile data that is rendered client-side.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/VectorTile.js").default<FeatureType>} [VectorTileSourceType=import("../source/VectorTile.js").default<*>]
   * @template {import("../Feature.js").FeatureLike} [FeatureType=ExtractedFeatureType<VectorTileSourceType>]
   * @extends {BaseVectorLayer<FeatureType, VectorTileSourceType, CanvasVectorTileLayerRenderer>}
   * @api
   */
  class VectorTileLayer extends BaseVectorLayer {
    /**
     * @param {Options<VectorTileSourceType, FeatureType>} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign({}, options);
      delete baseOptions.preload;
      const cacheSize = options.cacheSize === undefined ? 0 : options.cacheSize;
      delete options.cacheSize;
      delete baseOptions.useInterimTilesOnError;

      super(baseOptions);

      /***
       * @type {VectorTileLayerOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {VectorTileLayerOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {VectorTileLayerOnSignature<void>}
       */
      this.un;

      /**
       * @type {number|undefined}
       * @private
       */
      this.cacheSize_ = cacheSize;

      const renderMode = options.renderMode || 'hybrid';
      assert(
        renderMode == 'hybrid' || renderMode == 'vector',
        "`renderMode` must be `'hybrid'` or `'vector'`",
      );

      /**
       * @private
       * @type {VectorTileRenderType}
       */
      this.renderMode_ = renderMode;

      this.setPreload(options.preload ? options.preload : 0);
      this.setUseInterimTilesOnError(
        options.useInterimTilesOnError !== undefined
          ? options.useInterimTilesOnError
          : true,
      );

      /**
       * @return {import("./Base.js").BackgroundColor} Background color.
       * @function
       * @api
       */
      this.getBackground;

      /**
       * @param {import("./Base.js").BackgroundColor} background Background color.
       * @function
       * @api
       */
      this.setBackground;
    }

    /**
     * @override
     */
    createRenderer() {
      return new CanvasVectorTileLayerRenderer(this, {
        cacheSize: this.cacheSize_,
      });
    }

    /**
     * Get the topmost feature that intersects the given pixel on the viewport. Returns a promise
     * that resolves with an array of features. The array will either contain the topmost feature
     * when a hit was detected, or it will be empty.
     *
     * The hit detection algorithm used for this method is optimized for performance, but is less
     * accurate than the one used in [map.getFeaturesAtPixel()]{@link import("../Map.js").default#getFeaturesAtPixel}.
     * Text is not considered, and icons are only represented by their bounding box instead of the exact
     * image.
     *
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../Feature").FeatureLike>>} Promise that resolves with an array of features.
     * @api
     * @override
     */
    getFeatures(pixel) {
      return super.getFeatures(pixel);
    }

    /**
     * Get features whose bounding box intersects the provided extent. Only features for cached
     * tiles for the last rendered zoom level are available in the source. So this method is only
     * suitable for requesting tiles for extents that are currently rendered.
     *
     * Features are returned in random tile order and as they are included in the tiles. This means
     * they can be clipped, duplicated across tiles, and simplified to the render resolution.
     *
     * @param {import("../extent.js").Extent} extent Extent.
     * @return {Array<FeatureType>} Features.
     * @api
     */
    getFeaturesInExtent(extent) {
      return /** @type {Array<FeatureType>} */ (
        /** @type {*} */ (this.getRenderer().getFeaturesInExtent(extent))
      );
    }

    /**
     * @return {VectorTileRenderType} The render mode.
     */
    getRenderMode() {
      return this.renderMode_;
    }

    /**
     * Return the level as number to which we will preload tiles up to.
     * @return {number} The level to preload tiles up to.
     * @observable
     * @api
     */
    getPreload() {
      return /** @type {number} */ (this.get(TileProperty.PRELOAD));
    }

    /**
     * Deprecated.  Whether we use interim tiles on error.
     * @return {boolean} Use interim tiles on error.
     * @observable
     * @api
     */
    getUseInterimTilesOnError() {
      return /** @type {boolean} */ (
        this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)
      );
    }

    /**
     * Set the level as number to which we will preload tiles up to.
     * @param {number} preload The level to preload tiles up to.
     * @observable
     * @api
     */
    setPreload(preload) {
      this.set(TileProperty.PRELOAD, preload);
    }

    /**
     * Deprecated.  Set whether we use interim tiles on error.
     * @param {boolean} useInterimTilesOnError Use interim tiles on error.
     * @observable
     * @api
     */
    setUseInterimTilesOnError(useInterimTilesOnError) {
      this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);
    }
  }

  /**
   * @module ol/resolution
   */

  /**
   * @typedef {number|Array<number>} ResolutionLike
   */

  /**
   * @param {ResolutionLike} resolution Resolution.
   * @return {number} Resolution.
   */
  function fromResolutionLike(resolution) {
    if (Array.isArray(resolution)) {
      return Math.min(...resolution);
    }
    return resolution;
  }

  /**
   * @module ol/reproj/Image
   */


  /**
   * @typedef {function(import("../extent.js").Extent, number, number) : import("../Image.js").default} FunctionType
   */

  /**
   * @classdesc
   * Class encapsulating single reprojected image.
   * See {@link module:ol/source/Image~ImageSource}.
   */
  class ReprojImage extends ImageWrapper {
    /**
     * @param {import("../proj/Projection.js").default} sourceProj Source projection (of the data).
     * @param {import("../proj/Projection.js").default} targetProj Target projection.
     * @param {import("../extent.js").Extent} targetExtent Target extent.
     * @param {number} targetResolution Target resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {FunctionType} getImageFunction
     *     Function returning source images (extent, resolution, pixelRatio).
     * @param {boolean} interpolate Use linear interpolation when resampling.
     */
    constructor(
      sourceProj,
      targetProj,
      targetExtent,
      targetResolution,
      pixelRatio,
      getImageFunction,
      interpolate,
    ) {
      let maxSourceExtent = sourceProj.getExtent();
      if (maxSourceExtent && sourceProj.canWrapX()) {
        maxSourceExtent = maxSourceExtent.slice();
        maxSourceExtent[0] = -Infinity;
        maxSourceExtent[2] = Infinity;
      }
      let maxTargetExtent = targetProj.getExtent();
      if (maxTargetExtent && targetProj.canWrapX()) {
        maxTargetExtent = maxTargetExtent.slice();
        maxTargetExtent[0] = -Infinity;
        maxTargetExtent[2] = Infinity;
      }

      const limitedTargetExtent = maxTargetExtent
        ? getIntersection(targetExtent, maxTargetExtent)
        : targetExtent;

      const targetCenter = getCenter(limitedTargetExtent);
      const sourceResolution = calculateSourceResolution(
        sourceProj,
        targetProj,
        targetCenter,
        targetResolution,
      );

      const errorThresholdInPixels = ERROR_THRESHOLD;

      const triangulation = new Triangulation(
        sourceProj,
        targetProj,
        limitedTargetExtent,
        maxSourceExtent,
        sourceResolution * errorThresholdInPixels,
        targetResolution,
      );

      const sourceExtent = triangulation.calculateSourceExtent();
      const sourceImage = isEmpty(sourceExtent)
        ? null
        : getImageFunction(sourceExtent, sourceResolution, pixelRatio);
      const state = sourceImage ? ImageState.IDLE : ImageState.EMPTY;
      const sourcePixelRatio = sourceImage ? sourceImage.getPixelRatio() : 1;

      super(targetExtent, targetResolution, sourcePixelRatio, state);

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.targetProj_ = targetProj;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.maxSourceExtent_ = maxSourceExtent;

      /**
       * @private
       * @type {!import("./Triangulation.js").default}
       */
      this.triangulation_ = triangulation;

      /**
       * @private
       * @type {number}
       */
      this.targetResolution_ = targetResolution;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.targetExtent_ = targetExtent;

      /**
       * @private
       * @type {import("../Image.js").default}
       */
      this.sourceImage_ = sourceImage;

      /**
       * @private
       * @type {number}
       */
      this.sourcePixelRatio_ = sourcePixelRatio;

      /**
       * @private
       * @type {boolean}
       */
      this.interpolate_ = interpolate;

      /**
       * @private
       * @type {HTMLCanvasElement}
       */
      this.canvas_ = null;

      /**
       * @private
       * @type {?import("../events.js").EventsKey}
       */
      this.sourceListenerKey_ = null;
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      if (this.state == ImageState.LOADING) {
        this.unlistenSource_();
      }
      super.disposeInternal();
    }

    /**
     * @return {HTMLCanvasElement} Image.
     * @override
     */
    getImage() {
      return this.canvas_;
    }

    /**
     * @return {import("../proj/Projection.js").default} Projection.
     */
    getProjection() {
      return this.targetProj_;
    }

    /**
     * @private
     */
    reproject_() {
      const sourceState = this.sourceImage_.getState();
      if (sourceState == ImageState.LOADED) {
        const width = getWidth(this.targetExtent_) / this.targetResolution_;
        const height = getHeight(this.targetExtent_) / this.targetResolution_;
        this.canvas_ = render$1(
          width,
          height,
          this.sourcePixelRatio_,
          fromResolutionLike(this.sourceImage_.getResolution()),
          this.maxSourceExtent_,
          this.targetResolution_,
          this.targetExtent_,
          this.triangulation_,
          [
            {
              extent: this.sourceImage_.getExtent(),
              image: this.sourceImage_.getImage(),
            },
          ],
          0,
          undefined,
          this.interpolate_,
          true,
        );
      }
      this.state = sourceState;
      this.changed();
    }

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {
      if (this.state == ImageState.IDLE) {
        this.state = ImageState.LOADING;
        this.changed();

        const sourceState = this.sourceImage_.getState();
        if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) {
          this.reproject_();
        } else {
          this.sourceListenerKey_ = listen(
            this.sourceImage_,
            EventType.CHANGE,
            (e) => {
              const sourceState = this.sourceImage_.getState();
              if (
                sourceState == ImageState.LOADED ||
                sourceState == ImageState.ERROR
              ) {
                this.unlistenSource_();
                this.reproject_();
              }
            },
          );
          this.sourceImage_.load();
        }
      }
    }

    /**
     * @private
     */
    unlistenSource_() {
      unlistenByKey(
        /** @type {!import("../events.js").EventsKey} */ (
          this.sourceListenerKey_
        ),
      );
      this.sourceListenerKey_ = null;
    }
  }

  /**
   * @module ol/source/common
   */


  /**
   * Number of decimal digits to consider in integer values when rounding.
   * @type {number}
   */
  const DECIMALS$1 = 4;

  /**
   * @module ol/source/Image
   */

  /**
   * @enum {string}
   */
  const ImageSourceEventType = {
    /**
     * Triggered when an image starts loading.
     * @event module:ol/source/Image.ImageSourceEvent#imageloadstart
     * @api
     */
    IMAGELOADSTART: 'imageloadstart',

    /**
     * Triggered when an image finishes loading.
     * @event module:ol/source/Image.ImageSourceEvent#imageloadend
     * @api
     */
    IMAGELOADEND: 'imageloadend',

    /**
     * Triggered if image loading results in an error.
     * @event module:ol/source/Image.ImageSourceEvent#imageloaderror
     * @api
     */
    IMAGELOADERROR: 'imageloaderror',
  };

  /**
   * @typedef {'imageloadend'|'imageloaderror'|'imageloadstart'} ImageSourceEventTypes
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/source/Image~ImageSource} instances are instances of this
   * type.
   */
  class ImageSourceEvent extends BaseEvent {
    /**
     * @param {string} type Type.
     * @param {import("../Image.js").default} image The image.
     */
    constructor(type, image) {
      super(type);

      /**
       * The image related to the event.
       * @type {import("../Image.js").default}
       * @api
       */
      this.image = image;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<ImageSourceEventTypes, ImageSourceEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types
   *     |ImageSourceEventTypes, Return>} ImageSourceOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../Image.js").Loader} [loader] Loader. Can either be a custom loader, or one of the
   * loaders created with a `createLoader()` function ({@link module:ol/source/wms.createLoader wms},
   * {@link module:ol/source/arcgisRest.createLoader arcgisRest}, {@link module:ol/source/mapguide.createLoader mapguide},
   * {@link module:ol/source/static.createLoader static}).
   * @property {import("../proj.js").ProjectionLike} [projection] Projection.
   * @property {Array<number>} [resolutions] Resolutions.
   * @property {import("./Source.js").State} [state] State.
   */

  /**
   * @classdesc
   * Base class for sources providing a single image.
   * @fires module:ol/source/Image.ImageSourceEvent
   * @api
   */
  class ImageSource extends Source {
    /**
     * @param {Options} options Single image source options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        projection: options.projection,
        state: options.state,
        interpolate:
          options.interpolate !== undefined ? options.interpolate : true,
      });

      /***
       * @type {ImageSourceOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {ImageSourceOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {ImageSourceOnSignature<void>}
       */
      this.un;

      /**
       * @protected
       * @type {import("../Image.js").Loader}
       */
      this.loader = options.loader || null;

      /**
       * @private
       * @type {Array<number>|null}
       */
      this.resolutions_ =
        options.resolutions !== undefined ? options.resolutions : null;

      /**
       * @private
       * @type {import("../reproj/Image.js").default}
       */
      this.reprojectedImage_ = null;

      /**
       * @private
       * @type {number}
       */
      this.reprojectedRevision_ = 0;

      /**
       * @protected
       * @type {import("../Image.js").default}
       */
      this.image = null;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.wantedExtent_;

      /**
       * @private
       * @type {number}
       */
      this.wantedResolution_;

      /**
       * @private
       * @type {boolean}
       */
      this.static_ = options.loader ? options.loader.length === 0 : false;

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.wantedProjection_ = null;
    }

    /**
     * @return {Array<number>|null} Resolutions.
     * @override
     */
    getResolutions() {
      return this.resolutions_;
    }

    /**
     * @param {Array<number>|null} resolutions Resolutions.
     */
    setResolutions(resolutions) {
      this.resolutions_ = resolutions;
    }

    /**
     * @protected
     * @param {number} resolution Resolution.
     * @return {number} Resolution.
     */
    findNearestResolution(resolution) {
      const resolutions = this.getResolutions();
      if (resolutions) {
        const idx = linearFindNearest(resolutions, resolution, 0);
        resolution = resolutions[idx];
      }
      return resolution;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     */
    getImage(extent, resolution, pixelRatio, projection) {
      const sourceProjection = this.getProjection();
      if (
        !sourceProjection ||
        !projection ||
        equivalent$1(sourceProjection, projection)
      ) {
        if (sourceProjection) {
          projection = sourceProjection;
        }

        return this.getImageInternal(extent, resolution, pixelRatio, projection);
      }
      if (this.reprojectedImage_) {
        if (
          this.reprojectedRevision_ == this.getRevision() &&
          equivalent$1(this.reprojectedImage_.getProjection(), projection) &&
          this.reprojectedImage_.getResolution() == resolution &&
          equals$1(this.reprojectedImage_.getExtent(), extent)
        ) {
          return this.reprojectedImage_;
        }
        this.reprojectedImage_.dispose();
        this.reprojectedImage_ = null;
      }

      this.reprojectedImage_ = new ReprojImage(
        sourceProjection,
        projection,
        extent,
        resolution,
        pixelRatio,
        (extent, resolution, pixelRatio) =>
          this.getImageInternal(extent, resolution, pixelRatio, sourceProjection),
        this.getInterpolate(),
      );
      this.reprojectedRevision_ = this.getRevision();

      return this.reprojectedImage_;
    }

    /**
     * @abstract
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     * @protected
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      if (this.loader) {
        const requestExtent = getRequestExtent(extent, resolution, pixelRatio, 1);
        const requestResolution = this.findNearestResolution(resolution);
        if (
          this.image &&
          (this.static_ ||
            (this.wantedProjection_ === projection &&
              ((this.wantedExtent_ &&
                containsExtent(this.wantedExtent_, requestExtent)) ||
                containsExtent(this.image.getExtent(), requestExtent)) &&
              ((this.wantedResolution_ &&
                fromResolutionLike(this.wantedResolution_) ===
                  requestResolution) ||
                fromResolutionLike(this.image.getResolution()) ===
                  requestResolution)))
        ) {
          return this.image;
        }
        this.wantedProjection_ = projection;
        this.wantedExtent_ = requestExtent;
        this.wantedResolution_ = requestResolution;
        this.image = new ImageWrapper(
          requestExtent,
          requestResolution,
          pixelRatio,
          this.loader,
        );
        this.image.addEventListener(
          EventType.CHANGE,
          this.handleImageChange.bind(this),
        );
      }
      return this.image;
    }

    /**
     * Handle image change events.
     * @param {import("../events/Event.js").default} event Event.
     * @protected
     */
    handleImageChange(event) {
      const image = /** @type {import("../Image.js").default} */ (event.target);
      let type;
      switch (image.getState()) {
        case ImageState.LOADING:
          this.loading = true;
          type = ImageSourceEventType.IMAGELOADSTART;
          break;
        case ImageState.LOADED:
          this.loading = false;
          type = ImageSourceEventType.IMAGELOADEND;
          break;
        case ImageState.ERROR:
          this.loading = false;
          type = ImageSourceEventType.IMAGELOADERROR;
          break;
        default:
          return;
      }
      if (this.hasListener(type)) {
        this.dispatchEvent(new ImageSourceEvent(type, image));
      }
    }
  }

  /**
   * Default image load function for image sources that use import("../Image.js").Image image
   * instances.
   * @param {import("../Image.js").default} image Image.
   * @param {string} src Source.
   */
  function defaultImageLoadFunction(image, src) {
    /** @type {HTMLImageElement|HTMLVideoElement} */ (image.getImage()).src = src;
  }

  /**
   * Adjusts the extent so it aligns with pixel boundaries.
   * @param {import("../extent.js").Extent} extent Extent.
   * @param {number} resolution Reolution.
   * @param {number} pixelRatio Pixel ratio.
   * @param {number} ratio Ratio between request size and view size.
   * @return {import("../extent.js").Extent} Request extent.
   */
  function getRequestExtent(extent, resolution, pixelRatio, ratio) {
    const imageResolution = resolution / pixelRatio;
    const center = getCenter(extent);
    const viewWidth = ceil(getWidth(extent) / imageResolution, DECIMALS$1);
    const viewHeight = ceil(getHeight(extent) / imageResolution, DECIMALS$1);
    const marginWidth = ceil(((ratio - 1) * viewWidth) / 2, DECIMALS$1);
    const requestWidth = viewWidth + 2 * marginWidth;
    const marginHeight = ceil(((ratio - 1) * viewHeight) / 2, DECIMALS$1);
    const requestHeight = viewHeight + 2 * marginHeight;
    return getForViewAndSize(center, imageResolution, 0, [
      requestWidth,
      requestHeight,
    ]);
  }

  /**
   * @module ol/tilegrid/TileGrid
   */

  /**
   * @private
   * @type {import("../tilecoord.js").TileCoord}
   */
  const tmpTileCoord = [0, 0, 0];

  /**
   * Number of decimal digits to consider in integer values when rounding.
   * @type {number}
   */
  const DECIMALS = 5;

  /**
   * @typedef {Object} Options
   * @property {import("../extent.js").Extent} [extent] Extent for the tile grid. No tiles outside this
   * extent will be requested by {@link module:ol/source/Tile~TileSource} sources. When no `origin` or
   * `origins` are configured, the `origin` will be set to the top-left corner of the extent.
   * @property {number} [minZoom=0] Minimum zoom.
   * @property {import("../coordinate.js").Coordinate} [origin] The tile grid origin, i.e. where the `x`
   * and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left to right and downwards. If not
   * specified, `extent` or `origins` must be provided.
   * @property {Array<import("../coordinate.js").Coordinate>} [origins] Tile grid origins, i.e. where
   * the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If given, the array length
   * should match the length of the `resolutions` array, i.e. each resolution can have a different
   * origin. Tile coordinates increase left to right and downwards. If not specified, `extent` or
   * `origin` must be provided.
   * @property {!Array<number>} resolutions Resolutions. The array index of each resolution needs
   * to match the zoom level. This means that even if a `minZoom` is configured, the resolutions
   * array will have a length of `maxZoom + 1`.
   * @property {Array<import("../size.js").Size>} [sizes] Number of tile rows and columns
   * of the grid for each zoom level. If specified the values
   * define each zoom level's extent together with the `origin` or `origins`.
   * A grid `extent` can be configured in addition, and will further limit the extent
   * for which tile requests are made by sources. If the bottom-left corner of
   * an extent is used as `origin` or `origins`, then the `y` value must be
   * negative because OpenLayers tile coordinates use the top left as the origin.
   * @property {number|import("../size.js").Size} [tileSize] Tile size.
   * Default is `[256, 256]`.
   * @property {Array<number|import("../size.js").Size>} [tileSizes] Tile sizes. If given, the array length
   * should match the length of the `resolutions` array, i.e. each resolution can have a different
   * tile size.
   */

  /**
   * @classdesc
   * Base class for setting the grid pattern for sources accessing tiled-image
   * servers.
   * @api
   */
  class TileGrid {
    /**
     * @param {Options} options Tile grid options.
     */
    constructor(options) {
      /**
       * @protected
       * @type {number}
       */
      this.minZoom = options.minZoom !== undefined ? options.minZoom : 0;

      /**
       * @private
       * @type {!Array<number>}
       */
      this.resolutions_ = options.resolutions;
      assert(
        isSorted(
          this.resolutions_,
          /**
           * @param {number} a First resolution
           * @param {number} b Second resolution
           * @return {number} Comparison result
           */
          (a, b) => b - a),
        '`resolutions` must be sorted in descending order',
      );

      // check if we've got a consistent zoom factor and origin
      let zoomFactor;
      if (!options.origins) {
        for (let i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) {
          if (!zoomFactor) {
            zoomFactor = this.resolutions_[i] / this.resolutions_[i + 1];
          } else {
            if (this.resolutions_[i] / this.resolutions_[i + 1] !== zoomFactor) {
              zoomFactor = undefined;
              break;
            }
          }
        }
      }

      /**
       * @private
       * @type {number|undefined}
       */
      this.zoomFactor_ = zoomFactor;

      /**
       * @protected
       * @type {number}
       */
      this.maxZoom = this.resolutions_.length - 1;

      /**
       * @private
       * @type {import("../coordinate.js").Coordinate|null}
       */
      this.origin_ = options.origin !== undefined ? options.origin : null;

      /**
       * @private
       * @type {Array<import("../coordinate.js").Coordinate>}
       */
      this.origins_ = null;
      if (options.origins !== undefined) {
        this.origins_ = options.origins;
        assert(
          this.origins_.length == this.resolutions_.length,
          'Number of `origins` and `resolutions` must be equal',
        );
      }

      const extent = options.extent;

      if (extent !== undefined && !this.origin_ && !this.origins_) {
        this.origin_ = getTopLeft(extent);
      }

      assert(
        (!this.origin_ && this.origins_) || (this.origin_ && !this.origins_),
        'Either `origin` or `origins` must be configured, never both',
      );

      /**
       * @private
       * @type {Array<number|import("../size.js").Size>}
       */
      this.tileSizes_ = null;
      if (options.tileSizes !== undefined) {
        this.tileSizes_ = options.tileSizes;
        assert(
          this.tileSizes_.length == this.resolutions_.length,
          'Number of `tileSizes` and `resolutions` must be equal',
        );
      }

      /**
       * @private
       * @type {number|import("../size.js").Size}
       */
      this.tileSize_ =
        options.tileSize !== undefined
          ? options.tileSize
          : !this.tileSizes_
            ? DEFAULT_TILE_SIZE
            : null;
      assert(
        (!this.tileSize_ && this.tileSizes_) ||
          (this.tileSize_ && !this.tileSizes_),
        'Either `tileSize` or `tileSizes` must be configured, never both',
      );

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.extent_ = extent !== undefined ? extent : null;

      /**
       * @private
       * @type {Array<import("../TileRange.js").default>}
       */
      this.fullTileRanges_ = null;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.tmpSize_ = [0, 0];

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.tmpExtent_ = [0, 0, 0, 0];

      if (options.sizes !== undefined) {
        this.fullTileRanges_ = options.sizes.map((size, z) => {
          const tileRange = new TileRange(
            Math.min(0, size[0]),
            Math.max(size[0] - 1, -1),
            Math.min(0, size[1]),
            Math.max(size[1] - 1, -1),
          );
          if (extent) {
            const restrictedTileRange = this.getTileRangeForExtentAndZ(extent, z);
            tileRange.minX = Math.max(restrictedTileRange.minX, tileRange.minX);
            tileRange.maxX = Math.min(restrictedTileRange.maxX, tileRange.maxX);
            tileRange.minY = Math.max(restrictedTileRange.minY, tileRange.minY);
            tileRange.maxY = Math.min(restrictedTileRange.maxY, tileRange.maxY);
          }
          return tileRange;
        });
      } else if (extent) {
        this.calculateTileRanges_(extent);
      }
    }

    /**
     * Call a function with each tile coordinate for a given extent and zoom level.
     *
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} zoom Integer zoom level.
     * @param {function(import("../tilecoord.js").TileCoord): void} callback Function called with each tile coordinate.
     * @api
     */
    forEachTileCoord(extent, zoom, callback) {
      const tileRange = this.getTileRangeForExtentAndZ(extent, zoom);
      for (let i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) {
        for (let j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) {
          callback([zoom, i, j]);
        }
      }
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {function(number, import("../TileRange.js").default): boolean} callback Callback.
     * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object.
     * @param {import("../extent.js").Extent} [tempExtent] Temporary import("../extent.js").Extent object.
     * @return {boolean} Callback succeeded.
     */
    forEachTileCoordParentTileRange(
      tileCoord,
      callback,
      tempTileRange,
      tempExtent,
    ) {
      let tileRange, x, y;
      let tileCoordExtent = null;
      let z = tileCoord[0] - 1;
      if (this.zoomFactor_ === 2) {
        x = tileCoord[1];
        y = tileCoord[2];
      } else {
        tileCoordExtent = this.getTileCoordExtent(tileCoord, tempExtent);
      }
      while (z >= this.minZoom) {
        if (x !== undefined && y !== undefined) {
          x = Math.floor(x / 2);
          y = Math.floor(y / 2);
          tileRange = createOrUpdate$1(x, x, y, y, tempTileRange);
        } else {
          tileRange = this.getTileRangeForExtentAndZ(
            tileCoordExtent,
            z,
            tempTileRange,
          );
        }
        if (callback(z, tileRange)) {
          return true;
        }
        --z;
      }
      return false;
    }

    /**
     * Get the extent for this tile grid, if it was configured.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getExtent() {
      return this.extent_;
    }

    /**
     * Get the maximum zoom level for the grid.
     * @return {number} Max zoom.
     * @api
     */
    getMaxZoom() {
      return this.maxZoom;
    }

    /**
     * Get the minimum zoom level for the grid.
     * @return {number} Min zoom.
     * @api
     */
    getMinZoom() {
      return this.minZoom;
    }

    /**
     * Get the origin for the grid at the given zoom level.
     * @param {number} z Integer zoom level.
     * @return {import("../coordinate.js").Coordinate} Origin.
     * @api
     */
    getOrigin(z) {
      if (this.origin_) {
        return this.origin_;
      }
      return this.origins_[z];
    }

    /**
     * Get the resolution for the given zoom level.
     * @param {number} z Integer zoom level.
     * @return {number} Resolution.
     * @api
     */
    getResolution(z) {
      return this.resolutions_[z];
    }

    /**
     * Get the list of resolutions for the tile grid.
     * @return {Array<number>} Resolutions.
     * @api
     */
    getResolutions() {
      return this.resolutions_;
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object.
     * @param {import("../extent.js").Extent} [tempExtent] Temporary import("../extent.js").Extent object.
     * @return {import("../TileRange.js").default|null} Tile range.
     */
    getTileCoordChildTileRange(tileCoord, tempTileRange, tempExtent) {
      if (tileCoord[0] < this.maxZoom) {
        if (this.zoomFactor_ === 2) {
          const minX = tileCoord[1] * 2;
          const minY = tileCoord[2] * 2;
          return createOrUpdate$1(
            minX,
            minX + 1,
            minY,
            minY + 1,
            tempTileRange,
          );
        }
        const tileCoordExtent = this.getTileCoordExtent(
          tileCoord,
          tempExtent || this.tmpExtent_,
        );
        return this.getTileRangeForExtentAndZ(
          tileCoordExtent,
          tileCoord[0] + 1,
          tempTileRange,
        );
      }
      return null;
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {number} z Integer zoom level.
     * @param {import("../TileRange.js").default} [tempTileRange] Temporary import("../TileRange.js").default object.
     * @return {import("../TileRange.js").default|null} Tile range.
     */
    getTileRangeForTileCoordAndZ(tileCoord, z, tempTileRange) {
      if (z > this.maxZoom || z < this.minZoom) {
        return null;
      }

      const tileCoordZ = tileCoord[0];
      const tileCoordX = tileCoord[1];
      const tileCoordY = tileCoord[2];

      if (z === tileCoordZ) {
        return createOrUpdate$1(
          tileCoordX,
          tileCoordY,
          tileCoordX,
          tileCoordY,
          tempTileRange,
        );
      }

      if (this.zoomFactor_) {
        const factor = Math.pow(this.zoomFactor_, z - tileCoordZ);
        const minX = Math.floor(tileCoordX * factor);
        const minY = Math.floor(tileCoordY * factor);
        if (z < tileCoordZ) {
          return createOrUpdate$1(minX, minX, minY, minY, tempTileRange);
        }

        const maxX = Math.floor(factor * (tileCoordX + 1)) - 1;
        const maxY = Math.floor(factor * (tileCoordY + 1)) - 1;
        return createOrUpdate$1(minX, maxX, minY, maxY, tempTileRange);
      }

      const tileCoordExtent = this.getTileCoordExtent(tileCoord, this.tmpExtent_);
      return this.getTileRangeForExtentAndZ(tileCoordExtent, z, tempTileRange);
    }

    /**
     * Get a tile range for the given extent and integer zoom level.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} z Integer zoom level.
     * @param {import("../TileRange.js").default} [tempTileRange] Temporary tile range object.
     * @return {import("../TileRange.js").default} Tile range.
     */
    getTileRangeForExtentAndZ(extent, z, tempTileRange) {
      this.getTileCoordForXYAndZ_(extent[0], extent[3], z, false, tmpTileCoord);
      const minX = tmpTileCoord[1];
      const minY = tmpTileCoord[2];
      this.getTileCoordForXYAndZ_(extent[2], extent[1], z, true, tmpTileCoord);
      const maxX = tmpTileCoord[1];
      const maxY = tmpTileCoord[2];
      return createOrUpdate$1(minX, maxX, minY, maxY, tempTileRange);
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @return {import("../coordinate.js").Coordinate} Tile center.
     */
    getTileCoordCenter(tileCoord) {
      const origin = this.getOrigin(tileCoord[0]);
      const resolution = this.getResolution(tileCoord[0]);
      const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);
      return [
        origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution,
        origin[1] - (tileCoord[2] + 0.5) * tileSize[1] * resolution,
      ];
    }

    /**
     * Get the extent of a tile coordinate.
     *
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../extent.js").Extent} [tempExtent] Temporary extent object.
     * @return {import("../extent.js").Extent} Extent.
     * @api
     */
    getTileCoordExtent(tileCoord, tempExtent) {
      const origin = this.getOrigin(tileCoord[0]);
      const resolution = this.getResolution(tileCoord[0]);
      const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);
      const minX = origin[0] + tileCoord[1] * tileSize[0] * resolution;
      const minY = origin[1] - (tileCoord[2] + 1) * tileSize[1] * resolution;
      const maxX = minX + tileSize[0] * resolution;
      const maxY = minY + tileSize[1] * resolution;
      return createOrUpdate$2(minX, minY, maxX, maxY, tempExtent);
    }

    /**
     * Get the tile coordinate for the given map coordinate and resolution.  This
     * method considers that coordinates that intersect tile boundaries should be
     * assigned the higher tile coordinate.
     *
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} resolution Resolution.
     * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Destination import("../tilecoord.js").TileCoord object.
     * @return {import("../tilecoord.js").TileCoord} Tile coordinate.
     * @api
     */
    getTileCoordForCoordAndResolution(coordinate, resolution, opt_tileCoord) {
      return this.getTileCoordForXYAndResolution_(
        coordinate[0],
        coordinate[1],
        resolution,
        false,
        opt_tileCoord,
      );
    }

    /**
     * Note that this method should not be called for resolutions that correspond
     * to an integer zoom level.  Instead call the `getTileCoordForXYAndZ_` method.
     * @param {number} x X.
     * @param {number} y Y.
     * @param {number} resolution Resolution (for a non-integer zoom level).
     * @param {boolean} reverseIntersectionPolicy Instead of letting edge
     *     intersections go to the higher tile coordinate, let edge intersections
     *     go to the lower tile coordinate.
     * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Temporary import("../tilecoord.js").TileCoord object.
     * @return {import("../tilecoord.js").TileCoord} Tile coordinate.
     * @private
     */
    getTileCoordForXYAndResolution_(
      x,
      y,
      resolution,
      reverseIntersectionPolicy,
      opt_tileCoord,
    ) {
      const z = this.getZForResolution(resolution);
      const scale = resolution / this.getResolution(z);
      const origin = this.getOrigin(z);
      const tileSize = toSize(this.getTileSize(z), this.tmpSize_);

      let tileCoordX = (scale * (x - origin[0])) / resolution / tileSize[0];
      let tileCoordY = (scale * (origin[1] - y)) / resolution / tileSize[1];

      if (reverseIntersectionPolicy) {
        tileCoordX = ceil(tileCoordX, DECIMALS) - 1;
        tileCoordY = ceil(tileCoordY, DECIMALS) - 1;
      } else {
        tileCoordX = floor(tileCoordX, DECIMALS);
        tileCoordY = floor(tileCoordY, DECIMALS);
      }

      return createOrUpdate(z, tileCoordX, tileCoordY, opt_tileCoord);
    }

    /**
     * Although there is repetition between this method and `getTileCoordForXYAndResolution_`,
     * they should have separate implementations.  This method is for integer zoom
     * levels.  The other method should only be called for resolutions corresponding
     * to non-integer zoom levels.
     * @param {number} x Map x coordinate.
     * @param {number} y Map y coordinate.
     * @param {number} z Integer zoom level.
     * @param {boolean} reverseIntersectionPolicy Instead of letting edge
     *     intersections go to the higher tile coordinate, let edge intersections
     *     go to the lower tile coordinate.
     * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Temporary import("../tilecoord.js").TileCoord object.
     * @return {import("../tilecoord.js").TileCoord} Tile coordinate.
     * @private
     */
    getTileCoordForXYAndZ_(x, y, z, reverseIntersectionPolicy, opt_tileCoord) {
      const origin = this.getOrigin(z);
      const resolution = this.getResolution(z);
      const tileSize = toSize(this.getTileSize(z), this.tmpSize_);

      let tileCoordX = (x - origin[0]) / resolution / tileSize[0];
      let tileCoordY = (origin[1] - y) / resolution / tileSize[1];

      if (reverseIntersectionPolicy) {
        tileCoordX = ceil(tileCoordX, DECIMALS) - 1;
        tileCoordY = ceil(tileCoordY, DECIMALS) - 1;
      } else {
        tileCoordX = floor(tileCoordX, DECIMALS);
        tileCoordY = floor(tileCoordY, DECIMALS);
      }

      return createOrUpdate(z, tileCoordX, tileCoordY, opt_tileCoord);
    }

    /**
     * Get a tile coordinate given a map coordinate and zoom level.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} z Integer zoom level, e.g. the result of a `getZForResolution()` method call
     * @param {import("../tilecoord.js").TileCoord} [opt_tileCoord] Destination import("../tilecoord.js").TileCoord object.
     * @return {import("../tilecoord.js").TileCoord} Tile coordinate.
     * @api
     */
    getTileCoordForCoordAndZ(coordinate, z, opt_tileCoord) {
      return this.getTileCoordForXYAndZ_(
        coordinate[0],
        coordinate[1],
        z,
        false,
        opt_tileCoord,
      );
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @return {number} Tile resolution.
     */
    getTileCoordResolution(tileCoord) {
      return this.resolutions_[tileCoord[0]];
    }

    /**
     * Get the tile size for a zoom level. The type of the return value matches the
     * `tileSize` or `tileSizes` that the tile grid was configured with. To always
     * get an {@link import("../size.js").Size}, run the result through {@link module:ol/size.toSize}.
     * @param {number} z Z.
     * @return {number|import("../size.js").Size} Tile size.
     * @api
     */
    getTileSize(z) {
      if (this.tileSize_) {
        return this.tileSize_;
      }
      return this.tileSizes_[z];
    }

    /**
     * @param {number} z Zoom level.
     * @return {import("../TileRange.js").default|null} Extent tile range for the specified zoom level.
     */
    getFullTileRange(z) {
      if (!this.fullTileRanges_) {
        return this.extent_
          ? this.getTileRangeForExtentAndZ(this.extent_, z)
          : null;
      }
      return this.fullTileRanges_[z];
    }

    /**
     * @param {number} resolution Resolution.
     * @param {number|import("../array.js").NearestDirectionFunction} [opt_direction]
     *     If 0, the nearest resolution will be used.
     *     If 1, the nearest higher resolution (lower Z) will be used. If -1, the
     *     nearest lower resolution (higher Z) will be used. Default is 0.
     *     Use a {@link module:ol/array~NearestDirectionFunction} for more precise control.
     *
     * For example to change tile Z at the midpoint of zoom levels
     * ```js
     * function(value, high, low) {
     *   return value - low * Math.sqrt(high / low);
     * }
     * ```
     * @return {number} Z.
     * @api
     */
    getZForResolution(resolution, opt_direction) {
      const z = linearFindNearest(
        this.resolutions_,
        resolution,
        opt_direction || 0,
      );
      return clamp$1(z, this.minZoom, this.maxZoom);
    }

    /**
     * The tile with the provided tile coordinate intersects the given viewport.
     * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coordinate.
     * @param {Array<number>} viewport Viewport as returned from {@link module:ol/extent.getRotatedViewport}.
     * @return {boolean} The tile with the provided tile coordinate intersects the given viewport.
     */
    tileCoordIntersectsViewport(tileCoord, viewport) {
      return intersectsLinearRing(
        viewport,
        0,
        viewport.length,
        2,
        this.getTileCoordExtent(tileCoord),
      );
    }

    /**
     * @param {!import("../extent.js").Extent} extent Extent for this tile grid.
     * @private
     */
    calculateTileRanges_(extent) {
      const length = this.resolutions_.length;
      const fullTileRanges = new Array(length);
      for (let z = this.minZoom; z < length; ++z) {
        fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z);
      }
      this.fullTileRanges_ = fullTileRanges;
    }
  }

  /**
   * @module ol/tilegrid/WMTS
   */


  /**
   * @typedef {Object} Options
   * @property {import("../extent.js").Extent} [extent] Extent for the tile grid. No tiles
   * outside this extent will be requested by {@link module:ol/source/Tile~TileSource} sources.
   * When no `origin` or `origins` are configured, the `origin` will be set to the
   * top-left corner of the extent.
   * @property {import("../coordinate.js").Coordinate} [origin] The tile grid origin, i.e.
   * where the `x` and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left
   * to right and downwards. If not specified, `extent` or `origins` must be provided.
   * @property {Array<import("../coordinate.js").Coordinate>} [origins] Tile grid origins,
   * i.e. where the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If
   * given, the array length should match the length of the `resolutions` array, i.e.
   * each resolution can have a different origin. Tile coordinates increase left to
   * right and downwards. If not specified, `extent` or `origin` must be provided.
   * @property {!Array<number>} resolutions Resolutions. The array index of each
   * resolution needs to match the zoom level. This means that even if a `minZoom`
   * is configured, the resolutions array will have a length of `maxZoom + 1`
   * @property {!Array<string>} matrixIds matrix IDs. The length of this array needs
   * to match the length of the `resolutions` array.
   * @property {Array<import("../size.js").Size>} [sizes] Number of tile rows and columns
   * of the grid for each zoom level. The values here are the `TileMatrixWidth` and
   * `TileMatrixHeight` advertised in the GetCapabilities response of the WMTS, and
   * define each zoom level's extent together with the `origin` or `origins`.
   * A grid `extent` can be configured in addition, and will further limit the extent for
   * which tile requests are made by sources. If the bottom-left corner of
   * an extent is used as `origin` or `origins`, then the `y` value must be
   * negative because OpenLayers tile coordinates use the top left as the origin.
   * @property {number|import("../size.js").Size} [tileSize] Tile size.
   * @property {Array<number|import("../size.js").Size>} [tileSizes] Tile sizes. The length of
   * this array needs to match the length of the `resolutions` array.
   */

  /**
   * @classdesc
   * Set the grid pattern for sources accessing WMTS tiled-image servers.
   * @api
   */
  class WMTSTileGrid extends TileGrid {
    /**
     * @param {Options} options WMTS options.
     */
    constructor(options) {
      super({
        extent: options.extent,
        origin: options.origin,
        origins: options.origins,
        resolutions: options.resolutions,
        tileSize: options.tileSize,
        tileSizes: options.tileSizes,
        sizes: options.sizes,
      });

      /**
       * @private
       * @type {!Array<string>}
       */
      this.matrixIds_ = options.matrixIds;
    }

    /**
     * @param {number} z Z.
     * @return {string} MatrixId..
     */
    getMatrixId(z) {
      return this.matrixIds_[z];
    }

    /**
     * Get the list of matrix identifiers.
     * @return {Array<string>} MatrixIds.
     * @api
     */
    getMatrixIds() {
      return this.matrixIds_;
    }
  }

  /**
   * @module ol/tilegrid
   */

  /**
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @return {!TileGrid} Default tile grid for the
   * passed projection.
   */
  function getForProjection(projection) {
    let tileGrid = projection.getDefaultTileGrid();
    if (!tileGrid) {
      tileGrid = createForProjection(projection);
      projection.setDefaultTileGrid(tileGrid);
    }
    return tileGrid;
  }

  /**
   * @param {TileGrid} tileGrid Tile grid.
   * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @return {import("./tilecoord.js").TileCoord} Tile coordinate.
   */
  function wrapX(tileGrid, tileCoord, projection) {
    const z = tileCoord[0];
    const center = tileGrid.getTileCoordCenter(tileCoord);
    const projectionExtent = extentFromProjection(projection);
    if (!containsCoordinate(projectionExtent, center)) {
      const worldWidth = getWidth(projectionExtent);
      const worldsAway = Math.ceil(
        (projectionExtent[0] - center[0]) / worldWidth,
      );
      center[0] += worldWidth * worldsAway;
      return tileGrid.getTileCoordForCoordAndZ(center, z);
    }
    return tileCoord;
  }

  /**
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {number} [maxZoom] Maximum zoom level (default is
   *     DEFAULT_MAX_ZOOM).
   * @param {number|import("./size.js").Size} [tileSize] Tile size (default uses
   *     DEFAULT_TILE_SIZE).
   * @param {import("./extent.js").Corner} [corner] Extent corner (default is `'top-left'`).
   * @return {!TileGrid} TileGrid instance.
   */
  function createForExtent(extent, maxZoom, tileSize, corner) {
    corner = corner !== undefined ? corner : 'top-left';

    const resolutions = resolutionsFromExtent(extent, maxZoom, tileSize);

    return new TileGrid({
      extent: extent,
      origin: getCorner(extent, corner),
      resolutions: resolutions,
      tileSize: tileSize,
    });
  }

  /**
   * @typedef {Object} XYZOptions
   * @property {import("./extent.js").Extent} [extent] Extent for the tile grid. The origin for an XYZ tile grid is the
   * top-left corner of the extent. If `maxResolution` is not provided the zero level of the grid is defined by the resolution
   * at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used.
   * @property {number} [maxResolution] Resolution at level zero.
   * @property {number} [maxZoom] Maximum zoom. The default is `42`. This determines the number of levels
   * in the grid set. For example, a `maxZoom` of 21 means there are 22 levels in the grid set.
   * @property {number} [minZoom=0] Minimum zoom.
   * @property {number|import("./size.js").Size} [tileSize=[256, 256]] Tile size in pixels.
   */

  /**
   * Creates a tile grid with a standard XYZ tiling scheme.
   * @param {XYZOptions} [options] Tile grid options.
   * @return {!TileGrid} Tile grid instance.
   * @api
   */
  function createXYZ(options) {
    const xyzOptions = options || {};

    const extent = xyzOptions.extent || get$2('EPSG:3857').getExtent();

    const gridOptions = {
      extent: extent,
      minZoom: xyzOptions.minZoom,
      tileSize: xyzOptions.tileSize,
      resolutions: resolutionsFromExtent(
        extent,
        xyzOptions.maxZoom,
        xyzOptions.tileSize,
        xyzOptions.maxResolution,
      ),
    };
    return new TileGrid(gridOptions);
  }

  /**
   * Create a resolutions array from an extent.  A zoom factor of 2 is assumed.
   * @param {import("./extent.js").Extent} extent Extent.
   * @param {number} [maxZoom] Maximum zoom level (default is
   *     DEFAULT_MAX_ZOOM).
   * @param {number|import("./size.js").Size} [tileSize] Tile size (default uses
   *     DEFAULT_TILE_SIZE).
   * @param {number} [maxResolution] Resolution at level zero.
   * @return {!Array<number>} Resolutions array.
   */
  function resolutionsFromExtent(extent, maxZoom, tileSize, maxResolution) {
    maxZoom = maxZoom !== undefined ? maxZoom : DEFAULT_MAX_ZOOM;
    tileSize = toSize(tileSize !== undefined ? tileSize : DEFAULT_TILE_SIZE);

    const height = getHeight(extent);
    const width = getWidth(extent);

    maxResolution =
      maxResolution > 0
        ? maxResolution
        : Math.max(width / tileSize[0], height / tileSize[1]);

    const length = maxZoom + 1;
    const resolutions = new Array(length);
    for (let z = 0; z < length; ++z) {
      resolutions[z] = maxResolution / Math.pow(2, z);
    }
    return resolutions;
  }

  /**
   * @param {import("./proj.js").ProjectionLike} projection Projection.
   * @param {number} [maxZoom] Maximum zoom level (default is
   *     DEFAULT_MAX_ZOOM).
   * @param {number|import("./size.js").Size} [tileSize] Tile size (default uses
   *     DEFAULT_TILE_SIZE).
   * @param {import("./extent.js").Corner} [corner] Extent corner (default is `'top-left'`).
   * @return {!TileGrid} TileGrid instance.
   */
  function createForProjection(projection, maxZoom, tileSize, corner) {
    const extent = extentFromProjection(projection);
    return createForExtent(extent, maxZoom, tileSize, corner);
  }

  /**
   * Generate a tile grid extent from a projection.  If the projection has an
   * extent, it is used.  If not, a global extent is assumed.
   * @param {import("./proj.js").ProjectionLike} projection Projection.
   * @return {import("./extent.js").Extent} Extent.
   */
  function extentFromProjection(projection) {
    projection = get$2(projection);
    let extent = projection.getExtent();
    if (!extent) {
      const half =
        (180 * METERS_PER_UNIT$1.degrees) / projection.getMetersPerUnit();
      extent = createOrUpdate$2(-half, -half, half, half);
    }
    return extent;
  }

  /**
   * @module ol/source/Tile
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("./TileEventType").TileSourceEventTypes, TileSourceEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     import("./TileEventType").TileSourceEventTypes, Return>} TileSourceOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {number} [tilePixelRatio] TilePixelRatio.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection.
   * @property {import("./Source.js").State} [state] State.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] TileGrid.
   * @property {boolean} [wrapX=false] WrapX.
   * @property {number} [transition] Transition.
   * @property {string} [key] Key.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0] ZDirection.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for sources providing images divided into a tile grid.
   *
   * @template {import("../Tile.js").default} [TileType=import("../Tile.js").default]
   * @abstract
   * @api
   */
  class TileSource extends Source {
    /**
     * @param {Options} options SourceTile source options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        projection: options.projection,
        state: options.state,
        wrapX: options.wrapX,
        interpolate: options.interpolate,
      });

      /***
       * @type {TileSourceOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {TileSourceOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {TileSourceOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {number}
       */
      this.tilePixelRatio_ =
        options.tilePixelRatio !== undefined ? options.tilePixelRatio : 1;

      /**
       * @type {import("../tilegrid/TileGrid.js").default|null}
       * @protected
       */
      this.tileGrid = options.tileGrid !== undefined ? options.tileGrid : null;

      const tileSize = [256, 256];
      if (this.tileGrid) {
        toSize(this.tileGrid.getTileSize(this.tileGrid.getMinZoom()), tileSize);
      }

      /**
       * @protected
       * @type {import("../size.js").Size}
       */
      this.tmpSize = [0, 0];

      /**
       * @private
       * @type {string}
       */
      this.key_ = options.key || getUid(this);

      /**
       * @protected
       * @type {import("../Tile.js").Options}
       */
      this.tileOptions = {
        transition: options.transition,
        interpolate: options.interpolate,
      };

      /**
       * zDirection hint, read by the renderer. Indicates which resolution should be used
       * by a renderer if the views resolution does not match any resolution of the tile source.
       * If 0, the nearest resolution will be used. If 1, the nearest lower resolution
       * will be used. If -1, the nearest higher resolution will be used.
       * @type {number|import("../array.js").NearestDirectionFunction}
       */
      this.zDirection = options.zDirection ? options.zDirection : 0;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {number} Gutter.
     */
    getGutterForProjection(projection) {
      return 0;
    }

    /**
     * Return the key to be used for all tiles in the source.
     * @return {string} The key for all tiles.
     */
    getKey() {
      return this.key_;
    }

    /**
     * Set the value to be used as the key for all tiles in the source.
     * @param {string} key The key for tiles.
     * @protected
     */
    setKey(key) {
      if (this.key_ !== key) {
        this.key_ = key;
        this.changed();
      }
    }

    /**
     * @param {import("../proj/Projection").default} [projection] Projection.
     * @return {Array<number>|null} Resolutions.
     * @override
     */
    getResolutions(projection) {
      const tileGrid = projection
        ? this.getTileGridForProjection(projection)
        : this.tileGrid;
      if (!tileGrid) {
        return null;
      }
      return tileGrid.getResolutions();
    }

    /**
     * @abstract
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {TileType|null} Tile.
     */
    getTile(z, x, y, pixelRatio, projection) {
      return abstract();
    }

    /**
     * Return the tile grid of the tile source.
     * @return {import("../tilegrid/TileGrid.js").default|null} Tile grid.
     * @api
     */
    getTileGrid() {
      return this.tileGrid;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
     */
    getTileGridForProjection(projection) {
      if (!this.tileGrid) {
        return getForProjection(projection);
      }
      return this.tileGrid;
    }

    /**
     * Get the tile pixel ratio for this source. Subclasses may override this
     * method, which is meant to return a supported pixel ratio that matches the
     * provided `pixelRatio` as close as possible.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Tile pixel ratio.
     */
    getTilePixelRatio(pixelRatio) {
      return this.tilePixelRatio_;
    }

    /**
     * @param {number} z Z.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../size.js").Size} Tile size.
     */
    getTilePixelSize(z, pixelRatio, projection) {
      const tileGrid = this.getTileGridForProjection(projection);
      const tilePixelRatio = this.getTilePixelRatio(pixelRatio);
      const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize);
      if (tilePixelRatio == 1) {
        return tileSize;
      }
      return scale$1(tileSize, tilePixelRatio, this.tmpSize);
    }

    /**
     * Returns a tile coordinate wrapped around the x-axis. When the tile coordinate
     * is outside the resolution and extent range of the tile grid, `null` will be
     * returned.
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../proj/Projection.js").default} [projection] Projection.
     * @return {import("../tilecoord.js").TileCoord} Tile coordinate to be passed to the tileUrlFunction or
     *     null if no tile URL should be created for the passed `tileCoord`.
     */
    getTileCoordForTileUrlFunction(tileCoord, projection) {
      const gridProjection =
        projection !== undefined ? projection : this.getProjection();
      const tileGrid =
        projection !== undefined
          ? this.getTileGridForProjection(gridProjection)
          : this.tileGrid || this.getTileGridForProjection(gridProjection);
      if (this.getWrapX() && gridProjection.isGlobal()) {
        tileCoord = wrapX(tileGrid, tileCoord, gridProjection);
      }
      return withinExtentAndZ(tileCoord, tileGrid) ? tileCoord : null;
    }

    /**
     * Remove all cached reprojected tiles from the source. The next render cycle will create new tiles.
     * @api
     */
    clear() {}

    /**
     * @override
     */
    refresh() {
      this.clear();
      super.refresh();
    }
  }

  /**
   * @classdesc
   * Events emitted by {@link module:ol/source/Tile~TileSource} instances are instances of this
   * type.
   */
  class TileSourceEvent extends BaseEvent {
    /**
     * @param {string} type Type.
     * @param {import("../Tile.js").default} tile The tile.
     */
    constructor(type, tile) {
      super(type);

      /**
       * The tile related to the event.
       * @type {import("../Tile.js").default}
       * @api
       */
      this.tile = tile;
    }
  }

  /**
   * @module ol/source/Raster
   */

  /**
   * @typedef {Object} MinionData
   * @property {Array<ArrayBuffer>} buffers Array of buffers.
   * @property {Object} meta Operation metadata.
   * @property {boolean} imageOps The operation is an image operation.
   * @property {number} width The width of the image.
   * @property {number} height The height of the image.
   */

  /* istanbul ignore next */
  /**
   * Create a function for running operations.  This function is serialized for
   * use in a worker.
   * @param {function(Array, Object):*} operation The operation.
   * @return {function(MinionData):ArrayBuffer} A function that takes an object with
   * buffers, meta, imageOps, width, and height properties and returns an array
   * buffer.
   */
  function createMinion(operation) {
    return function (data) {
      // bracket notation for minification support
      const buffers = data['buffers'];
      const meta = data['meta'];
      const imageOps = data['imageOps'];
      const width = data['width'];
      const height = data['height'];

      const numBuffers = buffers.length;
      const numBytes = buffers[0].byteLength;

      if (imageOps) {
        const images = new Array(numBuffers);
        for (let b = 0; b < numBuffers; ++b) {
          images[b] = new ImageData(
            new Uint8ClampedArray(buffers[b]),
            width,
            height,
          );
        }
        const output = operation(images, meta).data;
        return output.buffer;
      }

      const output = new Uint8ClampedArray(numBytes);
      const arrays = new Array(numBuffers);
      const pixels = new Array(numBuffers);
      for (let b = 0; b < numBuffers; ++b) {
        arrays[b] = new Uint8ClampedArray(buffers[b]);
        pixels[b] = [0, 0, 0, 0];
      }
      for (let i = 0; i < numBytes; i += 4) {
        for (let j = 0; j < numBuffers; ++j) {
          const array = arrays[j];
          pixels[j][0] = array[i];
          pixels[j][1] = array[i + 1];
          pixels[j][2] = array[i + 2];
          pixels[j][3] = array[i + 3];
        }
        const pixel = operation(pixels, meta);
        output[i] = pixel[0];
        output[i + 1] = pixel[1];
        output[i + 2] = pixel[2];
        output[i + 3] = pixel[3];
      }
      return output.buffer;
    };
  }

  /**
   * Create a worker for running operations.
   * @param {ProcessorOptions} config Processor options.
   * @param {function(MessageEvent): void} onMessage Called with a message event.
   * @return {Worker} The worker.
   */
  function createWorker(config, onMessage) {
    const lib = Object.keys(config.lib || {}).map(function (name) {
      return 'const ' + name + ' = ' + config.lib[name].toString() + ';';
    });

    const lines = lib.concat([
      'const __minion__ = (' + createMinion.toString() + ')(',
      config.operation.toString(),
      ');',
      'self.addEventListener("message", function(event) {',
      '  const buffer = __minion__(event.data);',
      '  self.postMessage({buffer: buffer, meta: event.data.meta}, [buffer]);',
      '});',
    ]);

    const worker = new Worker(
      typeof Blob === 'undefined'
        ? 'data:text/javascript;base64,' +
          Buffer.from(lines.join('\n'), 'binary').toString('base64')
        : URL.createObjectURL(new Blob(lines, {type: 'text/javascript'})),
    );
    worker.addEventListener('message', onMessage);
    return worker;
  }

  /**
   * @typedef {Object} FauxMessageEvent
   * @property {Object} data Message data.
   */

  /**
   * Create a faux worker for running operations.
   * @param {ProcessorOptions} config Configuration.
   * @param {function(FauxMessageEvent): void} onMessage Called with a message event.
   * @return {Object} The faux worker.
   */
  function createFauxWorker(config, onMessage) {
    const minion = createMinion(config.operation);
    let terminated = false;
    return {
      postMessage: function (data) {
        setTimeout(function () {
          if (terminated) {
            return;
          }
          onMessage({data: {buffer: minion(data), meta: data['meta']}});
        }, 0);
      },
      terminate: function () {
        terminated = true;
      },
    };
  }

  /**
   * @typedef {function(Error, ImageData, (Object|Array<Object>)): void} JobCallback
   */

  /**
   * @typedef {Object} Job
   * @property {Object} meta Job metadata.
   * @property {Array<ImageData>} inputs Array of input data.
   * @property {JobCallback} callback Called when the job is complete.
   */

  /**
   * @typedef {Object} ProcessorOptions
   * @property {number} threads Number of workers to spawn.
   * @property {Operation} operation The operation.
   * @property {Object<string, Function>} [lib] Functions that will be made available to operations run in a worker.
   * @property {number} queue The number of queued jobs to allow.
   * @property {boolean} [imageOps=false] Pass all the image data to the operation instead of a single pixel.
   */

  /**
   * @classdesc
   * A processor runs pixel or image operations in workers.
   */
  class Processor extends Disposable {
    /**
     * @param {ProcessorOptions} config Configuration.
     */
    constructor(config) {
      super();

      /**
       * @type {boolean}
       * @private
       */
      this.imageOps_ = !!config.imageOps;
      let threads;
      if (config.threads === 0) {
        threads = 0;
      } else if (this.imageOps_) {
        threads = 1;
      } else {
        threads = config.threads || 1;
      }

      /**
       * @type {Array<Worker>}
       */
      const workers = new Array(threads);
      if (threads) {
        for (let i = 0; i < threads; ++i) {
          workers[i] = createWorker(config, this.onWorkerMessage_.bind(this, i));
        }
      } else {
        workers[0] = createFauxWorker(
          config,
          this.onWorkerMessage_.bind(this, 0),
        );
      }
      /**
       * @type {Array<Worker>}
       * @private
       */
      this.workers_ = workers;

      /**
       * @type {Array<Job>}
       * @private
       */
      this.queue_ = [];

      /**
       * @type {number}
       * @private
       */
      this.maxQueueLength_ = config.queue || Infinity;
      /**
       * @type {number}
       * @private
       */
      this.running_ = 0;

      /**
       * @type {Object<number, any>}
       * @private
       */
      this.dataLookup_ = {};

      /**
       * @type {Job|null}
       * @private
       */
      this.job_ = null;
    }

    /**
     * Run operation on input data.
     * @param {Array<ImageData>} inputs Array of image data.
     * @param {Object} meta A user data object.  This is passed to all operations
     *     and must be serializable.
     * @param {function(Error, ImageData, Object): void} callback Called when work
     *     completes.  The first argument is any error.  The second is the ImageData
     *     generated by operations.  The third is the user data object.
     */
    process(inputs, meta, callback) {
      this.enqueue_({
        inputs: inputs,
        meta: meta,
        callback: callback,
      });
      this.dispatch_();
    }

    /**
     * Add a job to the queue.
     * @param {Job} job The job.
     */
    enqueue_(job) {
      this.queue_.push(job);
      while (this.queue_.length > this.maxQueueLength_) {
        this.queue_.shift().callback(null, null);
      }
    }

    /**
     * Dispatch a job.
     */
    dispatch_() {
      if (this.running_ || this.queue_.length === 0) {
        return;
      }

      const job = this.queue_.shift();
      this.job_ = job;
      const width = job.inputs[0].width;
      const height = job.inputs[0].height;
      const buffers = job.inputs.map(function (input) {
        return input.data.buffer;
      });
      const threads = this.workers_.length;
      this.running_ = threads;
      if (threads === 1) {
        this.workers_[0].postMessage(
          {
            buffers: buffers,
            meta: job.meta,
            imageOps: this.imageOps_,
            width: width,
            height: height,
          },
          buffers,
        );
        return;
      }

      const length = job.inputs[0].data.length;
      const segmentLength = 4 * Math.ceil(length / 4 / threads);
      for (let i = 0; i < threads; ++i) {
        const offset = i * segmentLength;
        const slices = [];
        for (let j = 0, jj = buffers.length; j < jj; ++j) {
          slices.push(buffers[j].slice(offset, offset + segmentLength));
        }
        this.workers_[i].postMessage(
          {
            buffers: slices,
            meta: job.meta,
            imageOps: this.imageOps_,
            width: width,
            height: height,
          },
          slices,
        );
      }
    }

    /**
     * Handle messages from the worker.
     * @param {number} index The worker index.
     * @param {MessageEvent} event The message event.
     */
    onWorkerMessage_(index, event) {
      if (this.disposed) {
        return;
      }
      this.dataLookup_[index] = event.data;
      --this.running_;
      if (this.running_ === 0) {
        this.resolveJob_();
      }
    }

    /**
     * Resolve a job.  If there are no more worker threads, the processor callback
     * will be called.
     */
    resolveJob_() {
      const job = this.job_;
      const threads = this.workers_.length;
      let data, meta;
      if (threads === 1) {
        data = new Uint8ClampedArray(this.dataLookup_[0]['buffer']);
        meta = this.dataLookup_[0]['meta'];
      } else {
        const length = job.inputs[0].data.length;
        data = new Uint8ClampedArray(length);
        meta = new Array(threads);
        const segmentLength = 4 * Math.ceil(length / 4 / threads);
        for (let i = 0; i < threads; ++i) {
          const buffer = this.dataLookup_[i]['buffer'];
          const offset = i * segmentLength;
          data.set(new Uint8ClampedArray(buffer), offset);
          meta[i] = this.dataLookup_[i]['meta'];
        }
      }
      this.job_ = null;
      this.dataLookup_ = {};
      job.callback(
        null,
        new ImageData(data, job.inputs[0].width, job.inputs[0].height),
        meta,
      );
      this.dispatch_();
    }

    /**
     * Terminate all workers associated with the processor.
     * @override
     */
    disposeInternal() {
      for (let i = 0; i < this.workers_.length; ++i) {
        this.workers_[i].terminate();
      }
      this.workers_.length = 0;
    }
  }

  /**
   * A function that takes an array of input data, performs some operation, and
   * returns an array of output data.
   * For `pixel` type operations, the function will be called with an array of
   * pixels, where each pixel is an array of four numbers (`[r, g, b, a]`) in the
   * range of 0 - 255. It should return a single pixel array.
   * For `'image'` type operations, functions will be called with an array of
   * [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData)
   * and should return a single
   * [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData).
   * The operations
   * are called with a second "data" argument, which can be used for storage.  The
   * data object is accessible from raster events, where it can be initialized in
   * "beforeoperations" and accessed again in "afteroperations".
   *
   * @typedef {function((Array<Array<number>>|Array<ImageData>), Object):
   *     (Array<number>|ImageData)} Operation
   */

  /**
   * @enum {string}
   */
  const RasterEventType = {
    /**
     * Triggered before operations are run.  Listeners will receive an event object with
     * a `data` property that can be used to make data available to operations.
     * @event module:ol/source/Raster.RasterSourceEvent#beforeoperations
     * @api
     */
    BEFOREOPERATIONS: 'beforeoperations',

    /**
     * Triggered after operations are run.  Listeners will receive an event object with
     * a `data` property.  If more than one thread is used, `data` will be an array of
     * objects.  If a single thread is used, `data` will be a single object.
     * @event module:ol/source/Raster.RasterSourceEvent#afteroperations
     * @api
     */
    AFTEROPERATIONS: 'afteroperations',
  };

  /**
   * @typedef {'pixel' | 'image'} RasterOperationType
   * Raster operation type. Supported values are `'pixel'` and `'image'`.
   */

  /**
   * @typedef {import("./Image.js").ImageSourceEventTypes|'beforeoperations'|'afteroperations'} RasterSourceEventTypes
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/source/Raster~RasterSource} instances are instances of this
   * type.
   */
  class RasterSourceEvent extends BaseEvent {
    /**
     * @param {string} type Type.
     * @param {import("../Map.js").FrameState} frameState The frame state.
     * @param {Object|Array<Object>} data An object made available to operations.  For "afteroperations" evenets
     * this will be an array of objects if more than one thread is used.
     */
    constructor(type, frameState, data) {
      super(type);

      /**
       * The raster extent.
       * @type {import("../extent.js").Extent}
       * @api
       */
      this.extent = frameState.extent;

      /**
       * The pixel resolution (map units per pixel).
       * @type {number}
       * @api
       */
      this.resolution = frameState.viewState.resolution / frameState.pixelRatio;

      /**
       * An object made available to all operations.  This can be used by operations
       * as a storage object (e.g. for calculating statistics).
       * @type {Object}
       * @api
       */
      this.data = data;
    }
  }

  /**
   * @typedef {Object} Options
   * @property {Array<import("./Source.js").default|import("../layer/Layer.js").default>} sources Input
   * sources or layers.  For vector data, use an VectorImage layer.
   * @property {Operation} [operation] Raster operation.
   * The operation will be called with data from input sources
   * and the output will be assigned to the raster source.
   * @property {Object} [lib] Functions that will be made available to operations run in a worker.
   * @property {number} [threads] By default, operations will be run in a single worker thread.
   * To avoid using workers altogether, set `threads: 0`.  For pixel operations, operations can
   * be run in multiple worker threads.  Note that there is additional overhead in
   * transferring data to multiple workers, and that depending on the user's
   * system, it may not be possible to parallelize the work.
   * @property {RasterOperationType} [operationType='pixel'] Operation type.
   * Supported values are `'pixel'` and `'image'`.  By default,
   * `'pixel'` operations are assumed, and operations will be called with an
   * array of pixels from input sources.  If set to `'image'`, operations will
   * be called with an array of ImageData objects from input sources.
   * @property {Array<number>|null} [resolutions] Resolutions. If specified, raster operations will only
   * be run at the given resolutions.  By default, the resolutions of the first source with resolutions
   * specified will be used, if any. Set to `null` to use any view resolution instead.
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<import("./Image.js").ImageSourceEventTypes, import("./Image.js").ImageSourceEvent, Return> &
   *   import("../Observable").OnSignature<RasterSourceEventTypes, RasterSourceEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types
   *     |RasterSourceEventTypes, Return>} RasterSourceOnSignature
   */

  /**
   * @classdesc
   * A source that transforms data from any number of input sources using an
   * {@link module:ol/source/Raster~Operation} function to transform input pixel values into
   * output pixel values.
   *
   * @fires module:ol/source/Raster.RasterSourceEvent
   * @api
   */
  class RasterSource extends ImageSource {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      super({
        projection: null,
      });

      /***
       * @type {RasterSourceOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {RasterSourceOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {RasterSourceOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {Processor}
       */
      this.processor_ = null;

      /**
       * @private
       * @type {RasterOperationType}
       */
      this.operationType_ =
        options.operationType !== undefined ? options.operationType : 'pixel';

      /**
       * @private
       * @type {number}
       */
      this.threads_ = options.threads !== undefined ? options.threads : 1;

      /**
       * @private
       * @type {Array<import("../layer/Layer.js").default>}
       */
      this.layers_ = createLayers(options.sources);

      const changed = this.changed.bind(this);
      for (let i = 0, ii = this.layers_.length; i < ii; ++i) {
        this.layers_[i].addEventListener(EventType.CHANGE, changed);
      }

      /**
       * @private
       * @type {boolean}
       */
      this.useResolutions_ = options.resolutions !== null;

      /**
       * @private
       * @type {import("../TileQueue.js").default}
       */
      this.tileQueue_ = new TileQueue(function () {
        return 1;
      }, this.processSources_.bind(this));

      /**
       * The most recently requested frame state.
       * @type {import("../Map.js").FrameState}
       * @private
       */
      this.requestedFrameState_;

      /**
       * The most recently rendered image canvas.
       * @type {import("../ImageCanvas.js").default}
       * @private
       */
      this.renderedImageCanvas_ = null;

      /**
       * The most recently rendered revision.
       * @type {number}
       * @private
       */
      this.renderedRevision_;

      /**
       * @private
       * @type {import("../Map.js").FrameState}
       */
      this.frameState_ = {
        animate: false,
        coordinateToPixelTransform: create$3(),
        declutter: null,
        extent: null,
        index: 0,
        layerIndex: 0,
        layerStatesArray: getLayerStatesArray(this.layers_),
        pixelRatio: 1,
        pixelToCoordinateTransform: create$3(),
        postRenderFunctions: [],
        size: [0, 0],
        tileQueue: this.tileQueue_,
        time: Date.now(),
        usedTiles: {},
        viewState: /** @type {import("../View.js").State} */ ({
          rotation: 0,
        }),
        viewHints: [],
        wantedTiles: {},
        mapId: getUid(this),
        renderTargets: {},
      };

      this.setAttributions(function (frameState) {
        /** @type {Array<string>} */
        const attributions = [];
        for (let i = 0, iMax = options.sources.length; i < iMax; ++i) {
          const sourceOrLayer = options.sources[i];
          const source =
            sourceOrLayer instanceof Source
              ? sourceOrLayer
              : sourceOrLayer.getSource();
          if (!source) {
            continue;
          }
          const sourceAttributions = source.getAttributions()?.(frameState);
          if (typeof sourceAttributions === 'string') {
            attributions.push(sourceAttributions);
          } else if (sourceAttributions !== undefined) {
            attributions.push(...sourceAttributions);
          }
        }
        return attributions;
      });

      if (options.operation !== undefined) {
        this.setOperation(options.operation, options.lib);
      }
    }

    /**
     * Set the operation.
     * @param {Operation} operation New operation.
     * @param {Object} [lib] Functions that will be available to operations run
     *     in a worker.
     * @api
     */
    setOperation(operation, lib) {
      if (this.processor_) {
        this.processor_.dispose();
      }

      this.processor_ = new Processor({
        operation: operation,
        imageOps: this.operationType_ === 'image',
        queue: 1,
        lib: lib,
        threads: this.threads_,
      });
      this.changed();
    }

    /**
     * Update the stored frame state.
     * @param {import("../extent.js").Extent} extent The view extent (in map units).
     * @param {number} resolution The view resolution.
     * @param {import("../proj/Projection.js").default} projection The view projection.
     * @return {import("../Map.js").FrameState} The updated frame state.
     * @private
     */
    updateFrameState_(extent, resolution, projection) {
      const frameState = /** @type {import("../Map.js").FrameState} */ (
        Object.assign({}, this.frameState_)
      );

      frameState.viewState = /** @type {import("../View.js").State} */ (
        Object.assign({}, frameState.viewState)
      );

      const center = getCenter(extent);

      frameState.size[0] = Math.ceil(getWidth(extent) / resolution);
      frameState.size[1] = Math.ceil(getHeight(extent) / resolution);
      frameState.extent = [
        center[0] - (frameState.size[0] * resolution) / 2,
        center[1] - (frameState.size[1] * resolution) / 2,
        center[0] + (frameState.size[0] * resolution) / 2,
        center[1] + (frameState.size[1] * resolution) / 2,
      ];
      frameState.time = Date.now();

      const viewState = frameState.viewState;
      viewState.center = center;
      viewState.projection = projection;
      viewState.resolution = resolution;
      return frameState;
    }

    /**
     * Determine if all sources are ready.
     * @return {boolean} All sources are ready.
     * @private
     */
    allSourcesReady_() {
      let ready = true;
      let source;
      for (let i = 0, ii = this.layers_.length; i < ii; ++i) {
        source = this.layers_[i].getSource();
        if (!source || source.getState() !== 'ready') {
          ready = false;
          break;
        }
      }
      return ready;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../ImageCanvas.js").default} Single image.
     * @override
     */
    getImage(extent, resolution, pixelRatio, projection) {
      if (!this.allSourcesReady_()) {
        return null;
      }

      this.tileQueue_.loadMoreTiles(16, 16);

      resolution = this.findNearestResolution(resolution);
      const frameState = this.updateFrameState_(extent, resolution, projection);
      this.requestedFrameState_ = frameState;

      // check if we can't reuse the existing ol/ImageCanvas
      if (this.renderedImageCanvas_) {
        const renderedResolution = this.renderedImageCanvas_.getResolution();
        const renderedExtent = this.renderedImageCanvas_.getExtent();
        if (
          resolution !== renderedResolution ||
          !equals$1(frameState.extent, renderedExtent)
        ) {
          this.renderedImageCanvas_ = null;
        }
      }

      if (
        !this.renderedImageCanvas_ ||
        this.getRevision() !== this.renderedRevision_
      ) {
        this.processSources_();
      }

      if (frameState.animate) {
        requestAnimationFrame(this.changed.bind(this));
      }

      return this.renderedImageCanvas_;
    }

    /**
     * Start processing source data.
     * @private
     */
    processSources_() {
      const frameState = this.requestedFrameState_;
      const len = this.layers_.length;
      const imageDatas = new Array(len);
      for (let i = 0; i < len; ++i) {
        frameState.layerIndex = i;
        frameState.renderTargets = {};
        const imageData = getImageData(this.layers_[i], frameState);
        if (imageData) {
          imageDatas[i] = imageData;
        } else {
          return;
        }
      }

      const data = {};
      this.dispatchEvent(
        new RasterSourceEvent(RasterEventType.BEFOREOPERATIONS, frameState, data),
      );
      this.processor_.process(
        imageDatas,
        data,
        this.onWorkerComplete_.bind(this, frameState),
      );
    }

    /**
     * Called when pixel processing is complete.
     * @param {import("../Map.js").FrameState} frameState The frame state.
     * @param {Error} err Any error during processing.
     * @param {ImageData} output The output image data.
     * @param {Object|Array<Object>} data The user data (or an array if more than one thread).
     * @private
     */
    onWorkerComplete_(frameState, err, output, data) {
      if (err || !output) {
        return;
      }

      // do nothing if extent or resolution changed
      const extent = frameState.extent;
      const resolution = frameState.viewState.resolution;
      if (
        resolution !== this.requestedFrameState_.viewState.resolution ||
        !equals$1(extent, this.requestedFrameState_.extent)
      ) {
        return;
      }

      let context;
      if (this.renderedImageCanvas_) {
        context = this.renderedImageCanvas_.getImage().getContext('2d');
      } else {
        const width = Math.round(getWidth(extent) / resolution);
        const height = Math.round(getHeight(extent) / resolution);
        context = createCanvasContext2D(width, height);
        this.renderedImageCanvas_ = new ImageCanvas(
          extent,
          resolution,
          1,
          context.canvas,
        );
      }
      context.putImageData(output, 0, 0);

      if (frameState.animate) {
        requestAnimationFrame(this.changed.bind(this));
      } else {
        this.changed();
      }
      this.renderedRevision_ = this.getRevision();

      this.dispatchEvent(
        new RasterSourceEvent(RasterEventType.AFTEROPERATIONS, frameState, data),
      );
    }

    /**
     * @param {import("../proj/Projection").default} [projection] Projection.
     * @return {Array<number>|null} Resolutions.
     * @override
     */
    getResolutions(projection) {
      if (!this.useResolutions_) {
        return null;
      }
      let resolutions = super.getResolutions();
      if (!resolutions) {
        for (let i = 0, ii = this.layers_.length; i < ii; ++i) {
          const source = this.layers_[i].getSource();
          resolutions = source.getResolutions(projection);
          if (resolutions) {
            break;
          }
        }
      }
      return resolutions;
    }

    /**
     * @override
     */
    disposeInternal() {
      if (this.processor_) {
        this.processor_.dispose();
      }
      super.disposeInternal();
    }
  }

  /**
   * Clean up and unregister the worker.
   * @function
   * @api
   */
  RasterSource.prototype.dispose;

  /**
   * A reusable canvas context.
   * @type {CanvasRenderingContext2D}
   * @private
   */
  let sharedContext = null;

  /**
   * Get image data from a layer.
   * @param {import("../layer/Layer.js").default} layer Layer to render.
   * @param {import("../Map.js").FrameState} frameState The frame state.
   * @return {ImageData} The image data.
   */
  function getImageData(layer, frameState) {
    const renderer = layer.getRenderer();
    if (!renderer) {
      throw new Error('Unsupported layer type: ' + layer);
    }

    if (!renderer.prepareFrame(frameState)) {
      return null;
    }
    const width = frameState.size[0];
    const height = frameState.size[1];
    if (width === 0 || height === 0) {
      return null;
    }
    const container = renderer.renderFrame(frameState, null);
    let element;
    if (container instanceof HTMLCanvasElement) {
      element = container;
    } else {
      if (container) {
        element = container.firstElementChild;
      }
      if (!(element instanceof HTMLCanvasElement)) {
        throw new Error('Unsupported rendered element: ' + element);
      }
      if (element.width === width && element.height === height) {
        const context = element.getContext('2d');
        return context.getImageData(0, 0, width, height);
      }
    }

    if (!sharedContext) {
      sharedContext = createCanvasContext2D(width, height, undefined, {
        willReadFrequently: true,
      });
    } else {
      const canvas = sharedContext.canvas;
      if (canvas.width !== width || canvas.height !== height) {
        sharedContext = createCanvasContext2D(width, height, undefined, {
          willReadFrequently: true,
        });
      } else {
        sharedContext.clearRect(0, 0, width, height);
      }
    }
    sharedContext.drawImage(element, 0, 0, width, height);
    return sharedContext.getImageData(0, 0, width, height);
  }

  /**
   * Get a list of layer states from a list of layers.
   * @param {Array<import("../layer/Layer.js").default>} layers Layers.
   * @return {Array<import("../layer/Layer.js").State>} The layer states.
   */
  function getLayerStatesArray(layers) {
    return layers.map(function (layer) {
      return layer.getLayerState();
    });
  }

  /**
   * Create layers for all sources.
   * @param {Array<import("./Source.js").default|import("../layer/Layer.js").default>} sources The sources.
   * @return {Array<import("../layer/Layer.js").default>} Array of layers.
   */
  function createLayers(sources) {
    const len = sources.length;
    const layers = new Array(len);
    for (let i = 0; i < len; ++i) {
      layers[i] = createLayer(sources[i]);
    }
    return layers;
  }

  /**
   * Create a layer for the provided source.
   * @param {import("./Source.js").default|import("../layer/Layer.js").default} layerOrSource The layer or source.
   * @return {import("../layer/Layer.js").default} The layer.
   */
  function createLayer(layerOrSource) {
    // @type {import("../layer/Layer.js").default}
    let layer;
    if (layerOrSource instanceof Source) {
      if (layerOrSource instanceof TileSource) {
        layer = new TileLayer({source: layerOrSource});
      } else if (layerOrSource instanceof ImageSource) {
        layer = new ImageLayer({source: layerOrSource});
      }
    } else {
      layer = layerOrSource;
    }
    return layer;
  }

  /**
   * @module ol/net
   */

  /**
   * Simple JSONP helper. Supports error callbacks and a custom callback param.
   * The error callback will be called when no JSONP is executed after 10 seconds.
   *
   * @param {string} url Request url. A 'callback' query parameter will be
   *     appended.
   * @param {Function} callback Callback on success.
   * @param {Function} [errback] Callback on error.
   * @param {string} [callbackParam] Custom query parameter for the JSONP
   *     callback. Default is 'callback'.
   */
  function jsonp(url, callback, errback, callbackParam) {
    const script = document.createElement('script');
    const key = 'olc_' + getUid(callback);
    function cleanup() {
      delete window[key];
      script.parentNode.removeChild(script);
    }
    script.async = true;
    script.src =
      url +
      (url.includes('?') ? '&' : '?') +
      ('callback') +
      '=' +
      key;
    const timer = setTimeout(function () {
      cleanup();
      if (errback) {
        errback();
      }
    }, 10000);
    window[key] = function (data) {
      clearTimeout(timer);
      cleanup();
      callback(data);
    };
    document.head.appendChild(script);
  }

  class ResponseError extends Error {
    /**
     * @param {XMLHttpRequest} response The XHR object.
     */
    constructor(response) {
      const message = 'Unexpected response status: ' + response.status;
      super(message);

      /**
       * @type {string}
       */
      this.name = 'ResponseError';

      /**
       * @type {XMLHttpRequest}
       */
      this.response = response;
    }
  }

  class ClientError extends Error {
    /**
     * @param {XMLHttpRequest} client The XHR object.
     */
    constructor(client) {
      super('Failed to issue request');

      /**
       * @type {string}
       */
      this.name = 'ClientError';

      /**
       * @type {XMLHttpRequest}
       */
      this.client = client;
    }
  }

  /**
   * @param {string} url The URL.
   * @return {Promise<Object>} A promise that resolves to the JSON response.
   */
  function getJSON(url) {
    return new Promise(function (resolve, reject) {
      /**
       * @param {ProgressEvent<XMLHttpRequest>} event The load event.
       */
      function onLoad(event) {
        const client = event.target;
        // status will be 0 for file:// urls
        if (!client.status || (client.status >= 200 && client.status < 300)) {
          let data;
          try {
            data = JSON.parse(client.responseText);
          } catch (err) {
            const message = 'Error parsing response text as JSON: ' + err.message;
            reject(new Error(message));
            return;
          }
          resolve(data);
          return;
        }

        reject(new ResponseError(client));
      }

      /**
       * @param {ProgressEvent<XMLHttpRequest>} event The error event.
       */
      function onError(event) {
        reject(new ClientError(event.target));
      }

      const client = new XMLHttpRequest();
      client.addEventListener('load', onLoad);
      client.addEventListener('error', onError);
      client.open('GET', url);
      client.setRequestHeader('Accept', 'application/json');
      client.send();
    });
  }

  /**
   * @param {string} base The base URL.
   * @param {string} url The potentially relative URL.
   * @return {string} The full URL.
   */
  function resolveUrl(base, url) {
    if (url.includes('://')) {
      return url;
    }
    return new URL(url, base).href;
  }

  /**
   * @module ol/uri
   */


  /**
   * Appends query parameters to a URI.
   *
   * @param {string} uri The original URI, which may already have query data.
   * @param {!Object} params An object where keys are URI-encoded parameter keys,
   *     and the values are arbitrary types or arrays.
   * @return {string} The new URI.
   */
  function appendParams(uri, params) {
    /** @type {Array<string>} */
    const keyParams = [];
    // Skip any null or undefined parameter values
    Object.keys(params).forEach(function (k) {
      if (params[k] !== null && params[k] !== undefined) {
        keyParams.push(k + '=' + encodeURIComponent(params[k]));
      }
    });
    const qs = keyParams.join('&');
    // remove any trailing ? or &
    uri = uri.replace(/[?&]$/, '');
    // append ? or & depending on whether uri has existing parameters
    uri += uri.includes('?') ? '&' : '?';
    return uri + qs;
  }

  const zRegEx = /\{z\}/g;
  const xRegEx = /\{x\}/g;
  const yRegEx = /\{y\}/g;
  const dashYRegEx = /\{-y\}/g;

  /**
   * @param {string} template The URL template.  Should have `{x}`, `{y}`, and `{z}` placeholders.  If
   * the template has a `{-y}` placeholder, the `maxY` parameter must be supplied.
   * @param {number} z The tile z coordinate.
   * @param {number} x The tile x coordinate.
   * @param {number} y The tile y coordinate.
   * @param {number} [maxY] The maximum y coordinate at the given z level.
   * @return {string} The URL.
   */
  function renderXYZTemplate(template, z, x, y, maxY) {
    return template
      .replace(zRegEx, z.toString())
      .replace(xRegEx, x.toString())
      .replace(yRegEx, y.toString())
      .replace(dashYRegEx, function () {
        if (maxY === undefined) {
          throw new Error(
            'If the URL template has a {-y} placeholder, the grid extent must be known',
          );
        }
        return (maxY - y).toString();
      });
  }

  /**
   * @param {Array<string>} urls List of URLs.
   * @param {number} z The tile z coordinate.
   * @param {number} x The tile x coordinate.
   * @param {number} y The tile y coordinate.
   * @return {string} The chosen URL.
   */
  function pickUrl(urls, z, x, y) {
    const hash = hashZXY(z, x, y);
    const index = modulo(hash, urls.length);
    return urls[index];
  }

  /**
   * @param {string} url URL.
   * @return {Array<string>} Array of urls.
   */
  function expandUrl(url) {
    const urls = [];
    let match = /\{([a-z])-([a-z])\}/.exec(url);
    if (match) {
      // char range
      const startCharCode = match[1].charCodeAt(0);
      const stopCharCode = match[2].charCodeAt(0);
      let charCode;
      for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) {
        urls.push(url.replace(match[0], String.fromCharCode(charCode)));
      }
      return urls;
    }
    match = /\{(\d+)-(\d+)\}/.exec(url);
    if (match) {
      // number range
      const stop = parseInt(match[2], 10);
      for (let i = parseInt(match[1], 10); i <= stop; i++) {
        urls.push(url.replace(match[0], i.toString()));
      }
      return urls;
    }
    urls.push(url);
    return urls;
  }

  /**
   * @module ol/tileurlfunction
   */

  /**
   * @param {string} template Template.
   * @param {import("./tilegrid/TileGrid.js").default|null} tileGrid Tile grid.
   * @return {import("./Tile.js").UrlFunction} Tile URL function.
   */
  function createFromTemplate(template, tileGrid) {
    return (
      /**
       * @param {import("./tilecoord.js").TileCoord} tileCoord Tile Coordinate.
       * @param {number} pixelRatio Pixel ratio.
       * @param {import("./proj/Projection.js").default} projection Projection.
       * @return {string|undefined} Tile URL.
       */
      function (tileCoord, pixelRatio, projection) {
        if (!tileCoord) {
          return undefined;
        }
        let maxY;
        const z = tileCoord[0];
        if (tileGrid) {
          // The `{-y}` placeholder only works for sources that have a tile grid at construction
          const range = tileGrid.getFullTileRange(z);
          if (range) {
            maxY = range.getHeight() - 1;
          }
        }
        return renderXYZTemplate(template, z, tileCoord[1], tileCoord[2], maxY);
      }
    );
  }

  /**
   * @param {Array<string>} templates Templates.
   * @param {import("./tilegrid/TileGrid.js").default} tileGrid Tile grid.
   * @return {import("./Tile.js").UrlFunction} Tile URL function.
   */
  function createFromTemplates(templates, tileGrid) {
    const len = templates.length;
    const tileUrlFunctions = new Array(len);
    for (let i = 0; i < len; ++i) {
      tileUrlFunctions[i] = createFromTemplate(templates[i], tileGrid);
    }
    return createFromTileUrlFunctions(tileUrlFunctions);
  }

  /**
   * @param {Array<import("./Tile.js").UrlFunction>} tileUrlFunctions Tile URL Functions.
   * @return {import("./Tile.js").UrlFunction} Tile URL function.
   */
  function createFromTileUrlFunctions(tileUrlFunctions) {
    if (tileUrlFunctions.length === 1) {
      return tileUrlFunctions[0];
    }
    return (
      /**
       * @param {import("./tilecoord.js").TileCoord} tileCoord Tile Coordinate.
       * @param {number} pixelRatio Pixel ratio.
       * @param {import("./proj/Projection.js").default} projection Projection.
       * @return {string|undefined} Tile URL.
       */
      function (tileCoord, pixelRatio, projection) {
        if (!tileCoord) {
          return undefined;
        }
        const h = hash(tileCoord);
        const index = modulo(h, tileUrlFunctions.length);
        return tileUrlFunctions[index](tileCoord, pixelRatio, projection);
      }
    );
  }

  /**
   * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
   * @param {number} pixelRatio Pixel ratio.
   * @param {import("./proj/Projection.js").default} projection Projection.
   * @return {string|undefined} Tile URL.
   */
  function nullTileUrlFunction(tileCoord, pixelRatio, projection) {
    return undefined;
  }

  /**
   * @module ol/source/TileEventType
   */

  /**
   * @enum {string}
   */
  var TileEventType = {
    /**
     * Triggered when a tile starts loading.
     * @event module:ol/source/Tile.TileSourceEvent#tileloadstart
     * @api
     */
    TILELOADSTART: 'tileloadstart',

    /**
     * Triggered when a tile finishes loading, either when its data is loaded,
     * or when loading was aborted because the tile is no longer needed.
     * @event module:ol/source/Tile.TileSourceEvent#tileloadend
     * @api
     */
    TILELOADEND: 'tileloadend',

    /**
     * Triggered if tile loading results in an error. Note that this is not the
     * right place to re-fetch tiles. See {@link module:ol/ImageTile~ImageTile#load}
     * for details.
     * @event module:ol/source/Tile.TileSourceEvent#tileloaderror
     * @api
     */
    TILELOADERROR: 'tileloaderror',
  };

  /**
   * @typedef {'tileloadstart'|'tileloadend'|'tileloaderror'} TileSourceEventTypes
   */

  /**
   * @module ol/source/UrlTile
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection.
   * @property {import("./Source.js").State} [state] State.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] TileGrid.
   * @property {import("../Tile.js").LoadFunction} tileLoadFunction TileLoadFunction.
   * @property {number} [tilePixelRatio] TilePixelRatio.
   * @property {import("../Tile.js").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function
   * for the url option instead.
   * @property {string} [url] Url.
   * @property {Array<string>} [urls] Urls.
   * @property {boolean} [wrapX=true] WrapX.
   * @property {number} [transition] Transition.
   * @property {string} [key] Key.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0] ZDirection.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   */

  /**
   * @deprecated Use the ol/source/ImageTile.js instead.
   *
   * @fires import("./Tile.js").TileSourceEvent
   */
  class UrlTile extends TileSource {
    /**
     * @param {Options} options Image tile options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        projection: options.projection,
        state: options.state,
        tileGrid: options.tileGrid,
        tilePixelRatio: options.tilePixelRatio,
        wrapX: options.wrapX,
        transition: options.transition,
        interpolate: options.interpolate,
        key: options.key,
        attributionsCollapsible: options.attributionsCollapsible,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {boolean}
       */
      this.generateTileUrlFunction_ =
        this.tileUrlFunction === UrlTile.prototype.tileUrlFunction;

      /**
       * @protected
       * @type {import("../Tile.js").LoadFunction}
       */
      this.tileLoadFunction = options.tileLoadFunction;

      if (options.tileUrlFunction) {
        this.tileUrlFunction = options.tileUrlFunction;
      }

      /**
       * @protected
       * @type {!Array<string>|null}
       */
      this.urls = null;

      if (options.urls) {
        this.setUrls(options.urls);
      } else if (options.url) {
        this.setUrl(options.url);
      }

      /**
       * @private
       * @type {!Object<string, boolean>}
       */
      this.tileLoadingKeys_ = {};
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Return the tile load function of the source.
     * @return {import("../Tile.js").LoadFunction} TileLoadFunction
     * @api
     */
    getTileLoadFunction() {
      return this.tileLoadFunction;
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Return the tile URL function of the source.
     * @return {import("../Tile.js").UrlFunction} TileUrlFunction
     * @api
     */
    getTileUrlFunction() {
      return Object.getPrototypeOf(this).tileUrlFunction === this.tileUrlFunction
        ? this.tileUrlFunction.bind(this)
        : this.tileUrlFunction;
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Return the URLs used for this source.
     * When a tileUrlFunction is used instead of url or urls,
     * null will be returned.
     * @return {!Array<string>|null} URLs.
     * @api
     */
    getUrls() {
      return this.urls;
    }

    /**
     * Handle tile change events.
     * @param {import("../events/Event.js").default} event Event.
     * @protected
     */
    handleTileChange(event) {
      const tile = /** @type {import("../Tile.js").default} */ (event.target);
      const uid = getUid(tile);
      const tileState = tile.getState();
      let type;
      if (tileState == TileState.LOADING) {
        this.tileLoadingKeys_[uid] = true;
        type = TileEventType.TILELOADSTART;
      } else if (uid in this.tileLoadingKeys_) {
        delete this.tileLoadingKeys_[uid];
        type =
          tileState == TileState.ERROR
            ? TileEventType.TILELOADERROR
            : tileState == TileState.LOADED
              ? TileEventType.TILELOADEND
              : undefined;
      }
      if (type != undefined) {
        this.dispatchEvent(new TileSourceEvent(type, tile));
      }
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Set the tile load function of the source.
     * @param {import("../Tile.js").LoadFunction} tileLoadFunction Tile load function.
     * @api
     */
    setTileLoadFunction(tileLoadFunction) {
      this.tileLoadFunction = tileLoadFunction;
      this.changed();
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Set the tile URL function of the source.
     * @param {import("../Tile.js").UrlFunction} tileUrlFunction Tile URL function.
     * @param {string} [key] Optional new tile key for the source.
     * @api
     */
    setTileUrlFunction(tileUrlFunction, key) {
      this.tileUrlFunction = tileUrlFunction;
      if (typeof key !== 'undefined') {
        this.setKey(key);
      } else {
        this.changed();
      }
    }

    /**
     * Set the URL to use for requests.
     * @param {string} url URL.
     * @api
     */
    setUrl(url) {
      const urls = expandUrl(url);
      this.urls = urls;
      this.setUrls(urls);
    }

    /**
     * Deprecated.  Use an ImageTile source instead.
     * Set the URLs to use for requests.
     * @param {Array<string>} urls URLs.
     * @api
     */
    setUrls(urls) {
      this.urls = urls;
      const key = urls.join('\n');
      if (this.generateTileUrlFunction_) {
        this.setTileUrlFunction(createFromTemplates(urls, this.tileGrid), key);
      } else {
        this.setKey(key);
      }
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {string|undefined} Tile URL.
     */
    tileUrlFunction(tileCoord, pixelRatio, projection) {
      return undefined;
    }
  }

  /**
   * @module ol/source/TileImage
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("./Source.js").State} [state] Source state.
   * @property {typeof import("../ImageTile.js").default} [tileClass] Class used to instantiate image tiles.
   * Default is {@link module:ol/ImageTile~ImageTile}.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service. For example, if the tile
   * service advertizes 256px by 256px tiles but actually sends 512px
   * by 512px images (for retina/hidpi devices) then `tilePixelRatio`
   * should be set to `2`.
   * @property {import("../Tile.js").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function
   * for the url option instead.
   * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.
   * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be
   * used instead of defining each one separately in the `urls` option.
   * @property {Array<string>} [urls] An array of URL templates.
   * @property {boolean} [wrapX] Whether to wrap the world horizontally. The default, is to
   * request out-of-bounds tiles from the server. When set to `false`, only one
   * world will be rendered. When set to `true`, tiles will be requested for one
   * world only, but they will be wrapped horizontally to render multiple worlds.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {string} [key] Optional tile key for proper cache fetching
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @deprecated Use the ol/source/ImageTile.js instead.
   *
   * @fires import("./Tile.js").TileSourceEvent
   * @api
   */
  class TileImage extends UrlTile {
    /**
     * @param {!Options} options Image tile options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        projection: options.projection,
        state: options.state,
        tileGrid: options.tileGrid,
        tileLoadFunction: options.tileLoadFunction
          ? options.tileLoadFunction
          : defaultTileLoadFunction,
        tilePixelRatio: options.tilePixelRatio,
        tileUrlFunction: options.tileUrlFunction,
        url: options.url,
        urls: options.urls,
        wrapX: options.wrapX,
        transition: options.transition,
        interpolate:
          options.interpolate !== undefined ? options.interpolate : true,
        key: options.key,
        attributionsCollapsible: options.attributionsCollapsible,
        zDirection: options.zDirection,
      });

      /**
       * @protected
       * @type {?string}
       */
      this.crossOrigin =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      /**
       * @protected
       * @type {typeof ImageTile}
       */
      this.tileClass =
        options.tileClass !== undefined ? options.tileClass : ImageTile;

      /**
       * @protected
       * @type {!Object<string, import("../tilegrid/TileGrid.js").default>}
       */
      this.tileGridForProjection = {};

      /**
       * @private
       * @type {number|undefined}
       */
      this.reprojectionErrorThreshold_ = options.reprojectionErrorThreshold;

      /**
       * @private
       * @type {boolean}
       */
      this.renderReprojectionEdges_ = false;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {number} Gutter.
     * @override
     */
    getGutterForProjection(projection) {
      if (
        this.getProjection() &&
        projection &&
        !equivalent$1(this.getProjection(), projection)
      ) {
        return 0;
      }
      return this.getGutter();
    }

    /**
     * @return {number} Gutter.
     */
    getGutter() {
      return 0;
    }

    /**
     * Return the key to be used for all tiles in the source.
     * @return {string} The key for all tiles.
     * @override
     */
    getKey() {
      let key = super.getKey();
      if (!this.getInterpolate()) {
        key += ':disable-interpolation';
      }
      return key;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
     * @override
     */
    getTileGridForProjection(projection) {
      const thisProj = this.getProjection();
      if (this.tileGrid && (!thisProj || equivalent$1(thisProj, projection))) {
        return this.tileGrid;
      }
      const projKey = getUid(projection);
      if (!(projKey in this.tileGridForProjection)) {
        this.tileGridForProjection[projKey] =
          getForProjection(projection);
      }
      return this.tileGridForProjection[projKey];
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @param {string} key The key set on the tile.
     * @return {!ImageTile} Tile.
     * @private
     */
    createTile_(z, x, y, pixelRatio, projection, key) {
      const tileCoord = [z, x, y];
      const urlTileCoord = this.getTileCoordForTileUrlFunction(
        tileCoord,
        projection,
      );
      const tileUrl = urlTileCoord
        ? this.tileUrlFunction(urlTileCoord, pixelRatio, projection)
        : undefined;
      const tile = new this.tileClass(
        tileCoord,
        tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY,
        tileUrl !== undefined ? tileUrl : '',
        this.crossOrigin,
        this.tileLoadFunction,
        this.tileOptions,
      );
      tile.key = key;
      tile.addEventListener(EventType.CHANGE, this.handleTileChange.bind(this));
      return tile;
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!(ImageTile|ReprojTile)} Tile.
     * @override
     */
    getTile(z, x, y, pixelRatio, projection) {
      const sourceProjection = this.getProjection();
      if (
        !sourceProjection ||
        !projection ||
        equivalent$1(sourceProjection, projection)
      ) {
        return this.getTileInternal(
          z,
          x,
          y,
          pixelRatio,
          sourceProjection || projection,
        );
      }
      const tileCoord = [z, x, y];
      const key = this.getKey();
      const sourceTileGrid = this.getTileGridForProjection(sourceProjection);
      const targetTileGrid = this.getTileGridForProjection(projection);
      const wrappedTileCoord = this.getTileCoordForTileUrlFunction(
        tileCoord,
        projection,
      );
      const tile = new ReprojTile(
        sourceProjection,
        sourceTileGrid,
        projection,
        targetTileGrid,
        tileCoord,
        wrappedTileCoord,
        this.getTilePixelRatio(pixelRatio),
        this.getGutter(),
        (z, x, y, pixelRatio) =>
          this.getTileInternal(z, x, y, pixelRatio, sourceProjection),
        this.reprojectionErrorThreshold_,
        this.renderReprojectionEdges_,
        this.tileOptions,
      );
      tile.key = key;
      return tile;
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {!import("../proj/Projection.js").default} projection Projection.
     * @return {!ImageTile} Tile.
     * @protected
     */
    getTileInternal(z, x, y, pixelRatio, projection) {
      const key = this.getKey();
      return this.createTile_(z, x, y, pixelRatio, projection, key);
    }

    /**
     * Sets whether to render reprojection edges or not (usually for debugging).
     * @param {boolean} render Render the edges.
     * @api
     */
    setRenderReprojectionEdges(render) {
      if (this.renderReprojectionEdges_ == render) {
        return;
      }
      this.renderReprojectionEdges_ = render;
      this.changed();
    }

    /**
     * Sets the tile grid to use when reprojecting the tiles to the given
     * projection instead of the default tile grid for the projection.
     *
     * This can be useful when the default tile grid cannot be created
     * (e.g. projection has no extent defined) or
     * for optimization reasons (custom tile size, resolutions, ...).
     *
     * @param {import("../proj.js").ProjectionLike} projection Projection.
     * @param {import("../tilegrid/TileGrid.js").default} tilegrid Tile grid to use for the projection.
     * @api
     */
    setTileGridForProjection(projection, tilegrid) {
      const proj = get$2(projection);
      if (proj) {
        const projKey = getUid(proj);
        if (!(projKey in this.tileGridForProjection)) {
          this.tileGridForProjection[projKey] = tilegrid;
        }
      }
    }
  }

  /**
   * @param {ImageTile} imageTile Image tile.
   * @param {string} src Source.
   */
  function defaultTileLoadFunction(imageTile, src) {
    /** @type {HTMLImageElement|HTMLVideoElement} */ (imageTile.getImage()).src =
      src;
  }

  /**
   * @module ol/source/TileJSON
   */
  // FIXME check order of async callbacks


  /**
   * @typedef {Object} Config
   * @property {string} [name] The name.
   * @property {string} [description] The description.
   * @property {string} [version] The version.
   * @property {string} [attribution] The attribution.
   * @property {string} [template] The template.
   * @property {string} [legend] The legend.
   * @property {string} [scheme] The scheme.
   * @property {Array<string>} tiles The tile URL templates.
   * @property {Array<string>} [grids] Optional grids.
   * @property {number} [minzoom] Minimum zoom level.
   * @property {number} [maxzoom] Maximum zoom level.
   * @property {Array<number>} [bounds] Optional bounds.
   * @property {Array<number>} [center] Optional center.
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {boolean} [jsonp=false] Use JSONP with callback to load the TileJSON.
   * Useful when the server does not support CORS..
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {Config} [tileJSON] TileJSON configuration for this source.
   * If not provided, `url` must be configured.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The tile size used by the tile service.
   * Note: `tileSize` and other non-standard TileJSON properties are currently ignored.
   * @property {string} [url] URL to the TileJSON file. If not provided, `tileJSON` must be configured.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data in TileJSON format.
   * @api
   */
  class TileJSON extends TileImage {
    /**
     * @param {Options} options TileJSON options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: get$2('EPSG:3857'),
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        state: 'loading',
        tileLoadFunction: options.tileLoadFunction,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @type {Config}
       * @private
       */
      this.tileJSON_ = null;

      /**
       * @type {number|import("../size.js").Size}
       * @private
       */
      this.tileSize_ = options.tileSize;

      if (options.url) {
        if (options.jsonp) {
          jsonp(
            options.url,
            this.handleTileJSONResponse.bind(this),
            this.handleTileJSONError.bind(this),
          );
        } else {
          const client = new XMLHttpRequest();
          client.addEventListener('load', this.onXHRLoad_.bind(this));
          client.addEventListener('error', this.onXHRError_.bind(this));
          client.open('GET', options.url);
          client.send();
        }
      } else if (options.tileJSON) {
        this.handleTileJSONResponse(options.tileJSON);
      } else {
        throw new Error('Either `url` or `tileJSON` options must be provided');
      }
    }

    /**
     * @private
     * @param {Event} event The load event.
     */
    onXHRLoad_(event) {
      const client = /** @type {XMLHttpRequest} */ (event.target);
      // status will be 0 for file:// urls
      if (!client.status || (client.status >= 200 && client.status < 300)) {
        let response;
        try {
          response = /** @type {Config} */ (JSON.parse(client.responseText));
        } catch {
          this.handleTileJSONError();
          return;
        }
        this.handleTileJSONResponse(response);
      } else {
        this.handleTileJSONError();
      }
    }

    /**
     * @private
     * @param {Event} event The error event.
     */
    onXHRError_(event) {
      this.handleTileJSONError();
    }

    /**
     * @return {Config} The tilejson object.
     * @api
     */
    getTileJSON() {
      return this.tileJSON_;
    }

    /**
     * @protected
     * @param {Config} tileJSON Tile JSON.
     */
    handleTileJSONResponse(tileJSON) {
      const epsg4326Projection = get$2('EPSG:4326');

      const sourceProjection = this.getProjection();
      let extent;
      if (tileJSON['bounds'] !== undefined) {
        const transform = getTransformFromProjections(
          epsg4326Projection,
          sourceProjection,
        );
        extent = applyTransform(tileJSON['bounds'], transform);
      }

      const gridExtent = extentFromProjection(sourceProjection);
      const minZoom = tileJSON['minzoom'] || 0;
      const maxZoom = tileJSON['maxzoom'] || 22;
      const tileGrid = createXYZ({
        extent: gridExtent,
        maxZoom: maxZoom,
        minZoom: minZoom,
        tileSize: this.tileSize_,
      });
      this.tileGrid = tileGrid;

      this.tileUrlFunction = createFromTemplates(tileJSON['tiles'], tileGrid);

      if (tileJSON['attribution'] && !this.getAttributions()) {
        const attributionExtent = extent !== undefined ? extent : gridExtent;
        this.setAttributions(function (frameState) {
          if (intersects$2(attributionExtent, frameState.extent)) {
            return [tileJSON['attribution']];
          }
          return null;
        });
      }
      this.tileJSON_ = tileJSON;
      this.setState('ready');
    }

    /**
     * @protected
     */
    handleTileJSONError() {
      this.setState('error');
    }
  }

  /**
   * @module ol/source/VectorTile
   */


  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least twice the number of tiles in the viewport.
   * @property {import("../extent.js").Extent} [extent] Extent.
   * @property {import("../format/Feature.js").default<FeatureType>} [format] Feature format for tiles. Used and required by the default.
   * @property {boolean} [overlaps=true] This source may have overlapping geometries. Setting this
   * to `false` (e.g. for sources with polygons that represent administrative
   * boundaries or TopoJSON sources) allows the renderer to optimise fill and
   * stroke operations.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Projection of the tile grid.
   * @property {import("./Source.js").State} [state] Source state.
   * @property {typeof import("../VectorTile.js").default} [tileClass] Class used to instantiate tiles.
   * Default is {@link module:ol/VectorTile~VectorTile}.
   * @property {number} [maxZoom=22] Optional max zoom level. Not used if `tileGrid` is provided.
   * @property {number} [minZoom] Optional min zoom level. Not used if `tileGrid` is provided.
   * @property {number|import("../size.js").Size} [tileSize=512] Optional tile size. Not used if `tileGrid` is provided.
   * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction]
   * Optional function to load a tile given a URL. Could look like this for pbf tiles:
   * ```js
   * function(tile, url) {
   *   tile.setLoader(function(extent, resolution, projection) {
   *     fetch(url).then(function(response) {
   *       response.arrayBuffer().then(function(data) {
   *         const format = tile.getFormat() // ol/format/MVT configured as source format
   *         const features = format.readFeatures(data, {
   *           extent: extent,
   *           featureProjection: projection
   *         });
   *         tile.setFeatures(features);
   *       });
   *     });
   *   });
   * }
   * ```
   * If you do not need extent, resolution and projection to get the features for a tile (e.g.
   * for GeoJSON tiles), your `tileLoadFunction` does not need a `setLoader()` call. Only make sure
   * to call `setFeatures()` on the tile:
   * ```js
   * const format = new GeoJSON({featureProjection: map.getView().getProjection()});
   * async function tileLoadFunction(tile, url) {
   *   const response = await fetch(url);
   *   const data = await response.json();
   *   tile.setFeatures(format.readFeatures(data));
   * }
   * ```
   * @property {import("../Tile.js").UrlFunction} [tileUrlFunction] Optional function to get tile URL given a tile coordinate and the projection.
   * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.
   * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be
   * used instead of defining each one separately in the `urls` option.
   * @property {number} [transition] A duration for tile opacity
   * transitions in milliseconds. A duration of 0 disables the opacity transition.
   * @property {Array<string>} [urls] An array of URL templates.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * When set to `false`, only one world
   * will be rendered. When set to `true`, tiles will be wrapped horizontally to
   * render multiple worlds.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=1]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Class for layer sources providing vector data divided into a tile grid, to be
   * used with {@link module:ol/layer/VectorTile~VectorTileLayer}. Although this source receives tiles
   * with vector features from the server, it is not meant for feature editing.
   * Features are optimized for rendering, their geometries are clipped at or near
   * tile boundaries and simplified for a view resolution. See
   * {@link module:ol/source/Vector~VectorSource} for vector sources that are suitable for feature
   * editing.
   *
   * @fires import("./Tile.js").TileSourceEvent
   * @api
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   */
  class VectorTile extends UrlTile {
    /**
     * @param {!Options<FeatureType>} options Vector tile options.
     */
    constructor(options) {
      const projection = options.projection || 'EPSG:3857';

      const extent = options.extent || extentFromProjection(projection);

      const tileGrid =
        options.tileGrid ||
        createXYZ({
          extent: extent,
          maxResolution: options.maxResolution,
          maxZoom: options.maxZoom !== undefined ? options.maxZoom : 22,
          minZoom: options.minZoom,
          tileSize: options.tileSize || 512,
        });

      super({
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        cacheSize: options.cacheSize,
        interpolate: true,
        projection: projection,
        state: options.state,
        tileGrid: tileGrid,
        tileLoadFunction: options.tileLoadFunction
          ? options.tileLoadFunction
          : defaultLoadFunction,
        tileUrlFunction: options.tileUrlFunction,
        url: options.url,
        urls: options.urls,
        wrapX: options.wrapX === undefined ? true : options.wrapX,
        transition: options.transition,
        zDirection: options.zDirection === undefined ? 1 : options.zDirection,
      });

      /**
       * @private
       * @type {import("../format/Feature.js").default<FeatureType>|null}
       */
      this.format_ = options.format ? options.format : null;

      /**
       * @type {Object<string, Array<string>>}
       * @private
       */
      this.tileKeysBySourceTileUrl_ = {};

      /**
       @type {Object<string, Tile<FeatureType>>}
       */
      this.sourceTiles_ = {};

      /**
       * @private
       * @type {boolean}
       */
      this.overlaps_ = options.overlaps == undefined ? true : options.overlaps;

      /**
       * @protected
       * @type {typeof import("../VectorTile.js").default}
       */
      this.tileClass = options.tileClass ? options.tileClass : VectorTile$1;

      /**
       * @private
       * @type {Object<string, import("../tilegrid/TileGrid.js").default>}
       */
      this.tileGrids_ = {};
    }

    /**
     * @return {boolean} The source can have overlapping geometries.
     */
    getOverlaps() {
      return this.overlaps_;
    }

    /**
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection").default} projection Projection.
     * @param {VectorRenderTile} tile Vector render tile.
     * @return {Array<import("../VectorTile").default>} Tile keys.
     */
    getSourceTiles(pixelRatio, projection, tile) {
      if (tile.getState() === TileState.IDLE) {
        tile.setState(TileState.LOADING);
        const urlTileCoord = tile.wrappedTileCoord;
        const tileGrid = this.getTileGridForProjection(projection);
        const extent = tileGrid.getTileCoordExtent(urlTileCoord);
        const z = urlTileCoord[0];
        const resolution = tileGrid.getResolution(z);
        // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space
        buffer$1(extent, -resolution, extent);
        const sourceTileGrid = this.tileGrid;
        const sourceExtent = sourceTileGrid.getExtent();
        if (sourceExtent) {
          getIntersection(extent, sourceExtent, extent);
        }
        const sourceZ = sourceTileGrid.getZForResolution(
          resolution,
          this.zDirection,
        );

        sourceTileGrid.forEachTileCoord(extent, sourceZ, (sourceTileCoord) => {
          const tileUrl = this.tileUrlFunction(
            sourceTileCoord,
            pixelRatio,
            projection,
          );
          if (!this.sourceTiles_[tileUrl]) {
            this.sourceTiles_[tileUrl] = new this.tileClass(
              sourceTileCoord,
              tileUrl ? TileState.IDLE : TileState.EMPTY,
              tileUrl,
              this.format_,
              this.tileLoadFunction,
            );
          }
          const sourceTile = this.sourceTiles_[tileUrl];
          tile.sourceTiles.push(sourceTile);
          if (!this.tileKeysBySourceTileUrl_[tileUrl]) {
            this.tileKeysBySourceTileUrl_[tileUrl] = [];
          }
          this.tileKeysBySourceTileUrl_[tileUrl].push(tile.getKey());
          const sourceTileState = sourceTile.getState();
          if (sourceTileState < TileState.LOADED) {
            const listenChange = (event) => {
              this.handleTileChange(event);
              const state = sourceTile.getState();
              if (state === TileState.LOADED || state === TileState.ERROR) {
                const sourceTileKey = sourceTile.getKey();
                if (sourceTileKey in tile.errorTileKeys) {
                  if (sourceTile.getState() === TileState.LOADED) {
                    delete tile.errorTileKeys[sourceTileKey];
                  }
                } else {
                  tile.loadingSourceTiles--;
                }
                if (state === TileState.ERROR) {
                  tile.errorTileKeys[sourceTileKey] = true;
                } else {
                  sourceTile.removeEventListener(EventType.CHANGE, listenChange);
                }
                if (tile.loadingSourceTiles === 0) {
                  tile.setState(
                    isEmpty$1(tile.errorTileKeys)
                      ? TileState.LOADED
                      : TileState.ERROR,
                  );
                }
              }
            };
            sourceTile.addEventListener(EventType.CHANGE, listenChange);
            tile.loadingSourceTiles++;
          }
          if (sourceTileState === TileState.IDLE) {
            sourceTile.extent =
              sourceTileGrid.getTileCoordExtent(sourceTileCoord);
            sourceTile.projection = projection;
            sourceTile.resolution = sourceTileGrid.getResolution(
              sourceTileCoord[0],
            );
            sourceTile.load();
          }
        });
        if (!tile.loadingSourceTiles) {
          tile.setState(
            tile.sourceTiles.some(
              (sourceTile) => sourceTile.getState() === TileState.ERROR,
            )
              ? TileState.ERROR
              : TileState.LOADED,
          );
        }
      }

      return tile.sourceTiles;
    }

    /**
     * @param {VectorRenderTile} tile Vector render tile.
     */
    removeSourceTiles(tile) {
      const tileKey = tile.getKey();
      const sourceTiles = tile.sourceTiles;
      for (let i = 0, ii = sourceTiles.length; i < ii; ++i) {
        const sourceTileUrl = sourceTiles[i].getTileUrl();
        if (!this.tileKeysBySourceTileUrl_[sourceTileUrl]) {
          return;
        }
        const index =
          this.tileKeysBySourceTileUrl_[sourceTileUrl].indexOf(tileKey);
        if (index === -1) {
          continue;
        }
        this.tileKeysBySourceTileUrl_[sourceTileUrl].splice(index, 1);
        if (this.tileKeysBySourceTileUrl_[sourceTileUrl].length === 0) {
          delete this.tileKeysBySourceTileUrl_[sourceTileUrl];
          delete this.sourceTiles_[sourceTileUrl];
        }
      }
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!VectorRenderTile} Tile.
     * @override
     */
    getTile(z, x, y, pixelRatio, projection) {
      const tileCoord = [z, x, y];
      let urlTileCoord = this.getTileCoordForTileUrlFunction(
        tileCoord,
        projection,
      );
      const sourceExtent = this.getTileGrid().getExtent();
      const tileGrid = this.getTileGridForProjection(projection);
      if (urlTileCoord && sourceExtent) {
        const tileExtent = tileGrid.getTileCoordExtent(urlTileCoord);
        // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space
        buffer$1(tileExtent, -tileGrid.getResolution(z), tileExtent);
        if (!intersects$2(sourceExtent, tileExtent)) {
          urlTileCoord = null;
        }
      }
      let empty = true;
      if (urlTileCoord !== null) {
        const sourceTileGrid = this.tileGrid;
        const resolution = tileGrid.getResolution(z);
        const sourceZ = sourceTileGrid.getZForResolution(resolution, 1);
        // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space
        const extent = tileGrid.getTileCoordExtent(urlTileCoord);
        buffer$1(extent, -resolution, extent);
        sourceTileGrid.forEachTileCoord(extent, sourceZ, (sourceTileCoord) => {
          empty =
            empty &&
            !this.tileUrlFunction(sourceTileCoord, pixelRatio, projection);
        });
      }
      const newTile = new VectorRenderTile(
        tileCoord,
        empty ? TileState.EMPTY : TileState.IDLE,
        urlTileCoord,
        this.getSourceTiles.bind(this, pixelRatio, projection),
        this.removeSourceTiles.bind(this),
      );
      newTile.key = this.getKey();
      return newTile;
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
     * @override
     */
    getTileGridForProjection(projection) {
      const code = projection.getCode();
      let tileGrid = this.tileGrids_[code];
      if (!tileGrid) {
        const sourceProjection = this.getProjection();
        assert(
          sourceProjection === null || equivalent$1(sourceProjection, projection),
          'A VectorTile source can only be rendered if it has a projection compatible with the view projection.',
        );

        // A tile grid that matches the tile size of the source tile grid is more
        // likely to have 1:1 relationships between source tiles and rendered tiles.
        const sourceTileGrid = this.tileGrid;
        const resolutions = sourceTileGrid.getResolutions().slice();
        const origins = resolutions.map(function (resolution, z) {
          return sourceTileGrid.getOrigin(z);
        });
        const tileSizes = resolutions.map(function (resolution, z) {
          return sourceTileGrid.getTileSize(z);
        });
        const length = DEFAULT_MAX_ZOOM + 1;
        for (let z = resolutions.length; z < length; ++z) {
          resolutions.push(resolutions[z - 1] / 2);
          origins.push(origins[z - 1]);
          tileSizes.push(tileSizes[z - 1]);
        }
        tileGrid = new TileGrid({
          extent: sourceTileGrid.getExtent(),
          origins: origins,
          resolutions: resolutions,
          tileSizes: tileSizes,
        });
        this.tileGrids_[code] = tileGrid;
      }
      return tileGrid;
    }

    /**
     * Get the tile pixel ratio for this source.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Tile pixel ratio.
     * @override
     */
    getTilePixelRatio(pixelRatio) {
      return pixelRatio;
    }

    /**
     * @param {number} z Z.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../size.js").Size} Tile size.
     * @override
     */
    getTilePixelSize(z, pixelRatio, projection) {
      const tileGrid = this.getTileGridForProjection(projection);
      const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize);
      return [
        Math.round(tileSize[0] * pixelRatio),
        Math.round(tileSize[1] * pixelRatio),
      ];
    }

    /**
     * @param {boolean} overlaps The source has overlapping geometries.
     */
    setOverlaps(overlaps) {
      this.overlaps_ = overlaps;
      this.changed();
    }
  }

  /**
   * Sets the loader for a tile.
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   * @param {import("../VectorTile.js").default<FeatureType>} tile Vector tile.
   * @param {string} url URL.
   */
  function defaultLoadFunction(tile, url) {
    tile.setLoader(
      /**
       * @param {import("../extent.js").Extent} extent Extent.
       * @param {number} resolution Resolution.
       * @param {import("../proj/Projection.js").default} projection Projection.
       */
      function (extent, resolution, projection) {
        loadFeaturesXhr(
          url,
          tile.getFormat(),
          extent,
          resolution,
          projection,
          tile.onLoad.bind(tile),
          tile.onError.bind(tile),
        );
      },
    );
  }

  /*
  ol-mapbox-style - Use Mapbox/MapLibre Style objects with OpenLayers
  Copyright 2016-present ol-mapbox-style contributors
  License: https://raw.githubusercontent.com/openlayers/ol-mapbox-style/master/LICENSE
  */


  /**
   * @typedef {Object} FeatureIdentifier
   * @property {string|number} id The feature id.
   * @property {string} source The source id.
   */

  /**
   * @typedef {Object} Options
   * @property {string} [accessToken] Access token for 'mapbox://' urls.
   * @property {function(string, import("./util.js").ResourceType): (Request|string|Response|Promise<Request|string|Response>|void)} [transformRequest]
   * Function for controlling how `ol-mapbox-style` fetches resources. Can be used for modifying
   * the url, adding headers or setting credentials options. Called with the url and the resource
   * type as arguments, this function is supposed to return a `Request`, a url `string` or a `Response`, or a promise tehereof.
   * Without a return value the original request will not be modified.
   * @property {string} [projection='EPSG:3857'] Only useful when working with non-standard projections.
   * Code of a projection registered with OpenLayers. All sources of the style must be provided in this
   * projection. The projection must also have a valid extent defined, which will be used to determine the
   * origin and resolutions of the tile grid for all tiled sources of the style. When provided, the bbox
   * placeholder in tile and geojson urls changes: the default is `{bbox-epsg-3857}`, when projection is e.g.
   * set to `EPSG:4326`, the bbox placeholder will be `{bbox-epsg-4326}`.
   * @property {Array<number>} [resolutions] Only useful when working with non-standard projections.
   * Resolutions for mapping resolution to the `zoom` used in the Mapbox/MapLibre style.
   * @property {string} [styleUrl] URL of the Mapbox GL style. Required for styles that were provided
   * as object, when they contain a relative sprite url, or sources referencing data by relative url.
   * @property {string} [webfonts] Template for resolving webfonts. Can be used to specify where to fetch
   * web fonts when no `ol:webfonts` metadata is set in the style object. See `getFonts()` and the
   * "Font handling" section in `README.md` for details.
   * @property {function(VectorLayer|VectorTileLayer, string):HTMLImageElement|HTMLCanvasElement|string|undefined} [getImage=undefined]
   * Function that returns an image for an icon name. If the result is an HTMLImageElement, it must already be
   * loaded. The layer can be used to call layer.changed() when the loading and processing of the image has finished.
   * This function be used for icons not in the sprite or to override sprite icons.
   * @property {string} [accessTokenParam='access_token'] Access token param. For internal use.
   */

  /**
   * @typedef {Object} ApplyStyleOptions
   * @property {string} [source=''] Source. Default is `''`, which causes the first source in the
   * style to be used.
   * @property {Array<string>} [layers] Layers. If no source is provided, the layers with the
   * provided ids will be used from the style's `layers` array. All layers need to use the same source.
   * @property {boolean} [updateSource=true] Update or create vector (tile) layer source with parameters
   * specified for the source in the mapbox style definition.
   */

  /**
   * @param {import("ol/proj/Projection.js").default} projection Projection.
   * @param {number} [tileSize] Tile size.
   * @return {Array<number>} Resolutions.
   */
  function getTileResolutions(projection, tileSize = 512) {
    return projection.getExtent()
      ? createXYZ({
          extent: projection.getExtent(),
          tileSize: tileSize,
          maxZoom: 22,
        }).getResolutions()
      : defaultResolutions;
  }

  /**
   * @param {string} styleUrl Style URL.
   * @param {Options} options Options.
   * @return {Options} Completed options with accessToken and accessTokenParam.
   */
  function completeOptions(styleUrl, options) {
    if (!options.accessToken) {
      options = Object.assign({}, options);
      const searchParams = new URL(styleUrl).searchParams;
      // The last search parameter is the access token
      searchParams.forEach((value, key) => {
        options.accessToken = value;
        options.accessTokenParam = key;
      });
    }
    return options;
  }

  /**
   * Applies a style function to an `ol/layer/VectorTile` or `ol/layer/Vector`
   * with an `ol/source/VectorTile` or an `ol/source/Vector`. If the layer does not have a source
   * yet, it will be created and populated from the information in the `glStyle` (unless `updateSource` is
   * set to `false`).
   *
   * **Example:**
   * ```js
   * import {applyStyle} from 'ol-mapbox-style';
   * import {VectorTile} from 'ol/layer.js';
   *
   * const layer = new VectorTile({declutter: true});
   * applyStyle(layer, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');
   * ```
   *
   * The style function will render all layers from the `glStyle` object that use the source
   * of the first layer, the specified `source`, or a subset of layers from the same source. The
   * source needs to be a `"type": "vector"` or `"type": "geojson"` source.
   *
   * Two additional properties will be set on the provided layer:
   *
   *  * `mapbox-source`: The `id` of the Mapbox/MapLibre Style document's source that the
   *    OpenLayers layer was created from. Usually `apply()` creates one
   *    OpenLayers layer per Mapbox/MapLibre Style source, unless the layer stack has
   *    layers from different sources in between.
   *  * `mapbox-layers`: The `id`s of the Mapbox/MapLibre Style document's layers that are
   *    included in the OpenLayers layer.
   *
   * @param {VectorTileLayer|VectorLayer} layer OpenLayers layer. When the layer has a source configured,
   * it will be modified to use the configuration from the glStyle's `source`. Options specified on the
   * layer's source will override those from the glStyle's `source`, except for `url` and
   * `tileUrlFunction`. When the source projection is the default (`EPSG:3857`), the `tileGrid` will
   * also be overridden. If you'd rather not have ol-mapbox-style modify the source, configure `applyStyle()`
   * with the `updateSource: false` option.
   * @param {string|Object} glStyle Mapbox/MapLibre Style object.
   * @param {string|Array<string>|Options&ApplyStyleOptions} [sourceOrLayersOrOptions] Options or
   * `source` key or an array of layer `id`s from the Mapbox/MapLibre Style object. When a `source` key is
   * provided, all layers for the specified source will be included in the style function. When layer
   * `id`s are provided, they must be from layers that use the same source. When not provided or a falsey
   * value, all layers using the same source as the first layer matching the provided `layer` type will be rendered.
   * @param {Options&ApplyStyleOptions|string} [optionsOrPath] **Deprecated**. Options. Alternatively the path of the style file
   * (only required when a relative path is used for the `"sprite"` property of the style).
   * @param {Array<number>} [resolutions] **Deprecated**. Resolutions for mapping resolution to zoom level.
   * Only needed when working with non-standard tile grids or projections, can also be supplied with
   * options.
   * @return {Promise} Promise which will be resolved when the style can be used
   * for rendering.
   */
  function applyStyle(
    layer,
    glStyle,
    sourceOrLayersOrOptions = '',
    optionsOrPath = {},
    resolutions = undefined,
  ) {
    let styleUrl, sourceId;
    /** @type {Options&ApplyStyleOptions} */
    let options;
    let sourceOrLayers;
    let updateSource = true;
    if (
      typeof sourceOrLayersOrOptions !== 'string' &&
      !Array.isArray(sourceOrLayersOrOptions)
    ) {
      options = sourceOrLayersOrOptions;
      sourceOrLayers = options.source || options.layers;
      optionsOrPath = options;
    } else {
      sourceOrLayers = sourceOrLayersOrOptions;
    }
    if (typeof optionsOrPath === 'string') {
      styleUrl = optionsOrPath;
      options = {};
    } else {
      styleUrl = optionsOrPath.styleUrl;
      options = optionsOrPath;
    }
    if (options.updateSource === false) {
      updateSource = false;
    }
    if (!resolutions) {
      resolutions = options.resolutions;
    }
    if (
      !styleUrl &&
      typeof glStyle === 'string' &&
      !glStyle.trim().startsWith('{')
    ) {
      styleUrl = glStyle;
    }
    if (styleUrl) {
      styleUrl = styleUrl.startsWith('data:')
        ? location.href
        : normalizeStyleUrl(styleUrl, options.accessToken);
      options = completeOptions(styleUrl, options);
    }

    return new Promise(function (resolve, reject) {
      // TODO: figure out where best place to check source type is
      // Note that the source arg is an array of gl layer ids and each must be
      // dereferenced to get source type to validate
      getGlStyle(glStyle, options)
        .then(function (glStyle) {
          if (glStyle.version != 8) {
            return reject(new Error('glStyle version 8 required.'));
          }
          if (
            !(layer instanceof VectorLayer || layer instanceof VectorTileLayer)
          ) {
            return reject(
              new Error('Can only apply to VectorLayer or VectorTileLayer'),
            );
          }

          const type = layer instanceof VectorTileLayer ? 'vector' : 'geojson';
          if (!sourceOrLayers) {
            sourceId = glStyle.layers.find(function (layer) {
              return layer.source && glStyle.sources[layer.source].type === type;
            }).source;

            sourceOrLayers = sourceId;
          } else if (Array.isArray(sourceOrLayers)) {
            sourceId = glStyle.layers.find(function (layer) {
              return layer.id === sourceOrLayers[0];
            }).source;
          } else {
            sourceId = sourceOrLayers;
          }
          if (!sourceId) {
            return reject(new Error(`No ${type} source found in the glStyle.`));
          }

          function assignSource() {
            if (!updateSource) {
              return Promise.resolve();
            }
            if (layer instanceof VectorTileLayer) {
              return setupVectorSource(
                glStyle.sources[sourceId],
                styleUrl,
                options,
              ).then(function (source) {
                const targetSource = layer.getSource();
                if (!targetSource) {
                  layer.setSource(source);
                } else if (source !== targetSource) {
                  targetSource.setTileUrlFunction(source.getTileUrlFunction());
                  if (
                    typeof targetSource.setUrls === 'function' &&
                    typeof source.getUrls === 'function'
                  ) {
                    // to get correct keys for tile cache and queue
                    targetSource.setUrls(source.getUrls());
                  }
                  //@ts-ignore
                  if (!targetSource.format_) {
                    //@ts-ignore
                    targetSource.format_ = source.format_;
                  }
                  if (!targetSource.getAttributions()) {
                    targetSource.setAttributions(source.getAttributions());
                  }
                  if (
                    targetSource.getTileLoadFunction() === defaultLoadFunction
                  ) {
                    targetSource.setTileLoadFunction(
                      source.getTileLoadFunction(),
                    );
                  }
                  if (
                    equivalent$1(
                      targetSource.getProjection(),
                      source.getProjection(),
                    )
                  ) {
                    //@ts-ignore
                    targetSource.tileGrid = source.getTileGrid();
                  }
                }
                const tileGrid = layer.getSource().getTileGrid();
                if (
                  !isFinite(layer.getMaxResolution()) &&
                  !isFinite(layer.getMinZoom()) &&
                  tileGrid.getMinZoom() > 0
                ) {
                  layer.setMaxResolution(
                    getResolutionForZoom(
                      Math.max(0, tileGrid.getMinZoom() - 1e-12),
                      tileGrid.getResolutions(),
                    ),
                  );
                }
              });
            }

            const glSource = glStyle.sources[sourceId];
            let source = layer.getSource();
            if (!source || source.get('mapbox-source') !== glSource) {
              source = setupGeoJSONSource(glSource, styleUrl, options);
            }
            const targetSource = /** @type {VectorSource} */ (layer.getSource());
            if (!targetSource) {
              layer.setSource(source);
            } else if (source !== targetSource) {
              if (!targetSource.getAttributions()) {
                targetSource.setAttributions(source.getAttributions());
              }
              //@ts-ignore
              if (!targetSource.format_) {
                //@ts-ignore
                targetSource.format_ = source.getFormat();
              }
              //@ts-ignore
              targetSource.url_ = source.getUrl();
            }
            return Promise.resolve();
          }

          let spriteScale, style;
          const spriteData = {};
          /** @type {import('./stylefunction.js').SpriteImageUrl} */
          const spriteImageUrl = {};
          function onChange() {
            if (!style && (!glStyle.sprite || spriteData)) {
              if (options.projection && !resolutions) {
                const projection = get$2(options.projection);
                const units = projection.getUnits();
                if (units !== 'm') {
                  resolutions = defaultResolutions.map(
                    (resolution) => resolution / METERS_PER_UNIT$1[units],
                  );
                }
              }
              style = stylefunction(
                layer,
                glStyle,
                sourceOrLayers,
                resolutions,
                spriteData,
                spriteImageUrl,
                (fonts, templateUrl = options.webfonts) =>
                  getFonts(fonts, templateUrl),
                options.getImage,
              );
              if (!layer.getStyle()) {
                reject(new Error(`Nothing to show for source [${sourceId}]`));
              } else {
                assignSource().then(resolve).catch(reject);
              }
            } else if (style) {
              layer.setStyle(style);
              assignSource().then(resolve).catch(reject);
            } else {
              reject(new Error('Something went wrong trying to apply style.'));
            }
          }

          if (glStyle.sprite) {
            const sprites = normalizeSpriteDefinition(
              glStyle.sprite,
              options.accessToken,
              styleUrl || location.href,
            );
            spriteScale = window.devicePixelRatio >= 1.5 ? 0.5 : 1;
            const sizeFactor = spriteScale == 0.5 ? '@2x' : '';

            Promise.all(
              sprites.map(function (sprite) {
                const spriteBaseUrl = new URL(sprite.url);
                let spriteUrl =
                  spriteBaseUrl.origin +
                  spriteBaseUrl.pathname +
                  sizeFactor +
                  '.json' +
                  spriteBaseUrl.search;

                return new Promise(function (resolve, reject) {
                  fetchResource('Sprite', spriteUrl, options)
                    .then(resolve)
                    .catch(function (error) {
                      spriteUrl =
                        spriteBaseUrl.origin +
                        spriteBaseUrl.pathname +
                        '.json' +
                        spriteBaseUrl.search;
                      fetchResource('Sprite', spriteUrl, options)
                        .then(resolve)
                        .catch(reject);
                    });
                })
                  .then(function (spritesJson) {
                    if (spritesJson === undefined) {
                      reject(new Error('No sprites found.'));
                    }

                    let imageUrl;
                    imageUrl =
                      spriteBaseUrl.origin +
                      spriteBaseUrl.pathname +
                      sizeFactor +
                      '.png' +
                      spriteBaseUrl.search;

                    if (options.transformRequest) {
                      const transformed =
                        options.transformRequest(imageUrl, 'SpriteImage') ||
                        imageUrl;
                      if (
                        transformed instanceof Request ||
                        transformed instanceof Promise
                      ) {
                        imageUrl = transformed;
                      }
                    }
                    spriteImageUrl[sprite.id] = imageUrl;

                    // add sprite data with prefix according to spec
                    for (const spriteName in spritesJson) {
                      const key =
                        sprite.id == 'default'
                          ? spriteName
                          : `${sprite.id}:${spriteName}`;
                      spriteData[key] = spritesJson[spriteName];
                    }
                  })
                  .catch(function (err) {
                    reject(
                      new Error(
                        `Sprites cannot be loaded: ${spriteUrl}: ${err.message}`,
                      ),
                    );
                  });
              }),
            )
              .then(onChange)
              .catch(reject);
          } else {
            onChange();
          }
        })
        .catch(reject);
    });
  }

  function setFirstBackground(mapOrLayer, glStyle, options) {
    glStyle.layers.some(function (layer) {
      if (layer.type === 'background') {
        if (mapOrLayer instanceof Layer) {
          mapOrLayer.setBackground(function (resolution) {
            return getBackgroundColor(layer, resolution, options, {});
          });
          return true;
        }
        if (mapOrLayer instanceof Map$1 || mapOrLayer instanceof LayerGroup) {
          mapOrLayer
            .getLayers()
            .insertAt(0, setupBackgroundLayer(layer, options, {}));
          return true;
        }
      }
    });
  }

  /**
   * Applies properties of the Mapbox/MapLibre Style's first `background` layer to the
   * provided map or layer (group).
   *
   * **Example:**
   * ```js
   * import {applyBackground} from 'ol-mapbox-style';
   * import {Map} from 'ol';
   *
   * const map = new Map({target: 'map'});
   * applyBackground(map, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');
   * ```
   * @param {Map|import("ol/layer/Base.js").default} mapOrLayer OpenLayers Map or layer (group).
   * @param {Object|string} glStyle Mapbox/MapLibre Style object or url.
   * @param {Options} options Options.
   * @return {Promise} Promise that resolves when the background is applied.
   */
  function applyBackground(mapOrLayer, glStyle, options = {}) {
    return getGlStyle(glStyle, options).then(function (glStyle) {
      setFirstBackground(mapOrLayer, glStyle, options);
    });
  }

  function extentFromTileJSON(tileJSON, projection) {
    const bounds = tileJSON.bounds;
    if (bounds) {
      const ll = fromLonLat([bounds[0], bounds[1]], projection);
      const tr = fromLonLat([bounds[2], bounds[3]], projection);
      return [ll[0], ll[1], tr[0], tr[1]];
    }
    return get$2(projection).getExtent();
  }

  function sourceOptionsFromTileJSON(glSource, tileJSON, options) {
    const tileJSONSource = new TileJSON({
      tileJSON: tileJSON,
      tileSize: glSource.tileSize || tileJSON.tileSize || 512,
    });
    const tileJSONDoc = tileJSONSource.getTileJSON();
    const tileGrid = tileJSONSource.getTileGrid();
    const projection = get$2(options.projection || 'EPSG:3857');
    const extent = extentFromTileJSON(tileJSONDoc, projection);
    const projectionExtent = projection.getExtent();
    const minZoom = tileJSONDoc.minzoom || 0;
    const maxZoom = tileJSONDoc.maxzoom || 22;
    /** @type {import("ol/source/VectorTile.js").Options<import("ol/render/Feature.js").default>} */
    const sourceOptions = {
      attributions: tileJSONSource.getAttributions(),
      projection: projection,
      tileGrid: new TileGrid({
        origin: projectionExtent
          ? getTopLeft(projectionExtent)
          : tileGrid.getOrigin(0),
        extent: extent || tileGrid.getExtent(),
        minZoom: minZoom,
        resolutions: getTileResolutions(projection, tileJSON.tileSize).slice(
          0,
          maxZoom + 1,
        ),
        tileSize: tileGrid.getTileSize(0),
      }),
    };
    if (Array.isArray(tileJSONDoc.tiles)) {
      sourceOptions.urls = tileJSONDoc.tiles;
    } else {
      sourceOptions.url = tileJSONDoc.tiles;
    }
    return sourceOptions;
  }

  function getBackgroundColor(glLayer, resolution, options, functionCache) {
    const background = {
      id: glLayer.id,
      type: glLayer.type,
    };
    const layout = glLayer.layout || {};
    const paint = glLayer.paint || {};
    background['paint'] = paint;
    cameraObj.zoom = getZoomForResolution(
      resolution,
      options.resolutions || defaultResolutions,
    );
    cameraObj.distanceFromCenter = 0;
    let opacity;
    const bg = getValue(
      background,
      'paint',
      'background-color',
      emptyObj,
      functionCache,
    );
    if (paint['background-opacity'] !== undefined) {
      opacity = getValue(
        background,
        'paint',
        'background-opacity',
        emptyObj,
        functionCache,
      );
    }
    return layout.visibility == 'none'
      ? undefined
      : colorWithOpacity(bg, opacity);
  }

  /**
   * @param {Object} glLayer Mapbox/MapLibre Style layer object.
   * @param {Options} options Options.
   * @param {Object} functionCache Cache for functions.
   * @return {Layer} OpenLayers layer.
   */
  function setupBackgroundLayer(glLayer, options, functionCache) {
    const div = document.createElement('div');
    div.className = 'ol-mapbox-style-background';
    div.style.position = 'absolute';
    div.style.width = '100%';
    div.style.height = '100%';
    return new Layer({
      source: new Source({}),
      render(frameState) {
        const color = getBackgroundColor(
          glLayer,
          frameState.viewState.resolution,
          options,
          functionCache,
        );
        div.style.backgroundColor = color;
        return div;
      },
    });
  }

  /**
   * Creates an OpenLayers VectorTile source for a gl source entry.
   * @param {Object} glSource "source" entry from a Mapbox/MapLibre Style object.
   * @param {string|undefined} styleUrl URL to use for the source. This is expected to be the complete http(s) url,
   * with access key applied.
   * @param {Options} options Options.
   * @return {Promise<import("ol/source/VectorTile").default>} Promise resolving to a VectorTile source.
   * @private
   */
  function setupVectorSource(glSource, styleUrl, options) {
    return new Promise(function (resolve, reject) {
      getTileJson(glSource, styleUrl, options)
        .then(function ({tileJson, tileLoadFunction}) {
          const sourceOptions = sourceOptionsFromTileJSON(
            glSource,
            tileJson,
            options,
          );
          sourceOptions.tileLoadFunction = tileLoadFunction;
          sourceOptions.format = new MVT({layerName: 'mvt:layer'});
          const source = new VectorTile(sourceOptions);
          source.set('mapbox-source', glSource);
          resolve(source);
        })
        .catch(reject);
    });
  }

  function getBboxTemplate(projection) {
    const projCode = projection ? projection.getCode() : 'EPSG:3857';
    return `{bbox-${projCode.toLowerCase().replace(/[^a-z0-9]/g, '-')}}`;
  }

  /**
   * @param {Object} glSource glStyle source.
   * @param {string} styleUrl Style URL.
   * @param {Options} options Options.
   * @return {VectorSource} Configured vector source.
   */
  function setupGeoJSONSource(glSource, styleUrl, options) {
    const geoJsonFormat = options.projection
      ? new GeoJSON({dataProjection: options.projection})
      : new GeoJSON();
    const data = glSource.data;
    const sourceOptions = {};
    if (typeof data == 'string') {
      const [geoJsonUrl] = normalizeSourceUrl(
        data,
        options.accessToken,
        options.accessTokenParam || 'access_token',
        styleUrl || location.href,
      );
      if (/\{bbox-[0-9a-z-]+\}/.test(geoJsonUrl)) {
        const extentUrl = (extent, resolution, projection) => {
          const bboxTemplate = getBboxTemplate(projection);
          return geoJsonUrl.replace(bboxTemplate, `${extent.join(',')}`);
        };
        const source = new VectorSource({
          attributions: glSource.attribution,
          format: geoJsonFormat,
          loader: (extent, resolution, projection, success, failure) => {
            const url =
              typeof extentUrl === 'function'
                ? extentUrl(extent, resolution, projection)
                : extentUrl;
            fetchResource('GeoJSON', url, options)
              .then((json) => {
                const features = /** @type {*} */ (
                  source
                    .getFormat()
                    .readFeatures(json, {featureProjection: projection})
                );
                source.addFeatures(features);
                success(features);
              })
              .catch((response) => {
                source.removeLoadedExtent(extent);
                failure();
              });
          },
          strategy: bbox$1,
        });
        source.set('mapbox-source', glSource);
        return source;
      }
      const source = new VectorSource({
        attributions: glSource.attribution,
        format: geoJsonFormat,
        url: geoJsonUrl,
        loader: (extent, resolution, projection, success, failure) => {
          fetchResource('GeoJSON', geoJsonUrl, options)
            .then((json) => {
              const features = /** @type {*} */ (
                source
                  .getFormat()
                  .readFeatures(json, {featureProjection: projection})
              );
              source.addFeatures(features);
              success(features);
            })
            .catch((response) => {
              source.removeLoadedExtent(extent);
              failure();
            });
        },
      });
      return source;
    }
    sourceOptions.features = geoJsonFormat.readFeatures(data, {
      featureProjection: getUserProjection() || 'EPSG:3857',
    });

    const source = new VectorSource(
      Object.assign(
        {
          attributions: glSource.attribution,
          format: geoJsonFormat,
        },
        sourceOptions,
      ),
    );
    source.set('mapbox-source', glSource);
    return /** @type {VectorSource} */ (source);
  }

  /** @typedef {import("ol/Map.js").default} Map */

  /**
   * Event emitted on configuration or loading error.
   */
  class ErrorEvent extends BaseEvent {
    /**
     * @param {Error} error error object.
     */
    constructor(error) {
      super(EventType.ERROR);

      /**
       * @type {Error}
       */
      this.error = error;
    }
  }

  /**
   * @typedef {Object} Options
   * @property {string} styleUrl The URL of the Mapbox/MapLibre Style object to use for this layer.  For a
   * style created with Mapbox Studio and hosted on Mapbox, this will look like
   * 'mapbox://styles/you/your-style'.
   * @property {string} [accessToken] The access token for your Mapbox/MapLibre style. This has to be provided
   * for `mapbox://` style urls. For `https://` and other urls, any access key must be the last query
   * parameter of the style url.
   * @property {string} [source] If your style uses more than one source, you need to use either the
   * `source` property or the `layers` property to limit rendering to a single vector source.  The
   * `source` property corresponds to the id of a vector source in your Mapbox/MapLibre style.
   * @property {Array<string>} [layers] Limit rendering to the list of included layers.  All layers
   * must share the same vector source.  If your style uses more than one source, you need to use
   * either the `source` property or the `layers` property to limit rendering to a single vector
   * source.
   * @property {boolean} [declutter=true] Declutter images and text. Decluttering is applied to all
   * image and text styles of all Vector and VectorTile layers that have set this to `true`. The priority
   * is defined by the z-index of the layer, the `zIndex` of the style and the render order of features.
   * Higher z-index means higher priority. Within the same z-index, a feature rendered before another has
   * higher priority.
   *
   * As an optimization decluttered features from layers with the same `className` are rendered above
   * the fill and stroke styles of all of those layers regardless of z-index.  To opt out of this
   * behavior and place declutterd features with their own layer configure the layer with a `className`
   * other than `ol-layer`.
   * @property {import("ol/layer/Base.js").BackgroundColor|false} [background] Background color for the layer.
   * If not specified, the background from the Mapbox/MapLibre Style object will be used. Set to `false` to prevent
   * the Mapbox/MapLibre style's background from being used.
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("ol/extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible. If neither `maxResolution` nor `minZoom` are defined, the layer's `maxResolution` will
   * match the style source's `minzoom`.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will
   * be visible. If neither `maxResolution` nor `minZoom` are defined, the layer's `minZoom` will match
   * the style source's `minzoom`.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("ol/render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
   * features before rendering. By default features are drawn in the order that they are created. Use
   * `null` to avoid the sort, but get an undefined draw order.
   * @property {number} [renderBuffer=100] The buffer in pixels around the tile extent used by the
   * renderer when getting features from the vector tile for the rendering or hit-detection.
   * Recommended value: Vector tiles are usually generated with a buffer, so this value should match
   * the largest possible buffer of the used tiles. It should be at least the size of the largest
   * point symbol or line width.
   * @property {import("ol/layer/VectorTile.js").VectorTileRenderType} [renderMode='hybrid'] Render mode for vector tiles:
   *  * `'hybrid'`: Polygon and line elements are rendered as images, so pixels are scaled during zoom
   *    animations. Point symbols and texts are accurately rendered as vectors and can stay upright on
   *    rotated views.
   *  * `'vector'`: Everything is rendered as vectors. Use this mode for improved performance on vector
   *    tile layers with only a few rendered features (e.g. for highlighting a subset of features of
   *    another layer with the same source).
   * @property {import("ol/Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use `map.addLayer()`.
   * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will be
   * recreated during animations. This means that no vectors will be shown clipped, but the setting
   * will have a performance impact for large amounts of vector data. When set to `false`, batches
   * will be recreated when no animation is active.
   * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will be
   * recreated during interactions. See also `updateWhileAnimating`.
   * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
   * means no preloading.
   * @property {boolean} [useInterimTilesOnError=true] Use interim tiles on error.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * ```js
   * import {MapboxVectorLayer} from 'ol-mapbox-style';
   * ```
   * A vector tile layer based on a Mapbox/MapLibre style that uses a single vector source.  Configure
   * the layer with the `styleUrl` and `accessToken` shown in Mapbox Studio's share panel.
   * If the style uses more than one source, use the `source` property to choose a single
   * vector source.  If you want to render a subset of the layers in the style, use the `layers`
   * property (all layers must share the same vector source).  See the constructor options for
   * more detail.
   *
   *     const map = new Map({
   *       view: new View({
   *         center: [0, 0],
   *         zoom: 1,
   *       }),
   *       layers: [
   *         new MapboxVectorLayer({
   *           styleUrl: 'mapbox://styles/mapbox/bright-v9',
   *           accessToken: 'your-mapbox-access-token-here',
   *         }),
   *       ],
   *       target: 'map',
   *     });
   *
   * On configuration or loading error, the layer will trigger an `'error'` event.  Listeners
   * will receive an object with an `error` property that can be used to diagnose the problem.
   *
   * Instances of this class emit an `error` event when an error occurs during style loading:
   *
   *     layer.on('error', function() {
   *       console.error('Error loading style');
   *     }
   *
   * **Note for users of the full build**: The `MapboxVectorLayer` requires the
   * [ol-mapbox-style](https://github.com/openlayers/ol-mapbox-style) library to be loaded as well.
   *
   * @param {Options} options Options.
   * @extends {VectorTileLayer<import("ol/source/VectorTile.js").default>}
   */
  class MapboxVectorLayer extends VectorTileLayer {
    /**
     * @param {Options} options Layer options.  At a minimum, `styleUrl` and `accessToken`
     * must be provided.
     */
    constructor(options) {
      const declutter = 'declutter' in options ? options.declutter : true;
      const source = new VectorTile({
        state: 'loading',
        format: new MVT({layerName: 'mvt:layer'}),
      });

      super({
        source: source,
        background: options.background === false ? null : options.background,
        declutter: declutter,
        className: options.className,
        opacity: options.opacity,
        visible: options.visible,
        zIndex: options.zIndex,
        minResolution: options.minResolution,
        maxResolution: options.maxResolution,
        minZoom: options.minZoom,
        maxZoom: options.maxZoom,
        renderOrder: options.renderOrder,
        renderBuffer: options.renderBuffer,
        renderMode: options.renderMode,
        map: options.map,
        updateWhileAnimating: options.updateWhileAnimating,
        updateWhileInteracting: options.updateWhileInteracting,
        preload: options.preload,
        useInterimTilesOnError: options.useInterimTilesOnError,
        properties: options.properties,
      });

      if (options.accessToken) {
        this.accessToken = options.accessToken;
      }
      const url = options.styleUrl;
      const promises = [
        applyStyle(this, url, options.layers || options.source, {
          accessToken: this.accessToken,
        }),
      ];
      if (this.getBackground() === undefined) {
        promises.push(
          applyBackground(this, options.styleUrl, {
            accessToken: this.accessToken,
          }),
        );
      }
      Promise.all(promises)
        .then(() => {
          source.setState('ready');
        })
        .catch((error) => {
          this.dispatchEvent(new ErrorEvent(error));
          const source = this.getSource();
          source.setState('error');
        });
    }
  }

  /**
   * @module ol/control/FullScreen
   */

  const events = ['fullscreenchange', 'webkitfullscreenchange'];

  /**
   * @enum {string}
   */
  const FullScreenEventType = {
    /**
     * Triggered after the map entered fullscreen.
     * @event FullScreenEventType#enterfullscreen
     * @api
     */
    ENTERFULLSCREEN: 'enterfullscreen',

    /**
     * Triggered after the map leave fullscreen.
     * @event FullScreenEventType#leavefullscreen
     * @api
     */
    LEAVEFULLSCREEN: 'leavefullscreen',
  };

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes|
   *     'enterfullscreen'|'leavefullscreen', import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types, import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|
   *     'enterfullscreen'|'leavefullscreen'|import("../ObjectEventType").Types, Return>} FullScreenOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-full-screen'] CSS class name.
   * @property {string|Text|HTMLElement} [label='\u2922'] Text label to use for the button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string|Text|HTMLElement} [labelActive='\u00d7'] Text label to use for the
   * button when full-screen is active.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [activeClassName=className + '-true'] CSS class name for the button
   * when full-screen is active.
   * @property {string} [inactiveClassName=className + '-false'] CSS class name for the button
   * when full-screen is inactive.
   * @property {string} [tipLabel='Toggle full-screen'] Text label to use for the button tip.
   * @property {boolean} [keys=false] Full keyboard access.
   * @property {HTMLElement|string} [target] Specify a target if you want the
   * control to be rendered outside of the map's viewport.
   * @property {HTMLElement|string} [source] The element to be displayed
   * fullscreen. When not provided, the element containing the map viewport will
   * be displayed fullscreen.
   */

  /**
   * @classdesc
   * Provides a button that when clicked fills up the full screen with the map.
   * The full screen source element is by default the element containing the map viewport unless
   * overridden by providing the `source` option. In which case, the dom
   * element introduced using this parameter will be displayed in full screen.
   *
   * When in full screen mode, a close button is shown to exit full screen mode.
   * The [Fullscreen API](https://www.w3.org/TR/fullscreen/) is used to
   * toggle the map in full screen mode.
   *
   * @fires FullScreenEventType#enterfullscreen
   * @fires FullScreenEventType#leavefullscreen
   * @api
   */
  class FullScreen extends Control {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        target: options.target,
      });

      /***
       * @type {FullScreenOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {FullScreenOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {FullScreenOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {boolean}
       */
      this.keys_ = options.keys !== undefined ? options.keys : false;

      /**
       * @private
       * @type {HTMLElement|string|undefined}
       */
      this.source_ = options.source;

      /**
       * @type {boolean}
       * @private
       */
      this.isInFullscreen_ = false;

      /**
       * @private
       */
      this.boundHandleMapTargetChange_ = this.handleMapTargetChange_.bind(this);

      /**
       * @private
       * @type {string}
       */
      this.cssClassName_ =
        options.className !== undefined ? options.className : 'ol-full-screen';

      /**
       * @private
       * @type {Array<import("../events.js").EventsKey>}
       */
      this.documentListeners_ = [];

      /**
       * @private
       * @type {Array<string>}
       */
      this.activeClassName_ =
        options.activeClassName !== undefined
          ? options.activeClassName.split(' ')
          : [this.cssClassName_ + '-true'];

      /**
       * @private
       * @type {Array<string>}
       */
      this.inactiveClassName_ =
        options.inactiveClassName !== undefined
          ? options.inactiveClassName.split(' ')
          : [this.cssClassName_ + '-false'];

      const label = options.label !== undefined ? options.label : '\u2922';

      /**
       * @private
       * @type {Text|HTMLElement}
       */
      this.labelNode_ =
        typeof label === 'string' ? document.createTextNode(label) : label;

      const labelActive =
        options.labelActive !== undefined ? options.labelActive : '\u00d7';

      /**
       * @private
       * @type {Text|HTMLElement}
       */
      this.labelActiveNode_ =
        typeof labelActive === 'string'
          ? document.createTextNode(labelActive)
          : labelActive;

      const tipLabel = options.tipLabel ? options.tipLabel : 'Toggle full-screen';

      /**
       * @private
       * @type {HTMLElement}
       */
      this.button_ = document.createElement('button');
      this.button_.title = tipLabel;
      this.button_.setAttribute('type', 'button');
      this.button_.appendChild(this.labelNode_);
      this.button_.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this),
        false,
      );
      this.setClassName_(this.button_, this.isInFullscreen_);

      this.element.className = `${this.cssClassName_} ${CLASS_UNSELECTABLE} ${CLASS_CONTROL}`;
      this.element.appendChild(this.button_);
    }

    /**
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(event) {
      event.preventDefault();
      this.handleFullScreen_();
    }

    /**
     * @private
     */
    handleFullScreen_() {
      const map = this.getMap();
      if (!map) {
        return;
      }
      const doc = map.getOwnerDocument();
      if (!isFullScreenSupported(doc)) {
        return;
      }
      if (isFullScreen(doc)) {
        exitFullScreen(doc);
      } else {
        let element;
        if (this.source_) {
          element =
            typeof this.source_ === 'string'
              ? doc.getElementById(this.source_)
              : this.source_;
        } else {
          element = map.getTargetElement();
        }
        if (this.keys_) {
          requestFullScreenWithKeys(element);
        } else {
          requestFullScreen(element);
        }
      }
    }

    /**
     * @private
     */
    handleFullScreenChange_() {
      const map = this.getMap();
      if (!map) {
        return;
      }
      const wasInFullscreen = this.isInFullscreen_;
      this.isInFullscreen_ = isFullScreen(map.getOwnerDocument());
      if (wasInFullscreen !== this.isInFullscreen_) {
        this.setClassName_(this.button_, this.isInFullscreen_);
        if (this.isInFullscreen_) {
          replaceNode(this.labelActiveNode_, this.labelNode_);
          this.dispatchEvent(FullScreenEventType.ENTERFULLSCREEN);
        } else {
          replaceNode(this.labelNode_, this.labelActiveNode_);
          this.dispatchEvent(FullScreenEventType.LEAVEFULLSCREEN);
        }
        map.updateSize();
      }
    }

    /**
     * @param {HTMLElement} element Target element
     * @param {boolean} fullscreen True if fullscreen class name should be active
     * @private
     */
    setClassName_(element, fullscreen) {
      if (fullscreen) {
        element.classList.remove(...this.inactiveClassName_);
        element.classList.add(...this.activeClassName_);
      } else {
        element.classList.remove(...this.activeClassName_);
        element.classList.add(...this.inactiveClassName_);
      }
    }

    /**
     * Remove the control from its current map and attach it to the new map.
     * Pass `null` to just remove the control from the current map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     * @override
     */
    setMap(map) {
      const oldMap = this.getMap();
      if (oldMap) {
        oldMap.removeChangeListener(
          MapProperty.TARGET,
          this.boundHandleMapTargetChange_,
        );
      }

      super.setMap(map);

      this.handleMapTargetChange_();
      if (map) {
        map.addChangeListener(
          MapProperty.TARGET,
          this.boundHandleMapTargetChange_,
        );
      }
    }

    /**
     * @private
     */
    handleMapTargetChange_() {
      const listeners = this.documentListeners_;
      for (let i = 0, ii = listeners.length; i < ii; ++i) {
        unlistenByKey(listeners[i]);
      }
      listeners.length = 0;

      const map = this.getMap();
      if (map) {
        const doc = map.getOwnerDocument();
        if (isFullScreenSupported(doc)) {
          this.element.classList.remove(CLASS_UNSUPPORTED);
        } else {
          this.element.classList.add(CLASS_UNSUPPORTED);
        }

        for (let i = 0, ii = events.length; i < ii; ++i) {
          listeners.push(
            listen(doc, events[i], this.handleFullScreenChange_, this),
          );
        }
        this.handleFullScreenChange_();
      }
    }
  }

  /**
   * @param {Document} doc The root document to check.
   * @return {boolean} Fullscreen is supported by the current platform.
   */
  function isFullScreenSupported(doc) {
    const body = doc.body;
    return !!(
      body['webkitRequestFullscreen'] ||
      (body.requestFullscreen && doc.fullscreenEnabled)
    );
  }

  /**
   * @param {Document} doc The root document to check.
   * @return {boolean} Element is currently in fullscreen.
   */
  function isFullScreen(doc) {
    return !!(doc['webkitIsFullScreen'] || doc.fullscreenElement);
  }

  /**
   * Request to fullscreen an element.
   * @param {HTMLElement} element Element to request fullscreen
   */
  function requestFullScreen(element) {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element['webkitRequestFullscreen']) {
      element['webkitRequestFullscreen']();
    }
  }

  /**
   * Request to fullscreen an element with keyboard input.
   * @param {HTMLElement} element Element to request fullscreen
   */
  function requestFullScreenWithKeys(element) {
    if (element['webkitRequestFullscreen']) {
      element['webkitRequestFullscreen']();
    } else {
      requestFullScreen(element);
    }
  }

  /**
   * Exit fullscreen.
   * @param {Document} doc The document to exit fullscren from
   */
  function exitFullScreen(doc) {
    if (doc.exitFullscreen) {
      doc.exitFullscreen();
    } else if (doc['webkitExitFullscreen']) {
      doc['webkitExitFullscreen']();
    }
  }

  /**
   * @module ol/control/MousePosition
   */


  /**
   * @type {string}
   */
  const PROJECTION = 'projection';

  /**
   * @type {string}
   */
  const COORDINATE_FORMAT = 'coordinateFormat';

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:coordinateFormat'|'change:projection', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:coordinateFormat'|'change:projection', Return>} MousePositionOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-mouse-position'] CSS class name.
   * @property {import("../coordinate.js").CoordinateFormat} [coordinateFormat] Coordinate format.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when the
   * control should be re-rendered. This is called in a `requestAnimationFrame`
   * callback.
   * @property {HTMLElement|string} [target] Specify a target if you want the
   * control to be rendered outside of the map's viewport.
   * @property {string} [placeholder] Markup to show when the mouse position is not
   * available (e.g. when the pointer leaves the map viewport).  By default, a non-breaking space is rendered
   * initially and the last position is retained when the mouse leaves the viewport.
   * When a string is provided (e.g. `'no position'` or `''` for an empty string) it is used as a
   * placeholder.
   * @property {boolean} [wrapX=true] Wrap the world horizontally on the projection's antimeridian, if it
   * is a global projection.
   */

  /**
   * @classdesc
   * A control to show the 2D coordinates of the mouse cursor. By default, these
   * are in the view projection, but can be in any supported projection.
   * By default the control is shown in the top right corner of the map, but this
   * can be changed by using the css selector `.ol-mouse-position`.
   *
   * On touch devices, which usually do not have a mouse cursor, the coordinates
   * of the currently touched position are shown.
   *
   * @api
   */
  class MousePosition extends Control {
    /**
     * @param {Options} [options] Mouse position options.
     */
    constructor(options) {
      options = options ? options : {};

      const element = document.createElement('div');
      element.className =
        options.className !== undefined ? options.className : 'ol-mouse-position';

      super({
        element: element,
        render: options.render,
        target: options.target,
      });

      /***
       * @type {MousePositionOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {MousePositionOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {MousePositionOnSignature<void>}
       */
      this.un;

      this.addChangeListener(PROJECTION, this.handleProjectionChanged_);

      if (options.coordinateFormat) {
        this.setCoordinateFormat(options.coordinateFormat);
      }
      if (options.projection) {
        this.setProjection(options.projection);
      }

      /**
       * @private
       * @type {boolean}
       */
      this.renderOnMouseOut_ = options.placeholder !== undefined;

      /**
       * @private
       * @type {string}
       */
      this.placeholder_ = this.renderOnMouseOut_ ? options.placeholder : '&#160;';

      /**
       * @private
       * @type {string}
       */
      this.renderedHTML_ = element.innerHTML;

      /**
       * @private
       * @type {?import("../proj/Projection.js").default}
       */
      this.mapProjection_ = null;

      /**
       * @private
       * @type {?import("../proj.js").TransformFunction}
       */
      this.transform_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.wrapX_ = options.wrapX === false ? false : true;
    }

    /**
     * @private
     */
    handleProjectionChanged_() {
      this.transform_ = null;
    }

    /**
     * Return the coordinate format type used to render the current position or
     * undefined.
     * @return {import("../coordinate.js").CoordinateFormat|undefined} The format to render the current
     *     position in.
     * @observable
     * @api
     */
    getCoordinateFormat() {
      return /** @type {import("../coordinate.js").CoordinateFormat|undefined} */ (
        this.get(COORDINATE_FORMAT)
      );
    }

    /**
     * Return the projection that is used to report the mouse position.
     * @return {import("../proj/Projection.js").default|undefined} The projection to report mouse
     *     position in.
     * @observable
     * @api
     */
    getProjection() {
      return /** @type {import("../proj/Projection.js").default|undefined} */ (
        this.get(PROJECTION)
      );
    }

    /**
     * @param {MouseEvent} event Browser event.
     * @protected
     */
    handleMouseMove(event) {
      const map = this.getMap();
      this.updateHTML_(map.getEventPixel(event));
    }

    /**
     * @param {Event} event Browser event.
     * @protected
     */
    handleMouseOut(event) {
      this.updateHTML_(null);
    }

    /**
     * Remove the control from its current map and attach it to the new map.
     * Pass `null` to just remove the control from the current map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     * @override
     */
    setMap(map) {
      super.setMap(map);
      if (map) {
        const viewport = map.getViewport();
        this.listenerKeys.push(
          listen(viewport, PointerEventType.POINTERMOVE, this.handleMouseMove, this),
        );
        if (this.renderOnMouseOut_) {
          this.listenerKeys.push(
            listen(viewport, PointerEventType.POINTEROUT, this.handleMouseOut, this),
          );
        }
        this.updateHTML_(null);
      }
    }

    /**
     * Set the coordinate format type used to render the current position.
     * @param {import("../coordinate.js").CoordinateFormat} format The format to render the current
     *     position in.
     * @observable
     * @api
     */
    setCoordinateFormat(format) {
      this.set(COORDINATE_FORMAT, format);
    }

    /**
     * Set the projection that is used to report the mouse position.
     * @param {import("../proj.js").ProjectionLike} projection The projection to report mouse
     *     position in.
     * @observable
     * @api
     */
    setProjection(projection) {
      this.set(PROJECTION, get$2(projection));
    }

    /**
     * @param {?import("../pixel.js").Pixel} pixel Pixel.
     * @private
     */
    updateHTML_(pixel) {
      let html = this.placeholder_;
      if (pixel && this.mapProjection_) {
        if (!this.transform_) {
          const projection = this.getProjection();
          if (projection) {
            this.transform_ = getTransformFromProjections(
              this.mapProjection_,
              projection,
            );
          } else {
            this.transform_ = identityTransform;
          }
        }
        const map = this.getMap();
        const coordinate = map.getCoordinateFromPixelInternal(pixel);
        if (coordinate) {
          const userProjection = getUserProjection();
          if (userProjection) {
            this.transform_ = getTransformFromProjections(
              this.mapProjection_,
              userProjection,
            );
          }
          this.transform_(coordinate, coordinate);
          if (this.wrapX_) {
            const projection =
              userProjection || this.getProjection() || this.mapProjection_;
            wrapX$1(coordinate, projection);
          }
          const coordinateFormat = this.getCoordinateFormat();
          if (coordinateFormat) {
            html = coordinateFormat(coordinate);
          } else {
            html = coordinate.toString();
          }
        }
      }
      if (!this.renderedHTML_ || html !== this.renderedHTML_) {
        this.element.innerHTML = html;
        this.renderedHTML_ = html;
      }
    }

    /**
     * Update the projection. Rendering of the coordinates is done in
     * `handleMouseMove` and `handleMouseUp`.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      const frameState = mapEvent.frameState;
      if (!frameState) {
        this.mapProjection_ = null;
      } else {
        if (this.mapProjection_ != frameState.viewState.projection) {
          this.mapProjection_ = frameState.viewState.projection;
          this.transform_ = null;
        }
      }
    }
  }

  /**
   * @module ol/control/OverviewMap
   */

  /**
   * Maximum width and/or height extent ratio that determines when the overview
   * map should be zoomed out.
   * @type {number}
   */
  const MAX_RATIO = 0.75;

  /**
   * Minimum width and/or height extent ratio that determines when the overview
   * map should be zoomed in.
   * @type {number}
   */
  const MIN_RATIO = 0.1;

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-overviewmap'] CSS class name.
   * @property {boolean} [collapsed=true] Whether the control should start collapsed or not (expanded).
   * @property {string|HTMLElement} [collapseLabel='‹'] Text label to use for the
   * expanded overviewmap button. Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {boolean} [collapsible=true] Whether the control can be collapsed or not.
   * @property {string|HTMLElement} [label='›'] Text label to use for the collapsed
   * overviewmap button. Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {Array<import("../layer/Base.js").default>|import("../Collection.js").default<import("../layer/Base.js").default>} [layers]
   * Layers for the overview map.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when the control
   * should be re-rendered. This is called in a `requestAnimationFrame` callback.
   * @property {boolean} [rotateWithView=false] Whether the control view should rotate with the main map view.
   * @property {HTMLElement|string} [target] Specify a target if you want the control
   * to be rendered outside of the map's viewport.
   * @property {string} [tipLabel='Overview map'] Text label to use for the button tip.
   * @property {View} [view] Custom view for the overview map (should use same projection as main map). If not provided,
   * a default view with the same projection as the main map will be used.
   */

  /**
   * Create a new control with a map acting as an overview map for another
   * defined map.
   *
   * @api
   */
  class OverviewMap extends Control {
    /**
     * @param {Options} [options] OverviewMap options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        render: options.render,
        target: options.target,
      });

      /**
       * @private
       */
      this.boundHandleRotationChanged_ = this.handleRotationChanged_.bind(this);

      /**
       * @type {boolean}
       * @private
       */
      this.collapsed_ =
        options.collapsed !== undefined ? options.collapsed : true;

      /**
       * @private
       * @type {boolean}
       */
      this.collapsible_ =
        options.collapsible !== undefined ? options.collapsible : true;

      if (!this.collapsible_) {
        this.collapsed_ = false;
      }

      /**
       * @private
       * @type {boolean}
       */
      this.rotateWithView_ =
        options.rotateWithView !== undefined ? options.rotateWithView : false;

      /**
       * @private
       * @type {import("../extent.js").Extent|undefined}
       */
      this.viewExtent_ = undefined;

      const className =
        options.className !== undefined ? options.className : 'ol-overviewmap';

      const tipLabel =
        options.tipLabel !== undefined ? options.tipLabel : 'Overview map';

      const collapseLabel =
        options.collapseLabel !== undefined ? options.collapseLabel : '\u2039';

      if (typeof collapseLabel === 'string') {
        /**
         * @private
         * @type {HTMLElement}
         */
        this.collapseLabel_ = document.createElement('span');
        this.collapseLabel_.textContent = collapseLabel;
      } else {
        this.collapseLabel_ = collapseLabel;
      }

      const label = options.label !== undefined ? options.label : '\u203A';

      if (typeof label === 'string') {
        /**
         * @private
         * @type {HTMLElement}
         */
        this.label_ = document.createElement('span');
        this.label_.textContent = label;
      } else {
        this.label_ = label;
      }

      const activeLabel =
        this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_;
      const button = document.createElement('button');
      button.setAttribute('type', 'button');
      button.title = tipLabel;
      button.appendChild(activeLabel);

      button.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this),
        false,
      );

      /**
       * @type {HTMLElement}
       * @private
       */
      this.ovmapDiv_ = document.createElement('div');
      this.ovmapDiv_.className = 'ol-overviewmap-map';

      /**
       * Explicitly given view to be used instead of a view derived from the main map.
       * @type {View}
       * @private
       */
      this.view_ = options.view;

      const ovmap = new Map$1({
        view: options.view,
        controls: new Collection(),
        interactions: new Collection(),
      });

      /**
       * @type {Map}
       * @private
       */
      this.ovmap_ = ovmap;

      if (options.layers) {
        options.layers.forEach(function (layer) {
          ovmap.addLayer(layer);
        });
      }

      const box = document.createElement('div');
      box.className = 'ol-overviewmap-box';
      box.style.boxSizing = 'border-box';

      /**
       * @type {import("../Overlay.js").default}
       * @private
       */
      this.boxOverlay_ = new Overlay({
        position: [0, 0],
        positioning: 'center-center',
        element: box,
      });
      this.ovmap_.addOverlay(this.boxOverlay_);

      const cssClasses =
        className +
        ' ' +
        CLASS_UNSELECTABLE +
        ' ' +
        CLASS_CONTROL +
        (this.collapsed_ && this.collapsible_ ? ' ' + CLASS_COLLAPSED : '') +
        (this.collapsible_ ? '' : ' ol-uncollapsible');
      const element = this.element;
      element.className = cssClasses;
      element.appendChild(this.ovmapDiv_);
      element.appendChild(button);

      /* Interactive map */

      const overlay = this.boxOverlay_;
      const overlayBox = this.boxOverlay_.getElement();

      /* Functions definition */

      const computeDesiredMousePosition = (mousePosition) => {
        return {
          clientX: mousePosition.clientX,
          clientY: mousePosition.clientY,
        };
      };

      const move = function (event) {
        const position = /** @type {?} */ (computeDesiredMousePosition(event));
        const coordinates = ovmap.getEventCoordinate(
          /** @type {MouseEvent} */ (position),
        );

        overlay.setPosition(coordinates);
      };

      const endMoving = (event) => {
        const coordinates = ovmap.getEventCoordinateInternal(event);

        const map = this.getMap();

        map.getView().setCenterInternal(coordinates);

        const ownerDocument = map.getOwnerDocument();
        ownerDocument.removeEventListener('pointermove', move);
        ownerDocument.removeEventListener('pointerup', endMoving);
      };

      /* Binding */

      this.ovmapDiv_.addEventListener('pointerdown', (event) => {
        const ownerDocument = this.getMap().getOwnerDocument();
        if (event.target === overlayBox) {
          ownerDocument.addEventListener('pointermove', move);
        }
        ownerDocument.addEventListener('pointerup', endMoving);
      });
    }

    /**
     * Remove the control from its current map and attach it to the new map.
     * Pass `null` to just remove the control from the current map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     * @override
     */
    setMap(map) {
      const oldMap = this.getMap();
      if (map === oldMap) {
        return;
      }
      if (oldMap) {
        const oldView = oldMap.getView();
        if (oldView) {
          this.unbindView_(oldView);
        }
        this.ovmap_.setTarget(null);
      }
      super.setMap(map);

      if (map) {
        this.ovmap_.setTarget(this.ovmapDiv_);
        this.listenerKeys.push(
          listen(
            map,
            ObjectEventType.PROPERTYCHANGE,
            this.handleMapPropertyChange_,
            this,
          ),
        );

        const view = map.getView();
        if (view) {
          this.bindView_(view);
        }

        if (!this.ovmap_.isRendered()) {
          this.updateBoxAfterOvmapIsRendered_();
        }
      }
    }

    /**
     * Handle map property changes.  This only deals with changes to the map's view.
     * @param {import("../Object.js").ObjectEvent} event The propertychange event.
     * @private
     */
    handleMapPropertyChange_(event) {
      if (event.key === MapProperty.VIEW) {
        const oldView = /** @type {import("../View.js").default} */ (
          event.oldValue
        );
        if (oldView) {
          this.unbindView_(oldView);
        }
        const newView = this.getMap().getView();
        this.bindView_(newView);
      } else if (
        !this.ovmap_.isRendered() &&
        (event.key === MapProperty.TARGET || event.key === MapProperty.SIZE)
      ) {
        this.ovmap_.updateSize();
      }
    }

    /**
     * Register listeners for view property changes.
     * @param {import("../View.js").default} view The view.
     * @private
     */
    bindView_(view) {
      if (!this.view_) {
        // Unless an explicit view definition was given, derive default from whatever main map uses.
        const newView = new View({
          projection: view.getProjection(),
        });
        this.ovmap_.setView(newView);
      }

      view.addChangeListener(
        ViewProperty.ROTATION,
        this.boundHandleRotationChanged_,
      );
      // Sync once with the new view
      this.handleRotationChanged_();

      if (view.isDef()) {
        this.ovmap_.updateSize();
        this.resetExtent_();
      }
    }

    /**
     * Unregister listeners for view property changes.
     * @param {import("../View.js").default} view The view.
     * @private
     */
    unbindView_(view) {
      view.removeChangeListener(
        ViewProperty.ROTATION,
        this.boundHandleRotationChanged_,
      );
    }

    /**
     * Handle rotation changes to the main map.
     * @private
     */
    handleRotationChanged_() {
      if (this.rotateWithView_) {
        this.ovmap_.getView().setRotation(this.getMap().getView().getRotation());
      }
    }

    /**
     * Reset the overview map extent if the box size (width or
     * height) is less than the size of the overview map size times minRatio
     * or is greater than the size of the overview size times maxRatio.
     *
     * If the map extent was not reset, the box size can fits in the defined
     * ratio sizes. This method then checks if is contained inside the overview
     * map current extent. If not, recenter the overview map to the current
     * main map center location.
     * @private
     */
    validateExtent_() {
      const map = this.getMap();
      const ovmap = this.ovmap_;

      if (!map.isRendered() || !ovmap.isRendered()) {
        return;
      }

      const mapSize = /** @type {import("../size.js").Size} */ (map.getSize());

      const view = map.getView();
      const extent = view.calculateExtentInternal(mapSize);

      if (this.viewExtent_ && equals$1(extent, this.viewExtent_)) {
        // repeats of the same extent may indicate constraint conflicts leading to an endless cycle
        return;
      }
      this.viewExtent_ = extent;

      const ovmapSize = /** @type {import("../size.js").Size} */ (
        ovmap.getSize()
      );

      const ovview = ovmap.getView();
      const ovextent = ovview.calculateExtentInternal(ovmapSize);

      const topLeftPixel = ovmap.getPixelFromCoordinateInternal(
        getTopLeft(extent),
      );
      const bottomRightPixel = ovmap.getPixelFromCoordinateInternal(
        getBottomRight(extent),
      );

      const boxWidth = Math.abs(topLeftPixel[0] - bottomRightPixel[0]);
      const boxHeight = Math.abs(topLeftPixel[1] - bottomRightPixel[1]);

      const ovmapWidth = ovmapSize[0];
      const ovmapHeight = ovmapSize[1];

      if (
        boxWidth < ovmapWidth * MIN_RATIO ||
        boxHeight < ovmapHeight * MIN_RATIO ||
        boxWidth > ovmapWidth * MAX_RATIO ||
        boxHeight > ovmapHeight * MAX_RATIO
      ) {
        this.resetExtent_();
      } else if (!containsExtent(ovextent, extent)) {
        this.recenter_();
      }
    }

    /**
     * Reset the overview map extent to half calculated min and max ratio times
     * the extent of the main map.
     * @private
     */
    resetExtent_() {

      const map = this.getMap();
      const ovmap = this.ovmap_;

      const mapSize = /** @type {import("../size.js").Size} */ (map.getSize());

      const view = map.getView();
      const extent = view.calculateExtentInternal(mapSize);

      const ovview = ovmap.getView();

      // get how many times the current map overview could hold different
      // box sizes using the min and max ratio, pick the step in the middle used
      // to calculate the extent from the main map to set it to the overview map,
      const steps = Math.log(MAX_RATIO / MIN_RATIO) / Math.LN2;
      const ratio = 1 / (Math.pow(2, steps / 2) * MIN_RATIO);
      scaleFromCenter(extent, ratio);
      ovview.fitInternal(fromExtent(extent));
    }

    /**
     * Set the center of the overview map to the map center without changing its
     * resolution.
     * @private
     */
    recenter_() {
      const map = this.getMap();
      const ovmap = this.ovmap_;

      const view = map.getView();

      const ovview = ovmap.getView();

      ovview.setCenterInternal(view.getCenterInternal());
    }

    /**
     * Update the box using the main map extent
     * @private
     */
    updateBox_() {
      const map = this.getMap();
      const ovmap = this.ovmap_;

      if (!map.isRendered() || !ovmap.isRendered()) {
        return;
      }

      const mapSize = /** @type {import("../size.js").Size} */ (map.getSize());

      const view = map.getView();

      const ovview = ovmap.getView();

      const rotation = this.rotateWithView_ ? 0 : -view.getRotation();

      const overlay = this.boxOverlay_;
      const box = this.boxOverlay_.getElement();
      const center = view.getCenter();
      const resolution = view.getResolution();
      const ovresolution = ovview.getResolution();
      const width = (mapSize[0] * resolution) / ovresolution;
      const height = (mapSize[1] * resolution) / ovresolution;

      // set position using center coordinates
      overlay.setPosition(center);

      // set box size calculated from map extent size and overview map resolution
      if (box) {
        box.style.width = width + 'px';
        box.style.height = height + 'px';
        const transform = 'rotate(' + rotation + 'rad)';
        box.style.transform = transform;
      }
    }

    /**
     * @private
     */
    updateBoxAfterOvmapIsRendered_() {
      if (this.ovmapPostrenderKey_) {
        return;
      }
      this.ovmapPostrenderKey_ = listenOnce(
        this.ovmap_,
        MapEventType.POSTRENDER,
        (event) => {
          delete this.ovmapPostrenderKey_;
          this.updateBox_();
        },
      );
    }

    /**
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(event) {
      event.preventDefault();
      this.handleToggle_();
    }

    /**
     * @private
     */
    handleToggle_() {
      this.element.classList.toggle(CLASS_COLLAPSED);
      if (this.collapsed_) {
        replaceNode(this.collapseLabel_, this.label_);
      } else {
        replaceNode(this.label_, this.collapseLabel_);
      }
      this.collapsed_ = !this.collapsed_;

      // manage overview map if it had not been rendered before and control
      // is expanded
      const ovmap = this.ovmap_;
      if (!this.collapsed_) {
        if (ovmap.isRendered()) {
          this.viewExtent_ = undefined;
          ovmap.render();
          return;
        }
        ovmap.updateSize();
        this.resetExtent_();
        this.updateBoxAfterOvmapIsRendered_();
      }
    }

    /**
     * Return `true` if the overview map is collapsible, `false` otherwise.
     * @return {boolean} True if the widget is collapsible.
     * @api
     */
    getCollapsible() {
      return this.collapsible_;
    }

    /**
     * Set whether the overview map should be collapsible.
     * @param {boolean} collapsible True if the widget is collapsible.
     * @api
     */
    setCollapsible(collapsible) {
      if (this.collapsible_ === collapsible) {
        return;
      }
      this.collapsible_ = collapsible;
      this.element.classList.toggle('ol-uncollapsible');
      if (!collapsible && this.collapsed_) {
        this.handleToggle_();
      }
    }

    /**
     * Collapse or expand the overview map according to the passed parameter. Will
     * not do anything if the overview map isn't collapsible or if the current
     * collapsed state is already the one requested.
     * @param {boolean} collapsed True if the widget is collapsed.
     * @api
     */
    setCollapsed(collapsed) {
      if (!this.collapsible_ || this.collapsed_ === collapsed) {
        return;
      }
      this.handleToggle_();
    }

    /**
     * Determine if the overview map is collapsed.
     * @return {boolean} The overview map is collapsed.
     * @api
     */
    getCollapsed() {
      return this.collapsed_;
    }

    /**
     * Return `true` if the overview map view can rotate, `false` otherwise.
     * @return {boolean} True if the control view can rotate.
     * @api
     */
    getRotateWithView() {
      return this.rotateWithView_;
    }

    /**
     * Set whether the overview map view should rotate with the main map view.
     * @param {boolean} rotateWithView True if the control view should rotate.
     * @api
     */
    setRotateWithView(rotateWithView) {
      if (this.rotateWithView_ === rotateWithView) {
        return;
      }
      this.rotateWithView_ = rotateWithView;
      if (this.getMap().getView().getRotation() !== 0) {
        if (this.rotateWithView_) {
          this.handleRotationChanged_();
        } else {
          this.ovmap_.getView().setRotation(0);
        }
        this.viewExtent_ = undefined;
        this.validateExtent_();
        this.updateBox_();
      }
    }

    /**
     * Return the overview map.
     * @return {import("../Map.js").default} Overview map.
     * @api
     */
    getOverviewMap() {
      return this.ovmap_;
    }

    /**
     * Update the overview map element.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      this.validateExtent_();
      this.updateBox_();
    }
  }

  /**
   * @module ol/control/ScaleLine
   */

  /**
   * @type {string}
   */
  const UNITS_PROP = 'units';

  /**
   * @typedef {'degrees' | 'imperial' | 'nautical' | 'metric' | 'us'} Units
   * Units for the scale line.
   */

  /**
   * @const
   * @type {Array<number>}
   */
  const LEADING_DIGITS = [1, 2, 5];

  /**
   * @const
   * @type {number}
   */
  const DEFAULT_DPI = 25.4 / 0.28;

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:units', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types
   *     |'change:units', Return>} ScaleLineOnSignature
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className] CSS class name. The default is `ol-scale-bar` when configured with
   * `bar: true`. Otherwise the default is `ol-scale-line`.
   * @property {number} [minWidth=64] Minimum width in pixels at the OGC default dpi. The width will be
   * adjusted to match the dpi used.
   * @property {number} [maxWidth] Maximum width in pixels at the OGC default dpi. The width will be
   * adjusted to match the dpi used.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when the control
   * should be re-rendered. This is called in a `requestAnimationFrame` callback.
   * @property {HTMLElement|string} [target] Specify a target if you want the control
   * to be rendered outside of the map's viewport.
   * @property {Units} [units='metric'] Units.
   * @property {boolean} [bar=false] Render scalebars instead of a line.
   * @property {number} [steps=4] Number of steps the scalebar should use. Use even numbers
   * for best results. Only applies when `bar` is `true`.
   * @property {boolean} [text=false] Render the text scale above of the scalebar. Only applies
   * when `bar` is `true`.
   * @property {number|undefined} [dpi=undefined] dpi of output device such as printer. Only applies
   * when `bar` is `true`. If undefined the OGC default screen pixel size of 0.28mm will be assumed.
   */

  /**
   * @classdesc
   * A control displaying rough y-axis distances, calculated for the center of the
   * viewport. For conformal projections (e.g. EPSG:3857, the default view
   * projection in OpenLayers), the scale is valid for all directions.
   * No scale line will be shown when the y-axis distance of a pixel at the
   * viewport center cannot be calculated in the view projection.
   * By default the scale line will show in the bottom left portion of the map,
   * but this can be changed by using the css selector `.ol-scale-line`.
   * When specifying `bar` as `true`, a scalebar will be rendered instead
   * of a scaleline.
   * For cartesian measurements of the scaleline, you need to set the
   * `getPointResolution` method of your projection to simply return the input
   * value, e.g. `projection.setGetPointResolution(r => r);`
   *
   * @api
   */
  class ScaleLine extends Control {
    /**
     * @param {Options} [options] Scale line options.
     */
    constructor(options) {
      options = options ? options : {};

      const element = document.createElement('div');
      element.style.pointerEvents = 'none';

      super({
        element: element,
        render: options.render,
        target: options.target,
      });

      /***
       * @type {ScaleLineOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {ScaleLineOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {ScaleLineOnSignature<void>}
       */
      this.un;

      const className =
        options.className !== undefined
          ? options.className
          : options.bar
            ? 'ol-scale-bar'
            : 'ol-scale-line';

      /**
       * @private
       * @type {HTMLElement}
       */
      this.innerElement_ = document.createElement('div');
      this.innerElement_.className = className + '-inner';

      this.element.className = className + ' ' + CLASS_UNSELECTABLE;
      this.element.appendChild(this.innerElement_);

      /**
       * @private
       * @type {?import("../View.js").State}
       */
      this.viewState_ = null;

      /**
       * @private
       * @type {number}
       */
      this.minWidth_ = options.minWidth !== undefined ? options.minWidth : 64;

      /**
       * @private
       * @type {number|undefined}
       */
      this.maxWidth_ = options.maxWidth;

      /**
       * @private
       * @type {boolean}
       */
      this.renderedVisible_ = false;

      /**
       * @private
       * @type {number|undefined}
       */
      this.renderedWidth_ = undefined;

      /**
       * @private
       * @type {string}
       */
      this.renderedHTML_ = '';

      this.addChangeListener(UNITS_PROP, this.handleUnitsChanged_);

      this.setUnits(options.units || 'metric');

      /**
       * @private
       * @type {boolean}
       */
      this.scaleBar_ = options.bar || false;

      /**
       * @private
       * @type {number}
       */
      this.scaleBarSteps_ = options.steps || 4;

      /**
       * @private
       * @type {boolean}
       */
      this.scaleBarText_ = options.text || false;

      /**
       * @private
       * @type {number|undefined}
       */
      this.dpi_ = options.dpi || undefined;
    }

    /**
     * Return the units to use in the scale line.
     * @return {Units} The units
     * to use in the scale line.
     * @observable
     * @api
     */
    getUnits() {
      return this.get(UNITS_PROP);
    }

    /**
     * @private
     */
    handleUnitsChanged_() {
      this.updateElement_();
    }

    /**
     * Set the units to use in the scale line.
     * @param {Units} units The units to use in the scale line.
     * @observable
     * @api
     */
    setUnits(units) {
      this.set(UNITS_PROP, units);
    }

    /**
     * Specify the dpi of output device such as printer.
     * @param {number|undefined} dpi The dpi of output device.
     * @api
     */
    setDpi(dpi) {
      this.dpi_ = dpi;
    }

    /**
     * @private
     */
    updateElement_() {
      const viewState = this.viewState_;

      if (!viewState) {
        if (this.renderedVisible_) {
          this.element.style.display = 'none';
          this.renderedVisible_ = false;
        }
        return;
      }

      const center = viewState.center;
      const projection = viewState.projection;
      const units = this.getUnits();
      const pointResolutionUnits = units == 'degrees' ? 'degrees' : 'm';
      let pointResolution = getPointResolution(
        projection,
        viewState.resolution,
        center,
        pointResolutionUnits,
      );

      const minWidth =
        (this.minWidth_ * (this.dpi_ || DEFAULT_DPI)) / DEFAULT_DPI;

      const maxWidth =
        this.maxWidth_ !== undefined
          ? (this.maxWidth_ * (this.dpi_ || DEFAULT_DPI)) / DEFAULT_DPI
          : undefined;

      let nominalCount = minWidth * pointResolution;
      let suffix = '';
      if (units == 'degrees') {
        const metersPerDegree = METERS_PER_UNIT$1.degrees;
        nominalCount *= metersPerDegree;
        if (nominalCount < metersPerDegree / 60) {
          suffix = '\u2033'; // seconds
          pointResolution *= 3600;
        } else if (nominalCount < metersPerDegree) {
          suffix = '\u2032'; // minutes
          pointResolution *= 60;
        } else {
          suffix = '\u00b0'; // degrees
        }
      } else if (units == 'imperial') {
        if (nominalCount < 0.9144) {
          suffix = 'in';
          pointResolution /= 0.0254;
        } else if (nominalCount < 1609.344) {
          suffix = 'ft';
          pointResolution /= 0.3048;
        } else {
          suffix = 'mi';
          pointResolution /= 1609.344;
        }
      } else if (units == 'nautical') {
        pointResolution /= 1852;
        suffix = 'NM';
      } else if (units == 'metric') {
        if (nominalCount < 1e-6) {
          suffix = 'nm';
          pointResolution *= 1e9;
        } else if (nominalCount < 0.001) {
          suffix = 'μm';
          pointResolution *= 1000000;
        } else if (nominalCount < 1) {
          suffix = 'mm';
          pointResolution *= 1000;
        } else if (nominalCount < 1000) {
          suffix = 'm';
        } else {
          suffix = 'km';
          pointResolution /= 1000;
        }
      } else if (units == 'us') {
        if (nominalCount < 0.9144) {
          suffix = 'in';
          pointResolution *= 39.37;
        } else if (nominalCount < 1609.344) {
          suffix = 'ft';
          pointResolution /= 0.30480061;
        } else {
          suffix = 'mi';
          pointResolution /= 1609.3472;
        }
      } else {
        throw new Error('Invalid units');
      }

      let i = 3 * Math.floor(Math.log(minWidth * pointResolution) / Math.log(10));
      let count, width, decimalCount;
      let previousCount = 0;
      let previousWidth, previousDecimalCount;
      while (true) {
        decimalCount = Math.floor(i / 3);
        const decimal = Math.pow(10, decimalCount);
        count = LEADING_DIGITS[((i % 3) + 3) % 3] * decimal;
        width = Math.round(count / pointResolution);
        if (isNaN(width)) {
          this.element.style.display = 'none';
          this.renderedVisible_ = false;
          return;
        }
        if (maxWidth !== undefined && width >= maxWidth) {
          count = previousCount;
          width = previousWidth;
          decimalCount = previousDecimalCount;
          break;
        } else if (width >= minWidth) {
          break;
        }
        previousCount = count;
        previousWidth = width;
        previousDecimalCount = decimalCount;
        ++i;
      }
      const html = this.scaleBar_
        ? this.createScaleBar(width, count, suffix)
        : count.toFixed(decimalCount < 0 ? -decimalCount : 0) + ' ' + suffix;

      if (this.renderedHTML_ != html) {
        this.innerElement_.innerHTML = html;
        this.renderedHTML_ = html;
      }

      if (this.renderedWidth_ != width) {
        this.innerElement_.style.width = width + 'px';
        this.renderedWidth_ = width;
      }

      if (!this.renderedVisible_) {
        this.element.style.display = '';
        this.renderedVisible_ = true;
      }
    }

    /**
     * @private
     * @param {number} width The current width of the scalebar.
     * @param {number} scale The current scale.
     * @param {string} suffix The suffix to append to the scale text.
     * @return {string} The stringified HTML of the scalebar.
     */
    createScaleBar(width, scale, suffix) {
      const resolutionScale = this.getScaleForResolution();
      const mapScale =
        resolutionScale < 1
          ? Math.round(1 / resolutionScale).toLocaleString() + ' : 1'
          : '1 : ' + Math.round(resolutionScale).toLocaleString();
      const steps = this.scaleBarSteps_;
      const stepWidth = width / steps;
      const scaleSteps = [this.createMarker('absolute')];
      for (let i = 0; i < steps; ++i) {
        const cls =
          i % 2 === 0 ? 'ol-scale-singlebar-odd' : 'ol-scale-singlebar-even';
        scaleSteps.push(
          '<div>' +
            '<div ' +
            `class="ol-scale-singlebar ${cls}" ` +
            `style="width: ${stepWidth}px;"` +
            '>' +
            '</div>' +
            this.createMarker('relative') +
            // render text every second step, except when only 2 steps
            (i % 2 === 0 || steps === 2
              ? this.createStepText(i, width, false, scale, suffix)
              : '') +
            '</div>',
        );
      }
      // render text at the end
      scaleSteps.push(this.createStepText(steps, width, true, scale, suffix));

      const scaleBarText = this.scaleBarText_
        ? `<div class="ol-scale-text" style="width: ${width}px;">` +
          mapScale +
          '</div>'
        : '';
      return scaleBarText + scaleSteps.join('');
    }

    /**
     * Creates a marker at given position
     * @param {'absolute'|'relative'} position The position, absolute or relative
     * @return {string} The stringified div containing the marker
     */
    createMarker(position) {
      const top = position === 'absolute' ? 3 : -10;
      return (
        '<div ' +
        'class="ol-scale-step-marker" ' +
        `style="position: ${position}; top: ${top}px;"` +
        '></div>'
      );
    }

    /**
     * Creates the label for a marker marker at given position
     * @param {number} i The iterator
     * @param {number} width The width the scalebar will currently use
     * @param {boolean} isLast Flag indicating if we add the last step text
     * @param {number} scale The current scale for the whole scalebar
     * @param {string} suffix The suffix for the scale
     * @return {string} The stringified div containing the step text
     */
    createStepText(i, width, isLast, scale, suffix) {
      const length =
        i === 0 ? 0 : Math.round((scale / this.scaleBarSteps_) * i * 100) / 100;
      const lengthString = length + (i === 0 ? '' : ' ' + suffix);
      const margin = i === 0 ? -3 : (width / this.scaleBarSteps_) * -1;
      const minWidth = i === 0 ? 0 : (width / this.scaleBarSteps_) * 2;
      return (
        '<div ' +
        'class="ol-scale-step-text" ' +
        'style="' +
        `margin-left: ${margin}px;` +
        `text-align: ${i === 0 ? 'left' : 'center'};` +
        `min-width: ${minWidth}px;` +
        `left: ${isLast ? width + 'px' : 'unset'};` +
        '">' +
        lengthString +
        '</div>'
      );
    }

    /**
     * Returns the appropriate scale for the given resolution and units.
     * @return {number} The appropriate scale.
     */
    getScaleForResolution() {
      const resolution = getPointResolution(
        this.viewState_.projection,
        this.viewState_.resolution,
        this.viewState_.center,
        'm',
      );
      const dpi = this.dpi_ || DEFAULT_DPI;
      const inchesPerMeter = 1000 / 25.4;
      return resolution * inchesPerMeter * dpi;
    }

    /**
     * Update the scale line element.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      const frameState = mapEvent.frameState;
      if (!frameState) {
        this.viewState_ = null;
      } else {
        this.viewState_ = frameState.viewState;
      }
      this.updateElement_();
    }
  }

  /**
   * @module ol/control/ZoomSlider
   */


  /**
   * The enum for available directions.
   *
   * @enum {number}
   */
  const Direction = {
    VERTICAL: 0,
    HORIZONTAL: 1,
  };

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-zoomslider'] CSS class name.
   * @property {number} [duration=200] Animation duration in milliseconds.
   * @property {function(import("../MapEvent.js").default):void} [render] Function called when the control
   * should be re-rendered. This is called in a `requestAnimationFrame` callback.
   * @property {HTMLElement|string} [target] Specify a target if you want the control to be
   * rendered outside of the map's viewport.
   */

  /**
   * @classdesc
   * A slider type of control for zooming.
   *
   * Example:
   *
   *     map.addControl(new ZoomSlider());
   *
   * @api
   */
  class ZoomSlider extends Control {
    /**
     * @param {Options} [options] Zoom slider options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        target: options.target,
        element: document.createElement('div'),
        render: options.render,
      });

      /**
       * @type {!Array<import("../events.js").EventsKey>}
       * @private
       */
      this.dragListenerKeys_ = [];

      /**
       * Will hold the current resolution of the view.
       *
       * @type {number|undefined}
       * @private
       */
      this.currentResolution_ = undefined;

      /**
       * The direction of the slider. Will be determined from actual display of the
       * container and defaults to Direction.VERTICAL.
       *
       * @type {Direction}
       * @private
       */
      this.direction_ = Direction.VERTICAL;

      /**
       * @type {boolean}
       * @private
       */
      this.dragging_;

      /**
       * @type {number}
       * @private
       */
      this.heightLimit_ = 0;

      /**
       * @type {number}
       * @private
       */
      this.widthLimit_ = 0;

      /**
       * @type {number|undefined}
       * @private
       */
      this.startX_;

      /**
       * @type {number|undefined}
       * @private
       */
      this.startY_;

      /**
       * The calculated thumb size (border box plus margins).  Set when initSlider_
       * is called.
       * @type {import("../size.js").Size}
       * @private
       */
      this.thumbSize_ = null;

      /**
       * Whether the slider is initialized.
       * @type {boolean}
       * @private
       */
      this.sliderInitialized_ = false;

      /**
       * @type {number}
       * @private
       */
      this.duration_ = options.duration !== undefined ? options.duration : 200;

      const className =
        options.className !== undefined ? options.className : 'ol-zoomslider';
      const thumbElement = document.createElement('button');
      thumbElement.setAttribute('type', 'button');
      thumbElement.className = className + '-thumb ' + CLASS_UNSELECTABLE;
      const containerElement = this.element;
      containerElement.className =
        className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
      containerElement.appendChild(thumbElement);

      containerElement.addEventListener(
        PointerEventType.POINTERDOWN,
        this.handleDraggerStart_.bind(this),
        false,
      );
      containerElement.addEventListener(
        PointerEventType.POINTERMOVE,
        this.handleDraggerDrag_.bind(this),
        false,
      );
      containerElement.addEventListener(
        PointerEventType.POINTERUP,
        this.handleDraggerEnd_.bind(this),
        false,
      );

      containerElement.addEventListener(
        EventType.CLICK,
        this.handleContainerClick_.bind(this),
        false,
      );
      thumbElement.addEventListener(EventType.CLICK, stopPropagation, false);
    }

    /**
     * Remove the control from its current map and attach it to the new map.
     * Pass `null` to just remove the control from the current map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     * @override
     */
    setMap(map) {
      super.setMap(map);
      if (map) {
        map.render();
      }
    }

    /**
     * Initializes the slider element. This will determine and set this controls
     * direction_ and also constrain the dragging of the thumb to always be within
     * the bounds of the container.
     *
     * @return {boolean} Initialization successful
     * @private
     */
    initSlider_() {
      const container = this.element;
      let containerWidth = container.offsetWidth;
      let containerHeight = container.offsetHeight;
      if (containerWidth === 0 && containerHeight === 0) {
        return (this.sliderInitialized_ = false);
      }

      const containerStyle = getComputedStyle(container);
      containerWidth -=
        parseFloat(containerStyle['paddingRight']) +
        parseFloat(containerStyle['paddingLeft']);
      containerHeight -=
        parseFloat(containerStyle['paddingTop']) +
        parseFloat(containerStyle['paddingBottom']);
      const thumb = /** @type {HTMLElement} */ (container.firstElementChild);
      const thumbStyle = getComputedStyle(thumb);
      const thumbWidth =
        thumb.offsetWidth +
        parseFloat(thumbStyle['marginRight']) +
        parseFloat(thumbStyle['marginLeft']);
      const thumbHeight =
        thumb.offsetHeight +
        parseFloat(thumbStyle['marginTop']) +
        parseFloat(thumbStyle['marginBottom']);
      this.thumbSize_ = [thumbWidth, thumbHeight];

      if (containerWidth > containerHeight) {
        this.direction_ = Direction.HORIZONTAL;
        this.widthLimit_ = containerWidth - thumbWidth;
      } else {
        this.direction_ = Direction.VERTICAL;
        this.heightLimit_ = containerHeight - thumbHeight;
      }
      return (this.sliderInitialized_ = true);
    }

    /**
     * @param {PointerEvent} event The browser event to handle.
     * @private
     */
    handleContainerClick_(event) {
      const view = this.getMap().getView();

      const relativePosition = this.getRelativePosition_(
        event.offsetX - this.thumbSize_[0] / 2,
        event.offsetY - this.thumbSize_[1] / 2,
      );

      const resolution = this.getResolutionForPosition_(relativePosition);
      const zoom = view.getConstrainedZoom(view.getZoomForResolution(resolution));

      view.animateInternal({
        zoom: zoom,
        duration: this.duration_,
        easing: easeOut,
      });
    }

    /**
     * Handle dragger start events.
     * @param {PointerEvent} event The drag event.
     * @private
     */
    handleDraggerStart_(event) {
      if (!this.dragging_ && event.target === this.element.firstElementChild) {
        const element = /** @type {HTMLElement} */ (
          this.element.firstElementChild
        );
        this.getMap().getView().beginInteraction();
        this.startX_ = event.clientX - parseFloat(element.style.left);
        this.startY_ = event.clientY - parseFloat(element.style.top);
        this.dragging_ = true;

        if (this.dragListenerKeys_.length === 0) {
          const drag = this.handleDraggerDrag_;
          const end = this.handleDraggerEnd_;
          const doc = this.getMap().getOwnerDocument();
          this.dragListenerKeys_.push(
            listen(doc, PointerEventType.POINTERMOVE, drag, this),
            listen(doc, PointerEventType.POINTERUP, end, this),
          );
        }
      }
    }

    /**
     * Handle dragger drag events.
     *
     * @param {PointerEvent} event The drag event.
     * @private
     */
    handleDraggerDrag_(event) {
      if (this.dragging_) {
        const deltaX = event.clientX - this.startX_;
        const deltaY = event.clientY - this.startY_;
        const relativePosition = this.getRelativePosition_(deltaX, deltaY);
        this.currentResolution_ =
          this.getResolutionForPosition_(relativePosition);
        this.getMap().getView().setResolution(this.currentResolution_);
      }
    }

    /**
     * Handle dragger end events.
     * @param {PointerEvent} event The drag event.
     * @private
     */
    handleDraggerEnd_(event) {
      if (this.dragging_) {
        const view = this.getMap().getView();
        view.endInteraction();

        this.dragging_ = false;
        this.startX_ = undefined;
        this.startY_ = undefined;
        this.dragListenerKeys_.forEach(unlistenByKey);
        this.dragListenerKeys_.length = 0;
      }
    }

    /**
     * Positions the thumb inside its container according to the given resolution.
     *
     * @param {number} res The res.
     * @private
     */
    setThumbPosition_(res) {
      const position = this.getPositionForResolution_(res);
      const thumb = /** @type {HTMLElement} */ (this.element.firstElementChild);

      if (this.direction_ == Direction.HORIZONTAL) {
        thumb.style.left = this.widthLimit_ * position + 'px';
      } else {
        thumb.style.top = this.heightLimit_ * position + 'px';
      }
    }

    /**
     * Calculates the relative position of the thumb given x and y offsets.  The
     * relative position scales from 0 to 1.  The x and y offsets are assumed to be
     * in pixel units within the dragger limits.
     *
     * @param {number} x Pixel position relative to the left of the slider.
     * @param {number} y Pixel position relative to the top of the slider.
     * @return {number} The relative position of the thumb.
     * @private
     */
    getRelativePosition_(x, y) {
      let amount;
      if (this.direction_ === Direction.HORIZONTAL) {
        amount = x / this.widthLimit_;
      } else {
        amount = y / this.heightLimit_;
      }
      return clamp$1(amount, 0, 1);
    }

    /**
     * Calculates the corresponding resolution of the thumb given its relative
     * position (where 0 is the minimum and 1 is the maximum).
     *
     * @param {number} position The relative position of the thumb.
     * @return {number} The corresponding resolution.
     * @private
     */
    getResolutionForPosition_(position) {
      const fn = this.getMap().getView().getResolutionForValueFunction();
      return fn(1 - position);
    }

    /**
     * Determines the relative position of the slider for the given resolution.  A
     * relative position of 0 corresponds to the minimum view resolution.  A
     * relative position of 1 corresponds to the maximum view resolution.
     *
     * @param {number} res The resolution.
     * @return {number} The relative position value (between 0 and 1).
     * @private
     */
    getPositionForResolution_(res) {
      const fn = this.getMap().getView().getValueForResolutionFunction();
      return clamp$1(1 - fn(res), 0, 1);
    }

    /**
     * Update the zoomslider element.
     * @param {import("../MapEvent.js").default} mapEvent Map event.
     * @override
     */
    render(mapEvent) {
      if (!mapEvent.frameState) {
        return;
      }
      if (!this.sliderInitialized_ && !this.initSlider_()) {
        return;
      }
      const res = mapEvent.frameState.viewState.resolution;
      this.currentResolution_ = res;
      this.setThumbPosition_(res);
    }
  }

  /**
   * @module ol/control/ZoomToExtent
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-zoom-extent'] Class name.
   * @property {HTMLElement|string} [target] Specify a target if you want the control
   * to be rendered outside of the map's viewport.
   * @property {string|HTMLElement} [label='E'] Text label to use for the button.
   * Instead of text, also an element (e.g. a `span` element) can be used.
   * @property {string} [tipLabel='Fit to extent'] Text label to use for the button tip.
   * @property {import("../extent.js").Extent} [extent] The extent to zoom to. If undefined the validity
   * extent of the view projection is used.
   */

  /**
   * @classdesc
   * A button control which, when pressed, changes the map view to a specific
   * extent. To style this control use the css selector `.ol-zoom-extent`.
   *
   * @api
   */
  class ZoomToExtent extends Control {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        element: document.createElement('div'),
        target: options.target,
      });

      /**
       * @type {?import("../extent.js").Extent|null}
       * @protected
       */
      this.extent = options.extent ? options.extent : null;

      const className =
        options.className !== undefined ? options.className : 'ol-zoom-extent';

      const label = options.label !== undefined ? options.label : 'E';
      const tipLabel =
        options.tipLabel !== undefined ? options.tipLabel : 'Fit to extent';
      const button = document.createElement('button');
      button.setAttribute('type', 'button');
      button.title = tipLabel;
      button.appendChild(
        typeof label === 'string' ? document.createTextNode(label) : label,
      );

      button.addEventListener(
        EventType.CLICK,
        this.handleClick_.bind(this),
        false,
      );

      const cssClasses =
        className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;
      const element = this.element;
      element.className = cssClasses;
      element.appendChild(button);
    }

    /**
     * @param {MouseEvent} event The event to handle
     * @private
     */
    handleClick_(event) {
      event.preventDefault();
      this.handleZoomToExtent();
    }

    /**
     * @protected
     */
    handleZoomToExtent() {
      const map = this.getMap();
      const view = map.getView();
      const extent = !this.extent
        ? view.getProjection().getExtent()
        : fromUserExtent(this.extent, view.getProjection());
      view.fitInternal(fromExtent(extent));
    }
  }

  /**
   * @module ol/control
   */

  var nsControl = {
    __proto__: null,
    Attribution: Attribution,
    Control: Control,
    FullScreen: FullScreen,
    MousePosition: MousePosition,
    OverviewMap: OverviewMap,
    Rotate: Rotate,
    ScaleLine: ScaleLine,
    Zoom: Zoom,
    ZoomSlider: ZoomSlider,
    ZoomToExtent: ZoomToExtent,
    defaults: defaults$1
  };

  /**
   * @module ol/format/EsriJSON
   */

  /**
   * @typedef {import("arcgis-rest-api").Feature} EsriJSONFeature
   * @typedef {import("arcgis-rest-api").FeatureSet} EsriJSONFeatureSet
   * @typedef {import("arcgis-rest-api").Geometry} EsriJSONGeometry
   * @typedef {import("arcgis-rest-api").Point} EsriJSONPoint
   * @typedef {import("arcgis-rest-api").Polyline} EsriJSONPolyline
   * @typedef {import("arcgis-rest-api").Polygon} EsriJSONPolygon
   * @typedef {import("arcgis-rest-api").Multipoint} EsriJSONMultipoint
   * @typedef {import("arcgis-rest-api").HasZM} EsriJSONHasZM
   * @typedef {import("arcgis-rest-api").Position} EsriJSONPosition
   * @typedef {import("arcgis-rest-api").SpatialReferenceWkid} EsriJSONSpatialReferenceWkid
   */

  /**
   * @typedef {Object} EsriJSONMultiPolygon
   * @property {Array<Array<Array<Array<number>>>>} rings Rings for the MultiPolygon.
   * @property {boolean} [hasM] If the polygon coordinates have an M value.
   * @property {boolean} [hasZ] If the polygon coordinates have a Z value.
   * @property {EsriJSONSpatialReferenceWkid} [spatialReference] The coordinate reference system.
   */

  /**
   * @const
   * @type {Object<import("../geom/Geometry.js").Type, function(EsriJSONGeometry): import("../geom/Geometry.js").default>}
   */
  const GEOMETRY_READERS$1 = {
    Point: readPointGeometry$1,
    LineString: readLineStringGeometry$1,
    Polygon: readPolygonGeometry$1,
    MultiPoint: readMultiPointGeometry$1,
    MultiLineString: readMultiLineStringGeometry$1,
    MultiPolygon: readMultiPolygonGeometry$1,
  };

  /**
   * @const
   * @type {Object<import("../geom/Geometry.js").Type, function(import("../geom/Geometry.js").default, import("./Feature.js").WriteOptions=): (EsriJSONGeometry)>}
   */
  const GEOMETRY_WRITERS = {
    Point: writePointGeometry,
    LineString: writeLineStringGeometry,
    Polygon: writePolygonGeometry,
    MultiPoint: writeMultiPointGeometry,
    MultiLineString: writeMultiLineStringGeometry,
    MultiPolygon: writeMultiPolygonGeometry,
  };

  /**
   * @typedef {Object} Options
   * @property {string} [geometryName] Geometry name to use when creating features.
   */

  /**
   * @classdesc
   * Feature format for reading and writing data in the EsriJSON format.
   *
   * @api
   */
  class EsriJSON extends JSONFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super();

      /**
       * Name of the geometry attribute for features.
       * @type {string|undefined}
       * @private
       */
      this.geometryName_ = options.geometryName;
    }

    /**
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @param {string} [idField] Name of the field where to get the id from.
     * @protected
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromObject(object, options, idField) {
      const esriJSONFeature = /** @type {EsriJSONFeature} */ (object);
      const geometry = readGeometry(esriJSONFeature.geometry, options);
      const feature = new Feature();
      if (this.geometryName_) {
        feature.setGeometryName(this.geometryName_);
      }
      feature.setGeometry(geometry);
      if (esriJSONFeature.attributes) {
        feature.setProperties(esriJSONFeature.attributes, true);
        const id = esriJSONFeature.attributes[idField];
        if (id !== undefined) {
          feature.setId(/** @type {number} */ (id));
        }
      }
      return feature;
    }

    /**
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<Feature>} Features.
     * @override
     */
    readFeaturesFromObject(object, options) {
      options = options ? options : {};
      if (object['features']) {
        const esriJSONFeatureSet = /** @type {EsriJSONFeatureSet} */ (object);
        /** @type {Array<import("../Feature.js").default>} */
        const features = [];
        const esriJSONFeatures = esriJSONFeatureSet.features;
        for (let i = 0, ii = esriJSONFeatures.length; i < ii; ++i) {
          features.push(
            this.readFeatureFromObject(
              esriJSONFeatures[i],
              options,
              object.objectIdFieldName,
            ),
          );
        }
        return features;
      }
      return [this.readFeatureFromObject(object, options)];
    }

    /**
     * @param {EsriJSONGeometry} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometryFromObject(object, options) {
      return readGeometry(object, options);
    }

    /**
     * @param {Object} object Object.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromObject(object) {
      if (
        object['spatialReference'] &&
        object['spatialReference']['wkid'] !== undefined
      ) {
        const spatialReference = /** @type {EsriJSONSpatialReferenceWkid} */ (
          object['spatialReference']
        );
        const crs = spatialReference.wkid;
        return get$2('EPSG:' + crs);
      }
      return null;
    }

    /**
     * Encode a geometry as a EsriJSON object.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {EsriJSONGeometry} Object.
     * @api
     * @override
     */
    writeGeometryObject(geometry, options) {
      return writeGeometry(geometry, this.adaptOptions(options));
    }

    /**
     * Encode a feature as a esriJSON Feature object.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {Object} Object.
     * @api
     * @override
     */
    writeFeatureObject(feature, options) {
      options = this.adaptOptions(options);
      const object = {};
      if (!feature.hasProperties()) {
        object['attributes'] = {};
        return object;
      }
      const properties = feature.getProperties();
      const geometry = feature.getGeometry();
      if (geometry) {
        object['geometry'] = writeGeometry(geometry, options);
        const projection =
          options && (options.dataProjection || options.featureProjection);
        if (projection) {
          object['geometry']['spatialReference'] =
            /** @type {EsriJSONSpatialReferenceWkid} */ ({
              wkid: Number(get$2(projection).getCode().split(':').pop()),
            });
        }
        delete properties[feature.getGeometryName()];
      }
      if (!isEmpty$1(properties)) {
        object['attributes'] = properties;
      } else {
        object['attributes'] = {};
      }
      return object;
    }

    /**
     * Encode an array of features as a EsriJSON object.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {EsriJSONFeatureSet} EsriJSON Object.
     * @api
     * @override
     */
    writeFeaturesObject(features, options) {
      options = this.adaptOptions(options);
      const objects = [];
      for (let i = 0, ii = features.length; i < ii; ++i) {
        objects.push(this.writeFeatureObject(features[i], options));
      }
      return {
        'features': objects,
      };
    }
  }

  /**
   * @param {EsriJSONGeometry} object Object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {import("../geom/Geometry.js").default} Geometry.
   */
  function readGeometry(object, options) {
    if (!object) {
      return null;
    }
    /** @type {import("../geom/Geometry.js").Type} */
    let type;
    if (typeof object['x'] === 'number' && typeof object['y'] === 'number') {
      type = 'Point';
    } else if (object['points']) {
      type = 'MultiPoint';
    } else if (object['paths']) {
      const esriJSONPolyline = /** @type {EsriJSONPolyline} */ (object);
      if (esriJSONPolyline.paths.length === 1) {
        type = 'LineString';
      } else {
        type = 'MultiLineString';
      }
    } else if (object['rings']) {
      const esriJSONPolygon = /** @type {EsriJSONPolygon} */ (object);
      const layout = getGeometryLayout(esriJSONPolygon);
      const rings = convertRings(esriJSONPolygon.rings, layout);
      if (rings.length === 1) {
        type = 'Polygon';
        object = Object.assign({}, object, {['rings']: rings[0]});
      } else {
        type = 'MultiPolygon';
        object = Object.assign({}, object, {['rings']: rings});
      }
    }
    const geometryReader = GEOMETRY_READERS$1[type];
    return transformGeometryWithOptions(geometryReader(object), false, options);
  }

  /**
   * Determines inner and outer rings.
   * Checks if any polygons in this array contain any other polygons in this
   * array. It is used for checking for holes.
   * Logic inspired by: https://github.com/Esri/terraformer-arcgis-parser
   * @param {Array<!Array<!Array<number>>>} rings Rings.
   * @param {import("../geom/Geometry.js").GeometryLayout} layout Geometry layout.
   * @return {Array<!Array<!Array<!Array<number>>>>} Transformed rings.
   */
  function convertRings(rings, layout) {
    const flatRing = [];
    const outerRings = [];
    const holes = [];
    let i, ii;
    for (i = 0, ii = rings.length; i < ii; ++i) {
      flatRing.length = 0;
      deflateCoordinates(flatRing, 0, rings[i], layout.length);
      // is this ring an outer ring? is it clockwise?
      const clockwise = linearRingIsClockwise(
        flatRing,
        0,
        flatRing.length,
        layout.length,
      );
      if (clockwise) {
        outerRings.push([rings[i]]);
      } else {
        holes.push(rings[i]);
      }
    }
    while (holes.length) {
      const hole = holes.shift();
      let matched = false;
      // loop over all outer rings and see if they contain our hole.
      for (i = outerRings.length - 1; i >= 0; i--) {
        const outerRing = outerRings[i][0];
        const containsHole = containsExtent(
          new LinearRing(outerRing).getExtent(),
          new LinearRing(hole).getExtent(),
        );
        if (containsHole) {
          // the hole is contained push it into our polygon
          outerRings[i].push(hole);
          matched = true;
          break;
        }
      }
      if (!matched) {
        // no outer rings contain this hole turn it into and outer
        // ring (reverse it)
        outerRings.push([hole.reverse()]);
      }
    }
    return outerRings;
  }

  /**
   * @param {EsriJSONPoint} object Object.
   * @return {import("../geom/Geometry.js").default} Point.
   */
  function readPointGeometry$1(object) {
    let point;
    if (object.m !== undefined && object.z !== undefined) {
      point = new Point([object.x, object.y, object.z, object.m], 'XYZM');
    } else if (object.z !== undefined) {
      point = new Point([object.x, object.y, object.z], 'XYZ');
    } else if (object.m !== undefined) {
      point = new Point([object.x, object.y, object.m], 'XYM');
    } else {
      point = new Point([object.x, object.y]);
    }
    return point;
  }

  /**
   * @param {EsriJSONPolyline} object Object.
   * @return {import("../geom/Geometry.js").default} LineString.
   */
  function readLineStringGeometry$1(object) {
    const layout = getGeometryLayout(object);
    return new LineString(object.paths[0], layout);
  }

  /**
   * @param {EsriJSONPolyline} object Object.
   * @return {import("../geom/Geometry.js").default} MultiLineString.
   */
  function readMultiLineStringGeometry$1(object) {
    const layout = getGeometryLayout(object);
    return new MultiLineString(object.paths, layout);
  }

  /**
   * @param {EsriJSONHasZM} object Object.
   * @return {import("../geom/Geometry.js").GeometryLayout} The geometry layout to use.
   */
  function getGeometryLayout(object) {
    /** @type {import("../geom/Geometry.js").GeometryLayout} */
    let layout = 'XY';
    if (object.hasZ === true && object.hasM === true) {
      layout = 'XYZM';
    } else if (object.hasZ === true) {
      layout = 'XYZ';
    } else if (object.hasM === true) {
      layout = 'XYM';
    }
    return layout;
  }

  /**
   * @param {EsriJSONMultipoint} object Object.
   * @return {import("../geom/Geometry.js").default} MultiPoint.
   */
  function readMultiPointGeometry$1(object) {
    const layout = getGeometryLayout(object);
    return new MultiPoint(object.points, layout);
  }

  /**
   * @param {EsriJSONMultiPolygon} object Object.
   * @return {import("../geom/Geometry.js").default} MultiPolygon.
   */
  function readMultiPolygonGeometry$1(object) {
    const layout = getGeometryLayout(object);
    return new MultiPolygon(object.rings, layout);
  }

  /**
   * @param {EsriJSONPolygon} object Object.
   * @return {import("../geom/Geometry.js").default} Polygon.
   */
  function readPolygonGeometry$1(object) {
    const layout = getGeometryLayout(object);
    return new Polygon(object.rings, layout);
  }

  /**
   * @param {import("../geom/Point.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONPoint} EsriJSON geometry.
   */
  function writePointGeometry(geometry, options) {
    const coordinates = geometry.getCoordinates();
    /** @type {EsriJSONPoint} */
    let esriJSON;
    const layout = geometry.getLayout();
    if (layout === 'XYZ') {
      esriJSON = {
        x: coordinates[0],
        y: coordinates[1],
        z: coordinates[2],
      };
    } else if (layout === 'XYM') {
      esriJSON = {
        x: coordinates[0],
        y: coordinates[1],
        m: coordinates[2],
      };
    } else if (layout === 'XYZM') {
      esriJSON = {
        x: coordinates[0],
        y: coordinates[1],
        z: coordinates[2],
        m: coordinates[3],
      };
    } else if (layout === 'XY') {
      esriJSON = {
        x: coordinates[0],
        y: coordinates[1],
      };
    } else {
      throw new Error('Invalid geometry layout');
    }
    return esriJSON;
  }

  /**
   * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry.
   * @return {Object} Object with boolean hasZ and hasM keys.
   */
  function getHasZM(geometry) {
    const layout = geometry.getLayout();
    return {
      hasZ: layout === 'XYZ' || layout === 'XYZM',
      hasM: layout === 'XYM' || layout === 'XYZM',
    };
  }

  /**
   * @param {import("../geom/LineString.js").default} lineString Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONPolyline} EsriJSON geometry.
   */
  function writeLineStringGeometry(lineString, options) {
    const hasZM = getHasZM(lineString);
    return {
      hasZ: hasZM.hasZ,
      hasM: hasZM.hasM,
      paths: [
        /** @type {Array<EsriJSONPosition>} */ (lineString.getCoordinates()),
      ],
    };
  }

  /**
   * @param {import("../geom/Polygon.js").default} polygon Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONPolygon} EsriJSON geometry.
   */
  function writePolygonGeometry(polygon, options) {
    // Esri geometries use the left-hand rule
    const hasZM = getHasZM(polygon);
    return {
      hasZ: hasZM.hasZ,
      hasM: hasZM.hasM,
      rings: /** @type {Array<Array<EsriJSONPosition>>} */ (
        polygon.getCoordinates(false)
      ),
    };
  }

  /**
   * @param {import("../geom/MultiLineString.js").default} multiLineString Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONPolyline} EsriJSON geometry.
   */
  function writeMultiLineStringGeometry(multiLineString, options) {
    const hasZM = getHasZM(multiLineString);
    return {
      hasZ: hasZM.hasZ,
      hasM: hasZM.hasM,
      paths: /** @type {Array<Array<EsriJSONPosition>>} */ (
        multiLineString.getCoordinates()
      ),
    };
  }

  /**
   * @param {import("../geom/MultiPoint.js").default} multiPoint Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONMultipoint} EsriJSON geometry.
   */
  function writeMultiPointGeometry(multiPoint, options) {
    const hasZM = getHasZM(multiPoint);
    return {
      hasZ: hasZM.hasZ,
      hasM: hasZM.hasM,
      points: /** @type {Array<EsriJSONPosition>} */ (
        multiPoint.getCoordinates()
      ),
    };
  }

  /**
   * @param {import("../geom/MultiPolygon.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONPolygon} EsriJSON geometry.
   */
  function writeMultiPolygonGeometry(geometry, options) {
    const hasZM = getHasZM(geometry);
    const coordinates = geometry.getCoordinates(false);
    const output = [];
    for (let i = 0; i < coordinates.length; i++) {
      for (let x = coordinates[i].length - 1; x >= 0; x--) {
        output.push(coordinates[i][x]);
      }
    }
    return {
      hasZ: hasZM.hasZ,
      hasM: hasZM.hasM,
      rings: /** @type {Array<Array<EsriJSONPosition>>} */ (output),
    };
  }

  /**
   * @param {import("../geom/Geometry.js").default} geometry Geometry.
   * @param {import("./Feature.js").WriteOptions} [options] Write options.
   * @return {EsriJSONGeometry} EsriJSON geometry.
   */
  function writeGeometry(geometry, options) {
    const geometryWriter = GEOMETRY_WRITERS[geometry.getType()];
    return geometryWriter(
      transformGeometryWithOptions(geometry, true, options),
      options,
    );
  }

  /**
   * @module ol/xml
   */

  /**
   * When using {@link module:ol/xml.makeChildAppender} or
   * {@link module:ol/xml.makeSimpleNodeFactory}, the top `objectStack` item needs
   * to have this structure.
   * @typedef {Object} NodeStackItem
   * @property {Element} node Node.
   */

  /**
   * @typedef {function(Element, Array<*>): void} Parser
   */

  /**
   * @typedef {function(Element, *, Array<*>): void} Serializer
   */

  /**
   * @type {string}
   */
  const XML_SCHEMA_INSTANCE_URI =
    'http://www.w3.org/2001/XMLSchema-instance';

  /**
   * @param {string} namespaceURI Namespace URI.
   * @param {string} qualifiedName Qualified name.
   * @return {Element} Node.
   */
  function createElementNS(namespaceURI, qualifiedName) {
    return getDocument().createElementNS(namespaceURI, qualifiedName);
  }

  /**
   * Recursively grab all text content of child nodes into a single string.
   * @param {Node} node Node.
   * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line
   * breaks.
   * @return {string} All text content.
   * @api
   */
  function getAllTextContent(node, normalizeWhitespace) {
    return getAllTextContent_(node, normalizeWhitespace, []).join('');
  }

  /**
   * Recursively grab all text content of child nodes into a single string.
   * @param {Node} node Node.
   * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line
   * breaks.
   * @param {Array<string>} accumulator Accumulator.
   * @private
   * @return {Array<string>} Accumulator.
   */
  function getAllTextContent_(node, normalizeWhitespace, accumulator) {
    if (
      node.nodeType == Node.CDATA_SECTION_NODE ||
      node.nodeType == Node.TEXT_NODE
    ) {
      {
        accumulator.push(node.nodeValue);
      }
    } else {
      let n;
      for (n = node.firstChild; n; n = n.nextSibling) {
        getAllTextContent_(n, normalizeWhitespace, accumulator);
      }
    }
    return accumulator;
  }

  /**
   * @param {Object} object Object.
   * @return {boolean} Is a document.
   */
  function isDocument(object) {
    return 'documentElement' in object;
  }

  /**
   * @param {Element} node Node.
   * @param {?string} namespaceURI Namespace URI.
   * @param {string} name Attribute name.
   * @return {string} Value
   */
  function getAttributeNS(node, namespaceURI, name) {
    return node.getAttributeNS(namespaceURI, name) || '';
  }

  /**
   * Parse an XML string to an XML Document.
   * @param {string} xml XML.
   * @return {Document} Document.
   * @api
   */
  function parse(xml) {
    return new DOMParser().parseFromString(xml, 'application/xml');
  }

  /**
   * Make an array extender function for extending the array at the top of the
   * object stack.
   * @param {function(this: T, Node, Array<*>): (Array<*>|undefined)} valueReader Value reader.
   * @param {T} [thisArg] The object to use as `this` in `valueReader`.
   * @return {Parser} Parser.
   * @template T
   */
  function makeArrayExtender(valueReader, thisArg) {
    return (
      /**
       * @param {Node} node Node.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, objectStack) {
        const value = valueReader.call(thisArg ?? this, node, objectStack);
        if (value !== undefined) {
          const array = /** @type {Array<*>} */ (
            objectStack[objectStack.length - 1]
          );
          extend$2(array, value);
        }
      }
    );
  }

  /**
   * Make an array pusher function for pushing to the array at the top of the
   * object stack.
   * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.
   * @param {T} [thisArg] The object to use as `this` in `valueReader`.
   * @return {Parser} Parser.
   * @template T
   */
  function makeArrayPusher(valueReader, thisArg) {
    return (
      /**
       * @param {Element} node Node.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, objectStack) {
        const value = valueReader.call(thisArg ?? this, node, objectStack);
        if (value !== undefined) {
          const array = /** @type {Array<*>} */ (
            objectStack[objectStack.length - 1]
          );
          array.push(value);
        }
      }
    );
  }

  /**
   * Make an object stack replacer function for replacing the object at the
   * top of the stack.
   * @param {function(this: T, Node, Array<*>): *} valueReader Value reader.
   * @param {T} [thisArg] The object to use as `this` in `valueReader`.
   * @return {Parser} Parser.
   * @template T
   */
  function makeReplacer(valueReader, thisArg) {
    return (
      /**
       * @param {Node} node Node.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, objectStack) {
        const value = valueReader.call(thisArg ?? this, node, objectStack);
        if (value !== undefined) {
          objectStack[objectStack.length - 1] = value;
        }
      }
    );
  }

  /**
   * Make an object property pusher function for adding a property to the
   * object at the top of the stack.
   * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.
   * @param {string} [property] Property.
   * @param {T} [thisArg] The object to use as `this` in `valueReader`.
   * @return {Parser} Parser.
   * @template T
   */
  function makeObjectPropertyPusher(valueReader, property, thisArg) {
    return (
      /**
       * @param {Element} node Node.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, objectStack) {
        const value = valueReader.call(this, node, objectStack);
        if (value !== undefined) {
          const object = /** @type {!Object} */ (
            objectStack[objectStack.length - 1]
          );
          const name = node.localName;
          let array;
          if (name in object) {
            array = object[name];
          } else {
            array = [];
            object[name] = array;
          }
          array.push(value);
        }
      }
    );
  }

  /**
   * Make an object property setter function.
   * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.
   * @param {string} [property] Property.
   * @param {T} [thisArg] The object to use as `this` in `valueReader`.
   * @return {Parser} Parser.
   * @template T
   */
  function makeObjectPropertySetter(valueReader, property, thisArg) {
    return (
      /**
       * @param {Element} node Node.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, objectStack) {
        const value = valueReader.call(this, node, objectStack);
        if (value !== undefined) {
          const object = /** @type {!Object} */ (
            objectStack[objectStack.length - 1]
          );
          const name = property !== undefined ? property : node.localName;
          object[name] = value;
        }
      }
    );
  }

  /**
   * Create a serializer that appends nodes written by its `nodeWriter` to its
   * designated parent. The parent is the `node` of the
   * {@link module:ol/xml~NodeStackItem} at the top of the `objectStack`.
   * @param {function(this: T, Node, V, Array<*>): void} nodeWriter Node writer.
   * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.
   * @return {Serializer} Serializer.
   * @template T, V
   */
  function makeChildAppender(nodeWriter, thisArg) {
    return (
      /**
       * @param {Element} node Node.
       * @param {*} value Value to be written.
       * @param {Array<*>} objectStack Object stack.
       * @this {*}
       */
      function (node, value, objectStack) {
        nodeWriter.call(thisArg ?? this, node, value, objectStack);
        const parent = /** @type {NodeStackItem} */ (
          objectStack[objectStack.length - 1]
        );
        const parentNode = parent.node;
        parentNode.appendChild(node);
      }
    );
  }

  /**
   * Create a serializer that calls the provided `nodeWriter` from
   * {@link module:ol/xml.serialize}. This can be used by the parent writer to have the
   * `nodeWriter` called with an array of values when the `nodeWriter` was
   * designed to serialize a single item. An example would be a LineString
   * geometry writer, which could be reused for writing MultiLineString
   * geometries.
   * @param {function(this: T, Element, V, Array<*>): void} nodeWriter Node writer.
   * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.
   * @return {Serializer} Serializer.
   * @template T, V
   */
  function makeArraySerializer(nodeWriter, thisArg) {
    let serializersNS, nodeFactory;
    return function (node, value, objectStack) {
      if (serializersNS === undefined) {
        serializersNS = {};
        const serializers = {};
        serializers[node.localName] = nodeWriter;
        serializersNS[node.namespaceURI] = serializers;
        nodeFactory = makeSimpleNodeFactory(node.localName);
      }
      serialize(serializersNS, nodeFactory, value, objectStack);
    };
  }

  /**
   * Create a node factory which can use the `keys` passed to
   * {@link module:ol/xml.serialize} or {@link module:ol/xml.pushSerializeAndPop} as node names,
   * or a fixed node name. The namespace of the created nodes can either be fixed,
   * or the parent namespace will be used.
   * @param {string} [fixedNodeName] Fixed node name which will be used for all
   *     created nodes. If not provided, the 3rd argument to the resulting node
   *     factory needs to be provided and will be the nodeName.
   * @param {string} [fixedNamespaceURI] Fixed namespace URI which will be used for
   *     all created nodes. If not provided, the namespace of the parent node will
   *     be used.
   * @return {function(*, Array<*>, string=): (Node|undefined)} Node factory.
   */
  function makeSimpleNodeFactory(fixedNodeName, fixedNamespaceURI) {
    return (
      /**
       * @param {*} value Value.
       * @param {Array<*>} objectStack Object stack.
       * @param {string} [newNodeName] Node name.
       * @return {Node} Node.
       */
      function (value, objectStack, newNodeName) {
        const context = /** @type {NodeStackItem} */ (
          objectStack[objectStack.length - 1]
        );
        const node = context.node;
        let nodeName = fixedNodeName;
        if (nodeName === undefined) {
          nodeName = newNodeName;
        }

        const namespaceURI =
          fixedNamespaceURI !== undefined ? fixedNamespaceURI : node.namespaceURI;
        return createElementNS(namespaceURI, /** @type {string} */ (nodeName));
      }
    );
  }

  /**
   * A node factory that creates a node using the parent's `namespaceURI` and the
   * `nodeName` passed by {@link module:ol/xml.serialize} or
   * {@link module:ol/xml.pushSerializeAndPop} to the node factory.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const OBJECT_PROPERTY_NODE_FACTORY = makeSimpleNodeFactory();

  /**
   * Create an array of `values` to be used with {@link module:ol/xml.serialize} or
   * {@link module:ol/xml.pushSerializeAndPop}, where `orderedKeys` has to be provided as
   * `key` argument.
   * @param {Object<string, *>} object Key-value pairs for the sequence. Keys can
   *     be a subset of the `orderedKeys`.
   * @param {Array<string>} orderedKeys Keys in the order of the sequence.
   * @return {Array<*>} Values in the order of the sequence. The resulting array
   *     has the same length as the `orderedKeys` array. Values that are not
   *     present in `object` will be `undefined` in the resulting array.
   */
  function makeSequence(object, orderedKeys) {
    const length = orderedKeys.length;
    const sequence = new Array(length);
    for (let i = 0; i < length; ++i) {
      sequence[i] = object[orderedKeys[i]];
    }
    return sequence;
  }

  /**
   * Create a namespaced structure, using the same values for each namespace.
   * This can be used as a starting point for versioned parsers, when only a few
   * values are version specific.
   * @param {Array<string>} namespaceURIs Namespace URIs.
   * @param {T} structure Structure.
   * @param {Object<string, T>} [structureNS] Namespaced structure to add to.
   * @return {Object<string, T>} Namespaced structure.
   * @template T
   */
  function makeStructureNS(namespaceURIs, structure, structureNS) {
    structureNS = structureNS !== undefined ? structureNS : {};
    let i, ii;
    for (i = 0, ii = namespaceURIs.length; i < ii; ++i) {
      structureNS[namespaceURIs[i]] = structure;
    }
    return structureNS;
  }

  /**
   * Parse a node using the parsers and object stack.
   * @param {Object<string, Object<string, Parser>>} parsersNS
   *     Parsers by namespace.
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @param {*} [thisArg] The object to use as `this`.
   */
  function parseNode(parsersNS, node, objectStack, thisArg) {
    let n;
    for (n = node.firstElementChild; n; n = n.nextElementSibling) {
      const parsers = parsersNS[n.namespaceURI];
      if (parsers !== undefined) {
        const parser = parsers[n.localName];
        if (parser !== undefined) {
          parser.call(thisArg, n, objectStack);
        }
      }
    }
  }

  /**
   * Push an object on top of the stack, parse and return the popped object.
   * @param {T} object Object.
   * @param {Object<string, Object<string, Parser>>} parsersNS
   *     Parsers by namespace.
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @param {*} [thisArg] The object to use as `this`.
   * @return {T} Object.
   * @template T
   */
  function pushParseAndPop(object, parsersNS, node, objectStack, thisArg) {
    objectStack.push(object);
    parseNode(parsersNS, node, objectStack, thisArg);
    return /** @type {T} */ (objectStack.pop());
  }

  /**
   * Walk through an array of `values` and call a serializer for each value.
   * @param {Object<string, Object<string, Serializer>>} serializersNS
   *     Namespaced serializers.
   * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory
   *     Node factory. The `nodeFactory` creates the node whose namespace and name
   *     will be used to choose a node writer from `serializersNS`. This
   *     separation allows us to decide what kind of node to create, depending on
   *     the value we want to serialize. An example for this would be different
   *     geometry writers based on the geometry type.
   * @param {Array<*>} values Values to serialize. An example would be an array
   *     of {@link module:ol/Feature~Feature} instances.
   * @param {Array<*>} objectStack Node stack.
   * @param {Array<string>} [keys] Keys of the `values`. Will be passed to the
   *     `nodeFactory`. This is used for serializing object literals where the
   *     node name relates to the property key. The array length of `keys` has
   *     to match the length of `values`. For serializing a sequence, `keys`
   *     determines the order of the sequence.
   * @param {T} [thisArg] The object to use as `this` for the node factory and
   *     serializers.
   * @template T
   */
  function serialize(
    serializersNS,
    nodeFactory,
    values,
    objectStack,
    keys,
    thisArg,
  ) {
    const length = (keys !== undefined ? keys : values).length;
    let value, node;
    for (let i = 0; i < length; ++i) {
      value = values[i];
      if (value !== undefined) {
        node = nodeFactory.call(
          thisArg,
          value,
          objectStack,
          keys !== undefined ? keys[i] : undefined,
        );
        if (node !== undefined) {
          serializersNS[node.namespaceURI][node.localName].call(
            thisArg,
            node,
            value,
            objectStack,
          );
        }
      }
    }
  }

  /**
   * @param {O} object Object.
   * @param {Object<string, Object<string, Serializer>>} serializersNS
   *     Namespaced serializers.
   * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory
   *     Node factory. The `nodeFactory` creates the node whose namespace and name
   *     will be used to choose a node writer from `serializersNS`. This
   *     separation allows us to decide what kind of node to create, depending on
   *     the value we want to serialize. An example for this would be different
   *     geometry writers based on the geometry type.
   * @param {Array<*>} values Values to serialize. An example would be an array
   *     of {@link module:ol/Feature~Feature} instances.
   * @param {Array<*>} objectStack Node stack.
   * @param {Array<string>} [keys] Keys of the `values`. Will be passed to the
   *     `nodeFactory`. This is used for serializing object literals where the
   *     node name relates to the property key. The array length of `keys` has
   *     to match the length of `values`. For serializing a sequence, `keys`
   *     determines the order of the sequence.
   * @param {T} [thisArg] The object to use as `this` for the node factory and
   *     serializers.
   * @return {O|undefined} Object.
   * @template O, T
   */
  function pushSerializeAndPop(
    object,
    serializersNS,
    nodeFactory,
    values,
    objectStack,
    keys,
    thisArg,
  ) {
    objectStack.push(object);
    serialize(serializersNS, nodeFactory, values, objectStack, keys, thisArg);
    return /** @type {O|undefined} */ (objectStack.pop());
  }

  let xmlSerializer_ = undefined;

  /**
   * @return {XMLSerializer} The XMLSerializer.
   */
  function getXMLSerializer() {
    if (xmlSerializer_ === undefined && typeof XMLSerializer !== 'undefined') {
      xmlSerializer_ = new XMLSerializer();
    }
    return xmlSerializer_;
  }

  let document_ = undefined;

  /**
   * Get a document that should be used when creating nodes for XML serializations.
   * @return {Document} The document.
   */
  function getDocument() {
    if (document_ === undefined && typeof document !== 'undefined') {
      document_ = document.implementation.createDocument('', '', null);
    }
    return document_;
  }

  /**
   * @module ol/format/XMLFeature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for XML feature formats.
   *
   * @abstract
   */
  class XMLFeature extends FeatureFormat {
    constructor() {
      super();

      /**
       * @type {XMLSerializer}
       * @private
       */
      this.xmlSerializer_ = getXMLSerializer();
    }

    /**
     * @return {import("./Feature.js").Type} Format.
     * @override
     */
    getType() {
      return 'xml';
    }

    /**
     * Read a single feature.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @api
     * @override
     */
    readFeature(source, options) {
      if (!source) {
        return null;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readFeatureFromDocument(doc, options);
      }
      if (isDocument(source)) {
        return this.readFeatureFromDocument(
          /** @type {Document} */ (source),
          options,
        );
      }
      return this.readFeatureFromNode(/** @type {Element} */ (source), options);
    }

    /**
     * @param {Document} doc Document.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {import("../Feature.js").default} Feature.
     */
    readFeatureFromDocument(doc, options) {
      const features = this.readFeaturesFromDocument(doc, options);
      if (features.length > 0) {
        return features[0];
      }
      return null;
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {import("../Feature.js").default} Feature.
     */
    readFeatureFromNode(node, options) {
      return null; // not implemented
    }

    /**
     * Read all features from a feature collection.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @api
     * @override
     */
    readFeatures(source, options) {
      if (!source) {
        return [];
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readFeaturesFromDocument(doc, options);
      }
      if (isDocument(source)) {
        return this.readFeaturesFromDocument(
          /** @type {Document} */ (source),
          options,
        );
      }
      return this.readFeaturesFromNode(/** @type {Element} */ (source), options);
    }

    /**
     * @param {Document} doc Document.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @protected
     * @return {Array<import("../Feature.js").default>} Features.
     */
    readFeaturesFromDocument(doc, options) {
      /** @type {Array<import("../Feature.js").default>} */
      const features = [];
      for (let n = doc.firstChild; n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          extend$2(
            features,
            this.readFeaturesFromNode(/** @type {Element} */ (n), options),
          );
        }
      }
      return features;
    }

    /**
     * @abstract
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @protected
     * @return {Array<import("../Feature.js").default>} Features.
     */
    readFeaturesFromNode(node, options) {
      return abstract();
    }

    /**
     * Read a single geometry from a source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometry(source, options) {
      if (!source) {
        return null;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readGeometryFromDocument(doc, options);
      }
      if (isDocument(source)) {
        return this.readGeometryFromDocument(
          /** @type {Document} */ (source),
          options,
        );
      }
      return this.readGeometryFromNode(/** @type {Element} */ (source), options);
    }

    /**
     * @param {Document} doc Document.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     */
    readGeometryFromDocument(doc, options) {
      return null; // not implemented
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     */
    readGeometryFromNode(node, options) {
      return null; // not implemented
    }

    /**
     * Read the projection from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {import("../proj/Projection.js").default} Projection.
     * @api
     * @override
     */
    readProjection(source) {
      if (!source) {
        return null;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readProjectionFromDocument(doc);
      }
      if (isDocument(source)) {
        return this.readProjectionFromDocument(/** @type {Document} */ (source));
      }
      return this.readProjectionFromNode(/** @type {Element} */ (source));
    }

    /**
     * @param {Document} doc Document.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     */
    readProjectionFromDocument(doc) {
      return this.dataProjection;
    }

    /**
     * @param {Element} node Node.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     */
    readProjectionFromNode(node) {
      return this.dataProjection;
    }

    /**
     * Encode a feature as string.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded feature.
     * @override
     */
    writeFeature(feature, options) {
      const node = this.writeFeatureNode(feature, options);
      return this.xmlSerializer_.serializeToString(node);
    }

    /**
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @protected
     * @return {Node} Node.
     */
    writeFeatureNode(feature, options) {
      return null; // not implemented
    }

    /**
     * Encode an array of features as string.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Result.
     * @api
     * @override
     */
    writeFeatures(features, options) {
      const node = this.writeFeaturesNode(features, options);
      return this.xmlSerializer_.serializeToString(node);
    }

    /**
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Node} Node.
     */
    writeFeaturesNode(features, options) {
      return null; // not implemented
    }

    /**
     * Encode a geometry as string.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded geometry.
     * @override
     */
    writeGeometry(geometry, options) {
      const node = this.writeGeometryNode(geometry, options);
      return this.xmlSerializer_.serializeToString(node);
    }

    /**
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Node} Node.
     */
    writeGeometryNode(geometry, options) {
      return null; // not implemented
    }
  }

  /**
   * @module ol/format/GMLBase
   */
  // FIXME Envelopes should not be treated as geometries! readEnvelope_ is part
  // of GEOMETRY_PARSERS_ and methods using GEOMETRY_PARSERS_ do not expect
  // envelopes/extents, only geometries!

  /**
   * @const
   * @type {string}
   */
  const GMLNS = 'http://www.opengis.net/gml';

  /**
   * A regular expression that matches if a string only contains whitespace
   * characters. It will e.g. match `''`, `' '`, `'\n'` etc.
   *
   * @const
   * @type {RegExp}
   */
  const ONLY_WHITESPACE_RE = /^\s*$/;

  /**
   * @typedef {Object} Options
   * @property {Object<string, string>|string} [featureNS] Feature
   * namespace. If not defined will be derived from GML. If multiple
   * feature types have been configured which come from different feature
   * namespaces, this will be an object with the keys being the prefixes used
   * in the entries of featureType array. The values of the object will be the
   * feature namespaces themselves. So for instance there might be a featureType
   * item `topp:states` in the `featureType` array and then there will be a key
   * `topp` in the featureNS object with value `http://www.openplans.org/topp`.
   * @property {Array<string>|string} [featureType] Feature type(s) to parse.
   * If multiple feature types need to be configured
   * which come from different feature namespaces, `featureNS` will be an object
   * with the keys being the prefixes used in the entries of featureType array.
   * The values of the object will be the feature namespaces themselves.
   * So for instance there might be a featureType item `topp:states` and then
   * there will be a key named `topp` in the featureNS object with value
   * `http://www.openplans.org/topp`.
   * @property {string} [srsName] srsName to use when writing geometries.
   * @property {boolean} [surface=false] Write gml:Surface instead of gml:Polygon
   * elements. This also affects the elements in multi-part geometries.
   * @property {boolean} [curve=false] Write gml:Curve instead of gml:LineString
   * elements. This also affects the elements in multi-part geometries.
   * @property {boolean} [multiCurve=true] Write gml:MultiCurve instead of gml:MultiLineString.
   * Since the latter is deprecated in GML 3.
   * @property {boolean} [multiSurface=true] Write gml:multiSurface instead of
   * gml:MultiPolygon. Since the latter is deprecated in GML 3.
   * @property {string} [schemaLocation] Optional schemaLocation to use when
   * writing out the GML, this will override the default provided.
   * @property {boolean} [hasZ=false] If coordinates have a Z value.
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Feature base format for reading and writing data in the GML format.
   * This class cannot be instantiated, it contains only base content that
   * is shared with versioned format classes GML2 and GML3.
   *
   * @abstract
   * @api
   */
  class GMLBase extends XMLFeature {
    /**
     * @param {Options} [options] Optional configuration object.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @protected
       * @type {Array<string>|string|undefined}
       */
      this.featureType = options.featureType;

      /**
       * @protected
       * @type {Object<string, string>|string|undefined}
       */
      this.featureNS = options.featureNS;

      /**
       * @protected
       * @type {string|undefined}
       */
      this.srsName = options.srsName;

      /**
       * @protected
       * @type {string}
       */
      this.schemaLocation = '';

      /**
       * @type {Object<string, Object<string, Object>>}
       */
      this.FEATURE_COLLECTION_PARSERS = {};
      this.FEATURE_COLLECTION_PARSERS[this.namespace] = {
        'featureMember': makeArrayPusher(this.readFeaturesInternal),
        'featureMembers': makeReplacer(this.readFeaturesInternal),
      };

      this.supportedMediaTypes = ['application/gml+xml'];
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<Feature> | undefined} Features.
     */
    readFeaturesInternal(node, objectStack) {
      const localName = node.localName;
      let features = null;
      if (localName == 'FeatureCollection') {
        features = pushParseAndPop(
          [],
          this.FEATURE_COLLECTION_PARSERS,
          node,
          objectStack,
          this,
        );
      } else if (
        localName == 'featureMembers' ||
        localName == 'featureMember' ||
        localName == 'member'
      ) {
        const context = objectStack[0];
        let featureType = context['featureType'];
        let featureNS = context['featureNS'];
        const prefix = 'p';
        const defaultPrefix = 'p0';
        if (!featureType && node.childNodes) {
          (featureType = []), (featureNS = {});
          for (let i = 0, ii = node.childNodes.length; i < ii; ++i) {
            const child = /** @type {Element} */ (node.childNodes[i]);
            if (child.nodeType === 1) {
              const ft = child.nodeName.split(':').pop();
              if (!featureType.includes(ft)) {
                let key = '';
                let count = 0;
                const uri = child.namespaceURI;
                for (const candidate in featureNS) {
                  if (featureNS[candidate] === uri) {
                    key = candidate;
                    break;
                  }
                  ++count;
                }
                if (!key) {
                  key = prefix + count;
                  featureNS[key] = uri;
                }
                featureType.push(key + ':' + ft);
              }
            }
          }
          if (localName != 'featureMember') {
            // recheck featureType for each featureMember
            context['featureType'] = featureType;
            context['featureNS'] = featureNS;
          }
        }
        if (typeof featureNS === 'string') {
          const ns = featureNS;
          featureNS = {};
          featureNS[defaultPrefix] = ns;
        }
        /** @type {Object<string, Object<string, import("../xml.js").Parser>>} */
        const parsersNS = {};
        const featureTypes = Array.isArray(featureType)
          ? featureType
          : [featureType];
        for (const p in featureNS) {
          /** @type {Object<string, import("../xml.js").Parser>} */
          const parsers = {};
          for (let i = 0, ii = featureTypes.length; i < ii; ++i) {
            const featurePrefix = featureTypes[i].includes(':')
              ? featureTypes[i].split(':')[0]
              : defaultPrefix;
            if (featurePrefix === p) {
              parsers[featureTypes[i].split(':').pop()] =
                localName == 'featureMembers'
                  ? makeArrayPusher(this.readFeatureElement, this)
                  : makeReplacer(this.readFeatureElement, this);
            }
          }
          parsersNS[featureNS[p]] = parsers;
        }
        if (localName == 'featureMember' || localName == 'member') {
          features = pushParseAndPop(undefined, parsersNS, node, objectStack);
        } else {
          features = pushParseAndPop([], parsersNS, node, objectStack);
        }
      }
      if (features === null) {
        features = [];
      }
      return features;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {import("../geom/Geometry.js").default|import("../extent.js").Extent|undefined} Geometry.
     */
    readGeometryOrExtent(node, objectStack) {
      const context = /** @type {Object} */ (objectStack[0]);
      context['srsName'] = node.firstElementChild.getAttribute('srsName');
      context['srsDimension'] =
        node.firstElementChild.getAttribute('srsDimension');
      return pushParseAndPop(
        null,
        this.GEOMETRY_PARSERS,
        node,
        objectStack,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {import("../extent.js").Extent|undefined} Geometry.
     */
    readExtentElement(node, objectStack) {
      const context = /** @type {Object} */ (objectStack[0]);
      const extent = /** @type {import("../extent.js").Extent} */ (
        this.readGeometryOrExtent(node, objectStack)
      );
      return extent ? transformExtentWithOptions(extent, context) : undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {import("../geom/Geometry.js").default|undefined} Geometry.
     */
    readGeometryElement(node, objectStack) {
      const context = /** @type {Object} */ (objectStack[0]);
      const geometry = /** @type {import("../geom/Geometry.js").default} */ (
        this.readGeometryOrExtent(node, objectStack)
      );
      return geometry
        ? transformGeometryWithOptions(geometry, false, context)
        : undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @param {boolean} asFeature whether result should be wrapped as a feature.
     * @return {Feature|Object} Feature
     */
    readFeatureElementInternal(node, objectStack, asFeature) {
      let geometryName;
      const values = {};
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        let value;
        const localName = n.localName;
        // first, check if it is simple attribute
        if (
          n.childNodes.length === 0 ||
          (n.childNodes.length === 1 &&
            (n.firstChild.nodeType === 3 || n.firstChild.nodeType === 4))
        ) {
          value = getAllTextContent(n, false);
          if (ONLY_WHITESPACE_RE.test(value)) {
            value = undefined;
          }
        } else {
          if (asFeature) {
            //if feature, try it as a geometry or extent
            value =
              localName === 'boundedBy'
                ? this.readExtentElement(n, objectStack)
                : this.readGeometryElement(n, objectStack);
          }
          if (!value) {
            //if not a geometry or not a feature, treat it as a complex attribute
            value = this.readFeatureElementInternal(n, objectStack, false);
          } else if (localName !== 'boundedBy') {
            // boundedBy is an extent and must not be considered as a geometry
            geometryName = localName;
          }
        }

        const len = n.attributes.length;
        if (len > 0 && !(value instanceof Geometry)) {
          value = {_content_: value};
          for (let i = 0; i < len; i++) {
            const attName = n.attributes[i].name;
            value[attName] = n.attributes[i].value;
          }
        }

        if (values[localName]) {
          if (!(values[localName] instanceof Array)) {
            values[localName] = [values[localName]];
          }
          values[localName].push(value);
        } else {
          values[localName] = value;
        }
      }
      if (!asFeature) {
        return values;
      }
      const feature = new Feature(values);
      if (geometryName) {
        feature.setGeometryName(geometryName);
      }
      const fid =
        node.getAttribute('fid') || getAttributeNS(node, this.namespace, 'id');
      if (fid) {
        feature.setId(fid);
      }
      return feature;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Feature} Feature.
     */
    readFeatureElement(node, objectStack) {
      return this.readFeatureElementInternal(node, objectStack, true);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Point|undefined} Point.
     */
    readPoint(node, objectStack) {
      const flatCoordinates = this.readFlatCoordinatesFromNode(node, objectStack);
      if (flatCoordinates) {
        return new Point(flatCoordinates, 'XYZ');
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {MultiPoint|undefined} MultiPoint.
     */
    readMultiPoint(node, objectStack) {
      /** @type {Array<Array<number>>} */
      const coordinates = pushParseAndPop(
        [],
        this.MULTIPOINT_PARSERS,
        node,
        objectStack,
        this,
      );
      if (coordinates) {
        return new MultiPoint(coordinates);
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {MultiLineString|undefined} MultiLineString.
     */
    readMultiLineString(node, objectStack) {
      /** @type {Array<LineString>} */
      const lineStrings = pushParseAndPop(
        [],
        this.MULTILINESTRING_PARSERS,
        node,
        objectStack,
        this,
      );
      if (lineStrings) {
        return new MultiLineString(lineStrings);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {MultiPolygon|undefined} MultiPolygon.
     */
    readMultiPolygon(node, objectStack) {
      /** @type {Array<Polygon>} */
      const polygons = pushParseAndPop(
        [],
        this.MULTIPOLYGON_PARSERS,
        node,
        objectStack,
        this,
      );
      if (polygons) {
        return new MultiPolygon(polygons);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    pointMemberParser(node, objectStack) {
      parseNode(this.POINTMEMBER_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    lineStringMemberParser(node, objectStack) {
      parseNode(this.LINESTRINGMEMBER_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    polygonMemberParser(node, objectStack) {
      parseNode(this.POLYGONMEMBER_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {LineString|undefined} LineString.
     */
    readLineString(node, objectStack) {
      const flatCoordinates = this.readFlatCoordinatesFromNode(node, objectStack);
      if (flatCoordinates) {
        const lineString = new LineString(flatCoordinates, 'XYZ');
        return lineString;
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} LinearRing flat coordinates.
     */
    readFlatLinearRing(node, objectStack) {
      const ring = pushParseAndPop(
        null,
        this.GEOMETRY_FLAT_COORDINATES_PARSERS,
        node,
        objectStack,
        this,
      );
      if (ring) {
        return ring;
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {LinearRing|undefined} LinearRing.
     */
    readLinearRing(node, objectStack) {
      const flatCoordinates = this.readFlatCoordinatesFromNode(node, objectStack);
      if (flatCoordinates) {
        return new LinearRing(flatCoordinates, 'XYZ');
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Polygon|undefined} Polygon.
     */
    readPolygon(node, objectStack) {
      /** @type {Array<Array<number>>} */
      const flatLinearRings = pushParseAndPop(
        [null],
        this.FLAT_LINEAR_RINGS_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRings && flatLinearRings[0]) {
        const flatCoordinates = flatLinearRings[0];
        const ends = [flatCoordinates.length];
        let i, ii;
        for (i = 1, ii = flatLinearRings.length; i < ii; ++i) {
          extend$2(flatCoordinates, flatLinearRings[i]);
          ends.push(flatCoordinates.length);
        }
        return new Polygon(flatCoordinates, 'XYZ', ends);
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>} Flat coordinates.
     */
    readFlatCoordinatesFromNode(node, objectStack) {
      return pushParseAndPop(
        null,
        this.GEOMETRY_FLAT_COORDINATES_PARSERS,
        node,
        objectStack,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometryFromNode(node, options) {
      const geometry = this.readGeometryElement(node, [
        this.getReadOptions(node, options ? options : {}),
      ]);
      return geometry ? geometry : null;
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @override
     */
    readFeaturesFromNode(node, options) {
      const internalOptions = {
        featureType: this.featureType,
        featureNS: this.featureNS,
      };
      if (internalOptions) {
        Object.assign(internalOptions, this.getReadOptions(node, options));
      }
      const features = this.readFeaturesInternal(node, [internalOptions]);
      return features || [];
    }

    /**
     * @param {Element} node Node.
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromNode(node) {
      return get$2(
        this.srsName
          ? this.srsName
          : node.firstElementChild.getAttribute('srsName'),
      );
    }
  }

  GMLBase.prototype.namespace = GMLNS;

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.FLAT_LINEAR_RINGS_PARSERS = {
    'http://www.opengis.net/gml': {},
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS = {
    'http://www.opengis.net/gml': {},
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.GEOMETRY_PARSERS = {
    'http://www.opengis.net/gml': {},
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.MULTIPOINT_PARSERS = {
    'http://www.opengis.net/gml': {
      'pointMember': makeArrayPusher(GMLBase.prototype.pointMemberParser),
      'pointMembers': makeArrayPusher(GMLBase.prototype.pointMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.MULTILINESTRING_PARSERS = {
    'http://www.opengis.net/gml': {
      'lineStringMember': makeArrayPusher(
        GMLBase.prototype.lineStringMemberParser,
      ),
      'lineStringMembers': makeArrayPusher(
        GMLBase.prototype.lineStringMemberParser,
      ),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.MULTIPOLYGON_PARSERS = {
    'http://www.opengis.net/gml': {
      'polygonMember': makeArrayPusher(GMLBase.prototype.polygonMemberParser),
      'polygonMembers': makeArrayPusher(GMLBase.prototype.polygonMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.POINTMEMBER_PARSERS = {
    'http://www.opengis.net/gml': {
      'Point': makeArrayPusher(GMLBase.prototype.readFlatCoordinatesFromNode),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.LINESTRINGMEMBER_PARSERS = {
    'http://www.opengis.net/gml': {
      'LineString': makeArrayPusher(GMLBase.prototype.readLineString),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.POLYGONMEMBER_PARSERS = {
    'http://www.opengis.net/gml': {
      'Polygon': makeArrayPusher(GMLBase.prototype.readPolygon),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.RING_PARSERS = {
    'http://www.opengis.net/gml': {
      'LinearRing': makeReplacer(GMLBase.prototype.readFlatLinearRing),
    },
  };

  /**
   * @module ol/format/xsd
   */

  /**
   * @param {Node} node Node.
   * @return {boolean|undefined} Boolean.
   */
  function readBoolean(node) {
    const s = getAllTextContent(node, false);
    return readBooleanString(s);
  }

  /**
   * @param {string} string String.
   * @return {boolean|undefined} Boolean.
   */
  function readBooleanString(string) {
    const m = /^\s*(true|1)|(false|0)\s*$/.exec(string);
    if (m) {
      return m[1] !== undefined || false;
    }
    return undefined;
  }

  /**
   * @param {Node} node Node.
   * @return {number|undefined} DateTime in seconds.
   */
  function readDateTime(node) {
    const s = getAllTextContent(node, false);
    const dateTime = Date.parse(s);
    return isNaN(dateTime) ? undefined : dateTime / 1000;
  }

  /**
   * @param {Node} node Node.
   * @return {number|undefined} Decimal.
   */
  function readDecimal(node) {
    const s = getAllTextContent(node, false);
    return readDecimalString(s);
  }

  /**
   * @param {string} string String.
   * @return {number|undefined} Decimal.
   */
  function readDecimalString(string) {
    // FIXME check spec
    const m = /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)\s*$/i.exec(string);
    if (m) {
      return parseFloat(m[1]);
    }
    return undefined;
  }

  /**
   * @param {Node} node Node.
   * @return {number|undefined} Non negative integer.
   */
  function readPositiveInteger(node) {
    const s = getAllTextContent(node, false);
    return readNonNegativeIntegerString(s);
  }

  /**
   * @param {string} string String.
   * @return {number|undefined} Non negative integer.
   */
  function readNonNegativeIntegerString(string) {
    const m = /^\s*(\d+)\s*$/.exec(string);
    if (m) {
      return parseInt(m[1], 10);
    }
    return undefined;
  }

  /**
   * @param {Node} node Node.
   * @return {string|undefined} String.
   */
  function readString(node) {
    return getAllTextContent(node, false).trim();
  }

  /**
   * @param {Node} node Node to append a TextNode with the boolean to.
   * @param {boolean} bool Boolean.
   */
  function writeBooleanTextNode(node, bool) {
    writeStringTextNode(node, bool ? '1' : '0');
  }

  /**
   * @param {Node} node Node to append a CDATA Section with the string to.
   * @param {string} string String.
   */
  function writeCDATASection(node, string) {
    node.appendChild(getDocument().createCDATASection(string));
  }

  /**
   * @param {Node} node Node to append a TextNode with the dateTime to.
   * @param {number} dateTime DateTime in seconds.
   */
  function writeDateTimeTextNode(node, dateTime) {
    const date = new Date(dateTime * 1000);
    const string =
      date.getUTCFullYear() +
      '-' +
      padNumber(date.getUTCMonth() + 1, 2) +
      '-' +
      padNumber(date.getUTCDate(), 2) +
      'T' +
      padNumber(date.getUTCHours(), 2) +
      ':' +
      padNumber(date.getUTCMinutes(), 2) +
      ':' +
      padNumber(date.getUTCSeconds(), 2) +
      'Z';
    node.appendChild(getDocument().createTextNode(string));
  }

  /**
   * @param {Node} node Node to append a TextNode with the decimal to.
   * @param {number} decimal Decimal.
   */
  function writeDecimalTextNode(node, decimal) {
    const string = decimal.toPrecision();
    node.appendChild(getDocument().createTextNode(string));
  }

  /**
   * @param {Node} node Node to append a TextNode with the decimal to.
   * @param {number} nonNegativeInteger Non negative integer.
   */
  function writeNonNegativeIntegerTextNode(node, nonNegativeInteger) {
    const string = nonNegativeInteger.toString();
    node.appendChild(getDocument().createTextNode(string));
  }

  const whiteSpaceStart = /^\s/;
  const whiteSpaceEnd = /\s$/;
  const cdataCharacters = /(\n|\t|\r|<|&| {2})/;

  /**
   * @param {Node} node Node to append a TextNode with the string to.
   * @param {string} string String.
   */
  function writeStringTextNode(node, string) {
    if (
      typeof string === 'string' &&
      (whiteSpaceStart.test(string) ||
        whiteSpaceEnd.test(string) ||
        cdataCharacters.test(string))
    ) {
      string.split(']]>').forEach((part, i, a) => {
        if (i < a.length - 1) {
          part += ']]';
        }
        if (i > 0) {
          part = '>' + part;
        }
        writeCDATASection(node, part);
      });
    } else {
      node.appendChild(getDocument().createTextNode(string));
    }
  }

  /**
   * @module ol/format/GML2
   */

  /**
   * @const
   * @type {string}
   */
  const schemaLocation$1 =
    GMLNS + ' http://schemas.opengis.net/gml/2.1.2/feature.xsd';

  /**
   * @const
   * @type {Object<string, string>}
   */
  const MULTIGEOMETRY_TO_MEMBER_NODENAME$1 = {
    'MultiLineString': 'lineStringMember',
    'MultiCurve': 'curveMember',
    'MultiPolygon': 'polygonMember',
    'MultiSurface': 'surfaceMember',
  };

  /**
   * @classdesc
   * Feature format for reading and writing data in the GML format,
   * version 2.1.2.
   *
   * @api
   */
  class GML2 extends GMLBase {
    /**
     * @param {import("./GMLBase.js").Options} [options] Optional configuration object.
     */
    constructor(options) {
      options = options ? options : {};

      super(options);

      this.FEATURE_COLLECTION_PARSERS[GMLNS]['featureMember'] = makeArrayPusher(
        this.readFeaturesInternal,
      );

      /**
       * @type {string}
       */
      this.schemaLocation = options.schemaLocation
        ? options.schemaLocation
        : schemaLocation$1;
    }

    /**
     * @param {Node} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} Flat coordinates.
     */
    readFlatCoordinates(node, objectStack) {
      const s = getAllTextContent(node, false).replace(/^\s*|\s*$/g, '');
      const context = /** @type {import("../xml.js").NodeStackItem} */ (
        objectStack[0]
      );
      const containerSrs = context['srsName'];
      let axisOrientation = 'enu';
      if (containerSrs) {
        const proj = get$2(containerSrs);
        if (proj) {
          axisOrientation = proj.getAxisOrientation();
        }
      }
      const coordsGroups = s.trim().split(/\s+/);
      const flatCoordinates = [];
      for (let i = 0, ii = coordsGroups.length; i < ii; i++) {
        const coords = coordsGroups[i].split(/,+/);
        const x = parseFloat(coords[0]);
        const y = parseFloat(coords[1]);
        const z = coords.length === 3 ? parseFloat(coords[2]) : 0;
        if (axisOrientation.startsWith('en')) {
          flatCoordinates.push(x, y, z);
        } else {
          flatCoordinates.push(y, x, z);
        }
      }
      return flatCoordinates;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {import("../extent.js").Extent|undefined} Envelope.
     */
    readBox(node, objectStack) {
      /** @type {Array<number>} */
      const flatCoordinates = pushParseAndPop(
        [null],
        this.BOX_PARSERS_,
        node,
        objectStack,
        this,
      );
      return createOrUpdate$2(
        flatCoordinates[1][0],
        flatCoordinates[1][1],
        flatCoordinates[1][3],
        flatCoordinates[1][4],
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    innerBoundaryIsParser(node, objectStack) {
      /** @type {Array<number>|undefined} */
      const flatLinearRing = pushParseAndPop(
        undefined,
        this.RING_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRing) {
        const flatLinearRings =
          /** @type {Array<Array<number>>} */
          (objectStack[objectStack.length - 1]);
        flatLinearRings.push(flatLinearRing);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    outerBoundaryIsParser(node, objectStack) {
      /** @type {Array<number>|undefined} */
      const flatLinearRing = pushParseAndPop(
        undefined,
        this.RING_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRing) {
        const flatLinearRings =
          /** @type {Array<Array<number>>} */
          (objectStack[objectStack.length - 1]);
        flatLinearRings[0] = flatLinearRing;
      }
    }

    /**
     * @const
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Element|undefined} Node.
     * @private
     */
    GEOMETRY_NODE_FACTORY_(value, objectStack, nodeName) {
      const context = objectStack[objectStack.length - 1];
      const multiSurface = context['multiSurface'];
      const surface = context['surface'];
      const multiCurve = context['multiCurve'];
      if (!Array.isArray(value)) {
        nodeName = /** @type {import("../geom/Geometry.js").default} */ (
          value
        ).getType();
        if (nodeName === 'MultiPolygon' && multiSurface === true) {
          nodeName = 'MultiSurface';
        } else if (nodeName === 'Polygon' && surface === true) {
          nodeName = 'Surface';
        } else if (nodeName === 'MultiLineString' && multiCurve === true) {
          nodeName = 'MultiCurve';
        }
      } else {
        nodeName = 'Envelope';
      }
      return createElementNS('http://www.opengis.net/gml', nodeName);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../Feature.js").default} feature Feature.
     * @param {Array<*>} objectStack Node stack.
     */
    writeFeatureElement(node, feature, objectStack) {
      const fid = feature.getId();
      if (fid) {
        node.setAttribute('fid', /** @type {string} */ (fid));
      }
      const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
      const featureNS = context['featureNS'];
      const geometryName = feature.getGeometryName();
      if (!context.serializers) {
        context.serializers = {};
        context.serializers[featureNS] = {};
      }
      const keys = [];
      const values = [];
      if (feature.hasProperties()) {
        const properties = feature.getProperties();
        for (const key in properties) {
          const value = properties[key];
          if (value !== null && value !== undefined) {
            keys.push(key);
            values.push(value);
            if (
              key == geometryName ||
              typeof (/** @type {?} */ (value).getSimplifiedGeometry) ===
                'function'
            ) {
              if (!(key in context.serializers[featureNS])) {
                context.serializers[featureNS][key] = makeChildAppender(
                  this.writeGeometryElement,
                  this,
                );
              }
            } else {
              if (!(key in context.serializers[featureNS])) {
                context.serializers[featureNS][key] =
                  makeChildAppender(writeStringTextNode);
              }
            }
          }
        }
      }
      const item = Object.assign({}, context);
      item.node = node;
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        (item),
        context.serializers,
        makeSimpleNodeFactory(undefined, featureNS),
        values,
        objectStack,
        keys,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LineString.js").default} geometry LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeCurveOrLineString(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (node.nodeName !== 'LineStringSegment' && srsName) {
        node.setAttribute('srsName', srsName);
      }
      if (
        node.nodeName === 'LineString' ||
        node.nodeName === 'LineStringSegment'
      ) {
        const coordinates = this.createCoordinatesNode_(node.namespaceURI);
        node.appendChild(coordinates);
        this.writeCoordinates_(coordinates, geometry, objectStack);
      } else if (node.nodeName === 'Curve') {
        const segments = createElementNS(node.namespaceURI, 'segments');
        node.appendChild(segments);
        this.writeCurveSegments_(segments, geometry, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LineString.js").default} line LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeLineStringOrCurveMember(node, line, objectStack) {
      const child = this.GEOMETRY_NODE_FACTORY_(line, objectStack);
      if (child) {
        node.appendChild(child);
        this.writeCurveOrLineString(child, line, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/MultiLineString.js").default} geometry MultiLineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiCurveOrLineString(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      const curve = context['curve'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const lines = geometry.getLineStrings();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName, curve: curve},
        this.LINESTRINGORCURVEMEMBER_SERIALIZERS,
        this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,
        lines,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Node} node Node.
     * @param {import("../geom/Geometry.js").default|import("../extent.js").Extent} geometry Geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeGeometryElement(node, geometry, objectStack) {
      const context = /** @type {import("./Feature.js").WriteOptions} */ (
        objectStack[objectStack.length - 1]
      );
      const item = Object.assign({}, context);
      item['node'] = node;
      let value;
      if (Array.isArray(geometry)) {
        value = transformExtentWithOptions(
          /** @type {import("../extent.js").Extent} */ (geometry),
          context,
        );
      } else {
        value = transformGeometryWithOptions(
          /** @type {import("../geom/Geometry.js").default} */ (geometry),
          true,
          context,
        );
      }
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        (item),
        this.GEOMETRY_SERIALIZERS,
        this.GEOMETRY_NODE_FACTORY_,
        [value],
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {string} namespaceURI XML namespace.
     * @return {Element} coordinates node.
     * @private
     */
    createCoordinatesNode_(namespaceURI) {
      const coordinates = createElementNS(namespaceURI, 'coordinates');
      coordinates.setAttribute('decimal', '.');
      coordinates.setAttribute('cs', ',');
      coordinates.setAttribute('ts', ' ');

      return coordinates;
    }

    /**
     * @param {Node} node Node.
     * @param {import("../geom/LineString.js").default|import("../geom/LinearRing.js").default} value Geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeCoordinates_(node, value, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      // only 2d for simple features profile
      const points = value.getCoordinates();
      const len = points.length;
      const parts = new Array(len);
      for (let i = 0; i < len; ++i) {
        const point = points[i];
        parts[i] = this.getCoords_(point, srsName, hasZ);
      }
      writeStringTextNode(node, parts.join(' '));
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LineString.js").default} line LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeCurveSegments_(node, line, objectStack) {
      const child = createElementNS(node.namespaceURI, 'LineStringSegment');
      node.appendChild(child);
      this.writeCurveOrLineString(child, line, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Polygon.js").default} geometry Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeSurfaceOrPolygon(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      if (node.nodeName !== 'PolygonPatch' && srsName) {
        node.setAttribute('srsName', srsName);
      }
      if (node.nodeName === 'Polygon' || node.nodeName === 'PolygonPatch') {
        const rings = geometry.getLinearRings();
        pushSerializeAndPop(
          {node: node, hasZ: hasZ, srsName: srsName},
          this.RING_SERIALIZERS,
          this.RING_NODE_FACTORY_,
          rings,
          objectStack,
          undefined,
          this,
        );
      } else if (node.nodeName === 'Surface') {
        const patches = createElementNS(node.namespaceURI, 'patches');
        node.appendChild(patches);
        this.writeSurfacePatches_(patches, geometry, objectStack);
      }
    }

    /**
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Node} Node.
     * @private
     */
    RING_NODE_FACTORY_(value, objectStack, nodeName) {
      const context = objectStack[objectStack.length - 1];
      const parentNode = context.node;
      const exteriorWritten = context['exteriorWritten'];
      if (exteriorWritten === undefined) {
        context['exteriorWritten'] = true;
      }
      return createElementNS(
        parentNode.namespaceURI,
        exteriorWritten !== undefined ? 'innerBoundaryIs' : 'outerBoundaryIs',
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Polygon.js").default} polygon Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeSurfacePatches_(node, polygon, objectStack) {
      const child = createElementNS(node.namespaceURI, 'PolygonPatch');
      node.appendChild(child);
      this.writeSurfaceOrPolygon(child, polygon, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LinearRing.js").default} ring LinearRing geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeRing(node, ring, objectStack) {
      const linearRing = createElementNS(node.namespaceURI, 'LinearRing');
      node.appendChild(linearRing);
      this.writeLinearRing(linearRing, ring, objectStack);
    }

    /**
     * @param {Array<number>} point Point geometry.
     * @param {string} [srsName] Optional srsName
     * @param {boolean} [hasZ] whether the geometry has a Z coordinate (is 3D) or not.
     * @return {string} The coords string.
     * @private
     */
    getCoords_(point, srsName, hasZ) {
      const axisOrientation = srsName
        ? get$2(srsName).getAxisOrientation()
        : 'enu';
      let coords = axisOrientation.startsWith('en')
        ? point[0] + ',' + point[1]
        : point[1] + ',' + point[0];
      if (hasZ) {
        // For newly created points, Z can be undefined.
        const z = point[2] || 0;
        coords += ',' + z;
      }

      return coords;
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Point.js").default} geometry Point geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writePoint(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const coordinates = this.createCoordinatesNode_(node.namespaceURI);
      node.appendChild(coordinates);
      const point = geometry.getCoordinates();
      const coord = this.getCoords_(point, srsName, hasZ);
      writeStringTextNode(coordinates, coord);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/MultiPoint.js").default} geometry MultiPoint geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiPoint(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const points = geometry.getPoints();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName},
        this.POINTMEMBER_SERIALIZERS,
        makeSimpleNodeFactory('pointMember'),
        points,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Point.js").default} point Point geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writePointMember(node, point, objectStack) {
      const child = createElementNS(node.namespaceURI, 'Point');
      node.appendChild(child);
      this.writePoint(child, point, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LinearRing.js").default} geometry LinearRing geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeLinearRing(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const coordinates = this.createCoordinatesNode_(node.namespaceURI);
      node.appendChild(coordinates);
      this.writeCoordinates_(coordinates, geometry, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/MultiPolygon.js").default} geometry MultiPolygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiSurfaceOrPolygon(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      const surface = context['surface'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const polygons = geometry.getPolygons();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName, surface: surface},
        this.SURFACEORPOLYGONMEMBER_SERIALIZERS,
        this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,
        polygons,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Node} node Node.
     * @param {import("../geom/Polygon.js").default} polygon Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeSurfaceOrPolygonMember(node, polygon, objectStack) {
      const child = this.GEOMETRY_NODE_FACTORY_(polygon, objectStack);
      if (child) {
        node.appendChild(child);
        this.writeSurfaceOrPolygon(child, polygon, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {Array<*>} objectStack Node stack.
     */
    writeEnvelope(node, extent, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const keys = ['lowerCorner', 'upperCorner'];
      const values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]];
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        ({node: node}),
        this.ENVELOPE_SERIALIZERS,
        OBJECT_PROPERTY_NODE_FACTORY,
        values,
        objectStack,
        keys,
        this,
      );
    }

    /**
     * @const
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Node|undefined} Node.
     * @private
     */
    MULTIGEOMETRY_MEMBER_NODE_FACTORY_(value, objectStack, nodeName) {
      const parentNode = objectStack[objectStack.length - 1].node;
      return createElementNS(
        'http://www.opengis.net/gml',
        MULTIGEOMETRY_TO_MEMBER_NODENAME$1[parentNode.nodeName],
      );
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML2.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS = {
    'http://www.opengis.net/gml': {
      'coordinates': makeReplacer(GML2.prototype.readFlatCoordinates),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML2.prototype.FLAT_LINEAR_RINGS_PARSERS = {
    'http://www.opengis.net/gml': {
      'innerBoundaryIs': GML2.prototype.innerBoundaryIsParser,
      'outerBoundaryIs': GML2.prototype.outerBoundaryIsParser,
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML2.prototype.BOX_PARSERS_ = {
    'http://www.opengis.net/gml': {
      'coordinates': makeArrayPusher(GML2.prototype.readFlatCoordinates),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML2.prototype.GEOMETRY_PARSERS = {
    'http://www.opengis.net/gml': {
      'Point': makeReplacer(GMLBase.prototype.readPoint),
      'MultiPoint': makeReplacer(GMLBase.prototype.readMultiPoint),
      'LineString': makeReplacer(GMLBase.prototype.readLineString),
      'MultiLineString': makeReplacer(GMLBase.prototype.readMultiLineString),
      'LinearRing': makeReplacer(GMLBase.prototype.readLinearRing),
      'Polygon': makeReplacer(GMLBase.prototype.readPolygon),
      'MultiPolygon': makeReplacer(GMLBase.prototype.readMultiPolygon),
      'Box': makeReplacer(GML2.prototype.readBox),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.GEOMETRY_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'Curve': makeChildAppender(GML2.prototype.writeCurveOrLineString),
      'MultiCurve': makeChildAppender(GML2.prototype.writeMultiCurveOrLineString),
      'Point': makeChildAppender(GML2.prototype.writePoint),
      'MultiPoint': makeChildAppender(GML2.prototype.writeMultiPoint),
      'LineString': makeChildAppender(GML2.prototype.writeCurveOrLineString),
      'MultiLineString': makeChildAppender(
        GML2.prototype.writeMultiCurveOrLineString,
      ),
      'LinearRing': makeChildAppender(GML2.prototype.writeLinearRing),
      'Polygon': makeChildAppender(GML2.prototype.writeSurfaceOrPolygon),
      'MultiPolygon': makeChildAppender(
        GML2.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Surface': makeChildAppender(GML2.prototype.writeSurfaceOrPolygon),
      'MultiSurface': makeChildAppender(
        GML2.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Envelope': makeChildAppender(GML2.prototype.writeEnvelope),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.LINESTRINGORCURVEMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'lineStringMember': makeChildAppender(
        GML2.prototype.writeLineStringOrCurveMember,
      ),
      'curveMember': makeChildAppender(
        GML2.prototype.writeLineStringOrCurveMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.RING_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'outerBoundaryIs': makeChildAppender(GML2.prototype.writeRing),
      'innerBoundaryIs': makeChildAppender(GML2.prototype.writeRing),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.POINTMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'pointMember': makeChildAppender(GML2.prototype.writePointMember),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.SURFACEORPOLYGONMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'surfaceMember': makeChildAppender(
        GML2.prototype.writeSurfaceOrPolygonMember,
      ),
      'polygonMember': makeChildAppender(
        GML2.prototype.writeSurfaceOrPolygonMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML2.prototype.ENVELOPE_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'lowerCorner': makeChildAppender(writeStringTextNode),
      'upperCorner': makeChildAppender(writeStringTextNode),
    },
  };

  /**
   * @module ol/format/GML3
   */

  /**
   * @const
   * @type {string}
   * @private
   */
  const schemaLocation =
    GMLNS +
    ' http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/' +
    '1.0.0/gmlsf.xsd';

  /**
   * @const
   * @type {Object<string, string>}
   */
  const MULTIGEOMETRY_TO_MEMBER_NODENAME = {
    'MultiLineString': 'lineStringMember',
    'MultiCurve': 'curveMember',
    'MultiPolygon': 'polygonMember',
    'MultiSurface': 'surfaceMember',
  };

  /**
   * @classdesc
   * Feature format for reading and writing data in the GML format
   * version 3.1.1.
   * Currently only supports GML 3.1.1 Simple Features profile.
   *
   * @api
   */
  class GML3 extends GMLBase {
    /**
     * @param {import("./GMLBase.js").Options} [options] Optional configuration object.
     */
    constructor(options) {
      options = options ? options : {};

      super(options);

      /**
       * @private
       * @type {boolean}
       */
      this.surface_ = options.surface !== undefined ? options.surface : false;

      /**
       * @private
       * @type {boolean}
       */
      this.curve_ = options.curve !== undefined ? options.curve : false;

      /**
       * @private
       * @type {boolean}
       */
      this.multiCurve_ =
        options.multiCurve !== undefined ? options.multiCurve : true;

      /**
       * @private
       * @type {boolean}
       */
      this.multiSurface_ =
        options.multiSurface !== undefined ? options.multiSurface : true;

      /**
       * @type {string}
       */
      this.schemaLocation = options.schemaLocation
        ? options.schemaLocation
        : schemaLocation;

      /**
       * @private
       * @type {boolean}
       */
      this.hasZ = options.hasZ !== undefined ? options.hasZ : false;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {MultiLineString|undefined} MultiLineString.
     */
    readMultiCurve(node, objectStack) {
      /** @type {Array<LineString>} */
      const lineStrings = pushParseAndPop(
        [],
        this.MULTICURVE_PARSERS,
        node,
        objectStack,
        this,
      );
      if (lineStrings) {
        const multiLineString = new MultiLineString(lineStrings);
        return multiLineString;
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} Polygon.
     */
    readFlatCurveRing(node, objectStack) {
      /** @type {Array<LineString>} */
      const lineStrings = pushParseAndPop(
        [],
        this.MULTICURVE_PARSERS,
        node,
        objectStack,
        this,
      );
      const flatCoordinates = [];
      for (let i = 0, ii = lineStrings.length; i < ii; ++i) {
        extend$2(flatCoordinates, lineStrings[i].getFlatCoordinates());
      }
      return flatCoordinates;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {MultiPolygon|undefined} MultiPolygon.
     */
    readMultiSurface(node, objectStack) {
      /** @type {Array<Polygon>} */
      const polygons = pushParseAndPop(
        [],
        this.MULTISURFACE_PARSERS,
        node,
        objectStack,
        this,
      );
      if (polygons) {
        return new MultiPolygon(polygons);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    curveMemberParser(node, objectStack) {
      parseNode(this.CURVEMEMBER_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    surfaceMemberParser(node, objectStack) {
      parseNode(this.SURFACEMEMBER_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<(Array<number>)>|undefined} flat coordinates.
     */
    readPatch(node, objectStack) {
      return pushParseAndPop(
        [null],
        this.PATCHES_PARSERS,
        node,
        objectStack,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} flat coordinates.
     */
    readSegment(node, objectStack) {
      return pushParseAndPop([], this.SEGMENTS_PARSERS, node, objectStack, this);
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<(Array<number>)>|undefined} flat coordinates.
     */
    readPolygonPatch(node, objectStack) {
      return pushParseAndPop(
        [null],
        this.FLAT_LINEAR_RINGS_PARSERS,
        node,
        objectStack,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} flat coordinates.
     */
    readLineStringSegment(node, objectStack) {
      return pushParseAndPop(
        [null],
        this.GEOMETRY_FLAT_COORDINATES_PARSERS,
        node,
        objectStack,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    interiorParser(node, objectStack) {
      /** @type {Array<number>|undefined} */
      const flatLinearRing = pushParseAndPop(
        undefined,
        this.RING_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRing) {
        const flatLinearRings =
          /** @type {Array<Array<number>>} */
          (objectStack[objectStack.length - 1]);
        flatLinearRings.push(flatLinearRing);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     */
    exteriorParser(node, objectStack) {
      /** @type {Array<number>|undefined} */
      const flatLinearRing = pushParseAndPop(
        undefined,
        this.RING_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRing) {
        const flatLinearRings =
          /** @type {Array<Array<number>>} */
          (objectStack[objectStack.length - 1]);
        flatLinearRings[0] = flatLinearRing;
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Polygon|undefined} Polygon.
     */
    readSurface(node, objectStack) {
      /** @type {Array<Array<number>>} */
      const flatLinearRings = pushParseAndPop(
        [null],
        this.SURFACE_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatLinearRings && flatLinearRings[0]) {
        const flatCoordinates = flatLinearRings[0];
        const ends = [flatCoordinates.length];
        let i, ii;
        for (i = 1, ii = flatLinearRings.length; i < ii; ++i) {
          extend$2(flatCoordinates, flatLinearRings[i]);
          ends.push(flatCoordinates.length);
        }
        return new Polygon(flatCoordinates, 'XYZ', ends);
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {LineString|undefined} LineString.
     */
    readCurve(node, objectStack) {
      /** @type {Array<number>} */
      const flatCoordinates = pushParseAndPop(
        [null],
        this.CURVE_PARSERS,
        node,
        objectStack,
        this,
      );
      if (flatCoordinates) {
        const lineString = new LineString(flatCoordinates, 'XYZ');
        return lineString;
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {import("../extent.js").Extent|undefined} Envelope.
     */
    readEnvelope(node, objectStack) {
      /** @type {Array<number>} */
      const flatCoordinates = pushParseAndPop(
        [null],
        this.ENVELOPE_PARSERS,
        node,
        objectStack,
        this,
      );
      return createOrUpdate$2(
        flatCoordinates[1][0],
        flatCoordinates[1][1],
        flatCoordinates[2][0],
        flatCoordinates[2][1],
      );
    }

    /**
     * @param {Node} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} Flat coordinates.
     */
    readFlatPos(node, objectStack) {
      let s = getAllTextContent(node, false);
      const re = /^\s*([+\-]?\d*\.?\d+(?:[eE][+\-]?\d+)?)\s*/;
      /** @type {Array<number>} */
      const flatCoordinates = [];
      let m;
      while ((m = re.exec(s))) {
        flatCoordinates.push(parseFloat(m[1]));
        s = s.substr(m[0].length);
      }
      if (s !== '') {
        return undefined;
      }
      const context = objectStack[0];
      const containerSrs = context['srsName'];
      const axisOrientation = containerSrs
        ? get$2(containerSrs).getAxisOrientation()
        : 'enu';
      if (axisOrientation === 'neu') {
        for (let i = 0, ii = flatCoordinates.length; i < ii; i += 3) {
          const y = flatCoordinates[i];
          const x = flatCoordinates[i + 1];
          flatCoordinates[i] = x;
          flatCoordinates[i + 1] = y;
        }
      }
      const len = flatCoordinates.length;
      if (len == 2) {
        flatCoordinates.push(0);
      }
      if (len === 0) {
        return undefined;
      }
      return flatCoordinates;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<number>|undefined} Flat coordinates.
     */
    readFlatPosList(node, objectStack) {
      const s = getAllTextContent(node, false).replace(/^\s*|\s*$/g, '');
      const context = objectStack[0];
      const containerSrs = context['srsName'];
      const contextDimension = context['srsDimension'];
      const axisOrientation = containerSrs
        ? get$2(containerSrs).getAxisOrientation()
        : 'enu';
      const coords = s.split(/\s+/);
      // The "dimension" attribute is from the GML 3.0.1 spec.
      let dim = 2;
      if (node.getAttribute('srsDimension')) {
        dim = readNonNegativeIntegerString(node.getAttribute('srsDimension'));
      } else if (node.getAttribute('dimension')) {
        dim = readNonNegativeIntegerString(node.getAttribute('dimension'));
      } else if (
        /** @type {Element} */ (node.parentNode).getAttribute('srsDimension')
      ) {
        dim = readNonNegativeIntegerString(
          /** @type {Element} */ (node.parentNode).getAttribute('srsDimension'),
        );
      } else if (contextDimension) {
        dim = readNonNegativeIntegerString(contextDimension);
      }
      const asXYZ = axisOrientation.startsWith('en');
      let x, y, z;
      const flatCoordinates = [];
      for (let i = 0, ii = coords.length; i < ii; i += dim) {
        x = parseFloat(coords[i]);
        y = parseFloat(coords[i + 1]);
        z = dim === 3 ? parseFloat(coords[i + 2]) : 0;
        if (asXYZ) {
          flatCoordinates.push(x, y, z);
        } else {
          flatCoordinates.push(y, x, z);
        }
      }
      return flatCoordinates;
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Point.js").default} value Point geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writePos_(node, value, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsDimension = hasZ ? '3' : '2';
      node.setAttribute('srsDimension', srsDimension);
      const srsName = context['srsName'];
      const axisOrientation = srsName
        ? get$2(srsName).getAxisOrientation()
        : 'enu';
      const point = value.getCoordinates();
      // only 2d for simple features profile
      let coords = axisOrientation.startsWith('en')
        ? point[0] + ' ' + point[1]
        : point[1] + ' ' + point[0];
      if (hasZ) {
        // For newly created points, Z can be undefined.
        const z = point[2] || 0;
        coords += ' ' + z;
      }
      writeStringTextNode(node, coords);
    }

    /**
     * @param {Array<number>} point Point geometry.
     * @param {string} [srsName] Optional srsName
     * @param {boolean} [hasZ] whether the geometry has a Z coordinate (is 3D) or not.
     * @return {string} The coords string.
     * @private
     */
    getCoords_(point, srsName, hasZ) {
      const axisOrientation = srsName
        ? get$2(srsName).getAxisOrientation()
        : 'enu';
      let coords = axisOrientation.startsWith('en')
        ? point[0] + ' ' + point[1]
        : point[1] + ' ' + point[0];
      if (hasZ) {
        // For newly created points, Z can be undefined.
        const z = point[2] || 0;
        coords += ' ' + z;
      }

      return coords;
    }

    /**
     * @param {Element} node Node.
     * @param {LineString|import("../geom/LinearRing.js").default} value Geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writePosList_(node, value, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsDimension = hasZ ? '3' : '2';
      node.setAttribute('srsDimension', srsDimension);
      const srsName = context['srsName'];
      // only 2d for simple features profile
      const points = value.getCoordinates();
      const len = points.length;
      const parts = new Array(len);
      let point;
      for (let i = 0; i < len; ++i) {
        point = points[i];
        parts[i] = this.getCoords_(point, srsName, hasZ);
      }
      writeStringTextNode(node, parts.join(' '));
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Point.js").default} geometry Point geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writePoint(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const pos = createElementNS(node.namespaceURI, 'pos');
      node.appendChild(pos);
      this.writePos_(pos, geometry, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {Array<*>} objectStack Node stack.
     */
    writeEnvelope(node, extent, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const keys = ['lowerCorner', 'upperCorner'];
      const values = [extent[0] + ' ' + extent[1], extent[2] + ' ' + extent[3]];
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        ({node: node}),
        this.ENVELOPE_SERIALIZERS,
        OBJECT_PROPERTY_NODE_FACTORY,
        values,
        objectStack,
        keys,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LinearRing.js").default} geometry LinearRing geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeLinearRing(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const posList = createElementNS(node.namespaceURI, 'posList');
      node.appendChild(posList);
      this.writePosList_(posList, geometry, objectStack);
    }

    /**
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Node} Node.
     * @private
     */
    RING_NODE_FACTORY_(value, objectStack, nodeName) {
      const context = objectStack[objectStack.length - 1];
      const parentNode = context.node;
      const exteriorWritten = context['exteriorWritten'];
      if (exteriorWritten === undefined) {
        context['exteriorWritten'] = true;
      }
      return createElementNS(
        parentNode.namespaceURI,
        exteriorWritten !== undefined ? 'interior' : 'exterior',
      );
    }

    /**
     * @param {Element} node Node.
     * @param {Polygon} geometry Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeSurfaceOrPolygon(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      if (node.nodeName !== 'PolygonPatch' && srsName) {
        node.setAttribute('srsName', srsName);
      }
      if (node.nodeName === 'Polygon' || node.nodeName === 'PolygonPatch') {
        const rings = geometry.getLinearRings();
        pushSerializeAndPop(
          {node: node, hasZ: hasZ, srsName: srsName},
          this.RING_SERIALIZERS,
          this.RING_NODE_FACTORY_,
          rings,
          objectStack,
          undefined,
          this,
        );
      } else if (node.nodeName === 'Surface') {
        const patches = createElementNS(node.namespaceURI, 'patches');
        node.appendChild(patches);
        this.writeSurfacePatches_(patches, geometry, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {LineString} geometry LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeCurveOrLineString(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      if (node.nodeName !== 'LineStringSegment' && srsName) {
        node.setAttribute('srsName', srsName);
      }
      if (
        node.nodeName === 'LineString' ||
        node.nodeName === 'LineStringSegment'
      ) {
        const posList = createElementNS(node.namespaceURI, 'posList');
        node.appendChild(posList);
        this.writePosList_(posList, geometry, objectStack);
      } else if (node.nodeName === 'Curve') {
        const segments = createElementNS(node.namespaceURI, 'segments');
        node.appendChild(segments);
        this.writeCurveSegments_(segments, geometry, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {MultiPolygon} geometry MultiPolygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiSurfaceOrPolygon(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      const surface = context['surface'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const polygons = geometry.getPolygons();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName, surface: surface},
        this.SURFACEORPOLYGONMEMBER_SERIALIZERS,
        this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,
        polygons,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/MultiPoint.js").default} geometry MultiPoint geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiPoint(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const srsName = context['srsName'];
      const hasZ = context['hasZ'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const points = geometry.getPoints();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName},
        this.POINTMEMBER_SERIALIZERS,
        makeSimpleNodeFactory('pointMember'),
        points,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {MultiLineString} geometry MultiLineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeMultiCurveOrLineString(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      const hasZ = context['hasZ'];
      const srsName = context['srsName'];
      const curve = context['curve'];
      if (srsName) {
        node.setAttribute('srsName', srsName);
      }
      const lines = geometry.getLineStrings();
      pushSerializeAndPop(
        {node: node, hasZ: hasZ, srsName: srsName, curve: curve},
        this.LINESTRINGORCURVEMEMBER_SERIALIZERS,
        this.MULTIGEOMETRY_MEMBER_NODE_FACTORY_,
        lines,
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/LinearRing.js").default} ring LinearRing geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeRing(node, ring, objectStack) {
      const linearRing = createElementNS(node.namespaceURI, 'LinearRing');
      node.appendChild(linearRing);
      this.writeLinearRing(linearRing, ring, objectStack);
    }

    /**
     * @param {Node} node Node.
     * @param {Polygon} polygon Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeSurfaceOrPolygonMember(node, polygon, objectStack) {
      const child = this.GEOMETRY_NODE_FACTORY_(polygon, objectStack);
      if (child) {
        node.appendChild(child);
        this.writeSurfaceOrPolygon(child, polygon, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {import("../geom/Point.js").default} point Point geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writePointMember(node, point, objectStack) {
      const child = createElementNS(node.namespaceURI, 'Point');
      node.appendChild(child);
      this.writePoint(child, point, objectStack);
    }

    /**
     * @param {Node} node Node.
     * @param {LineString} line LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeLineStringOrCurveMember(node, line, objectStack) {
      const child = this.GEOMETRY_NODE_FACTORY_(line, objectStack);
      if (child) {
        node.appendChild(child);
        this.writeCurveOrLineString(child, line, objectStack);
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Polygon} polygon Polygon geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeSurfacePatches_(node, polygon, objectStack) {
      const child = createElementNS(node.namespaceURI, 'PolygonPatch');
      node.appendChild(child);
      this.writeSurfaceOrPolygon(child, polygon, objectStack);
    }

    /**
     * @param {Element} node Node.
     * @param {LineString} line LineString geometry.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeCurveSegments_(node, line, objectStack) {
      const child = createElementNS(node.namespaceURI, 'LineStringSegment');
      node.appendChild(child);
      this.writeCurveOrLineString(child, line, objectStack);
    }

    /**
     * @param {Node} node Node.
     * @param {import("../geom/Geometry.js").default|import("../extent.js").Extent} geometry Geometry.
     * @param {Array<*>} objectStack Node stack.
     */
    writeGeometryElement(node, geometry, objectStack) {
      const context = /** @type {import("./Feature.js").WriteOptions} */ (
        objectStack[objectStack.length - 1]
      );
      const item = Object.assign({}, context);
      item['node'] = node;
      let value;
      if (Array.isArray(geometry)) {
        value = transformExtentWithOptions(
          /** @type {import("../extent.js").Extent} */ (geometry),
          context,
        );
      } else {
        value = transformGeometryWithOptions(
          /** @type {import("../geom/Geometry.js").default} */ (geometry),
          true,
          context,
        );
      }
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        (item),
        this.GEOMETRY_SERIALIZERS,
        this.GEOMETRY_NODE_FACTORY_,
        [value],
        objectStack,
        undefined,
        this,
      );
    }

    /**
     * @param {Element} node Node.
     * @param {import("../Feature.js").default} feature Feature.
     * @param {Array<*>} objectStack Node stack.
     */
    writeFeatureElement(node, feature, objectStack) {
      const fid = feature.getId();
      if (fid) {
        node.setAttribute('fid', /** @type {string} */ (fid));
      }
      const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
      const featureNS = context['featureNS'];
      const geometryName = feature.getGeometryName();
      if (!context.serializers) {
        context.serializers = {};
        context.serializers[featureNS] = {};
      }
      const keys = [];
      const values = [];
      if (feature.hasProperties()) {
        const properties = feature.getProperties();
        for (const key in properties) {
          const value = properties[key];
          if (value !== null && value !== undefined) {
            keys.push(key);
            values.push(value);
            if (
              key == geometryName ||
              typeof (/** @type {?} */ (value).getSimplifiedGeometry) ===
                'function'
            ) {
              if (!(key in context.serializers[featureNS])) {
                context.serializers[featureNS][key] = makeChildAppender(
                  this.writeGeometryElement,
                  this,
                );
              }
            } else {
              if (!(key in context.serializers[featureNS])) {
                context.serializers[featureNS][key] =
                  makeChildAppender(writeStringTextNode);
              }
            }
          }
        }
      }
      const item = Object.assign({}, context);
      item.node = node;
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        (item),
        context.serializers,
        makeSimpleNodeFactory(undefined, featureNS),
        values,
        objectStack,
        keys,
      );
    }

    /**
     * @param {Node} node Node.
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {Array<*>} objectStack Node stack.
     * @private
     */
    writeFeatureMembers_(node, features, objectStack) {
      const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
      const featureType = context['featureType'];
      const featureNS = context['featureNS'];
      /** @type {Object<string, Object<string, import("../xml.js").Serializer>>} */
      const serializers = {};
      serializers[featureNS] = {};
      serializers[featureNS][featureType] = makeChildAppender(
        this.writeFeatureElement,
        this,
      );
      const item = Object.assign({}, context);
      item.node = node;
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        (item),
        serializers,
        makeSimpleNodeFactory(featureType, featureNS),
        features,
        objectStack,
      );
    }

    /**
     * @const
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Node|undefined} Node.
     * @private
     */
    MULTIGEOMETRY_MEMBER_NODE_FACTORY_(value, objectStack, nodeName) {
      const parentNode = objectStack[objectStack.length - 1].node;
      return createElementNS(
        this.namespace,
        MULTIGEOMETRY_TO_MEMBER_NODENAME[parentNode.nodeName],
      );
    }

    /**
     * @const
     * @param {*} value Value.
     * @param {Array<*>} objectStack Object stack.
     * @param {string} [nodeName] Node name.
     * @return {Element|undefined} Node.
     * @private
     */
    GEOMETRY_NODE_FACTORY_(value, objectStack, nodeName) {
      const context = objectStack[objectStack.length - 1];
      const multiSurface = context['multiSurface'];
      const surface = context['surface'];
      const curve = context['curve'];
      const multiCurve = context['multiCurve'];
      if (!Array.isArray(value)) {
        nodeName = /** @type {import("../geom/Geometry.js").default} */ (
          value
        ).getType();
        if (nodeName === 'MultiPolygon' && multiSurface === true) {
          nodeName = 'MultiSurface';
        } else if (nodeName === 'Polygon' && surface === true) {
          nodeName = 'Surface';
        } else if (nodeName === 'LineString' && curve === true) {
          nodeName = 'Curve';
        } else if (nodeName === 'MultiLineString' && multiCurve === true) {
          nodeName = 'MultiCurve';
        }
      } else {
        nodeName = 'Envelope';
      }
      return createElementNS(this.namespace, nodeName);
    }

    /**
     * Encode a geometry in GML 3.1.1 Simple Features.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Node} Node.
     * @api
     * @override
     */
    writeGeometryNode(geometry, options) {
      options = this.adaptOptions(options);
      const geom = createElementNS(this.namespace, 'geom');
      const context = {
        node: geom,
        hasZ: this.hasZ,
        srsName: this.srsName,
        curve: this.curve_,
        surface: this.surface_,
        multiSurface: this.multiSurface_,
        multiCurve: this.multiCurve_,
      };
      if (options) {
        Object.assign(context, options);
      }
      this.writeGeometryElement(geom, geometry, [context]);
      return geom;
    }

    /**
     * Encode an array of features in the GML 3.1.1 format as an XML node.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Element} Node.
     * @api
     * @override
     */
    writeFeaturesNode(features, options) {
      options = this.adaptOptions(options);
      const node = createElementNS(this.namespace, 'featureMembers');
      node.setAttributeNS(
        XML_SCHEMA_INSTANCE_URI,
        'xsi:schemaLocation',
        this.schemaLocation,
      );
      const context = {
        srsName: this.srsName,
        hasZ: this.hasZ,
        curve: this.curve_,
        surface: this.surface_,
        multiSurface: this.multiSurface_,
        multiCurve: this.multiCurve_,
        featureNS: this.featureNS,
        featureType: this.featureType,
      };
      if (options) {
        Object.assign(context, options);
      }
      this.writeFeatureMembers_(node, features, [context]);
      return node;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS = {
    'http://www.opengis.net/gml': {
      'pos': makeReplacer(GML3.prototype.readFlatPos),
      'posList': makeReplacer(GML3.prototype.readFlatPosList),
      'coordinates': makeReplacer(GML2.prototype.readFlatCoordinates),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.FLAT_LINEAR_RINGS_PARSERS = {
    'http://www.opengis.net/gml': {
      'interior': GML3.prototype.interiorParser,
      'exterior': GML3.prototype.exteriorParser,
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.GEOMETRY_PARSERS = {
    'http://www.opengis.net/gml': {
      'Point': makeReplacer(GMLBase.prototype.readPoint),
      'MultiPoint': makeReplacer(GMLBase.prototype.readMultiPoint),
      'LineString': makeReplacer(GMLBase.prototype.readLineString),
      'MultiLineString': makeReplacer(GMLBase.prototype.readMultiLineString),
      'LinearRing': makeReplacer(GMLBase.prototype.readLinearRing),
      'Polygon': makeReplacer(GMLBase.prototype.readPolygon),
      'MultiPolygon': makeReplacer(GMLBase.prototype.readMultiPolygon),
      'Surface': makeReplacer(GML3.prototype.readSurface),
      'MultiSurface': makeReplacer(GML3.prototype.readMultiSurface),
      'Curve': makeReplacer(GML3.prototype.readCurve),
      'MultiCurve': makeReplacer(GML3.prototype.readMultiCurve),
      'Envelope': makeReplacer(GML3.prototype.readEnvelope),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.MULTICURVE_PARSERS = {
    'http://www.opengis.net/gml': {
      'curveMember': makeArrayPusher(GML3.prototype.curveMemberParser),
      'curveMembers': makeArrayPusher(GML3.prototype.curveMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.MULTISURFACE_PARSERS = {
    'http://www.opengis.net/gml': {
      'surfaceMember': makeArrayPusher(GML3.prototype.surfaceMemberParser),
      'surfaceMembers': makeArrayPusher(GML3.prototype.surfaceMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.CURVEMEMBER_PARSERS = {
    'http://www.opengis.net/gml': {
      'LineString': makeArrayPusher(GMLBase.prototype.readLineString),
      'Curve': makeArrayPusher(GML3.prototype.readCurve),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.SURFACEMEMBER_PARSERS = {
    'http://www.opengis.net/gml': {
      'Polygon': makeArrayPusher(GMLBase.prototype.readPolygon),
      'Surface': makeArrayPusher(GML3.prototype.readSurface),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.SURFACE_PARSERS = {
    'http://www.opengis.net/gml': {
      'patches': makeReplacer(GML3.prototype.readPatch),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.CURVE_PARSERS = {
    'http://www.opengis.net/gml': {
      'segments': makeReplacer(GML3.prototype.readSegment),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.ENVELOPE_PARSERS = {
    'http://www.opengis.net/gml': {
      'lowerCorner': makeArrayPusher(GML3.prototype.readFlatPosList),
      'upperCorner': makeArrayPusher(GML3.prototype.readFlatPosList),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.PATCHES_PARSERS = {
    'http://www.opengis.net/gml': {
      'PolygonPatch': makeReplacer(GML3.prototype.readPolygonPatch),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML3.prototype.SEGMENTS_PARSERS = {
    'http://www.opengis.net/gml': {
      'LineStringSegment': makeArrayExtender(
        GML3.prototype.readLineStringSegment,
      ),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GMLBase.prototype.RING_PARSERS = {
    'http://www.opengis.net/gml': {
      'LinearRing': makeReplacer(GMLBase.prototype.readFlatLinearRing),
      'Ring': makeReplacer(GML3.prototype.readFlatCurveRing),
    },
  };

  /**
   * Encode an array of features in GML 3.1.1 Simple Features.
   *
   * @function
   * @param {Array<import("../Feature.js").default>} features Features.
   * @param {import("./Feature.js").WriteOptions} [options] Options.
   * @return {string} Result.
   * @api
   */
  GML3.prototype.writeFeatures;

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.RING_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'exterior': makeChildAppender(GML3.prototype.writeRing),
      'interior': makeChildAppender(GML3.prototype.writeRing),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.ENVELOPE_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'lowerCorner': makeChildAppender(writeStringTextNode),
      'upperCorner': makeChildAppender(writeStringTextNode),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.SURFACEORPOLYGONMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'surfaceMember': makeChildAppender(
        GML3.prototype.writeSurfaceOrPolygonMember,
      ),
      'polygonMember': makeChildAppender(
        GML3.prototype.writeSurfaceOrPolygonMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.POINTMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'pointMember': makeChildAppender(GML3.prototype.writePointMember),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.LINESTRINGORCURVEMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'lineStringMember': makeChildAppender(
        GML3.prototype.writeLineStringOrCurveMember,
      ),
      'curveMember': makeChildAppender(
        GML3.prototype.writeLineStringOrCurveMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML3.prototype.GEOMETRY_SERIALIZERS = {
    'http://www.opengis.net/gml': {
      'Curve': makeChildAppender(GML3.prototype.writeCurveOrLineString),
      'MultiCurve': makeChildAppender(GML3.prototype.writeMultiCurveOrLineString),
      'Point': makeChildAppender(GML3.prototype.writePoint),
      'MultiPoint': makeChildAppender(GML3.prototype.writeMultiPoint),
      'LineString': makeChildAppender(GML3.prototype.writeCurveOrLineString),
      'MultiLineString': makeChildAppender(
        GML3.prototype.writeMultiCurveOrLineString,
      ),
      'LinearRing': makeChildAppender(GML3.prototype.writeLinearRing),
      'Polygon': makeChildAppender(GML3.prototype.writeSurfaceOrPolygon),
      'MultiPolygon': makeChildAppender(
        GML3.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Surface': makeChildAppender(GML3.prototype.writeSurfaceOrPolygon),
      'MultiSurface': makeChildAppender(
        GML3.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Envelope': makeChildAppender(GML3.prototype.writeEnvelope),
    },
  };

  /**
   * @module ol/format/GML
   */

  /**
   * Feature format for reading and writing data in the GML format
   * version 3.1.1.
   * Currently only supports GML 3.1.1 Simple Features profile.
   *
   * @class
   * @param {import("./GMLBase.js").Options} [options]
   *     Optional configuration object.
   * @api
   */
  const GML = GML3;

  /**
   * Encode an array of features in GML 3.1.1 Simple Features.
   *
   * @function
   * @param {Array<import("../Feature.js").default>} features Features.
   * @param {import("./Feature.js").WriteOptions} [options] Options.
   * @return {string} Result.
   * @api
   */
  GML.prototype.writeFeatures;

  /**
   * Encode an array of features in the GML 3.1.1 format as an XML node.
   *
   * @function
   * @param {Array<import("../Feature.js").default>} features Features.
   * @param {import("./Feature.js").WriteOptions} [options] Options.
   * @return {Node} Node.
   * @api
   */
  GML.prototype.writeFeaturesNode;

  /**
   * @module ol/format/GPX
   */

  /**
   * @const
   * @type {Array<null|string>}
   */
  const NAMESPACE_URIS$4 = [
    null,
    'http://www.topografix.com/GPX/1/0',
    'http://www.topografix.com/GPX/1/1',
  ];

  /**
   * @const
   * @type {string}
   */
  const SCHEMA_LOCATION$1 =
    'http://www.topografix.com/GPX/1/1 ' +
    'http://www.topografix.com/GPX/1/1/gpx.xsd';

  /**
   * @const
   * @type {Object<string, function(Node, Array<*>): (Feature|undefined)>}
   */
  const FEATURE_READER = {
    'rte': readRte,
    'trk': readTrk,
    'wpt': readWpt,
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const GPX_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'rte': makeArrayPusher(readRte),
    'trk': makeArrayPusher(readTrk),
    'wpt': makeArrayPusher(readWpt),
  });

  /**
   * @typedef {Object} GPXLink
   * @property {string} [text] text
   * @property {string} [type] type
   */

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LINK_PARSERS$1 = makeStructureNS(NAMESPACE_URIS$4, {
    'text': makeObjectPropertySetter(readString, 'linkText'),
    'type': makeObjectPropertySetter(readString, 'linkType'),
  });

  /**
   * @typedef {Object} GPXAuthor
   * @property {string} [name] name
   * @property {string} [email] email
   * @property {GPXLink} [link] link
   */

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const AUTHOR_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeObjectPropertySetter(readString),
    'email': parseEmail,
    'link': parseLink,
  });

  /**
   * @typedef {Object} GPXMetadata
   * @property {string} [name] name
   * @property {string} [desc] desc
   * @property {GPXAuthor} [author] author
   * @property {GPXLink} [link] link
   * @property {number} [time] time
   * @property {string} [keywords] keywords
   * @property {Array<number>} [bounds] bounds
   * @property {Object} [extensions] extensions
   *
   */

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const METADATA_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeObjectPropertySetter(readString),
    'desc': makeObjectPropertySetter(readString),
    'author': makeObjectPropertySetter(readAuthor),
    'copyright': makeObjectPropertySetter(readCopyright),
    'link': parseLink,
    'time': makeObjectPropertySetter(readDateTime),
    'keywords': makeObjectPropertySetter(readString),
    'bounds': parseBounds,
    'extensions': parseExtensions,
  });

  /**
   * @typedef {Object} GPXCopyright
   * @property {string} [author] author
   * @property {number} [year] year
   * @property {string} [license] license
   */

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const COPYRIGHT_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'year': makeObjectPropertySetter(readPositiveInteger),
    'license': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const GPX_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'rte': makeChildAppender(writeRte),
    'trk': makeChildAppender(writeTrk),
    'wpt': makeChildAppender(writeWpt),
  });

  /**
   * @typedef {Object} Options
   * @property {function(Feature, Node):void} [readExtensions] Callback function
   * to process `extensions` nodes. To prevent memory leaks, this callback function must
   * not store any references to the node. Note that the `extensions`
   * node is not allowed in GPX 1.0. Moreover, only `extensions`
   * nodes from `wpt`, `rte` and `trk` can be processed, as those are
   * directly mapped to a feature.
   */

  /**
   * @typedef {Object} LayoutOptions
   * @property {boolean} [hasZ] HasZ.
   * @property {boolean} [hasM] HasM.
   */

  /**
   * @typedef {function(Feature, Node): void} ReadExtensions
   */

  /**
   * @classdesc
   * Feature format for reading and writing data in the GPX format.
   *
   * Note that {@link module:ol/format/GPX~GPX#readFeature} only reads the first
   * feature of the source.
   *
   * When reading, routes (`<rte>`) are converted into LineString geometries, and
   * tracks (`<trk>`) into MultiLineString. Any properties on route and track
   * waypoints are ignored.
   *
   * When writing, LineString geometries are output as routes (`<rte>`), and
   * MultiLineString as tracks (`<trk>`).
   *
   * @api
   */
  class GPX extends XMLFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2('EPSG:4326');

      /**
       * @type {ReadExtensions|undefined}
       * @private
       */
      this.readExtensions_ = options.readExtensions;
    }

    /**
     * @param {Array<Feature>} features List of features.
     * @private
     */
    handleReadExtensions_(features) {
      if (!features) {
        features = [];
      }
      for (let i = 0, ii = features.length; i < ii; ++i) {
        const feature = features[i];
        if (this.readExtensions_) {
          const extensionsNode = feature.get('extensionsNode_') || null;
          this.readExtensions_(feature, extensionsNode);
        }
        feature.set('extensionsNode_', undefined);
      }
    }

    /**
     * Reads a GPX file's metadata tag, reading among other things:
     *   - the name and description of this GPX
     *   - its author
     *   - the copyright associated with this GPX file
     *
     * Will return null if no metadata tag is present (or no valid source is given).
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {GPXMetadata | null} Metadata
     * @api
     */
    readMetadata(source) {
      if (!source) {
        return null;
      }
      if (typeof source === 'string') {
        return this.readMetadataFromDocument(parse(source));
      }
      if (isDocument(source)) {
        return this.readMetadataFromDocument(/** @type {Document} */ (source));
      }
      return this.readMetadataFromNode(source);
    }

    /**
     * @param {Document} doc Document.
     * @return {GPXMetadata | null} Metadata
     */
    readMetadataFromDocument(doc) {
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType === Node.ELEMENT_NODE) {
          const metadata = this.readMetadataFromNode(/** @type {Element} */ (n));
          if (metadata) {
            return metadata;
          }
        }
      }
      return null;
    }

    /**
     * @param {Element} node Node.
     * @return {Object} Metadata
     */
    readMetadataFromNode(node) {
      if (!NAMESPACE_URIS$4.includes(node.namespaceURI)) {
        return null;
      }
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        if (
          NAMESPACE_URIS$4.includes(n.namespaceURI) &&
          n.localName === 'metadata'
        ) {
          return pushParseAndPop({}, METADATA_PARSERS, n, []);
        }
      }
      return null;
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromNode(node, options) {
      if (!NAMESPACE_URIS$4.includes(node.namespaceURI)) {
        return null;
      }
      const featureReader = FEATURE_READER[node.localName];
      if (!featureReader) {
        return null;
      }
      const feature = featureReader(node, [this.getReadOptions(node, options)]);
      if (!feature) {
        return null;
      }
      this.handleReadExtensions_([feature]);
      return feature;
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @override
     */
    readFeaturesFromNode(node, options) {
      if (!NAMESPACE_URIS$4.includes(node.namespaceURI)) {
        return [];
      }
      if (node.localName == 'gpx') {
        /** @type {Array<Feature>} */
        const features = pushParseAndPop([], GPX_PARSERS, node, [
          this.getReadOptions(node, options),
        ]);
        if (features) {
          this.handleReadExtensions_(features);
          return features;
        }
        return [];
      }
      return [];
    }

    /**
     * Encode an array of features in the GPX format as an XML node.
     * LineString geometries are output as routes (`<rte>`), and MultiLineString
     * as tracks (`<trk>`).
     *
     * @param {Array<Feature>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Node} Node.
     * @api
     * @override
     */
    writeFeaturesNode(features, options) {
      options = this.adaptOptions(options);
      //FIXME Serialize metadata
      const gpx = createElementNS('http://www.topografix.com/GPX/1/1', 'gpx');
      const xmlnsUri = 'http://www.w3.org/2000/xmlns/';
      gpx.setAttributeNS(xmlnsUri, 'xmlns:xsi', XML_SCHEMA_INSTANCE_URI);
      gpx.setAttributeNS(
        XML_SCHEMA_INSTANCE_URI,
        'xsi:schemaLocation',
        SCHEMA_LOCATION$1,
      );
      gpx.setAttribute('version', '1.1');
      gpx.setAttribute('creator', 'OpenLayers');

      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */
        ({node: gpx}),
        GPX_SERIALIZERS,
        GPX_NODE_FACTORY,
        features,
        [options],
      );
      return gpx;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const RTE_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeObjectPropertySetter(readString),
    'cmt': makeObjectPropertySetter(readString),
    'desc': makeObjectPropertySetter(readString),
    'src': makeObjectPropertySetter(readString),
    'link': parseLink,
    'number': makeObjectPropertySetter(readPositiveInteger),
    'extensions': parseExtensions,
    'type': makeObjectPropertySetter(readString),
    'rtept': parseRtePt,
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const RTEPT_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'ele': makeObjectPropertySetter(readDecimal),
    'time': makeObjectPropertySetter(readDateTime),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TRK_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeObjectPropertySetter(readString),
    'cmt': makeObjectPropertySetter(readString),
    'desc': makeObjectPropertySetter(readString),
    'src': makeObjectPropertySetter(readString),
    'link': parseLink,
    'number': makeObjectPropertySetter(readPositiveInteger),
    'type': makeObjectPropertySetter(readString),
    'extensions': parseExtensions,
    'trkseg': parseTrkSeg,
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TRKSEG_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'trkpt': parseTrkPt,
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TRKPT_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'ele': makeObjectPropertySetter(readDecimal),
    'time': makeObjectPropertySetter(readDateTime),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const WPT_PARSERS = makeStructureNS(NAMESPACE_URIS$4, {
    'ele': makeObjectPropertySetter(readDecimal),
    'time': makeObjectPropertySetter(readDateTime),
    'magvar': makeObjectPropertySetter(readDecimal),
    'geoidheight': makeObjectPropertySetter(readDecimal),
    'name': makeObjectPropertySetter(readString),
    'cmt': makeObjectPropertySetter(readString),
    'desc': makeObjectPropertySetter(readString),
    'src': makeObjectPropertySetter(readString),
    'link': parseLink,
    'sym': makeObjectPropertySetter(readString),
    'type': makeObjectPropertySetter(readString),
    'fix': makeObjectPropertySetter(readString),
    'sat': makeObjectPropertySetter(readPositiveInteger),
    'hdop': makeObjectPropertySetter(readDecimal),
    'vdop': makeObjectPropertySetter(readDecimal),
    'pdop': makeObjectPropertySetter(readDecimal),
    'ageofdgpsdata': makeObjectPropertySetter(readDecimal),
    'dgpsid': makeObjectPropertySetter(readPositiveInteger),
    'extensions': parseExtensions,
  });

  /**
   * @const
   * @type {Array<string>}
   */
  const LINK_SEQUENCE = ['text', 'type'];

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const LINK_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'text': makeChildAppender(writeStringTextNode),
    'type': makeChildAppender(writeStringTextNode),
  });

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const RTE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$4, [
    'name',
    'cmt',
    'desc',
    'src',
    'link',
    'number',
    'type',
    'rtept',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const RTE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeChildAppender(writeStringTextNode),
    'cmt': makeChildAppender(writeStringTextNode),
    'desc': makeChildAppender(writeStringTextNode),
    'src': makeChildAppender(writeStringTextNode),
    'link': makeChildAppender(writeLink),
    'number': makeChildAppender(writeNonNegativeIntegerTextNode),
    'type': makeChildAppender(writeStringTextNode),
    'rtept': makeArraySerializer(makeChildAppender(writeWptType)),
  });

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const RTEPT_TYPE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$4, ['ele', 'time']);

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const TRK_SEQUENCE = makeStructureNS(NAMESPACE_URIS$4, [
    'name',
    'cmt',
    'desc',
    'src',
    'link',
    'number',
    'type',
    'trkseg',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const TRK_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'name': makeChildAppender(writeStringTextNode),
    'cmt': makeChildAppender(writeStringTextNode),
    'desc': makeChildAppender(writeStringTextNode),
    'src': makeChildAppender(writeStringTextNode),
    'link': makeChildAppender(writeLink),
    'number': makeChildAppender(writeNonNegativeIntegerTextNode),
    'type': makeChildAppender(writeStringTextNode),
    'trkseg': makeArraySerializer(makeChildAppender(writeTrkSeg)),
  });

  /**
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const TRKSEG_NODE_FACTORY = makeSimpleNodeFactory('trkpt');

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const TRKSEG_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'trkpt': makeChildAppender(writeWptType),
  });

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const WPT_TYPE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$4, [
    'ele',
    'time',
    'magvar',
    'geoidheight',
    'name',
    'cmt',
    'desc',
    'src',
    'link',
    'sym',
    'type',
    'fix',
    'sat',
    'hdop',
    'vdop',
    'pdop',
    'ageofdgpsdata',
    'dgpsid',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const WPT_TYPE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$4, {
    'ele': makeChildAppender(writeDecimalTextNode),
    'time': makeChildAppender(writeDateTimeTextNode),
    'magvar': makeChildAppender(writeDecimalTextNode),
    'geoidheight': makeChildAppender(writeDecimalTextNode),
    'name': makeChildAppender(writeStringTextNode),
    'cmt': makeChildAppender(writeStringTextNode),
    'desc': makeChildAppender(writeStringTextNode),
    'src': makeChildAppender(writeStringTextNode),
    'link': makeChildAppender(writeLink),
    'sym': makeChildAppender(writeStringTextNode),
    'type': makeChildAppender(writeStringTextNode),
    'fix': makeChildAppender(writeStringTextNode),
    'sat': makeChildAppender(writeNonNegativeIntegerTextNode),
    'hdop': makeChildAppender(writeDecimalTextNode),
    'vdop': makeChildAppender(writeDecimalTextNode),
    'pdop': makeChildAppender(writeDecimalTextNode),
    'ageofdgpsdata': makeChildAppender(writeDecimalTextNode),
    'dgpsid': makeChildAppender(writeNonNegativeIntegerTextNode),
  });

  /**
   * @const
   * @type {Object<string, string>}
   */
  const GEOMETRY_TYPE_TO_NODENAME$1 = {
    'Point': 'wpt',
    'LineString': 'rte',
    'MultiLineString': 'trk',
  };

  /**
   * @param {*} value Value.
   * @param {Array<*>} objectStack Object stack.
   * @param {string} [nodeName] Node name.
   * @return {Node|undefined} Node.
   */
  function GPX_NODE_FACTORY(value, objectStack, nodeName) {
    const geometry = /** @type {Feature} */ (value).getGeometry();
    if (geometry) {
      const nodeName = GEOMETRY_TYPE_TO_NODENAME$1[geometry.getType()];
      if (nodeName) {
        const parentNode = objectStack[objectStack.length - 1].node;
        return createElementNS(parentNode.namespaceURI, nodeName);
      }
    }
  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {LayoutOptions} layoutOptions Layout options.
   * @param {Element} node Node.
   * @param {!Object} values Values.
   * @return {Array<number>} Flat coordinates.
   */
  function appendCoordinate(flatCoordinates, layoutOptions, node, values) {
    flatCoordinates.push(
      parseFloat(node.getAttribute('lon')),
      parseFloat(node.getAttribute('lat')),
    );
    if ('ele' in values) {
      flatCoordinates.push(/** @type {number} */ (values['ele']));
      delete values['ele'];
      layoutOptions.hasZ = true;
    } else {
      flatCoordinates.push(0);
    }
    if ('time' in values) {
      flatCoordinates.push(/** @type {number} */ (values['time']));
      delete values['time'];
      layoutOptions.hasM = true;
    } else {
      flatCoordinates.push(0);
    }
    return flatCoordinates;
  }

  /**
   * Choose GeometryLayout based on flags in layoutOptions and adjust flatCoordinates
   * and ends arrays by shrinking them accordingly (removing unused zero entries).
   *
   * @param {LayoutOptions} layoutOptions Layout options.
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {Array<number>} [ends] Ends.
   * @return {import("../geom/Geometry.js").GeometryLayout} Layout.
   */
  function applyLayoutOptions(layoutOptions, flatCoordinates, ends) {
    /** @type {import("../geom/Geometry.js").GeometryLayout} */
    let layout = 'XY';
    let stride = 2;
    if (layoutOptions.hasZ && layoutOptions.hasM) {
      layout = 'XYZM';
      stride = 4;
    } else if (layoutOptions.hasZ) {
      layout = 'XYZ';
      stride = 3;
    } else if (layoutOptions.hasM) {
      layout = 'XYM';
      stride = 3;
    }
    if (stride !== 4) {
      for (let i = 0, ii = flatCoordinates.length / 4; i < ii; i++) {
        flatCoordinates[i * stride] = flatCoordinates[i * 4];
        flatCoordinates[i * stride + 1] = flatCoordinates[i * 4 + 1];
        if (layoutOptions.hasZ) {
          flatCoordinates[i * stride + 2] = flatCoordinates[i * 4 + 2];
        }
        if (layoutOptions.hasM) {
          flatCoordinates[i * stride + 2] = flatCoordinates[i * 4 + 3];
        }
      }
      flatCoordinates.length = (flatCoordinates.length / 4) * stride;
      if (ends) {
        for (let i = 0, ii = ends.length; i < ii; i++) {
          ends[i] = (ends[i] / 4) * stride;
        }
      }
    }
    return layout;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<any>} objectStack Object stack.
   * @return {GPXAuthor | undefined} Person object.
   */
  function readAuthor(node, objectStack) {
    const values = pushParseAndPop({}, AUTHOR_PARSERS, node, objectStack);
    if (values) {
      return values;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<any>} objectStack Object stack.
   * @return {GPXCopyright | undefined} Person object.
   */
  function readCopyright(node, objectStack) {
    const values = pushParseAndPop({}, COPYRIGHT_PARSERS, node, objectStack);
    if (values) {
      const author = node.getAttribute('author');
      if (author !== null) {
        values['author'] = author;
      }
      return values;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseBounds(node, objectStack) {
    const values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const minlat = node.getAttribute('minlat');
    const minlon = node.getAttribute('minlon');
    const maxlat = node.getAttribute('maxlat');
    const maxlon = node.getAttribute('maxlon');
    if (
      minlon !== null &&
      minlat !== null &&
      maxlon !== null &&
      maxlat !== null
    ) {
      values['bounds'] = [
        [parseFloat(minlon), parseFloat(minlat)],
        [parseFloat(maxlon), parseFloat(maxlat)],
      ];
    }
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseEmail(node, objectStack) {
    const values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const id = node.getAttribute('id');
    const domain = node.getAttribute('domain');
    if (id !== null && domain !== null) {
      values['email'] = `${id}@${domain}`;
    }
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseLink(node, objectStack) {
    const values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const href = node.getAttribute('href');
    if (href !== null) {
      values['link'] = href;
    }
    parseNode(LINK_PARSERS$1, node, objectStack);
  }

  /**
   * @param {Node} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseExtensions(node, objectStack) {
    const values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    values['extensionsNode_'] = node;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseRtePt(node, objectStack) {
    const values = pushParseAndPop({}, RTEPT_PARSERS, node, objectStack);
    if (values) {
      const rteValues = /** @type {!Object} */ (
        objectStack[objectStack.length - 1]
      );
      const flatCoordinates = /** @type {Array<number>} */ (
        rteValues['flatCoordinates']
      );
      const layoutOptions = /** @type {LayoutOptions} */ (
        rteValues['layoutOptions']
      );
      appendCoordinate(flatCoordinates, layoutOptions, node, values);
    }
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseTrkPt(node, objectStack) {
    const values = pushParseAndPop({}, TRKPT_PARSERS, node, objectStack);
    if (values) {
      const trkValues = /** @type {!Object} */ (
        objectStack[objectStack.length - 1]
      );
      const flatCoordinates = /** @type {Array<number>} */ (
        trkValues['flatCoordinates']
      );
      const layoutOptions = /** @type {LayoutOptions} */ (
        trkValues['layoutOptions']
      );
      appendCoordinate(flatCoordinates, layoutOptions, node, values);
    }
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function parseTrkSeg(node, objectStack) {
    const values = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    parseNode(TRKSEG_PARSERS, node, objectStack);
    const flatCoordinates =
      /** @type {Array<number>} */
      (values['flatCoordinates']);
    const ends = /** @type {Array<number>} */ (values['ends']);
    ends.push(flatCoordinates.length);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Feature|undefined} Track.
   */
  function readRte(node, objectStack) {
    const options = /** @type {import("./Feature.js").ReadOptions} */ (
      objectStack[0]
    );
    const values = pushParseAndPop(
      {
        'flatCoordinates': [],
        'layoutOptions': {},
      },
      RTE_PARSERS,
      node,
      objectStack,
    );
    if (!values) {
      return undefined;
    }
    const flatCoordinates =
      /** @type {Array<number>} */
      (values['flatCoordinates']);
    delete values['flatCoordinates'];
    const layoutOptions = /** @type {LayoutOptions} */ (values['layoutOptions']);
    delete values['layoutOptions'];
    const layout = applyLayoutOptions(layoutOptions, flatCoordinates);
    const geometry = new LineString(flatCoordinates, layout);
    transformGeometryWithOptions(geometry, false, options);
    const feature = new Feature(geometry);
    feature.setProperties(values, true);
    return feature;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Feature|undefined} Track.
   */
  function readTrk(node, objectStack) {
    const options = /** @type {import("./Feature.js").ReadOptions} */ (
      objectStack[0]
    );
    const values = pushParseAndPop(
      {
        'flatCoordinates': [],
        'ends': [],
        'layoutOptions': {},
      },
      TRK_PARSERS,
      node,
      objectStack,
    );
    if (!values) {
      return undefined;
    }
    const flatCoordinates =
      /** @type {Array<number>} */
      (values['flatCoordinates']);
    delete values['flatCoordinates'];
    const ends = /** @type {Array<number>} */ (values['ends']);
    delete values['ends'];
    const layoutOptions = /** @type {LayoutOptions} */ (values['layoutOptions']);
    delete values['layoutOptions'];
    const layout = applyLayoutOptions(layoutOptions, flatCoordinates, ends);
    const geometry = new MultiLineString(flatCoordinates, layout, ends);
    transformGeometryWithOptions(geometry, false, options);
    const feature = new Feature(geometry);
    feature.setProperties(values, true);
    return feature;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Feature|undefined} Waypoint.
   */
  function readWpt(node, objectStack) {
    const options = /** @type {import("./Feature.js").ReadOptions} */ (
      objectStack[0]
    );
    const values = pushParseAndPop({}, WPT_PARSERS, node, objectStack);
    if (!values) {
      return undefined;
    }
    const layoutOptions = /** @type {LayoutOptions} */ ({});
    const coordinates = appendCoordinate([], layoutOptions, node, values);
    const layout = applyLayoutOptions(layoutOptions, coordinates);
    const geometry = new Point(coordinates, layout);
    transformGeometryWithOptions(geometry, false, options);
    const feature = new Feature(geometry);
    feature.setProperties(values, true);
    return feature;
  }

  /**
   * @param {Element} node Node.
   * @param {string} value Value for the link's `href` attribute.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeLink(node, value, objectStack) {
    node.setAttribute('href', value);
    const context = objectStack[objectStack.length - 1];
    const properties = context['properties'];
    const link = [properties['linkText'], properties['linkType']];
    pushSerializeAndPop(
      /** @type {import("../xml.js").NodeStackItem} */ ({node: node}),
      LINK_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      link,
      objectStack,
      LINK_SEQUENCE,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeWptType(node, coordinate, objectStack) {
    const context = objectStack[objectStack.length - 1];
    const parentNode = context.node;
    const namespaceURI = parentNode.namespaceURI;
    const properties = context['properties'];
    //FIXME Projection handling
    node.setAttributeNS(null, 'lat', String(coordinate[1]));
    node.setAttributeNS(null, 'lon', String(coordinate[0]));
    const geometryLayout = context['geometryLayout'];
    switch (geometryLayout) {
      case 'XYZM':
        if (coordinate[3] !== 0) {
          properties['time'] = coordinate[3];
        }
      // fall through
      case 'XYZ':
        if (coordinate[2] !== 0) {
          properties['ele'] = coordinate[2];
        }
        break;
      case 'XYM':
        if (coordinate[2] !== 0) {
          properties['time'] = coordinate[2];
        }
        break;
      // pass
    }
    const orderedKeys =
      node.nodeName == 'rtept'
        ? RTEPT_TYPE_SEQUENCE[namespaceURI]
        : WPT_TYPE_SEQUENCE[namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      /** @type {import("../xml.js").NodeStackItem} */
      ({node: node, 'properties': properties}),
      WPT_TYPE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @param {Node} node Node.
   * @param {Feature} feature Feature.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeRte(node, feature, objectStack) {
    const options = /** @type {import("./Feature.js").WriteOptions} */ (
      objectStack[0]
    );
    const properties = feature.getProperties();
    const context = {node: node};
    context['properties'] = properties;
    const geometry = feature.getGeometry();
    if (geometry.getType() == 'LineString') {
      const lineString = /** @type {LineString} */ (
        transformGeometryWithOptions(geometry, true, options)
      );
      context['geometryLayout'] = lineString.getLayout();
      properties['rtept'] = lineString.getCoordinates();
    }
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = RTE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      RTE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {Feature} feature Feature.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeTrk(node, feature, objectStack) {
    const options = /** @type {import("./Feature.js").WriteOptions} */ (
      objectStack[0]
    );
    const properties = feature.getProperties();
    /** @type {import("../xml.js").NodeStackItem} */
    const context = {node: node};
    context['properties'] = properties;
    const geometry = feature.getGeometry();
    if (geometry.getType() == 'MultiLineString') {
      const multiLineString = /** @type {MultiLineString} */ (
        transformGeometryWithOptions(geometry, true, options)
      );
      properties['trkseg'] = multiLineString.getLineStrings();
    }
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = TRK_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      TRK_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {LineString} lineString LineString.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeTrkSeg(node, lineString, objectStack) {
    /** @type {import("../xml.js").NodeStackItem} */
    const context = {node: node};
    context['geometryLayout'] = lineString.getLayout();
    context['properties'] = {};
    pushSerializeAndPop(
      context,
      TRKSEG_SERIALIZERS,
      TRKSEG_NODE_FACTORY,
      lineString.getCoordinates(),
      objectStack,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {Feature} feature Feature.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeWpt(node, feature, objectStack) {
    const options = /** @type {import("./Feature.js").WriteOptions} */ (
      objectStack[0]
    );
    const context = objectStack[objectStack.length - 1];
    context['properties'] = feature.getProperties();
    const geometry = feature.getGeometry();
    if (geometry.getType() == 'Point') {
      const point = /** @type {Point} */ (
        transformGeometryWithOptions(geometry, true, options)
      );
      context['geometryLayout'] = point.getLayout();
      writeWptType(node, point.getCoordinates(), objectStack);
    }
  }

  /**
   * @module ol/format/TextFeature
   */

  /**
   * @classdesc
   * Abstract base class; normally only used for creating subclasses and not
   * instantiated in apps.
   * Base class for text feature formats.
   *
   * @abstract
   */
  class TextFeature extends FeatureFormat {
    constructor() {
      super();
    }

    /**
     * @return {import("./Feature.js").Type} Format.
     * @override
     */
    getType() {
      return 'text';
    }

    /**
     * Read the feature from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @api
     * @override
     */
    readFeature(source, options) {
      return this.readFeatureFromText(
        getText(source),
        this.adaptOptions(options),
      );
    }

    /**
     * @abstract
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../Feature.js").default} Feature.
     */
    readFeatureFromText(text, options) {
      return abstract();
    }

    /**
     * Read the features from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @api
     * @override
     */
    readFeatures(source, options) {
      return this.readFeaturesFromText(
        getText(source),
        this.adaptOptions(options),
      );
    }

    /**
     * @abstract
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<import("../Feature.js").default>} Features.
     */
    readFeaturesFromText(text, options) {
      return abstract();
    }

    /**
     * Read the geometry from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @api
     * @override
     */
    readGeometry(source, options) {
      return this.readGeometryFromText(
        getText(source),
        this.adaptOptions(options),
      );
    }

    /**
     * @abstract
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     */
    readGeometryFromText(text, options) {
      return abstract();
    }

    /**
     * Read the projection from the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {import("../proj/Projection.js").default|undefined} Projection.
     * @api
     * @override
     */
    readProjection(source) {
      return this.readProjectionFromText(getText(source));
    }

    /**
     * @param {string} text Text.
     * @protected
     * @return {import("../proj/Projection.js").default|undefined} Projection.
     */
    readProjectionFromText(text) {
      return this.dataProjection;
    }

    /**
     * Encode a feature as a string.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded feature.
     * @api
     * @override
     */
    writeFeature(feature, options) {
      return this.writeFeatureText(feature, this.adaptOptions(options));
    }

    /**
     * @abstract
     * @param {import("../Feature.js").default} feature Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     */
    writeFeatureText(feature, options) {
      return abstract();
    }

    /**
     * Encode an array of features as string.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Encoded features.
     * @api
     * @override
     */
    writeFeatures(features, options) {
      return this.writeFeaturesText(features, this.adaptOptions(options));
    }

    /**
     * @abstract
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     */
    writeFeaturesText(features, options) {
      return abstract();
    }

    /**
     * Write a single geometry.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string} Geometry.
     * @api
     * @override
     */
    writeGeometry(geometry, options) {
      return this.writeGeometryText(geometry, this.adaptOptions(options));
    }

    /**
     * @abstract
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     */
    writeGeometryText(geometry, options) {
      return abstract();
    }
  }

  /**
   * @param {Document|Element|Object|string} source Source.
   * @return {string} Text.
   */
  function getText(source) {
    if (typeof source === 'string') {
      return source;
    }
    return '';
  }

  /**
   * @module ol/format/IGC
   */

  /**
   * @typedef {'barometric' | 'gps' | 'none'} IGCZ
   * IGC altitude/z. One of 'barometric', 'gps', 'none'.
   */

  /**
   * @const
   * @type {RegExp}
   */
  const B_RECORD_RE =
    /^B(\d{2})(\d{2})(\d{2})(\d{2})(\d{5})([NS])(\d{3})(\d{5})([EW])([AV])(\d{5})(\d{5})/;

  /**
   * @const
   * @type {RegExp}
   */
  const H_RECORD_RE = /^H.([A-Z]{3}).*?:(.*)/;

  /**
   * @const
   * @type {RegExp}
   */
  const HFDTE_RECORD_RE = /^HFDTE(\d{2})(\d{2})(\d{2})/;

  /**
   * @const
   * @type {RegExp}
   */
  const HFDTEDATE_RECORD_RE = /^HFDTEDATE:(\d{2})(\d{2})(\d{2}),(\d{2})/;

  /**
   * A regular expression matching the newline characters `\r\n`, `\r` and `\n`.
   *
   * @const
   * @type {RegExp}
   */
  const NEWLINE_RE = /\r\n|\r|\n/;

  /**
   * @typedef {Object} Options
   * @property {IGCZ} [altitudeMode='none'] Altitude mode. Possible
   * values are `'barometric'`, `'gps'`, and `'none'`.
   */

  /**
   * @classdesc
   * Feature format for `*.igc` flight recording files.
   *
   * As IGC sources contain a single feature,
   * {@link module:ol/format/IGC~IGC#readFeatures} will return the feature in an
   * array
   *
   * @api
   */
  class IGC extends TextFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2('EPSG:4326');

      /**
       * @private
       * @type {IGCZ}
       */
      this.altitudeMode_ = options.altitudeMode ? options.altitudeMode : 'none';

      /**
       * @private
       * @type {boolean}
       */
      this.lad_ = false;

      /**
       * @private
       * @type {boolean}
       */
      this.lod_ = false;

      /**
       * @private
       * @type {number}
       */
      this.ladStart_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.ladStop_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.lodStart_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.lodStop_ = 0;
    }

    /**
     * @protected
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromText(text, options) {
      const altitudeMode = this.altitudeMode_;
      const lines = text.split(NEWLINE_RE);
      /** @type {Object<string, string>} */
      const properties = {};
      const flatCoordinates = [];
      let year = 2000;
      let month = 0;
      let day = 1;
      let lastDateTime = -1;
      let i, ii;
      for (i = 0, ii = lines.length; i < ii; ++i) {
        const line = lines[i];
        let m;
        if (line.charAt(0) == 'B') {
          m = B_RECORD_RE.exec(line);
          if (m) {
            const hour = parseInt(m[1], 10);
            const minute = parseInt(m[2], 10);
            const second = parseInt(m[3], 10);
            let y = parseInt(m[4], 10) + parseInt(m[5], 10) / 60000;
            if (this.lad_) {
              y +=
                parseInt(line.slice(this.ladStart_, this.ladStop_), 10) /
                60000 /
                10 ** (this.ladStop_ - this.ladStart_);
            }
            if (m[6] == 'S') {
              y = -y;
            }
            let x = parseInt(m[7], 10) + parseInt(m[8], 10) / 60000;
            if (this.lod_) {
              x +=
                parseInt(line.slice(this.lodStart_, this.lodStop_), 10) /
                60000 /
                10 ** (this.lodStop_ - this.lodStart_);
            }
            if (m[9] == 'W') {
              x = -x;
            }
            flatCoordinates.push(x, y);
            if (altitudeMode != 'none') {
              let z;
              if (altitudeMode == 'gps') {
                z = parseInt(m[11], 10);
              } else if (altitudeMode == 'barometric') {
                z = parseInt(m[12], 10);
              } else {
                z = 0;
              }
              flatCoordinates.push(z);
            }
            let dateTime = Date.UTC(year, month, day, hour, minute, second);
            // Detect UTC midnight wrap around.
            if (dateTime < lastDateTime) {
              dateTime = Date.UTC(year, month, day + 1, hour, minute, second);
            }
            flatCoordinates.push(dateTime / 1000);
            lastDateTime = dateTime;
          }
        } else if (line.charAt(0) == 'H') {
          m = HFDTEDATE_RECORD_RE.exec(line);
          if (m) {
            day = parseInt(m[1], 10);
            month = parseInt(m[2], 10) - 1;
            year = 2000 + parseInt(m[3], 10);
          } else {
            m = HFDTE_RECORD_RE.exec(line);
            if (m) {
              day = parseInt(m[1], 10);
              month = parseInt(m[2], 10) - 1;
              year = 2000 + parseInt(m[3], 10);
            } else {
              m = H_RECORD_RE.exec(line);
              if (m) {
                properties[m[1]] = m[2].trim();
              }
            }
          }
        } else if (line.charAt(0) == 'I') {
          const numberAdds = parseInt(line.slice(1, 3), 10);
          for (let i = 0; i < numberAdds; i++) {
            const addCode = line.slice(7 + i * 7, 10 + i * 7);
            if (addCode === 'LAD' || addCode === 'LOD') {
              // in IGC format, columns are numbered from 1
              const addStart = parseInt(line.slice(3 + i * 7, 5 + i * 7), 10) - 1;
              const addStop = parseInt(line.slice(5 + i * 7, 7 + i * 7), 10);
              if (addCode === 'LAD') {
                this.lad_ = true;
                this.ladStart_ = addStart;
                this.ladStop_ = addStop;
              } else if (addCode === 'LOD') {
                this.lod_ = true;
                this.lodStart_ = addStart;
                this.lodStop_ = addStop;
              }
            }
          }
        }
      }
      if (flatCoordinates.length === 0) {
        return null;
      }
      const layout = altitudeMode == 'none' ? 'XYM' : 'XYZM';
      const lineString = new LineString(flatCoordinates, layout);
      const feature = new Feature(
        transformGeometryWithOptions(lineString, false, options),
      );
      feature.setProperties(properties, true);
      return feature;
    }

    /**
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<Feature>} Features.
     * @override
     */
    readFeaturesFromText(text, options) {
      const feature = this.readFeatureFromText(text, options);
      if (feature) {
        return [feature];
      }
      return [];
    }
  }

  /**
   * @module ol/format/IIIFInfo
   */


  /**
   * @typedef {Object} PreferredOptions
   * @property {string} [format] Preferred image format. Will be used if the image information
   * indicates support for that format.
   * @property {string} [quality] IIIF image qualitiy.  Will be used if the image information
   * indicates support for that quality.
   */

  /**
   * @typedef {Object} SupportedFeatures
   * @property {Array<string>} [supports] Supported IIIF image size and region
   * calculation features.
   * @property {Array<string>} [formats] Supported image formats.
   * @property {Array<string>} [qualities] Supported IIIF image qualities.
   */

  /**
   * @typedef {Object} TileInfo
   * @property {Array<number>} scaleFactors Supported resolution scaling factors.
   * @property {number} width Tile width in pixels.
   * @property {number} [height] Tile height in pixels. Same as tile width if height is
   * not given.
   */

  /**
   * @typedef {Object} IiifProfile
   * @property {Array<string>} [formats] Supported image formats for the image service.
   * @property {Array<string>} [qualities] Supported IIIF image qualities.
   * @property {Array<string>} [supports] Supported features.
   * @property {number} [maxArea] Maximum area (pixels) available for this image service.
   * @property {number} [maxHeight] Maximum height.
   * @property {number} [maxWidth] Maximum width.
   */

  /**
   * @typedef {Object<string,string|number|Array<number|string|IiifProfile|Object<string, number>|TileInfo>>}
   *    ImageInformationResponse
   */

  /**
   * Enum representing the major IIIF Image API versions
   * @enum {string}
   */
  const Versions = {
    VERSION1: 'version1',
    VERSION2: 'version2',
    VERSION3: 'version3',
  };

  /**
   * Supported image formats, qualities and supported region / size calculation features
   * for different image API versions and compliance levels
   * @const
   * @type {Object<string, Object<string, SupportedFeatures>>}
   */
  const IIIF_PROFILE_VALUES = {};
  IIIF_PROFILE_VALUES[Versions.VERSION1] = {
    'level0': {
      supports: [],
      formats: [],
      qualities: ['native'],
    },
    'level1': {
      supports: ['regionByPx', 'sizeByW', 'sizeByH', 'sizeByPct'],
      formats: ['jpg'],
      qualities: ['native'],
    },
    'level2': {
      supports: [
        'regionByPx',
        'regionByPct',
        'sizeByW',
        'sizeByH',
        'sizeByPct',
        'sizeByConfinedWh',
        'sizeByWh',
      ],
      formats: ['jpg', 'png'],
      qualities: ['native', 'color', 'grey', 'bitonal'],
    },
  };
  IIIF_PROFILE_VALUES[Versions.VERSION2] = {
    'level0': {
      supports: [],
      formats: ['jpg'],
      qualities: ['default'],
    },
    'level1': {
      supports: ['regionByPx', 'sizeByW', 'sizeByH', 'sizeByPct'],
      formats: ['jpg'],
      qualities: ['default'],
    },
    'level2': {
      supports: [
        'regionByPx',
        'regionByPct',
        'sizeByW',
        'sizeByH',
        'sizeByPct',
        'sizeByConfinedWh',
        'sizeByDistortedWh',
        'sizeByWh',
      ],
      formats: ['jpg', 'png'],
      qualities: ['default', 'bitonal'],
    },
  };
  IIIF_PROFILE_VALUES[Versions.VERSION3] = {
    'level0': {
      supports: [],
      formats: ['jpg'],
      qualities: ['default'],
    },
    'level1': {
      supports: ['regionByPx', 'regionSquare', 'sizeByW', 'sizeByH', 'sizeByWh'],
      formats: ['jpg'],
      qualities: ['default'],
    },
    'level2': {
      supports: [
        'regionByPx',
        'regionSquare',
        'regionByPct',
        'sizeByW',
        'sizeByH',
        'sizeByPct',
        'sizeByConfinedWh',
        'sizeByWh',
      ],
      formats: ['jpg', 'png'],
      qualities: ['default'],
    },
  };
  IIIF_PROFILE_VALUES['none'] = {
    'none': {
      supports: [],
      formats: [],
      qualities: [],
    },
  };

  const COMPLIANCE_VERSION1 =
    /^https?:\/\/library\.stanford\.edu\/iiif\/image-api\/(?:1\.1\/)?compliance\.html#level[0-2]$/;
  const COMPLIANCE_VERSION2 =
    /^https?:\/\/iiif\.io\/api\/image\/2\/level[0-2](?:\.json)?$/;
  const COMPLIANCE_VERSION3 =
    /(^https?:\/\/iiif\.io\/api\/image\/3\/level[0-2](?:\.json)?$)|(^level[0-2]$)/;

  function generateVersion1Options(iiifInfo) {
    let levelProfile = iiifInfo.getComplianceLevelSupportedFeatures();
    // Version 1.0 and 1.1 do not require a profile.
    if (levelProfile === undefined) {
      levelProfile = IIIF_PROFILE_VALUES[Versions.VERSION1]['level0'];
    }
    return {
      url:
        iiifInfo.imageInfo['@id'] === undefined
          ? undefined
          : iiifInfo.imageInfo['@id'].replace(/\/?(?:info\.json)?$/g, ''),
      supports: levelProfile.supports,
      formats: [
        ...levelProfile.formats,
        iiifInfo.imageInfo.formats === undefined
          ? []
          : iiifInfo.imageInfo.formats,
      ],
      qualities: [
        ...levelProfile.qualities,
        iiifInfo.imageInfo.qualities === undefined
          ? []
          : iiifInfo.imageInfo.qualities,
      ],
      resolutions: iiifInfo.imageInfo.scale_factors,
      tileSize:
        iiifInfo.imageInfo.tile_width !== undefined
          ? iiifInfo.imageInfo.tile_height !== undefined
            ? [iiifInfo.imageInfo.tile_width, iiifInfo.imageInfo.tile_height]
            : [iiifInfo.imageInfo.tile_width, iiifInfo.imageInfo.tile_width]
          : iiifInfo.imageInfo.tile_height != undefined
            ? [iiifInfo.imageInfo.tile_height, iiifInfo.imageInfo.tile_height]
            : undefined,
    };
  }

  function generateVersion2Options(iiifInfo) {
    const levelProfile = iiifInfo.getComplianceLevelSupportedFeatures(),
      additionalProfile =
        Array.isArray(iiifInfo.imageInfo.profile) &&
        iiifInfo.imageInfo.profile.length > 1,
      profileSupports =
        additionalProfile && iiifInfo.imageInfo.profile[1].supports
          ? iiifInfo.imageInfo.profile[1].supports
          : [],
      profileFormats =
        additionalProfile && iiifInfo.imageInfo.profile[1].formats
          ? iiifInfo.imageInfo.profile[1].formats
          : [],
      profileQualities =
        additionalProfile && iiifInfo.imageInfo.profile[1].qualities
          ? iiifInfo.imageInfo.profile[1].qualities
          : [];
    return {
      url: iiifInfo.imageInfo['@id'].replace(/\/?(?:info\.json)?$/g, ''),
      sizes:
        iiifInfo.imageInfo.sizes === undefined
          ? undefined
          : iiifInfo.imageInfo.sizes.map(function (size) {
              return [size.width, size.height];
            }),
      tileSize:
        iiifInfo.imageInfo.tiles === undefined
          ? undefined
          : [
              iiifInfo.imageInfo.tiles.map(function (tile) {
                return tile.width;
              })[0],
              iiifInfo.imageInfo.tiles.map(function (tile) {
                return tile.height === undefined ? tile.width : tile.height;
              })[0],
            ],
      resolutions:
        iiifInfo.imageInfo.tiles === undefined
          ? undefined
          : iiifInfo.imageInfo.tiles.map(function (tile) {
              return tile.scaleFactors;
            })[0],
      supports: [...levelProfile.supports, ...profileSupports],
      formats: [...levelProfile.formats, ...profileFormats],
      qualities: [...levelProfile.qualities, ...profileQualities],
    };
  }

  function generateVersion3Options(iiifInfo) {
    const levelProfile = iiifInfo.getComplianceLevelSupportedFeatures(),
      formats =
        iiifInfo.imageInfo.extraFormats === undefined
          ? levelProfile.formats
          : [...levelProfile.formats, ...iiifInfo.imageInfo.extraFormats],
      preferredFormat =
        iiifInfo.imageInfo.preferredFormats !== undefined &&
        Array.isArray(iiifInfo.imageInfo.preferredFormats) &&
        iiifInfo.imageInfo.preferredFormats.length > 0
          ? iiifInfo.imageInfo.preferredFormats
              .filter(function (format) {
                return ['jpg', 'png', 'gif'].includes(format);
              })
              .reduce(function (acc, format) {
                return acc === undefined && formats.includes(format)
                  ? format
                  : acc;
              }, undefined)
          : undefined;
    return {
      url: iiifInfo.imageInfo['id'],
      sizes:
        iiifInfo.imageInfo.sizes === undefined
          ? undefined
          : iiifInfo.imageInfo.sizes.map(function (size) {
              return [size.width, size.height];
            }),
      tileSize:
        iiifInfo.imageInfo.tiles === undefined
          ? undefined
          : [
              iiifInfo.imageInfo.tiles.map(function (tile) {
                return tile.width;
              })[0],
              iiifInfo.imageInfo.tiles.map(function (tile) {
                return tile.height;
              })[0],
            ],
      resolutions:
        iiifInfo.imageInfo.tiles === undefined
          ? undefined
          : iiifInfo.imageInfo.tiles.map(function (tile) {
              return tile.scaleFactors;
            })[0],
      supports:
        iiifInfo.imageInfo.extraFeatures === undefined
          ? levelProfile.supports
          : [...levelProfile.supports, ...iiifInfo.imageInfo.extraFeatures],
      formats: formats,
      qualities:
        iiifInfo.imageInfo.extraQualities === undefined
          ? levelProfile.qualities
          : [...levelProfile.qualities, ...iiifInfo.imageInfo.extraQualities],
      preferredFormat: preferredFormat,
    };
  }

  const versionFunctions = {};
  versionFunctions[Versions.VERSION1] = generateVersion1Options;
  versionFunctions[Versions.VERSION2] = generateVersion2Options;
  versionFunctions[Versions.VERSION3] = generateVersion3Options;

  /**
   * @classdesc
   * Format for transforming IIIF Image API image information responses into
   * IIIF tile source ready options
   *
   * @api
   */
  class IIIFInfo {
    /**
     * @param {string|ImageInformationResponse} imageInfo
     * Deserialized image information JSON response object or JSON response as string
     */
    constructor(imageInfo) {
      this.setImageInfo(imageInfo);
    }

    /**
     * @param {string|ImageInformationResponse} imageInfo
     * Deserialized image information JSON response object or JSON response as string
     * @api
     */
    setImageInfo(imageInfo) {
      if (typeof imageInfo == 'string') {
        this.imageInfo = JSON.parse(imageInfo);
      } else {
        this.imageInfo = imageInfo;
      }
    }

    /**
     * @return {Versions|undefined} Major IIIF version.
     * @api
     */
    getImageApiVersion() {
      if (this.imageInfo === undefined) {
        return undefined;
      }
      let context = this.imageInfo['@context'] || 'ol-no-context';
      if (typeof context == 'string') {
        context = [context];
      }
      for (let i = 0; i < context.length; i++) {
        switch (context[i]) {
          case 'http://library.stanford.edu/iiif/image-api/1.1/context.json':
          case 'http://iiif.io/api/image/1/context.json':
            return Versions.VERSION1;
          case 'http://iiif.io/api/image/2/context.json':
            return Versions.VERSION2;
          case 'http://iiif.io/api/image/3/context.json':
            return Versions.VERSION3;
          case 'ol-no-context':
            // Image API 1.0 has no '@context'
            if (
              this.getComplianceLevelEntryFromProfile(Versions.VERSION1) &&
              this.imageInfo.identifier
            ) {
              return Versions.VERSION1;
            }
            break;
        }
      }
      assert(
        false,
        'Cannot determine IIIF Image API version from provided image information JSON',
      );
    }

    /**
     * @param {Versions} version Optional IIIF image API version
     * @return {string|undefined} Compliance level as it appears in the IIIF image information
     * response.
     */
    getComplianceLevelEntryFromProfile(version) {
      if (this.imageInfo === undefined || this.imageInfo.profile === undefined) {
        return undefined;
      }
      if (version === undefined) {
        version = this.getImageApiVersion();
      }
      switch (version) {
        case Versions.VERSION1:
          if (COMPLIANCE_VERSION1.test(this.imageInfo.profile)) {
            return this.imageInfo.profile;
          }
          break;
        case Versions.VERSION3:
          if (COMPLIANCE_VERSION3.test(this.imageInfo.profile)) {
            return this.imageInfo.profile;
          }
          break;
        case Versions.VERSION2:
          if (
            typeof this.imageInfo.profile === 'string' &&
            COMPLIANCE_VERSION2.test(this.imageInfo.profile)
          ) {
            return this.imageInfo.profile;
          }
          if (
            Array.isArray(this.imageInfo.profile) &&
            this.imageInfo.profile.length > 0 &&
            typeof this.imageInfo.profile[0] === 'string' &&
            COMPLIANCE_VERSION2.test(this.imageInfo.profile[0])
          ) {
            return this.imageInfo.profile[0];
          }
          break;
      }
      return undefined;
    }

    /**
     * @param {Versions} version Optional IIIF image API version
     * @return {string} Compliance level, on of 'level0', 'level1' or 'level2' or undefined
     */
    getComplianceLevelFromProfile(version) {
      const complianceLevel = this.getComplianceLevelEntryFromProfile(version);
      if (complianceLevel === undefined) {
        return undefined;
      }
      const level = complianceLevel.match(/level[0-2](?:\.json)?$/g);
      return Array.isArray(level) ? level[0].replace('.json', '') : undefined;
    }

    /**
     * @return {SupportedFeatures|undefined} Image formats, qualities and region / size calculation
     * methods that are supported by the IIIF service.
     */
    getComplianceLevelSupportedFeatures() {
      if (this.imageInfo === undefined) {
        return undefined;
      }
      const version = this.getImageApiVersion();
      const level = this.getComplianceLevelFromProfile(version);
      if (level === undefined) {
        return IIIF_PROFILE_VALUES['none']['none'];
      }
      return IIIF_PROFILE_VALUES[version][level];
    }

    /**
     * @param {PreferredOptions} [preferredOptions] Optional options for preferred format and quality.
     * @return {import("../source/IIIF.js").Options|undefined} IIIF tile source ready constructor options.
     * @api
     */
    getTileSourceOptions(preferredOptions) {
      const options = preferredOptions || {},
        version = this.getImageApiVersion();
      if (version === undefined) {
        return undefined;
      }
      const imageOptions =
        version === undefined ? undefined : versionFunctions[version](this);
      if (imageOptions === undefined) {
        return undefined;
      }
      return {
        url: imageOptions.url,
        version: version,
        size: [this.imageInfo.width, this.imageInfo.height],
        sizes: imageOptions.sizes,
        format:
          options.format !== undefined &&
          imageOptions.formats.includes(options.format)
            ? options.format
            : imageOptions.preferredFormat !== undefined
              ? imageOptions.preferredFormat
              : 'jpg',
        supports: imageOptions.supports,
        quality:
          options.quality && imageOptions.qualities.includes(options.quality)
            ? options.quality
            : imageOptions.qualities.includes('native')
              ? 'native'
              : 'default',
        resolutions: Array.isArray(imageOptions.resolutions)
          ? imageOptions.resolutions.sort(function (a, b) {
              return b - a;
            })
          : undefined,
        tileSize: imageOptions.tileSize,
      };
    }
  }

  /**
   * @module ol/format/KML
   */

  /**
   * @typedef {Object} Vec2
   * @property {number} x X coordinate.
   * @property {import("../style/Icon.js").IconAnchorUnits} xunits Units of x.
   * @property {number} y Y coordinate.
   * @property {import("../style/Icon.js").IconAnchorUnits} yunits Units of Y.
   * @property {import("../style/Icon.js").IconOrigin} [origin] Origin.
   */

  /**
   * @typedef {Object} GxTrackObject
   * @property {Array<Array<number>>} coordinates Coordinates.
   * @property {Array<number>} whens Whens.
   */

  /**
   * @const
   * @type {Array<string>}
   */
  const GX_NAMESPACE_URIS = ['http://www.google.com/kml/ext/2.2'];

  /**
   * @const
   * @type {Array<null|string>}
   */
  const NAMESPACE_URIS$3 = [
    null,
    'http://earth.google.com/kml/2.0',
    'http://earth.google.com/kml/2.1',
    'http://earth.google.com/kml/2.2',
    'http://www.opengis.net/kml/2.2',
  ];

  /**
   * @const
   * @type {string}
   */
  const SCHEMA_LOCATION =
    'http://www.opengis.net/kml/2.2 ' +
    'https://developers.google.com/kml/schema/kml22gx.xsd';

  /**
   * @type {Object<string, import("../style/Icon.js").IconAnchorUnits>}
   */
  const ICON_ANCHOR_UNITS_MAP = {
    'fraction': 'fraction',
    'pixels': 'pixels',
    'insetPixels': 'pixels',
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PLACEMARK_PARSERS = makeStructureNS(
    NAMESPACE_URIS$3,
    {
      'ExtendedData': extendedDataParser,
      'Region': regionParser,
      'MultiGeometry': makeObjectPropertySetter(readMultiGeometry, 'geometry'),
      'LineString': makeObjectPropertySetter(readLineString, 'geometry'),
      'LinearRing': makeObjectPropertySetter(readLinearRing, 'geometry'),
      'Point': makeObjectPropertySetter(readPoint, 'geometry'),
      'Polygon': makeObjectPropertySetter(readPolygon, 'geometry'),
      'Style': makeObjectPropertySetter(readStyle$2),
      'StyleMap': placemarkStyleMapParser,
      'address': makeObjectPropertySetter(readString),
      'description': makeObjectPropertySetter(readString),
      'name': makeObjectPropertySetter(readString),
      'open': makeObjectPropertySetter(readBoolean),
      'phoneNumber': makeObjectPropertySetter(readString),
      'styleUrl': makeObjectPropertySetter(readStyleURL),
      'visibility': makeObjectPropertySetter(readBoolean),
    },
    makeStructureNS(GX_NAMESPACE_URIS, {
      'MultiTrack': makeObjectPropertySetter(readGxMultiTrack, 'geometry'),
      'Track': makeObjectPropertySetter(readGxTrack, 'geometry'),
    }),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const NETWORK_LINK_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'ExtendedData': extendedDataParser,
    'Region': regionParser,
    'Link': linkParser,
    'address': makeObjectPropertySetter(readString),
    'description': makeObjectPropertySetter(readString),
    'name': makeObjectPropertySetter(readString),
    'open': makeObjectPropertySetter(readBoolean),
    'phoneNumber': makeObjectPropertySetter(readString),
    'visibility': makeObjectPropertySetter(readBoolean),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LINK_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'href': makeObjectPropertySetter(readURI),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CAMERA_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    Altitude: makeObjectPropertySetter(readDecimal),
    Longitude: makeObjectPropertySetter(readDecimal),
    Latitude: makeObjectPropertySetter(readDecimal),
    Tilt: makeObjectPropertySetter(readDecimal),
    AltitudeMode: makeObjectPropertySetter(readString),
    Heading: makeObjectPropertySetter(readDecimal),
    Roll: makeObjectPropertySetter(readDecimal),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const REGION_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'LatLonAltBox': latLonAltBoxParser,
    'Lod': lodParser,
  });

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const KML_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, ['Document', 'Placemark']);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const KML_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Document': makeChildAppender(writeDocument),
    'Placemark': makeChildAppender(writePlacemark),
  });

  /**
   * @type {import("../color.js").Color}
   */
  let DEFAULT_COLOR;

  /**
   * @type {Fill|null}
   */
  let DEFAULT_FILL_STYLE = null;

  /**
   * @type {import("../size.js").Size}
   */
  let DEFAULT_IMAGE_STYLE_ANCHOR;

  /**
   * @type {import("../style/Icon.js").IconAnchorUnits}
   */
  let DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS;

  /**
   * @type {import("../style/Icon.js").IconAnchorUnits}
   */
  let DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS;

  /**
   * @type {import("../size.js").Size}
   */
  let DEFAULT_IMAGE_STYLE_SIZE;

  /**
   * @type {string}
   */
  let DEFAULT_IMAGE_STYLE_SRC;

  /**
   * @type {import("../style/Image.js").default|null}
   */
  let DEFAULT_IMAGE_STYLE = null;

  /**
   * @type {string}
   */
  let DEFAULT_NO_IMAGE_STYLE;

  /**
   * @type {Stroke|null}
   */
  let DEFAULT_STROKE_STYLE = null;

  /**
   * @type {Stroke}
   */
  let DEFAULT_TEXT_STROKE_STYLE;

  /**
   * @type {Text|null}
   */
  let DEFAULT_TEXT_STYLE = null;

  /**
   * @type {Style|null}
   */
  let DEFAULT_STYLE = null;

  /**
   * @type {Array<Style>|null}
   */
  let DEFAULT_STYLE_ARRAY = null;

  /**
   * Function that returns the scale needed to normalize an icon image to 32 pixels.
   * @param {import("../size.js").Size} size Image size.
   * @return {number} Scale.
   */
  function scaleForSize(size) {
    return 32 / Math.min(size[0], size[1]);
  }

  function createStyleDefaults() {
    DEFAULT_COLOR = [255, 255, 255, 1];

    DEFAULT_FILL_STYLE = new Fill({
      color: DEFAULT_COLOR,
    });

    DEFAULT_IMAGE_STYLE_ANCHOR = [20, 2];

    DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS = 'pixels';

    DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS = 'pixels';

    DEFAULT_IMAGE_STYLE_SIZE = [64, 64];

    DEFAULT_IMAGE_STYLE_SRC =
      'https://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png';

    DEFAULT_IMAGE_STYLE = new Icon({
      anchor: DEFAULT_IMAGE_STYLE_ANCHOR,
      anchorOrigin: 'bottom-left',
      anchorXUnits: DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS,
      anchorYUnits: DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS,
      crossOrigin: 'anonymous',
      rotation: 0,
      scale: scaleForSize(DEFAULT_IMAGE_STYLE_SIZE),
      size: DEFAULT_IMAGE_STYLE_SIZE,
      src: DEFAULT_IMAGE_STYLE_SRC,
    });

    DEFAULT_NO_IMAGE_STYLE = 'NO_IMAGE';

    DEFAULT_STROKE_STYLE = new Stroke({
      color: DEFAULT_COLOR,
      width: 1,
    });

    DEFAULT_TEXT_STROKE_STYLE = new Stroke({
      color: [51, 51, 51, 1],
      width: 2,
    });

    DEFAULT_TEXT_STYLE = new Text({
      font: 'bold 16px Helvetica',
      fill: DEFAULT_FILL_STYLE,
      stroke: DEFAULT_TEXT_STROKE_STYLE,
      scale: 0.8,
    });

    DEFAULT_STYLE = new Style({
      fill: DEFAULT_FILL_STYLE,
      image: DEFAULT_IMAGE_STYLE,
      text: DEFAULT_TEXT_STYLE,
      stroke: DEFAULT_STROKE_STYLE,
      zIndex: 0,
    });

    DEFAULT_STYLE_ARRAY = [DEFAULT_STYLE];
  }

  /**
   * @type {HTMLTextAreaElement}
   */
  let TEXTAREA;

  /**
   * A function that takes a url `{string}` and returns a url `{string}`.
   * Might be used to change an icon path or to substitute a
   * data url obtained from a KMZ array buffer.
   *
   * @typedef {function(string):string} IconUrlFunction
   * @api
   */

  /**
   * Function that returns a url unchanged.
   * @param {string} href Input url.
   * @return {string} Output url.
   */
  function defaultIconUrlFunction(href) {
    return href;
  }

  /**
   * @typedef {Object} Options
   * @property {boolean} [extractStyles=true] Extract styles from the KML.
   * @property {boolean} [showPointNames=true] Show names as labels for placemarks which contain points.
   * @property {Array<Style>} [defaultStyle] Default style. The
   * default default style is the same as Google Earth.
   * @property {boolean} [writeStyles=true] Write styles into KML.
   * @property {null|string} [crossOrigin='anonymous'] The `crossOrigin` attribute for loaded images. Note that you must provide a
   * `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * @property {IconUrlFunction} [iconUrlFunction] Function that takes a url string and returns a url string.
   * Might be used to change an icon path or to substitute a data url obtained from a KMZ array buffer.
   */

  /**
   * @classdesc
   * Feature format for reading and writing data in the KML format.
   *
   * {@link module:ol/format/KML~KML#readFeature} will read the first feature from
   * a KML source.
   *
   * MultiGeometries are converted into GeometryCollections if they are a mix of
   * geometry types, and into MultiPoint/MultiLineString/MultiPolygon if they are
   * all of the same type.
   *
   * @api
   */
  class KML extends XMLFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      if (!DEFAULT_STYLE_ARRAY) {
        createStyleDefaults();
      }

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2('EPSG:4326');

      /**
       * @private
       * @type {Array<Style>}
       */
      this.defaultStyle_ = options.defaultStyle
        ? options.defaultStyle
        : DEFAULT_STYLE_ARRAY;

      /**
       * @private
       * @type {boolean}
       */
      this.extractStyles_ =
        options.extractStyles !== undefined ? options.extractStyles : true;

      /**
       * @type {boolean}
       */
      this.writeStyles_ =
        options.writeStyles !== undefined ? options.writeStyles : true;

      /**
       * @private
       * @type {!Object<string, (Array<Style>|string)>}
       */
      this.sharedStyles_ = {};

      /**
       * @private
       * @type {boolean}
       */
      this.showPointNames_ =
        options.showPointNames !== undefined ? options.showPointNames : true;

      /**
       * @type {null|string}
       */
      this.crossOrigin_ =
        options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous';

      /**
       * @type {IconUrlFunction}
       */
      this.iconUrlFunction_ = options.iconUrlFunction
        ? options.iconUrlFunction
        : defaultIconUrlFunction;

      this.supportedMediaTypes = ['application/vnd.google-earth.kml+xml'];
    }

    /**
     * @param {Node} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @private
     * @return {Array<Feature>|undefined} Features.
     */
    readDocumentOrFolder_(node, objectStack) {
      // FIXME use scope somehow
      const parsersNS = makeStructureNS(NAMESPACE_URIS$3, {
        'Document': makeArrayExtender(this.readDocumentOrFolder_, this),
        'Folder': makeArrayExtender(this.readDocumentOrFolder_, this),
        'Placemark': makeArrayPusher(this.readPlacemark_, this),
        'Style': this.readSharedStyle_.bind(this),
        'StyleMap': this.readSharedStyleMap_.bind(this),
      });
      /** @type {Array<Feature>} */
      // @ts-ignore
      const features = pushParseAndPop([], parsersNS, node, objectStack, this);
      if (features) {
        return features;
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @private
     * @return {Feature|undefined} Feature.
     */
    readPlacemark_(node, objectStack) {
      const object = pushParseAndPop(
        {'geometry': null},
        PLACEMARK_PARSERS,
        node,
        objectStack,
        this,
      );
      if (!object) {
        return undefined;
      }
      const feature = new Feature();
      const id = node.getAttribute('id');
      if (id !== null) {
        feature.setId(id);
      }
      const options = /** @type {import("./Feature.js").ReadOptions} */ (
        objectStack[0]
      );

      const geometry = object['geometry'];
      if (geometry) {
        transformGeometryWithOptions(geometry, false, options);
      }
      feature.setGeometry(geometry);
      delete object['geometry'];

      if (this.extractStyles_) {
        const style = object['Style'];
        const styleUrl = object['styleUrl'];
        const styleFunction = createFeatureStyleFunction(
          style,
          styleUrl,
          this.defaultStyle_,
          this.sharedStyles_,
          this.showPointNames_,
        );
        feature.setStyle(styleFunction);
      }
      delete object['Style'];
      // we do not remove the styleUrl property from the object, so it
      // gets stored on feature when setProperties is called

      feature.setProperties(object, true);

      return feature;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @private
     */
    readSharedStyle_(node, objectStack) {
      const id = node.getAttribute('id');
      if (id !== null) {
        const style = readStyle$2.call(this, node, objectStack);
        if (style) {
          let styleUri;
          let baseURI = node.baseURI;
          if (!baseURI || baseURI == 'about:blank') {
            baseURI = window.location.href;
          }
          if (baseURI) {
            const url = new URL('#' + id, baseURI);
            styleUri = url.href;
          } else {
            styleUri = '#' + id;
          }
          this.sharedStyles_[styleUri] = style;
        }
      }
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @private
     */
    readSharedStyleMap_(node, objectStack) {
      const id = node.getAttribute('id');
      if (id === null) {
        return;
      }
      const styleMapValue = readStyleMapValue.call(this, node, objectStack);
      if (!styleMapValue) {
        return;
      }
      let styleUri;
      let baseURI = node.baseURI;
      if (!baseURI || baseURI == 'about:blank') {
        baseURI = window.location.href;
      }
      if (baseURI) {
        const url = new URL('#' + id, baseURI);
        styleUri = url.href;
      } else {
        styleUri = '#' + id;
      }
      this.sharedStyles_[styleUri] = styleMapValue;
    }

    /**
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromNode(node, options) {
      if (!NAMESPACE_URIS$3.includes(node.namespaceURI)) {
        return null;
      }
      const feature = this.readPlacemark_(node, [
        this.getReadOptions(node, options),
      ]);
      if (feature) {
        return feature;
      }
      return null;
    }

    /**
     * @protected
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @override
     */
    readFeaturesFromNode(node, options) {
      if (!NAMESPACE_URIS$3.includes(node.namespaceURI)) {
        return [];
      }
      let features;
      const localName = node.localName;
      if (localName == 'Document' || localName == 'Folder') {
        features = this.readDocumentOrFolder_(node, [
          this.getReadOptions(node, options),
        ]);
        if (features) {
          return features;
        }
        return [];
      }
      if (localName == 'Placemark') {
        const feature = this.readPlacemark_(node, [
          this.getReadOptions(node, options),
        ]);
        if (feature) {
          return [feature];
        }
        return [];
      }
      if (localName == 'kml') {
        features = [];
        for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
          const fs = this.readFeaturesFromNode(n, options);
          if (fs) {
            extend$2(features, fs);
          }
        }
        return features;
      }
      return [];
    }

    /**
     * Read the name of the KML.
     *
     * @param {Document|Element|string} source Source.
     * @return {string|undefined} Name.
     * @api
     */
    readName(source) {
      if (!source) {
        return undefined;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readNameFromDocument(doc);
      }
      if (isDocument(source)) {
        return this.readNameFromDocument(/** @type {Document} */ (source));
      }
      return this.readNameFromNode(/** @type {Element} */ (source));
    }

    /**
     * @param {Document} doc Document.
     * @return {string|undefined} Name.
     */
    readNameFromDocument(doc) {
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          const name = this.readNameFromNode(/** @type {Element} */ (n));
          if (name) {
            return name;
          }
        }
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @return {string|undefined} Name.
     */
    readNameFromNode(node) {
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        if (NAMESPACE_URIS$3.includes(n.namespaceURI) && n.localName == 'name') {
          return readString(n);
        }
      }
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        const localName = n.localName;
        if (
          NAMESPACE_URIS$3.includes(n.namespaceURI) &&
          (localName == 'Document' ||
            localName == 'Folder' ||
            localName == 'Placemark' ||
            localName == 'kml')
        ) {
          const name = this.readNameFromNode(n);
          if (name) {
            return name;
          }
        }
      }
      return undefined;
    }

    /**
     * Read the network links of the KML.
     *
     * @param {Document|Element|string} source Source.
     * @return {Array<Object>} Network links.
     * @api
     */
    readNetworkLinks(source) {
      const networkLinks = [];
      if (typeof source === 'string') {
        const doc = parse(source);
        extend$2(networkLinks, this.readNetworkLinksFromDocument(doc));
      } else if (isDocument(source)) {
        extend$2(
          networkLinks,
          this.readNetworkLinksFromDocument(/** @type {Document} */ (source)),
        );
      } else {
        extend$2(
          networkLinks,
          this.readNetworkLinksFromNode(/** @type {Element} */ (source)),
        );
      }
      return networkLinks;
    }

    /**
     * @param {Document} doc Document.
     * @return {Array<Object>} Network links.
     */
    readNetworkLinksFromDocument(doc) {
      const networkLinks = [];
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          extend$2(
            networkLinks,
            this.readNetworkLinksFromNode(/** @type {Element} */ (n)),
          );
        }
      }
      return networkLinks;
    }

    /**
     * @param {Element} node Node.
     * @return {Array<Object>} Network links.
     */
    readNetworkLinksFromNode(node) {
      const networkLinks = [];
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        if (
          NAMESPACE_URIS$3.includes(n.namespaceURI) &&
          n.localName == 'NetworkLink'
        ) {
          const obj = pushParseAndPop({}, NETWORK_LINK_PARSERS, n, []);
          networkLinks.push(obj);
        }
      }
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        const localName = n.localName;
        if (
          NAMESPACE_URIS$3.includes(n.namespaceURI) &&
          (localName == 'Document' || localName == 'Folder' || localName == 'kml')
        ) {
          extend$2(networkLinks, this.readNetworkLinksFromNode(n));
        }
      }
      return networkLinks;
    }

    /**
     * Read the regions of the KML.
     *
     * @param {Document|Element|string} source Source.
     * @return {Array<Object>} Regions.
     * @api
     */
    readRegion(source) {
      const regions = [];
      if (typeof source === 'string') {
        const doc = parse(source);
        extend$2(regions, this.readRegionFromDocument(doc));
      } else if (isDocument(source)) {
        extend$2(
          regions,
          this.readRegionFromDocument(/** @type {Document} */ (source)),
        );
      } else {
        extend$2(regions, this.readRegionFromNode(/** @type {Element} */ (source)));
      }
      return regions;
    }

    /**
     * @param {Document} doc Document.
     * @return {Array<Object>} Region.
     */
    readRegionFromDocument(doc) {
      const regions = [];
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          extend$2(regions, this.readRegionFromNode(/** @type {Element} */ (n)));
        }
      }
      return regions;
    }

    /**
     * @param {Element} node Node.
     * @return {Array<Object>} Region.
     * @api
     */
    readRegionFromNode(node) {
      const regions = [];
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        if (NAMESPACE_URIS$3.includes(n.namespaceURI) && n.localName == 'Region') {
          const obj = pushParseAndPop({}, REGION_PARSERS, n, []);
          regions.push(obj);
        }
      }
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        const localName = n.localName;
        if (
          NAMESPACE_URIS$3.includes(n.namespaceURI) &&
          (localName == 'Document' || localName == 'Folder' || localName == 'kml')
        ) {
          extend$2(regions, this.readRegionFromNode(n));
        }
      }
      return regions;
    }

    /**
     * @typedef {Object} KMLCamera Specifies the observer's viewpoint and associated view parameters.
     * @property {number} [Latitude] Latitude of the camera.
     * @property {number} [Longitude] Longitude of the camera.
     * @property {number} [Altitude] Altitude of the camera.
     * @property {string} [AltitudeMode] Floor-related altitude mode.
     * @property {number} [Heading] Horizontal camera rotation.
     * @property {number} [Tilt] Lateral camera rotation.
     * @property {number} [Roll] Vertical camera rotation.
     */

    /**
     * Read the cameras of the KML.
     *
     * @param {Document|Element|string} source Source.
     * @return {Array<KMLCamera>} Cameras.
     * @api
     */
    readCamera(source) {
      const cameras = [];
      if (typeof source === 'string') {
        const doc = parse(source);
        extend$2(cameras, this.readCameraFromDocument(doc));
      } else if (isDocument(source)) {
        extend$2(
          cameras,
          this.readCameraFromDocument(/** @type {Document} */ (source)),
        );
      } else {
        extend$2(cameras, this.readCameraFromNode(/** @type {Element} */ (source)));
      }
      return cameras;
    }

    /**
     * @param {Document} doc Document.
     * @return {Array<KMLCamera>} Cameras.
     */
    readCameraFromDocument(doc) {
      const cameras = [];
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType === Node.ELEMENT_NODE) {
          extend$2(cameras, this.readCameraFromNode(/** @type {Element} */ (n)));
        }
      }
      return cameras;
    }

    /**
     * @param {Element} node Node.
     * @return {Array<KMLCamera>} Cameras.
     * @api
     */
    readCameraFromNode(node) {
      const cameras = [];
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        if (NAMESPACE_URIS$3.includes(n.namespaceURI) && n.localName === 'Camera') {
          const obj = pushParseAndPop({}, CAMERA_PARSERS, n, []);
          cameras.push(obj);
        }
      }
      for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
        const localName = n.localName;
        if (
          NAMESPACE_URIS$3.includes(n.namespaceURI) &&
          (localName === 'Document' ||
            localName === 'Folder' ||
            localName === 'Placemark' ||
            localName === 'kml')
        ) {
          extend$2(cameras, this.readCameraFromNode(n));
        }
      }
      return cameras;
    }

    /**
     * Encode an array of features in the KML format as an XML node. GeometryCollections,
     * MultiPoints, MultiLineStrings, and MultiPolygons are output as MultiGeometries.
     *
     * @param {Array<Feature>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Options.
     * @return {Node} Node.
     * @api
     * @override
     */
    writeFeaturesNode(features, options) {
      options = this.adaptOptions(options);
      const kml = createElementNS(NAMESPACE_URIS$3[4], 'kml');
      const xmlnsUri = 'http://www.w3.org/2000/xmlns/';
      kml.setAttributeNS(xmlnsUri, 'xmlns:gx', GX_NAMESPACE_URIS[0]);
      kml.setAttributeNS(xmlnsUri, 'xmlns:xsi', XML_SCHEMA_INSTANCE_URI);
      kml.setAttributeNS(
        XML_SCHEMA_INSTANCE_URI,
        'xsi:schemaLocation',
        SCHEMA_LOCATION,
      );

      const /** @type {import("../xml.js").NodeStackItem} */ context = {
          node: kml,
        };
      /** @type {!Object<string, (Array<Feature>|Feature|undefined)>} */
      const properties = {};
      if (features.length > 1) {
        properties['Document'] = features;
      } else if (features.length == 1) {
        properties['Placemark'] = features[0];
      }
      const orderedKeys = KML_SEQUENCE[kml.namespaceURI];
      const values = makeSequence(properties, orderedKeys);
      pushSerializeAndPop(
        context,
        KML_SERIALIZERS,
        OBJECT_PROPERTY_NODE_FACTORY,
        values,
        [options],
        orderedKeys,
        this,
      );
      return kml;
    }
  }

  /**
   * @param {Style|undefined} foundStyle Style.
   * @param {string} name Name.
   * @return {Style} style Style.
   */
  function createNameStyleFunction(foundStyle, name) {
    const textOffset = [0, 0];
    /** @type {CanvasTextAlign} */
    let textAlign = 'start';
    const imageStyle = foundStyle.getImage();
    if (imageStyle) {
      const imageSize = imageStyle.getSize();
      if (imageSize && imageSize.length == 2) {
        const imageScale = imageStyle.getScaleArray();
        const anchor = imageStyle.getAnchor();
        // Offset the label to be centered to the right of the icon,
        // if there is one.
        textOffset[0] = imageScale[0] * (imageSize[0] - anchor[0]);
        textOffset[1] = imageScale[1] * (imageSize[1] / 2 - anchor[1]);
        textAlign = 'left';
      }
    }
    let textStyle = foundStyle.getText();
    if (textStyle) {
      // clone the text style, customizing it with name, alignments and offset.
      // Note that kml does not support many text options that OpenLayers does (rotation, textBaseline).
      textStyle = textStyle.clone();
      textStyle.setFont(textStyle.getFont() || DEFAULT_TEXT_STYLE.getFont());
      textStyle.setScale(textStyle.getScale() || DEFAULT_TEXT_STYLE.getScale());
      textStyle.setFill(textStyle.getFill() || DEFAULT_TEXT_STYLE.getFill());
      textStyle.setStroke(textStyle.getStroke() || DEFAULT_TEXT_STROKE_STYLE);
    } else {
      textStyle = DEFAULT_TEXT_STYLE.clone();
    }
    textStyle.setText(name);
    textStyle.setOffsetX(textOffset[0]);
    textStyle.setOffsetY(textOffset[1]);
    textStyle.setTextAlign(textAlign);

    const nameStyle = new Style({
      image: imageStyle,
      text: textStyle,
    });
    return nameStyle;
  }

  /**
   * @param {Array<Style>|undefined} style Style.
   * @param {string} styleUrl Style URL.
   * @param {Array<Style>} defaultStyle Default style.
   * @param {!Object<string, (Array<Style>|string)>} sharedStyles Shared styles.
   * @param {boolean|undefined} showPointNames true to show names for point placemarks.
   * @return {import("../style/Style.js").StyleFunction} Feature style function.
   */
  function createFeatureStyleFunction(
    style,
    styleUrl,
    defaultStyle,
    sharedStyles,
    showPointNames,
  ) {
    return (
      /**
       * @param {Feature} feature feature.
       * @param {number} resolution Resolution.
       * @return {Array<Style>|Style} Style.
       */
      function (feature, resolution) {
        let drawName = showPointNames;
        let name = '';
        let multiGeometryPoints = [];
        if (drawName) {
          const geometry = feature.getGeometry();
          if (geometry) {
            if (geometry instanceof GeometryCollection) {
              multiGeometryPoints = geometry
                .getGeometriesArrayRecursive()
                .filter(function (geometry) {
                  const type = geometry.getType();
                  return type === 'Point' || type === 'MultiPoint';
                });
              drawName = multiGeometryPoints.length > 0;
            } else {
              const type = geometry.getType();
              drawName = type === 'Point' || type === 'MultiPoint';
            }
          }
        }

        if (drawName) {
          name = /** @type {string} */ (feature.get('name'));
          drawName = drawName && !!name;
          // convert any html character codes
          if (drawName && /&[^&]+;/.test(name)) {
            if (!TEXTAREA) {
              TEXTAREA = document.createElement('textarea');
            }
            TEXTAREA.innerHTML = name;
            name = TEXTAREA.value;
          }
        }

        let featureStyle = defaultStyle;
        if (style) {
          featureStyle = style;
        } else if (styleUrl) {
          featureStyle = findStyle(styleUrl, defaultStyle, sharedStyles);
        }
        if (drawName) {
          const nameStyle = createNameStyleFunction(featureStyle[0], name);
          if (multiGeometryPoints.length > 0) {
            // in multigeometries restrict the name style to points and create a
            // style without image or text for geometries requiring fill or stroke
            // including any polygon specific style if there is one
            nameStyle.setGeometry(new GeometryCollection(multiGeometryPoints));
            const baseStyle = new Style({
              geometry: featureStyle[0].getGeometry(),
              image: null,
              fill: featureStyle[0].getFill(),
              stroke: featureStyle[0].getStroke(),
              text: null,
            });
            return [nameStyle, baseStyle].concat(featureStyle.slice(1));
          }
          return nameStyle;
        }
        return featureStyle;
      }
    );
  }

  /**
   * @param {Array<Style>|string|undefined} styleValue Style value.
   * @param {Array<Style>} defaultStyle Default style.
   * @param {!Object<string, (Array<Style>|string)>} sharedStyles
   * Shared styles.
   * @return {Array<Style>} Style.
   */
  function findStyle(styleValue, defaultStyle, sharedStyles) {
    if (Array.isArray(styleValue)) {
      return styleValue;
    }
    if (typeof styleValue === 'string') {
      return findStyle(sharedStyles[styleValue], defaultStyle, sharedStyles);
    }
    return defaultStyle;
  }

  /**
   * @param {Node} node Node.
   * @return {import("../color.js").Color|undefined} Color.
   */
  function readColor(node) {
    const s = getAllTextContent(node, false);
    // The KML specification states that colors should not include a leading `#`
    // but we tolerate them.
    const m = /^\s*#?\s*([0-9A-Fa-f]{8})\s*$/.exec(s);
    if (m) {
      const hexColor = m[1];
      return [
        parseInt(hexColor.substr(6, 2), 16),
        parseInt(hexColor.substr(4, 2), 16),
        parseInt(hexColor.substr(2, 2), 16),
        parseInt(hexColor.substr(0, 2), 16) / 255,
      ];
    }
    return undefined;
  }

  /**
   * @param {Node} node Node.
   * @return {Array<number>|undefined} Flat coordinates.
   */
  function readFlatCoordinates(node) {
    let s = getAllTextContent(node, false);
    const flatCoordinates = [];
    // The KML specification states that coordinate tuples should not include
    // spaces, but we tolerate them.
    s = s.replace(/\s*,\s*/g, ',');
    const re =
      /^\s*([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?),([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)(?:\s+|,|$)(?:([+\-]?\d*\.?\d+(?:e[+\-]?\d+)?)(?:\s+|$))?\s*/i;
    let m;
    while ((m = re.exec(s))) {
      const x = parseFloat(m[1]);
      const y = parseFloat(m[2]);
      const z = m[3] ? parseFloat(m[3]) : 0;
      flatCoordinates.push(x, y, z);
      s = s.substr(m[0].length);
    }
    if (s !== '') {
      return undefined;
    }
    return flatCoordinates;
  }

  /**
   * @param {Node} node Node.
   * @return {string} URI.
   */
  function readURI(node) {
    const s = getAllTextContent(node, false).trim();
    let baseURI = node.baseURI;
    if (!baseURI || baseURI == 'about:blank') {
      baseURI = window.location.href;
    }
    if (baseURI) {
      const url = new URL(s, baseURI);
      return url.href;
    }
    return s;
  }

  /**
   * @param {Node} node Node.
   * @return {string} URI.
   */
  function readStyleURL(node) {
    // KML files in the wild occasionally forget the leading
    // `#` on styleUrlsdefined in the same document.
    const s = getAllTextContent(node, false)
      .trim()
      .replace(/^(?!.*#)/, '#');
    let baseURI = node.baseURI;
    if (!baseURI || baseURI == 'about:blank') {
      baseURI = window.location.href;
    }
    if (baseURI) {
      const url = new URL(s, baseURI);
      return url.href;
    }
    return s;
  }

  /**
   * @param {Element} node Node.
   * @return {Vec2} Vec2.
   */
  function readVec2(node) {
    const xunits = node.getAttribute('xunits');
    const yunits = node.getAttribute('yunits');
    /** @type {import('../style/Icon.js').IconOrigin} */
    let origin;
    if (xunits !== 'insetPixels') {
      if (yunits !== 'insetPixels') {
        origin = 'bottom-left';
      } else {
        origin = 'top-left';
      }
    } else {
      if (yunits !== 'insetPixels') {
        origin = 'bottom-right';
      } else {
        origin = 'top-right';
      }
    }
    return {
      x: parseFloat(node.getAttribute('x')),
      xunits: ICON_ANCHOR_UNITS_MAP[xunits],
      y: parseFloat(node.getAttribute('y')),
      yunits: ICON_ANCHOR_UNITS_MAP[yunits],
      origin: origin,
    };
  }

  /**
   * @param {Node} node Node.
   * @return {number|undefined} Scale.
   */
  function readScale(node) {
    return readDecimal(node);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const STYLE_MAP_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Pair': pairDataParser,
  });

  /**
   * @this {KML}
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<Style>|string|undefined} StyleMap.
   */
  function readStyleMapValue(node, objectStack) {
    return pushParseAndPop(undefined, STYLE_MAP_PARSERS, node, objectStack, this);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const ICON_STYLE_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Icon': makeObjectPropertySetter(readIcon),
    'color': makeObjectPropertySetter(readColor),
    'heading': makeObjectPropertySetter(readDecimal),
    'hotSpot': makeObjectPropertySetter(readVec2),
    'scale': makeObjectPropertySetter(readScale),
  });

  /**
   * @this {KML}
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function iconStyleParser(node, objectStack) {
    // FIXME refreshMode
    // FIXME refreshInterval
    // FIXME viewRefreshTime
    // FIXME viewBoundScale
    // FIXME viewFormat
    // FIXME httpQuery
    const object = pushParseAndPop({}, ICON_STYLE_PARSERS, node, objectStack);
    if (!object) {
      return;
    }
    const styleObject = /** @type {Object} */ (
      objectStack[objectStack.length - 1]
    );
    const IconObject = 'Icon' in object ? object['Icon'] : {};
    const drawIcon = !('Icon' in object) || Object.keys(IconObject).length > 0;
    let src;
    const href = /** @type {string|undefined} */ (IconObject['href']);
    if (href) {
      src = href;
    } else if (drawIcon) {
      src = DEFAULT_IMAGE_STYLE_SRC;
    }
    let anchor, anchorXUnits, anchorYUnits;
    /** @type {import('../style/Icon.js').IconOrigin|undefined} */
    let anchorOrigin = 'bottom-left';
    const hotSpot = /** @type {Vec2|undefined} */ (object['hotSpot']);
    if (hotSpot) {
      anchor = [hotSpot.x, hotSpot.y];
      anchorXUnits = hotSpot.xunits;
      anchorYUnits = hotSpot.yunits;
      anchorOrigin = hotSpot.origin;
    } else if (/^https?:\/\/maps\.(?:google|gstatic)\.com\//.test(src)) {
      // Google hotspots from https://kml4earth.appspot.com/icons.html#notes
      if (src.includes('pushpin')) {
        anchor = DEFAULT_IMAGE_STYLE_ANCHOR;
        anchorXUnits = DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS;
        anchorYUnits = DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS;
      } else if (src.includes('arrow-reverse')) {
        anchor = [54, 42];
        anchorXUnits = DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS;
        anchorYUnits = DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS;
      } else if (src.includes('paddle')) {
        anchor = [32, 1];
        anchorXUnits = DEFAULT_IMAGE_STYLE_ANCHOR_X_UNITS;
        anchorYUnits = DEFAULT_IMAGE_STYLE_ANCHOR_Y_UNITS;
      }
    }

    let offset;
    const x = /** @type {number|undefined} */ (IconObject['x']);
    const y = /** @type {number|undefined} */ (IconObject['y']);
    if (x !== undefined && y !== undefined) {
      offset = [x, y];
    }

    let size;
    const w = /** @type {number|undefined} */ (IconObject['w']);
    const h = /** @type {number|undefined} */ (IconObject['h']);
    if (w !== undefined && h !== undefined) {
      size = [w, h];
    }

    let rotation;
    const heading = /** @type {number} */ (object['heading']);
    if (heading !== undefined) {
      rotation = toRadians(heading);
    }

    const scale = /** @type {number|undefined} */ (object['scale']);

    const color = /** @type {Array<number>|undefined} */ (object['color']);

    if (drawIcon) {
      if (src == DEFAULT_IMAGE_STYLE_SRC) {
        size = DEFAULT_IMAGE_STYLE_SIZE;
      }

      const imageStyle = new Icon({
        anchor: anchor,
        anchorOrigin: anchorOrigin,
        anchorXUnits: anchorXUnits,
        anchorYUnits: anchorYUnits,
        crossOrigin: this.crossOrigin_,
        offset: offset,
        offsetOrigin: 'bottom-left',
        rotation: rotation,
        scale: scale,
        size: size,
        src: this.iconUrlFunction_(src),
        color: color,
      });

      const imageScale = imageStyle.getScaleArray()[0];
      const imageSize = imageStyle.getSize();
      if (imageSize === null) {
        const imageState = imageStyle.getImageState();
        if (imageState === ImageState.IDLE || imageState === ImageState.LOADING) {
          const listener = function () {
            const imageState = imageStyle.getImageState();
            if (
              !(
                imageState === ImageState.IDLE ||
                imageState === ImageState.LOADING
              )
            ) {
              const imageSize = imageStyle.getSize();
              if (imageSize && imageSize.length == 2) {
                const resizeScale = scaleForSize(imageSize);
                imageStyle.setScale(imageScale * resizeScale);
              }
              imageStyle.unlistenImageChange(listener);
            }
          };
          imageStyle.listenImageChange(listener);
          if (imageState === ImageState.IDLE) {
            imageStyle.load();
          }
        }
      } else if (imageSize.length == 2) {
        const resizeScale = scaleForSize(imageSize);
        imageStyle.setScale(imageScale * resizeScale);
      }
      styleObject['imageStyle'] = imageStyle;
    } else {
      // handle the case when we explicitly want to draw no icon.
      styleObject['imageStyle'] = DEFAULT_NO_IMAGE_STYLE;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LABEL_STYLE_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeObjectPropertySetter(readColor),
    'scale': makeObjectPropertySetter(readScale),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function labelStyleParser(node, objectStack) {
    // FIXME colorMode
    const object = pushParseAndPop({}, LABEL_STYLE_PARSERS, node, objectStack);
    if (!object) {
      return;
    }
    const styleObject = objectStack[objectStack.length - 1];
    const textStyle = new Text({
      fill: new Fill({
        color:
          /** @type {import("../color.js").Color} */
          ('color' in object ? object['color'] : DEFAULT_COLOR),
      }),
      scale: /** @type {number|undefined} */ (object['scale']),
    });
    styleObject['textStyle'] = textStyle;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LINE_STYLE_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeObjectPropertySetter(readColor),
    'width': makeObjectPropertySetter(readDecimal),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function lineStyleParser(node, objectStack) {
    // FIXME colorMode
    // FIXME gx:outerColor
    // FIXME gx:outerWidth
    // FIXME gx:physicalWidth
    // FIXME gx:labelVisibility
    const object = pushParseAndPop({}, LINE_STYLE_PARSERS, node, objectStack);
    if (!object) {
      return;
    }
    const styleObject = objectStack[objectStack.length - 1];
    const strokeStyle = new Stroke({
      color:
        /** @type {import("../color.js").Color} */
        ('color' in object ? object['color'] : DEFAULT_COLOR),
      width: /** @type {number} */ ('width' in object ? object['width'] : 1),
    });
    styleObject['strokeStyle'] = strokeStyle;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const POLY_STYLE_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeObjectPropertySetter(readColor),
    'fill': makeObjectPropertySetter(readBoolean),
    'outline': makeObjectPropertySetter(readBoolean),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function polyStyleParser(node, objectStack) {
    // FIXME colorMode
    const object = pushParseAndPop({}, POLY_STYLE_PARSERS, node, objectStack);
    if (!object) {
      return;
    }
    const styleObject = objectStack[objectStack.length - 1];
    const fillStyle = new Fill({
      color:
        /** @type {import("../color.js").Color} */
        ('color' in object ? object['color'] : DEFAULT_COLOR),
    });
    styleObject['fillStyle'] = fillStyle;
    const fill = /** @type {boolean|undefined} */ (object['fill']);
    if (fill !== undefined) {
      styleObject['fill'] = fill;
    }
    const outline = /** @type {boolean|undefined} */ (object['outline']);
    if (outline !== undefined) {
      styleObject['outline'] = outline;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const FLAT_LINEAR_RING_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'coordinates': makeReplacer(readFlatCoordinates),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<number>} LinearRing flat coordinates.
   */
  function readFlatLinearRing(node, objectStack) {
    return pushParseAndPop(null, FLAT_LINEAR_RING_PARSERS, node, objectStack);
  }

  /**
   * @param {Node} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function gxCoordParser(node, objectStack) {
    const gxTrackObject =
      /** @type {GxTrackObject} */
      (objectStack[objectStack.length - 1]);
    const coordinates = gxTrackObject.coordinates;
    const s = getAllTextContent(node, false);
    const re =
      /^\s*([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s+([+\-]?\d+(?:\.\d*)?(?:e[+\-]?\d*)?)\s*$/i;
    const m = re.exec(s);
    if (m) {
      const x = parseFloat(m[1]);
      const y = parseFloat(m[2]);
      const z = parseFloat(m[3]);
      coordinates.push([x, y, z]);
    } else {
      coordinates.push([]);
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const GX_MULTITRACK_GEOMETRY_PARSERS = makeStructureNS(GX_NAMESPACE_URIS, {
    'Track': makeArrayPusher(readGxTrack),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {MultiLineString|undefined} MultiLineString.
   */
  function readGxMultiTrack(node, objectStack) {
    const lineStrings = pushParseAndPop(
      [],
      GX_MULTITRACK_GEOMETRY_PARSERS,
      node,
      objectStack,
    );
    if (!lineStrings) {
      return undefined;
    }
    return new MultiLineString(lineStrings);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const GX_TRACK_PARSERS = makeStructureNS(
    NAMESPACE_URIS$3,
    {
      'when': whenParser,
    },
    makeStructureNS(GX_NAMESPACE_URIS, {
      'coord': gxCoordParser,
    }),
  );

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {LineString|undefined} LineString.
   */
  function readGxTrack(node, objectStack) {
    const gxTrackObject = pushParseAndPop(
      /** @type {GxTrackObject} */ ({
        coordinates: [],
        whens: [],
      }),
      GX_TRACK_PARSERS,
      node,
      objectStack,
    );
    if (!gxTrackObject) {
      return undefined;
    }
    const flatCoordinates = [];
    const coordinates = gxTrackObject.coordinates;
    const whens = gxTrackObject.whens;
    for (
      let i = 0, ii = Math.min(coordinates.length, whens.length);
      i < ii;
      ++i
    ) {
      if (coordinates[i].length == 3) {
        flatCoordinates.push(
          coordinates[i][0],
          coordinates[i][1],
          coordinates[i][2],
          whens[i],
        );
      }
    }
    return new LineString(flatCoordinates, 'XYZM');
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const ICON_PARSERS = makeStructureNS(
    NAMESPACE_URIS$3,
    {
      'href': makeObjectPropertySetter(readURI),
    },
    makeStructureNS(GX_NAMESPACE_URIS, {
      'x': makeObjectPropertySetter(readDecimal),
      'y': makeObjectPropertySetter(readDecimal),
      'w': makeObjectPropertySetter(readDecimal),
      'h': makeObjectPropertySetter(readDecimal),
    }),
  );

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object} Icon object.
   */
  function readIcon(node, objectStack) {
    const iconObject = pushParseAndPop({}, ICON_PARSERS, node, objectStack);
    if (iconObject) {
      return iconObject;
    }
    return null;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const GEOMETRY_FLAT_COORDINATES_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'coordinates': makeReplacer(readFlatCoordinates),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<number>} Flat coordinates.
   */
  function readFlatCoordinatesFromNode(node, objectStack) {
    return pushParseAndPop(
      null,
      GEOMETRY_FLAT_COORDINATES_PARSERS,
      node,
      objectStack,
    );
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const EXTRUDE_AND_ALTITUDE_MODE_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'extrude': makeObjectPropertySetter(readBoolean),
    'tessellate': makeObjectPropertySetter(readBoolean),
    'altitudeMode': makeObjectPropertySetter(readString),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {LineString|undefined} LineString.
   */
  function readLineString(node, objectStack) {
    const properties = pushParseAndPop(
      {},
      EXTRUDE_AND_ALTITUDE_MODE_PARSERS,
      node,
      objectStack,
    );
    const flatCoordinates = readFlatCoordinatesFromNode(node, objectStack);
    if (flatCoordinates) {
      const lineString = new LineString(flatCoordinates, 'XYZ');
      lineString.setProperties(properties, true);
      return lineString;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Polygon|undefined} Polygon.
   */
  function readLinearRing(node, objectStack) {
    const properties = pushParseAndPop(
      {},
      EXTRUDE_AND_ALTITUDE_MODE_PARSERS,
      node,
      objectStack,
    );
    const flatCoordinates = readFlatCoordinatesFromNode(node, objectStack);
    if (flatCoordinates) {
      const polygon = new Polygon(flatCoordinates, 'XYZ', [
        flatCoordinates.length,
      ]);
      polygon.setProperties(properties, true);
      return polygon;
    }
    return undefined;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const MULTI_GEOMETRY_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'LineString': makeArrayPusher(readLineString),
    'LinearRing': makeArrayPusher(readLinearRing),
    'MultiGeometry': makeArrayPusher(readMultiGeometry),
    'Point': makeArrayPusher(readPoint),
    'Polygon': makeArrayPusher(readPolygon),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {import("../geom/Geometry.js").default} Geometry.
   */
  function readMultiGeometry(node, objectStack) {
    const geometries = pushParseAndPop(
      [],
      MULTI_GEOMETRY_PARSERS,
      node,
      objectStack,
    );
    if (!geometries) {
      return null;
    }
    if (geometries.length === 0) {
      return new GeometryCollection(geometries);
    }
    let multiGeometry;
    let homogeneous = true;
    const type = geometries[0].getType();
    let geometry;
    for (let i = 1, ii = geometries.length; i < ii; ++i) {
      geometry = geometries[i];
      if (geometry.getType() != type) {
        homogeneous = false;
        break;
      }
    }
    if (homogeneous) {
      let layout;
      let flatCoordinates;
      if (type == 'Point') {
        const point = geometries[0];
        layout = point.getLayout();
        flatCoordinates = point.getFlatCoordinates();
        for (let i = 1, ii = geometries.length; i < ii; ++i) {
          geometry = geometries[i];
          extend$2(flatCoordinates, geometry.getFlatCoordinates());
        }
        multiGeometry = new MultiPoint(flatCoordinates, layout);
        setCommonGeometryProperties(multiGeometry, geometries);
      } else if (type == 'LineString') {
        multiGeometry = new MultiLineString(geometries);
        setCommonGeometryProperties(multiGeometry, geometries);
      } else if (type == 'Polygon') {
        multiGeometry = new MultiPolygon(geometries);
        setCommonGeometryProperties(multiGeometry, geometries);
      } else if (type == 'GeometryCollection' || type.startsWith('Multi')) {
        multiGeometry = new GeometryCollection(geometries);
      } else {
        throw new Error('Unknown geometry type found');
      }
    } else {
      multiGeometry = new GeometryCollection(geometries);
    }
    return /** @type {import("../geom/Geometry.js").default} */ (multiGeometry);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Point|undefined} Point.
   */
  function readPoint(node, objectStack) {
    const properties = pushParseAndPop(
      {},
      EXTRUDE_AND_ALTITUDE_MODE_PARSERS,
      node,
      objectStack,
    );
    const flatCoordinates = readFlatCoordinatesFromNode(node, objectStack);
    if (flatCoordinates) {
      const point = new Point(flatCoordinates, 'XYZ');
      point.setProperties(properties, true);
      return point;
    }
    return undefined;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const FLAT_LINEAR_RINGS_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'innerBoundaryIs': innerBoundaryIsParser,
    'outerBoundaryIs': outerBoundaryIsParser,
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Polygon|undefined} Polygon.
   */
  function readPolygon(node, objectStack) {
    const properties = pushParseAndPop(
      /** @type {Object<string,*>} */ ({}),
      EXTRUDE_AND_ALTITUDE_MODE_PARSERS,
      node,
      objectStack,
    );
    const flatLinearRings = pushParseAndPop(
      [null],
      FLAT_LINEAR_RINGS_PARSERS,
      node,
      objectStack,
    );
    if (flatLinearRings && flatLinearRings[0]) {
      const flatCoordinates = flatLinearRings[0];
      const ends = [flatCoordinates.length];
      for (let i = 1, ii = flatLinearRings.length; i < ii; ++i) {
        extend$2(flatCoordinates, flatLinearRings[i]);
        ends.push(flatCoordinates.length);
      }
      const polygon = new Polygon(flatCoordinates, 'XYZ', ends);
      polygon.setProperties(properties, true);
      return polygon;
    }
    return undefined;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const STYLE_PARSERS$2 = makeStructureNS(NAMESPACE_URIS$3, {
    'IconStyle': iconStyleParser,
    'LabelStyle': labelStyleParser,
    'LineStyle': lineStyleParser,
    'PolyStyle': polyStyleParser,
  });

  /**
   * @this {KML}
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<Style>} Style.
   */
  function readStyle$2(node, objectStack) {
    const styleObject = pushParseAndPop(
      {},
      STYLE_PARSERS$2,
      node,
      objectStack,
      this,
    );
    if (!styleObject) {
      return null;
    }
    let fillStyle =
      /** @type {Fill} */
      (
        'fillStyle' in styleObject ? styleObject['fillStyle'] : DEFAULT_FILL_STYLE
      );
    const fill = /** @type {boolean|undefined} */ (styleObject['fill']);
    if (fill !== undefined && !fill) {
      fillStyle = null;
    }
    let imageStyle;
    if ('imageStyle' in styleObject) {
      if (styleObject['imageStyle'] != DEFAULT_NO_IMAGE_STYLE) {
        imageStyle = /** @type {import("../style/Image.js").default} */ (
          styleObject['imageStyle']
        );
      }
    } else {
      imageStyle = DEFAULT_IMAGE_STYLE;
    }
    const textStyle =
      /** @type {Text} */
      (
        'textStyle' in styleObject ? styleObject['textStyle'] : DEFAULT_TEXT_STYLE
      );
    const strokeStyle =
      /** @type {Stroke} */
      (
        'strokeStyle' in styleObject
          ? styleObject['strokeStyle']
          : DEFAULT_STROKE_STYLE
      );
    const outline = /** @type {boolean|undefined} */ (styleObject['outline']);
    if (outline !== undefined && !outline) {
      // if the polystyle specifies no outline two styles are needed,
      // one for non-polygon geometries where linestrings require a stroke
      // and one for polygons where there should be no stroke
      return [
        new Style({
          geometry: function (feature) {
            const geometry = feature.getGeometry();
            const type = geometry.getType();
            if (type === 'GeometryCollection') {
              const collection =
                /** @type {import("../geom/GeometryCollection").default} */ (
                  geometry
                );
              return new GeometryCollection(
                collection
                  .getGeometriesArrayRecursive()
                  .filter(function (geometry) {
                    const type = geometry.getType();
                    return type !== 'Polygon' && type !== 'MultiPolygon';
                  }),
              );
            }
            if (type !== 'Polygon' && type !== 'MultiPolygon') {
              return geometry;
            }
          },
          fill: fillStyle,
          image: imageStyle,
          stroke: strokeStyle,
          text: textStyle,
          zIndex: undefined, // FIXME
        }),
        new Style({
          geometry: function (feature) {
            const geometry = feature.getGeometry();
            const type = geometry.getType();
            if (type === 'GeometryCollection') {
              const collection =
                /** @type {import("../geom/GeometryCollection").default} */ (
                  geometry
                );
              return new GeometryCollection(
                collection
                  .getGeometriesArrayRecursive()
                  .filter(function (geometry) {
                    const type = geometry.getType();
                    return type === 'Polygon' || type === 'MultiPolygon';
                  }),
              );
            }
            if (type === 'Polygon' || type === 'MultiPolygon') {
              return geometry;
            }
          },
          fill: fillStyle,
          stroke: null,
          zIndex: undefined, // FIXME
        }),
      ];
    }
    return [
      new Style({
        fill: fillStyle,
        image: imageStyle,
        stroke: strokeStyle,
        text: textStyle,
        zIndex: undefined, // FIXME
      }),
    ];
  }

  /**
   * Reads an array of geometries and creates arrays for common geometry
   * properties. Then sets them to the multi geometry.
   * @param {MultiPoint|MultiLineString|MultiPolygon} multiGeometry A multi-geometry.
   * @param {Array<import("../geom/Geometry.js").default>} geometries List of geometries.
   */
  function setCommonGeometryProperties(multiGeometry, geometries) {
    const ii = geometries.length;
    const extrudes = new Array(geometries.length);
    const tessellates = new Array(geometries.length);
    const altitudeModes = new Array(geometries.length);
    let hasExtrude, hasTessellate, hasAltitudeMode;
    hasExtrude = false;
    hasTessellate = false;
    hasAltitudeMode = false;
    for (let i = 0; i < ii; ++i) {
      const geometry = geometries[i];
      extrudes[i] = geometry.get('extrude');
      tessellates[i] = geometry.get('tessellate');
      altitudeModes[i] = geometry.get('altitudeMode');
      hasExtrude = hasExtrude || extrudes[i] !== undefined;
      hasTessellate = hasTessellate || tessellates[i] !== undefined;
      hasAltitudeMode = hasAltitudeMode || altitudeModes[i];
    }
    if (hasExtrude) {
      multiGeometry.set('extrude', extrudes);
    }
    if (hasTessellate) {
      multiGeometry.set('tessellate', tessellates);
    }
    if (hasAltitudeMode) {
      multiGeometry.set('altitudeMode', altitudeModes);
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const DATA_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'displayName': makeObjectPropertySetter(readString),
    'value': makeObjectPropertySetter(readString),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function dataParser(node, objectStack) {
    const name = node.getAttribute('name');
    parseNode(DATA_PARSERS, node, objectStack);
    const featureObject = /** @type {Object} */ (
      objectStack[objectStack.length - 1]
    );
    if (name && featureObject.displayName) {
      featureObject[name] = {
        value: featureObject.value,
        displayName: featureObject.displayName,
        toString: function () {
          return featureObject.value;
        },
      };
    } else if (name !== null) {
      featureObject[name] = featureObject.value;
    } else if (featureObject.displayName !== null) {
      featureObject[featureObject.displayName] = featureObject.value;
    }
    delete featureObject['value'];
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const EXTENDED_DATA_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Data': dataParser,
    'SchemaData': schemaDataParser,
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function extendedDataParser(node, objectStack) {
    parseNode(EXTENDED_DATA_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function regionParser(node, objectStack) {
    parseNode(REGION_PARSERS, node, objectStack);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PAIR_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Style': makeObjectPropertySetter(readStyle$2),
    'key': makeObjectPropertySetter(readString),
    'styleUrl': makeObjectPropertySetter(readStyleURL),
  });

  /**
   * @this {KML}
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function pairDataParser(node, objectStack) {
    const pairObject = pushParseAndPop({}, PAIR_PARSERS, node, objectStack, this);
    if (!pairObject) {
      return;
    }
    const key = /** @type {string|undefined} */ (pairObject['key']);
    if (key && key == 'normal') {
      const styleUrl = /** @type {string|undefined} */ (pairObject['styleUrl']);
      if (styleUrl) {
        objectStack[objectStack.length - 1] = styleUrl;
      }
      const style = /** @type {Style} */ (pairObject['Style']);
      if (style) {
        objectStack[objectStack.length - 1] = style;
      }
    }
  }

  /**
   * @this {KML}
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function placemarkStyleMapParser(node, objectStack) {
    const styleMapValue = readStyleMapValue.call(this, node, objectStack);
    if (!styleMapValue) {
      return;
    }
    const placemarkObject = objectStack[objectStack.length - 1];
    if (Array.isArray(styleMapValue)) {
      placemarkObject['Style'] = styleMapValue;
    } else if (typeof styleMapValue === 'string') {
      placemarkObject['styleUrl'] = styleMapValue;
    } else {
      throw new Error('`styleMapValue` has an unknown type');
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SCHEMA_DATA_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'SimpleData': simpleDataParser,
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function schemaDataParser(node, objectStack) {
    parseNode(SCHEMA_DATA_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function simpleDataParser(node, objectStack) {
    const name = node.getAttribute('name');
    if (name !== null) {
      const data = readString(node);
      const featureObject = /** @type {Object} */ (
        objectStack[objectStack.length - 1]
      );
      featureObject[name] = data;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LAT_LON_ALT_BOX_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'altitudeMode': makeObjectPropertySetter(readString),
    'minAltitude': makeObjectPropertySetter(readDecimal),
    'maxAltitude': makeObjectPropertySetter(readDecimal),
    'north': makeObjectPropertySetter(readDecimal),
    'south': makeObjectPropertySetter(readDecimal),
    'east': makeObjectPropertySetter(readDecimal),
    'west': makeObjectPropertySetter(readDecimal),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function latLonAltBoxParser(node, objectStack) {
    const object = pushParseAndPop(
      {},
      LAT_LON_ALT_BOX_PARSERS,
      node,
      objectStack,
    );
    if (!object) {
      return;
    }
    const regionObject = /** @type {Object} */ (
      objectStack[objectStack.length - 1]
    );
    const extent = [
      parseFloat(object['west']),
      parseFloat(object['south']),
      parseFloat(object['east']),
      parseFloat(object['north']),
    ];
    regionObject['extent'] = extent;
    regionObject['altitudeMode'] = object['altitudeMode'];
    regionObject['minAltitude'] = parseFloat(object['minAltitude']);
    regionObject['maxAltitude'] = parseFloat(object['maxAltitude']);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LOD_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'minLodPixels': makeObjectPropertySetter(readDecimal),
    'maxLodPixels': makeObjectPropertySetter(readDecimal),
    'minFadeExtent': makeObjectPropertySetter(readDecimal),
    'maxFadeExtent': makeObjectPropertySetter(readDecimal),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function lodParser(node, objectStack) {
    const object = pushParseAndPop({}, LOD_PARSERS, node, objectStack);
    if (!object) {
      return;
    }
    const lodObject = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    lodObject['minLodPixels'] = parseFloat(object['minLodPixels']);
    lodObject['maxLodPixels'] = parseFloat(object['maxLodPixels']);
    lodObject['minFadeExtent'] = parseFloat(object['minFadeExtent']);
    lodObject['maxFadeExtent'] = parseFloat(object['maxFadeExtent']);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const INNER_BOUNDARY_IS_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    // KML spec only allows one LinearRing  per innerBoundaryIs, but Google Earth
    // allows multiple, so we parse multiple here too.
    'LinearRing': makeArrayPusher(readFlatLinearRing),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function innerBoundaryIsParser(node, objectStack) {
    const innerBoundaryFlatLinearRings = pushParseAndPop(
      /** @type {Array<Array<number>>} */ ([]),
      INNER_BOUNDARY_IS_PARSERS,
      node,
      objectStack,
    );
    if (innerBoundaryFlatLinearRings.length > 0) {
      const flatLinearRings =
        /** @type {Array<Array<number>>} */
        (objectStack[objectStack.length - 1]);
      flatLinearRings.push(...innerBoundaryFlatLinearRings);
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const OUTER_BOUNDARY_IS_PARSERS = makeStructureNS(NAMESPACE_URIS$3, {
    'LinearRing': makeReplacer(readFlatLinearRing),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function outerBoundaryIsParser(node, objectStack) {
    /** @type {Array<number>|undefined} */
    const flatLinearRing = pushParseAndPop(
      undefined,
      OUTER_BOUNDARY_IS_PARSERS,
      node,
      objectStack,
    );
    if (flatLinearRing) {
      const flatLinearRings =
        /** @type {Array<Array<number>>} */
        (objectStack[objectStack.length - 1]);
      flatLinearRings[0] = flatLinearRing;
    }
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function linkParser(node, objectStack) {
    parseNode(LINK_PARSERS, node, objectStack);
  }

  /**
   * @param {Node} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function whenParser(node, objectStack) {
    const gxTrackObject =
      /** @type {GxTrackObject} */
      (objectStack[objectStack.length - 1]);
    const whens = gxTrackObject.whens;
    const s = getAllTextContent(node, false);
    const when = Date.parse(s);
    whens.push(isNaN(when) ? 0 : when);
  }

  /**
   * @param {Node} node Node to append a TextNode with the color to.
   * @param {import("../color.js").Color|string} color Color.
   */
  function writeColorTextNode(node, color) {
    const rgba = asArray(color);
    const opacity = rgba.length == 4 ? rgba[3] : 1;
    /** @type {Array<string|number>} */
    const abgr = [opacity * 255, rgba[2], rgba[1], rgba[0]];
    for (let i = 0; i < 4; ++i) {
      const hex = Math.floor(/** @type {number} */ (abgr[i])).toString(16);
      abgr[i] = hex.length == 1 ? '0' + hex : hex;
    }
    writeStringTextNode(node, abgr.join(''));
  }

  /**
   * @param {Node} node Node to append a TextNode with the coordinates to.
   * @param {Array<number>} coordinates Coordinates.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeCoordinatesTextNode(node, coordinates, objectStack) {
    const context = objectStack[objectStack.length - 1];

    const layout = context['layout'];
    const stride = context['stride'];

    let dimension;
    if (layout == 'XY' || layout == 'XYM') {
      dimension = 2;
    } else if (layout == 'XYZ' || layout == 'XYZM') {
      dimension = 3;
    } else {
      throw new Error('Invalid geometry layout');
    }

    const ii = coordinates.length;
    let text = '';
    if (ii > 0) {
      text += coordinates[0];
      for (let d = 1; d < dimension; ++d) {
        text += ',' + coordinates[d];
      }
      for (let i = stride; i < ii; i += stride) {
        text += ' ' + coordinates[i];
        for (let d = 1; d < dimension; ++d) {
          text += ',' + coordinates[i + d];
        }
      }
    }
    writeStringTextNode(node, text);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const EXTENDEDDATA_NODE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Data': makeChildAppender(writeDataNode),
    'value': makeChildAppender(writeDataNodeValue),
    'displayName': makeChildAppender(writeDataNodeName),
  });

  /**
   * @param {Element} node Node.
   * @param {{name: *, value: *}} pair Name value pair.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeDataNode(node, pair, objectStack) {
    node.setAttribute('name', pair.name);
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const value = pair.value;

    if (typeof value == 'object') {
      if (value !== null && value.displayName) {
        pushSerializeAndPop(
          context,
          EXTENDEDDATA_NODE_SERIALIZERS,
          OBJECT_PROPERTY_NODE_FACTORY,
          [value.displayName],
          objectStack,
          ['displayName'],
        );
      }

      if (value !== null && value.value) {
        pushSerializeAndPop(
          context,
          EXTENDEDDATA_NODE_SERIALIZERS,
          OBJECT_PROPERTY_NODE_FACTORY,
          [value.value],
          objectStack,
          ['value'],
        );
      }
    } else {
      pushSerializeAndPop(
        context,
        EXTENDEDDATA_NODE_SERIALIZERS,
        OBJECT_PROPERTY_NODE_FACTORY,
        [value],
        objectStack,
        ['value'],
      );
    }
  }

  /**
   * @param {Node} node Node to append a TextNode with the name to.
   * @param {string} name DisplayName.
   */
  function writeDataNodeName(node, name) {
    writeStringTextNode(node, name);
  }

  /**
   * @param {Node} node Node to append a CDATA Section with the value to.
   * @param {string} value Value.
   */
  function writeDataNodeValue(node, value) {
    writeStringTextNode(node, value);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const DOCUMENT_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Placemark': makeChildAppender(writePlacemark),
  });

  /**
   * @const
   * @param {*} value Value.
   * @param {Array<*>} objectStack Object stack.
   * @param {string} [nodeName] Node name.
   * @return {Node|undefined} Node.
   */
  const DOCUMENT_NODE_FACTORY = function (value, objectStack, nodeName) {
    const parentNode = objectStack[objectStack.length - 1].node;
    return createElementNS(parentNode.namespaceURI, 'Placemark');
  };

  /**
   * @param {Element} node Node.
   * @param {Array<Feature>} features Features.
   * @param {Array<*>} objectStack Object stack.
   * @this {KML}
   */
  function writeDocument(node, features, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    pushSerializeAndPop(
      context,
      DOCUMENT_SERIALIZERS,
      DOCUMENT_NODE_FACTORY,
      features,
      objectStack,
      undefined,
      this,
    );
  }

  /**
   * A factory for creating Data nodes.
   * @const
   * @type {function(*, Array<*>): (Node|undefined)}
   */
  const DATA_NODE_FACTORY = makeSimpleNodeFactory('Data');

  /**
   * @param {Element} node Node.
   * @param {{names: Array<string>, values: (Array<*>)}} namesAndValues Names and values.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeExtendedData(node, namesAndValues, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const names = namesAndValues.names;
    const values = namesAndValues.values;
    const length = names.length;

    for (let i = 0; i < length; i++) {
      pushSerializeAndPop(
        context,
        EXTENDEDDATA_NODE_SERIALIZERS,
        DATA_NODE_FACTORY,
        [{name: names[i], value: values[i]}],
        objectStack,
      );
    }
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const ICON_SEQUENCE = makeStructureNS(
    NAMESPACE_URIS$3,
    ['href'],
    makeStructureNS(GX_NAMESPACE_URIS, ['x', 'y', 'w', 'h']),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const ICON_SERIALIZERS = makeStructureNS(
    NAMESPACE_URIS$3,
    {
      'href': makeChildAppender(writeStringTextNode),
    },
    makeStructureNS(GX_NAMESPACE_URIS, {
      'x': makeChildAppender(writeDecimalTextNode),
      'y': makeChildAppender(writeDecimalTextNode),
      'w': makeChildAppender(writeDecimalTextNode),
      'h': makeChildAppender(writeDecimalTextNode),
    }),
  );

  /**
   * @const
   * @param {*} value Value.
   * @param {Array<*>} objectStack Object stack.
   * @param {string} [nodeName] Node name.
   * @return {Node|undefined} Node.
   */
  const GX_NODE_FACTORY = function (value, objectStack, nodeName) {
    return createElementNS(GX_NAMESPACE_URIS[0], 'gx:' + nodeName);
  };

  /**
   * @param {Element} node Node.
   * @param {Object} icon Icon object.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeIcon(node, icon, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const parentNode = objectStack[objectStack.length - 1].node;
    let orderedKeys = ICON_SEQUENCE[parentNode.namespaceURI];
    let values = makeSequence(icon, orderedKeys);
    pushSerializeAndPop(
      context,
      ICON_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
    orderedKeys = ICON_SEQUENCE[GX_NAMESPACE_URIS[0]];
    values = makeSequence(icon, orderedKeys);
    pushSerializeAndPop(
      context,
      ICON_SERIALIZERS,
      GX_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const ICON_STYLE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'scale',
    'heading',
    'Icon',
    'color',
    'hotSpot',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const ICON_STYLE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'Icon': makeChildAppender(writeIcon),
    'color': makeChildAppender(writeColorTextNode),
    'heading': makeChildAppender(writeDecimalTextNode),
    'hotSpot': makeChildAppender(writeVec2),
    'scale': makeChildAppender(writeScaleTextNode),
  });

  /**
   * @param {Element} node Node.
   * @param {import("../style/Icon.js").default} style Icon style.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeIconStyle(node, style, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const /** @type {Object<string, any>} */ properties = {};
    const src = style.getSrc();
    const size = style.getSize();
    const iconImageSize = style.getImageSize();
    const iconProperties = {
      'href': src,
    };

    if (size) {
      iconProperties['w'] = size[0];
      iconProperties['h'] = size[1];
      const anchor = style.getAnchor(); // top-left
      const origin = style.getOrigin(); // top-left

      if (origin && iconImageSize && origin[0] !== 0 && origin[1] !== size[1]) {
        iconProperties['x'] = origin[0];
        iconProperties['y'] = iconImageSize[1] - (origin[1] + size[1]);
      }

      if (anchor && (anchor[0] !== size[0] / 2 || anchor[1] !== size[1] / 2)) {
        const /** @type {Vec2} */ hotSpot = {
            x: anchor[0],
            xunits: 'pixels',
            y: size[1] - anchor[1],
            yunits: 'pixels',
          };
        properties['hotSpot'] = hotSpot;
      }
    }

    properties['Icon'] = iconProperties;

    let scale = style.getScaleArray()[0];
    let imageSize = size;
    if (imageSize === null) {
      imageSize = DEFAULT_IMAGE_STYLE_SIZE;
    }
    if (imageSize.length == 2) {
      const resizeScale = scaleForSize(imageSize);
      scale = scale / resizeScale;
    }
    if (scale !== 1) {
      properties['scale'] = scale;
    }

    const rotation = style.getRotation();
    if (rotation !== 0) {
      properties['heading'] = rotation; // 0-360
    }

    const color = style.getColor();
    if (color) {
      properties['color'] = color;
    }

    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = ICON_STYLE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      ICON_STYLE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const LABEL_STYLE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'color',
    'scale',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const LABEL_STYLE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeChildAppender(writeColorTextNode),
    'scale': makeChildAppender(writeScaleTextNode),
  });

  /**
   * @param {Element} node Node.
   * @param {Text} style style.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeLabelStyle(node, style, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const properties = {};
    const fill = style.getFill();
    if (fill) {
      properties['color'] = fill.getColor();
    }
    const scale = style.getScale();
    if (scale && scale !== 1) {
      properties['scale'] = scale;
    }
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = LABEL_STYLE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      LABEL_STYLE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const LINE_STYLE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, ['color', 'width']);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const LINE_STYLE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeChildAppender(writeColorTextNode),
    'width': makeChildAppender(writeDecimalTextNode),
  });

  /**
   * @param {Element} node Node.
   * @param {Stroke} style style.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeLineStyle(node, style, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const properties = {
      'color': style.getColor(),
      'width': Number(style.getWidth()) || 1,
    };
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = LINE_STYLE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      LINE_STYLE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @const
   * @type {Object<string, string>}
   */
  const GEOMETRY_TYPE_TO_NODENAME = {
    'Point': 'Point',
    'LineString': 'LineString',
    'LinearRing': 'LinearRing',
    'Polygon': 'Polygon',
    'MultiPoint': 'MultiGeometry',
    'MultiLineString': 'MultiGeometry',
    'MultiPolygon': 'MultiGeometry',
    'GeometryCollection': 'MultiGeometry',
  };

  /**
   * @const
   * @param {*} value Value.
   * @param {Array<*>} objectStack Object stack.
   * @param {string} [nodeName] Node name.
   * @return {Node|undefined} Node.
   */
  const GEOMETRY_NODE_FACTORY = function (value, objectStack, nodeName) {
    if (value) {
      const parentNode = objectStack[objectStack.length - 1].node;
      return createElementNS(
        parentNode.namespaceURI,
        GEOMETRY_TYPE_TO_NODENAME[
          /** @type {import("../geom/Geometry.js").default} */ (value).getType()
        ],
      );
    }
  };

  /**
   * A factory for creating Point nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const POINT_NODE_FACTORY = makeSimpleNodeFactory('Point');

  /**
   * A factory for creating LineString nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const LINE_STRING_NODE_FACTORY = makeSimpleNodeFactory('LineString');

  /**
   * A factory for creating LinearRing nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const LINEAR_RING_NODE_FACTORY = makeSimpleNodeFactory('LinearRing');

  /**
   * A factory for creating Polygon nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const POLYGON_NODE_FACTORY = makeSimpleNodeFactory('Polygon');

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const MULTI_GEOMETRY_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'LineString': makeChildAppender(writePrimitiveGeometry),
    'Point': makeChildAppender(writePrimitiveGeometry),
    'Polygon': makeChildAppender(writePolygon),
    'GeometryCollection': makeChildAppender(writeMultiGeometry),
  });

  /**
   * @param {Element} node Node.
   * @param {import("../geom/Geometry.js").default} geometry Geometry.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeMultiGeometry(node, geometry, objectStack) {
    /** @type {import("../xml.js").NodeStackItem} */
    const context = {node: node};
    const type = geometry.getType();
    /** @type {Array<import("../geom/Geometry.js").default>} */
    let geometries = [];
    /** @type {function(*, Array<*>, string=): (Node|undefined)} */
    let factory;
    if (type === 'GeometryCollection') {
      /** @type {GeometryCollection} */ (geometry)
        .getGeometriesArrayRecursive()
        .forEach(function (geometry) {
          const type = geometry.getType();
          if (type === 'MultiPoint') {
            geometries = geometries.concat(
              /** @type {MultiPoint} */ (geometry).getPoints(),
            );
          } else if (type === 'MultiLineString') {
            geometries = geometries.concat(
              /** @type {MultiLineString} */ (geometry).getLineStrings(),
            );
          } else if (type === 'MultiPolygon') {
            geometries = geometries.concat(
              /** @type {MultiPolygon} */ (geometry).getPolygons(),
            );
          } else if (
            type === 'Point' ||
            type === 'LineString' ||
            type === 'Polygon'
          ) {
            geometries.push(geometry);
          } else {
            throw new Error('Unknown geometry type');
          }
        });
      factory = GEOMETRY_NODE_FACTORY;
    } else if (type === 'MultiPoint') {
      geometries = /** @type {MultiPoint} */ (geometry).getPoints();
      factory = POINT_NODE_FACTORY;
    } else if (type === 'MultiLineString') {
      geometries = /** @type {MultiLineString} */ (geometry).getLineStrings();
      factory = LINE_STRING_NODE_FACTORY;
    } else if (type === 'MultiPolygon') {
      geometries = /** @type {MultiPolygon} */ (geometry).getPolygons();
      factory = POLYGON_NODE_FACTORY;
    } else {
      throw new Error('Unknown geometry type');
    }
    pushSerializeAndPop(
      context,
      MULTI_GEOMETRY_SERIALIZERS,
      factory,
      geometries,
      objectStack,
    );
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const BOUNDARY_IS_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'LinearRing': makeChildAppender(writePrimitiveGeometry),
  });

  /**
   * @param {Element} node Node.
   * @param {import("../geom/LinearRing.js").default} linearRing Linear ring.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeBoundaryIs(node, linearRing, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    pushSerializeAndPop(
      context,
      BOUNDARY_IS_SERIALIZERS,
      LINEAR_RING_NODE_FACTORY,
      [linearRing],
      objectStack,
    );
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const PLACEMARK_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'ExtendedData': makeChildAppender(writeExtendedData),
    'MultiGeometry': makeChildAppender(writeMultiGeometry),
    'LineString': makeChildAppender(writePrimitiveGeometry),
    'LinearRing': makeChildAppender(writePrimitiveGeometry),
    'Point': makeChildAppender(writePrimitiveGeometry),
    'Polygon': makeChildAppender(writePolygon),
    'Style': makeChildAppender(writeStyle),
    'address': makeChildAppender(writeStringTextNode),
    'description': makeChildAppender(writeStringTextNode),
    'name': makeChildAppender(writeStringTextNode),
    'open': makeChildAppender(writeBooleanTextNode),
    'phoneNumber': makeChildAppender(writeStringTextNode),
    'styleUrl': makeChildAppender(writeStringTextNode),
    'visibility': makeChildAppender(writeBooleanTextNode),
  });

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const PLACEMARK_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'name',
    'open',
    'visibility',
    'address',
    'phoneNumber',
    'description',
    'styleUrl',
    'Style',
  ]);

  /**
   * A factory for creating ExtendedData nodes.
   * @const
   * @type {function(*, Array<*>): (Node|undefined)}
   */
  const EXTENDEDDATA_NODE_FACTORY = makeSimpleNodeFactory('ExtendedData');

  /**
   * FIXME currently we do serialize arbitrary/custom feature properties
   * (ExtendedData).
   * @param {Element} node Node.
   * @param {Feature} feature Feature.
   * @param {Array<*>} objectStack Object stack.
   * @this {KML}
   */
  function writePlacemark(node, feature, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};

    // set id
    if (feature.getId()) {
      node.setAttribute('id', /** @type {string} */ (feature.getId()));
    }

    // serialize properties (properties unknown to KML are not serialized)
    const properties = feature.getProperties();

    // don't export these to ExtendedData
    const filter = {
      'address': 1,
      'description': 1,
      'name': 1,
      'open': 1,
      'phoneNumber': 1,
      'styleUrl': 1,
      'visibility': 1,
    };
    filter[feature.getGeometryName()] = 1;
    const keys = Object.keys(properties || {})
      .sort()
      .filter(function (v) {
        return !filter[v];
      });

    const styleFunction = feature.getStyleFunction();
    if (styleFunction) {
      // FIXME the styles returned by the style function are supposed to be
      // resolution-independent here
      const styles = styleFunction(feature, 0);
      if (styles) {
        const styleArray = Array.isArray(styles) ? styles : [styles];
        let pointStyles = styleArray;
        if (feature.getGeometry()) {
          pointStyles = styleArray.filter(function (style) {
            const geometry = style.getGeometryFunction()(feature);
            if (geometry) {
              const type = geometry.getType();
              if (type === 'GeometryCollection') {
                return /** @type {GeometryCollection} */ (geometry)
                  .getGeometriesArrayRecursive()
                  .filter(function (geometry) {
                    const type = geometry.getType();
                    return type === 'Point' || type === 'MultiPoint';
                  }).length;
              }
              return type === 'Point' || type === 'MultiPoint';
            }
          });
        }
        if (this.writeStyles_) {
          let lineStyles = styleArray;
          let polyStyles = styleArray;
          if (feature.getGeometry()) {
            lineStyles = styleArray.filter(function (style) {
              const geometry = style.getGeometryFunction()(feature);
              if (geometry) {
                const type = geometry.getType();
                if (type === 'GeometryCollection') {
                  return /** @type {GeometryCollection} */ (geometry)
                    .getGeometriesArrayRecursive()
                    .filter(function (geometry) {
                      const type = geometry.getType();
                      return type === 'LineString' || type === 'MultiLineString';
                    }).length;
                }
                return type === 'LineString' || type === 'MultiLineString';
              }
            });
            polyStyles = styleArray.filter(function (style) {
              const geometry = style.getGeometryFunction()(feature);
              if (geometry) {
                const type = geometry.getType();
                if (type === 'GeometryCollection') {
                  return /** @type {GeometryCollection} */ (geometry)
                    .getGeometriesArrayRecursive()
                    .filter(function (geometry) {
                      const type = geometry.getType();
                      return type === 'Polygon' || type === 'MultiPolygon';
                    }).length;
                }
                return type === 'Polygon' || type === 'MultiPolygon';
              }
            });
          }
          properties['Style'] = {
            pointStyles: pointStyles,
            lineStyles: lineStyles,
            polyStyles: polyStyles,
          };
        }
        if (pointStyles.length && properties['name'] === undefined) {
          const textStyle = pointStyles[0].getText();
          if (textStyle) {
            properties['name'] = textStyle.getText();
          }
        }
      }
    }
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = PLACEMARK_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      PLACEMARK_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );

    if (keys.length > 0) {
      const sequence = makeSequence(properties, keys);
      const namesAndValues = {names: keys, values: sequence};
      pushSerializeAndPop(
        context,
        PLACEMARK_SERIALIZERS,
        EXTENDEDDATA_NODE_FACTORY,
        [namesAndValues],
        objectStack,
      );
    }

    // serialize geometry
    const options = /** @type {import("./Feature.js").WriteOptions} */ (
      objectStack[0]
    );
    let geometry = feature.getGeometry();
    if (geometry) {
      geometry = transformGeometryWithOptions(geometry, true, options);
    }
    pushSerializeAndPop(
      context,
      PLACEMARK_SERIALIZERS,
      GEOMETRY_NODE_FACTORY,
      [geometry],
      objectStack,
    );
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const PRIMITIVE_GEOMETRY_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'extrude',
    'tessellate',
    'altitudeMode',
    'coordinates',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const PRIMITIVE_GEOMETRY_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'extrude': makeChildAppender(writeBooleanTextNode),
    'tessellate': makeChildAppender(writeBooleanTextNode),
    'altitudeMode': makeChildAppender(writeStringTextNode),
    'coordinates': makeChildAppender(writeCoordinatesTextNode),
  });

  /**
   * @param {Element} node Node.
   * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry.
   * @param {Array<*>} objectStack Object stack.
   */
  function writePrimitiveGeometry(node, geometry, objectStack) {
    const flatCoordinates = geometry.getFlatCoordinates();
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    context['layout'] = geometry.getLayout();
    context['stride'] = geometry.getStride();

    // serialize properties (properties unknown to KML are not serialized)
    const properties = geometry.getProperties();
    properties.coordinates = flatCoordinates;

    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = PRIMITIVE_GEOMETRY_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      PRIMITIVE_GEOMETRY_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const POLY_STYLE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'color',
    'fill',
    'outline',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const POLYGON_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'outerBoundaryIs': makeChildAppender(writeBoundaryIs),
    'innerBoundaryIs': makeChildAppender(writeBoundaryIs),
  });

  /**
   * A factory for creating innerBoundaryIs nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const INNER_BOUNDARY_NODE_FACTORY = makeSimpleNodeFactory('innerBoundaryIs');

  /**
   * A factory for creating outerBoundaryIs nodes.
   * @const
   * @type {function(*, Array<*>, string=): (Node|undefined)}
   */
  const OUTER_BOUNDARY_NODE_FACTORY = makeSimpleNodeFactory('outerBoundaryIs');

  /**
   * @param {Element} node Node.
   * @param {Polygon} polygon Polygon.
   * @param {Array<*>} objectStack Object stack.
   */
  function writePolygon(node, polygon, objectStack) {
    const linearRings = polygon.getLinearRings();
    const outerRing = linearRings.shift();
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    // inner rings
    pushSerializeAndPop(
      context,
      POLYGON_SERIALIZERS,
      INNER_BOUNDARY_NODE_FACTORY,
      linearRings,
      objectStack,
    );
    // outer ring
    pushSerializeAndPop(
      context,
      POLYGON_SERIALIZERS,
      OUTER_BOUNDARY_NODE_FACTORY,
      [outerRing],
      objectStack,
    );
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const POLY_STYLE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'color': makeChildAppender(writeColorTextNode),
    'fill': makeChildAppender(writeBooleanTextNode),
    'outline': makeChildAppender(writeBooleanTextNode),
  });

  /**
   * @param {Element} node Node.
   * @param {Style} style Style.
   * @param {Array<*>} objectStack Object stack.
   */
  function writePolyStyle(node, style, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const fill = style.getFill();
    const stroke = style.getStroke();
    const properties = {
      'color': fill ? fill.getColor() : undefined,
      'fill': fill ? undefined : false,
      'outline': stroke ? undefined : false,
    };
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = POLY_STYLE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      POLY_STYLE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @param {Node} node Node to append a TextNode with the scale to.
   * @param {number|undefined} scale Scale.
   */
  function writeScaleTextNode(node, scale) {
    // the Math is to remove any excess decimals created by float arithmetic
    writeDecimalTextNode(node, Math.round(scale * 1e6) / 1e6);
  }

  /**
   * @const
   * @type {Object<string, Array<string>>}
   */
  // @ts-ignore
  const STYLE_SEQUENCE = makeStructureNS(NAMESPACE_URIS$3, [
    'IconStyle',
    'LabelStyle',
    'LineStyle',
    'PolyStyle',
  ]);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  // @ts-ignore
  const STYLE_SERIALIZERS = makeStructureNS(NAMESPACE_URIS$3, {
    'IconStyle': makeChildAppender(writeIconStyle),
    'LabelStyle': makeChildAppender(writeLabelStyle),
    'LineStyle': makeChildAppender(writeLineStyle),
    'PolyStyle': makeChildAppender(writePolyStyle),
  });

  /**
   * @param {Element} node Node.
   * @param {Object<string, Array<Style>>} styles Styles.
   * @param {Array<*>} objectStack Object stack.
   */
  function writeStyle(node, styles, objectStack) {
    const /** @type {import("../xml.js").NodeStackItem} */ context = {node: node};
    const properties = {};
    if (styles.pointStyles.length) {
      const textStyle = styles.pointStyles[0].getText();
      if (textStyle) {
        properties['LabelStyle'] = textStyle;
      }
      const imageStyle = styles.pointStyles[0].getImage();
      if (
        imageStyle &&
        typeof (/** @type {?} */ (imageStyle).getSrc) === 'function'
      ) {
        properties['IconStyle'] = imageStyle;
      }
    }
    if (styles.lineStyles.length) {
      const strokeStyle = styles.lineStyles[0].getStroke();
      if (strokeStyle) {
        properties['LineStyle'] = strokeStyle;
      }
    }
    if (styles.polyStyles.length) {
      const strokeStyle = styles.polyStyles[0].getStroke();
      if (strokeStyle && !properties['LineStyle']) {
        properties['LineStyle'] = strokeStyle;
      }
      properties['PolyStyle'] = styles.polyStyles[0];
    }
    const parentNode = objectStack[objectStack.length - 1].node;
    const orderedKeys = STYLE_SEQUENCE[parentNode.namespaceURI];
    const values = makeSequence(properties, orderedKeys);
    pushSerializeAndPop(
      context,
      STYLE_SERIALIZERS,
      OBJECT_PROPERTY_NODE_FACTORY,
      values,
      objectStack,
      orderedKeys,
    );
  }

  /**
   * @param {Element} node Node to append a TextNode with the Vec2 to.
   * @param {Vec2} vec2 Vec2.
   */
  function writeVec2(node, vec2) {
    node.setAttribute('x', String(vec2.x));
    node.setAttribute('y', String(vec2.y));
    node.setAttribute('xunits', vec2.xunits);
    node.setAttribute('yunits', vec2.yunits);
  }

  /**
   * @module ol/format/XML
   */

  /**
   * @classdesc
   * Generic format for reading non-feature XML data
   *
   * @abstract
   */
  class XML {
    /**
     * Read the source document.
     *
     * @param {Document|Element|string} source The XML source.
     * @return {Object|null} An object representing the source.
     * @api
     */
    read(source) {
      if (!source) {
        return null;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readFromDocument(doc);
      }
      if (isDocument(source)) {
        return this.readFromDocument(/** @type {Document} */ (source));
      }
      return this.readFromNode(/** @type {Element} */ (source));
    }

    /**
     * @param {Document} doc Document.
     * @return {Object|null} Object
     */
    readFromDocument(doc) {
      for (let n = doc.firstChild; n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          return this.readFromNode(/** @type {Element} */ (n));
        }
      }
      return null;
    }

    /**
     * @abstract
     * @param {Element} node Node.
     * @return {Object|null} Object
     */
    readFromNode(node) {
      abstract();
    }
  }

  /**
   * @module ol/format/xlink
   */

  /**
   * @const
   * @type {string}
   */
  const NAMESPACE_URI = 'http://www.w3.org/1999/xlink';

  /**
   * @param {Element} node Node.
   * @return {string|null} href.
   */
  function readHref(node) {
    return node.getAttributeNS(NAMESPACE_URI, 'href');
  }

  /**
   * @module ol/format/OWS
   */

  /**
   * @const
   * @type {Array<null|string>}
   */
  const NAMESPACE_URIS$2 = [null, 'http://www.opengis.net/ows/1.1'];

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PARSERS$2 = makeStructureNS(NAMESPACE_URIS$2, {
    'ServiceIdentification': makeObjectPropertySetter(readServiceIdentification),
    'ServiceProvider': makeObjectPropertySetter(readServiceProvider),
    'OperationsMetadata': makeObjectPropertySetter(readOperationsMetadata),
  });

  class OWS extends XML {
    constructor() {
      super();
    }

    /**
     * @param {Element} node Node.
     * @return {Object|null} Object
     * @override
     */
    readFromNode(node) {
      const owsObject = pushParseAndPop({}, PARSERS$2, node, []);
      return owsObject ? owsObject : null;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const ADDRESS_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'DeliveryPoint': makeObjectPropertySetter(readString),
    'City': makeObjectPropertySetter(readString),
    'AdministrativeArea': makeObjectPropertySetter(readString),
    'PostalCode': makeObjectPropertySetter(readString),
    'Country': makeObjectPropertySetter(readString),
    'ElectronicMailAddress': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const ALLOWED_VALUES_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Value': makeObjectPropertyPusher(readValue),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONSTRAINT_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'AllowedValues': makeObjectPropertySetter(readAllowedValues),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONTACT_INFO_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Phone': makeObjectPropertySetter(readPhone),
    'Address': makeObjectPropertySetter(readAddress),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const DCP_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'HTTP': makeObjectPropertySetter(readHttp),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const HTTP_PARSERS$1 = makeStructureNS(NAMESPACE_URIS$2, {
    'Get': makeObjectPropertyPusher(readGet),
    'Post': undefined, // TODO
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const OPERATION_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'DCP': makeObjectPropertySetter(readDcp),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const OPERATIONS_METADATA_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Operation': readOperation,
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PHONE_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Voice': makeObjectPropertySetter(readString),
    'Facsimile': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const REQUEST_METHOD_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Constraint': makeObjectPropertyPusher(readConstraint),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SERVICE_CONTACT_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'IndividualName': makeObjectPropertySetter(readString),
    'PositionName': makeObjectPropertySetter(readString),
    'ContactInfo': makeObjectPropertySetter(readContactInfo),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SERVICE_IDENTIFICATION_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'Abstract': makeObjectPropertySetter(readString),
    'AccessConstraints': makeObjectPropertySetter(readString),
    'Fees': makeObjectPropertySetter(readString),
    'Title': makeObjectPropertySetter(readString),
    'ServiceTypeVersion': makeObjectPropertySetter(readString),
    'ServiceType': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SERVICE_PROVIDER_PARSERS = makeStructureNS(NAMESPACE_URIS$2, {
    'ProviderName': makeObjectPropertySetter(readString),
    'ProviderSite': makeObjectPropertySetter(readHref),
    'ServiceContact': makeObjectPropertySetter(readServiceContact),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The address.
   */
  function readAddress(node, objectStack) {
    return pushParseAndPop({}, ADDRESS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The values.
   */
  function readAllowedValues(node, objectStack) {
    return pushParseAndPop({}, ALLOWED_VALUES_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The constraint.
   */
  function readConstraint(node, objectStack) {
    const name = node.getAttribute('name');
    if (!name) {
      return undefined;
    }
    return pushParseAndPop({'name': name}, CONSTRAINT_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The contact info.
   */
  function readContactInfo(node, objectStack) {
    return pushParseAndPop({}, CONTACT_INFO_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The DCP.
   */
  function readDcp(node, objectStack) {
    return pushParseAndPop({}, DCP_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The GET object.
   */
  function readGet(node, objectStack) {
    const href = readHref(node);
    if (!href) {
      return undefined;
    }
    return pushParseAndPop(
      {'href': href},
      REQUEST_METHOD_PARSERS,
      node,
      objectStack,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The HTTP object.
   */
  function readHttp(node, objectStack) {
    return pushParseAndPop({}, HTTP_PARSERS$1, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The operation.
   */
  function readOperation(node, objectStack) {
    const name = node.getAttribute('name');
    const value = pushParseAndPop({}, OPERATION_PARSERS, node, objectStack);
    if (!value) {
      return undefined;
    }
    const object = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    object[name] = value;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The operations metadata.
   */
  function readOperationsMetadata(node, objectStack) {
    return pushParseAndPop({}, OPERATIONS_METADATA_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The phone.
   */
  function readPhone(node, objectStack) {
    return pushParseAndPop({}, PHONE_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The service identification.
   */
  function readServiceIdentification(node, objectStack) {
    return pushParseAndPop({}, SERVICE_IDENTIFICATION_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The service contact.
   */
  function readServiceContact(node, objectStack) {
    return pushParseAndPop({}, SERVICE_CONTACT_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} The service provider.
   */
  function readServiceProvider(node, objectStack) {
    return pushParseAndPop({}, SERVICE_PROVIDER_PARSERS, node, objectStack);
  }

  /**
   * @param {Node} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {string|undefined} The value.
   */
  function readValue(node, objectStack) {
    return readString(node);
  }

  /**
   * @module ol/geom/flat/flip
   */

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @param {Array<number>} [dest] Destination.
   * @param {number} [destOffset] Destination offset.
   * @return {Array<number>} Flat coordinates.
   */
  function flipXY(flatCoordinates, offset, end, stride, dest, destOffset) {
    if (dest !== undefined) {
      dest = dest;
      destOffset = destOffset !== undefined ? destOffset : 0;
    } else {
      dest = [];
      destOffset = 0;
    }
    let j = offset;
    while (j < end) {
      const x = flatCoordinates[j++];
      dest[destOffset++] = flatCoordinates[j++];
      dest[destOffset++] = x;
      for (let k = 2; k < stride; ++k) {
        dest[destOffset++] = flatCoordinates[j++];
      }
    }
    dest.length = destOffset;
    return dest;
  }

  /**
   * @module ol/format/Polyline
   */

  /**
   * @typedef {Object} Options
   * @property {number} [factor=1e5] The factor by which the coordinates values will be scaled.
   * @property {import("../geom/Geometry.js").GeometryLayout} [geometryLayout='XY'] Layout of the
   * feature geometries created by the format reader.
   */

  /**
   * @classdesc
   * Feature format for reading and writing data in the Encoded
   * Polyline Algorithm Format.
   *
   * When reading features, the coordinates are assumed to be in two dimensions
   * and in [latitude, longitude] order.
   *
   * As Polyline sources contain a single feature,
   * {@link module:ol/format/Polyline~Polyline#readFeatures} will return the
   * feature in an array.
   *
   * @api
   */
  class Polyline extends TextFeature {
    /**
     * @param {Options} [options] Optional configuration object.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2('EPSG:4326');

      /**
       * @private
       * @type {number}
       */
      this.factor_ = options.factor ? options.factor : 1e5;

      /**
       * @private
       * @type {import("../geom/Geometry.js").GeometryLayout}
       */
      this.geometryLayout_ = options.geometryLayout
        ? options.geometryLayout
        : 'XY';
    }

    /**
     * @protected
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromText(text, options) {
      const geometry = this.readGeometryFromText(text, options);
      return new Feature(geometry);
    }

    /**
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<Feature>} Features.
     * @override
     */
    readFeaturesFromText(text, options) {
      const feature = this.readFeatureFromText(text, options);
      return [feature];
    }

    /**
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometryFromText(text, options) {
      const stride = getStrideForLayout(this.geometryLayout_);
      const flatCoordinates = decodeDeltas(text, stride, this.factor_);
      flipXY(flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates);
      const coordinates = inflateCoordinates(
        flatCoordinates,
        0,
        flatCoordinates.length,
        stride,
      );
      const lineString = new LineString(coordinates, this.geometryLayout_);

      return transformGeometryWithOptions(
        lineString,
        false,
        this.adaptOptions(options),
      );
    }

    /**
     * @param {import("../Feature.js").default<LineString>} feature Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeFeatureText(feature, options) {
      const geometry = feature.getGeometry();
      if (geometry) {
        return this.writeGeometryText(geometry, options);
      }
      throw new Error('Expected `feature` to have a geometry');
    }

    /**
     * @param {Array<import("../Feature.js").default<LineString>>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeFeaturesText(features, options) {
      return this.writeFeatureText(features[0], options);
    }

    /**
     * @param {LineString} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeGeometryText(geometry, options) {
      geometry =
        /** @type {LineString} */
        (
          transformGeometryWithOptions(geometry, true, this.adaptOptions(options))
        );
      const flatCoordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      flipXY(flatCoordinates, 0, flatCoordinates.length, stride, flatCoordinates);
      return encodeDeltas(flatCoordinates, stride, this.factor_);
    }
  }

  /**
   * Encode a list of n-dimensional points and return an encoded string
   *
   * Attention: This function will modify the passed array!
   *
   * @param {Array<number>} numbers A list of n-dimensional points.
   * @param {number} stride The number of dimension of the points in the list.
   * @param {number} [factor] The factor by which the numbers will be
   *     multiplied. The remaining decimal places will get rounded away.
   *     Default is `1e5`.
   * @return {string} The encoded string.
   * @api
   */
  function encodeDeltas(numbers, stride, factor) {
    factor = factor ? factor : 1e5;
    let d;

    const lastNumbers = new Array(stride);
    for (d = 0; d < stride; ++d) {
      lastNumbers[d] = 0;
    }

    for (let i = 0, ii = numbers.length; i < ii; ) {
      for (d = 0; d < stride; ++d, ++i) {
        const num = numbers[i];
        const delta = num - lastNumbers[d];
        lastNumbers[d] = num;

        numbers[i] = delta;
      }
    }

    return encodeFloats(numbers, factor);
  }

  /**
   * Decode a list of n-dimensional points from an encoded string
   *
   * @param {string} encoded An encoded string.
   * @param {number} stride The number of dimension of the points in the
   *     encoded string.
   * @param {number} [factor] The factor by which the resulting numbers will
   *     be divided. Default is `1e5`.
   * @return {Array<number>} A list of n-dimensional points.
   * @api
   */
  function decodeDeltas(encoded, stride, factor) {
    factor = factor ? factor : 1e5;
    let d;

    /** @type {Array<number>} */
    const lastNumbers = new Array(stride);
    for (d = 0; d < stride; ++d) {
      lastNumbers[d] = 0;
    }

    const numbers = decodeFloats(encoded, factor);

    for (let i = 0, ii = numbers.length; i < ii; ) {
      for (d = 0; d < stride; ++d, ++i) {
        lastNumbers[d] += numbers[i];

        numbers[i] = lastNumbers[d];
      }
    }

    return numbers;
  }

  /**
   * Encode a list of floating point numbers and return an encoded string
   *
   * Attention: This function will modify the passed array!
   *
   * @param {Array<number>} numbers A list of floating point numbers.
   * @param {number} [factor] The factor by which the numbers will be
   *     multiplied. The remaining decimal places will get rounded away.
   *     Default is `1e5`.
   * @return {string} The encoded string.
   * @api
   */
  function encodeFloats(numbers, factor) {
    factor = factor ? factor : 1e5;
    for (let i = 0, ii = numbers.length; i < ii; ++i) {
      numbers[i] = Math.round(numbers[i] * factor);
    }

    return encodeSignedIntegers(numbers);
  }

  /**
   * Decode a list of floating point numbers from an encoded string
   *
   * @param {string} encoded An encoded string.
   * @param {number} [factor] The factor by which the result will be divided.
   *     Default is `1e5`.
   * @return {Array<number>} A list of floating point numbers.
   * @api
   */
  function decodeFloats(encoded, factor) {
    factor = factor ? factor : 1e5;
    const numbers = decodeSignedIntegers(encoded);
    for (let i = 0, ii = numbers.length; i < ii; ++i) {
      numbers[i] /= factor;
    }
    return numbers;
  }

  /**
   * Encode a list of signed integers and return an encoded string
   *
   * Attention: This function will modify the passed array!
   *
   * @param {Array<number>} numbers A list of signed integers.
   * @return {string} The encoded string.
   */
  function encodeSignedIntegers(numbers) {
    for (let i = 0, ii = numbers.length; i < ii; ++i) {
      const num = numbers[i];
      numbers[i] = num < 0 ? ~(num << 1) : num << 1;
    }
    return encodeUnsignedIntegers(numbers);
  }

  /**
   * Decode a list of signed integers from an encoded string
   *
   * @param {string} encoded An encoded string.
   * @return {Array<number>} A list of signed integers.
   */
  function decodeSignedIntegers(encoded) {
    const numbers = decodeUnsignedIntegers(encoded);
    for (let i = 0, ii = numbers.length; i < ii; ++i) {
      const num = numbers[i];
      numbers[i] = num & 1 ? ~(num >> 1) : num >> 1;
    }
    return numbers;
  }

  /**
   * Encode a list of unsigned integers and return an encoded string
   *
   * @param {Array<number>} numbers A list of unsigned integers.
   * @return {string} The encoded string.
   */
  function encodeUnsignedIntegers(numbers) {
    let encoded = '';
    for (let i = 0, ii = numbers.length; i < ii; ++i) {
      encoded += encodeUnsignedInteger(numbers[i]);
    }
    return encoded;
  }

  /**
   * Decode a list of unsigned integers from an encoded string
   *
   * @param {string} encoded An encoded string.
   * @return {Array<number>} A list of unsigned integers.
   */
  function decodeUnsignedIntegers(encoded) {
    const numbers = [];
    let current = 0;
    let shift = 0;
    for (let i = 0, ii = encoded.length; i < ii; ++i) {
      const b = encoded.charCodeAt(i) - 63;
      current |= (b & 0x1f) << shift;
      if (b < 0x20) {
        numbers.push(current);
        current = 0;
        shift = 0;
      } else {
        shift += 5;
      }
    }
    return numbers;
  }

  /**
   * Encode one single unsigned integer and return an encoded string
   *
   * @param {number} num Unsigned integer that should be encoded.
   * @return {string} The encoded string.
   */
  function encodeUnsignedInteger(num) {
    let value,
      encoded = '';
    while (num >= 0x20) {
      value = (0x20 | (num & 0x1f)) + 63;
      encoded += String.fromCharCode(value);
      num >>= 5;
    }
    value = num + 63;
    encoded += String.fromCharCode(value);
    return encoded;
  }

  /**
   * @module ol/format/TopoJSON
   */

  /**
   * @typedef {import("topojson-specification").Topology} TopoJSONTopology
   * @typedef {import("topojson-specification").GeometryCollection} TopoJSONGeometryCollection
   * @typedef {import("topojson-specification").GeometryObject} TopoJSONGeometry
   * @typedef {import("topojson-specification").Point} TopoJSONPoint
   * @typedef {import("topojson-specification").MultiPoint} TopoJSONMultiPoint
   * @typedef {import("topojson-specification").LineString} TopoJSONLineString
   * @typedef {import("topojson-specification").MultiLineString} TopoJSONMultiLineString
   * @typedef {import("topojson-specification").Polygon} TopoJSONPolygon
   * @typedef {import("topojson-specification").MultiPolygon} TopoJSONMultiPolygon
   */

  /**
   * @typedef {Object} Options
   * @property {import("../proj.js").ProjectionLike} [dataProjection='EPSG:4326'] Default data projection.
   * @property {string} [layerName] Set the name of the TopoJSON topology
   * `objects`'s children as feature property with the specified name. This means
   * that when set to `'layer'`, a topology like
   * ```
   * {
   *   "type": "Topology",
   *   "objects": {
   *     "example": {
   *       "type": "GeometryCollection",
   *       "geometries": []
   *     }
   *   }
   * }
   * ```
   * will result in features that have a property `'layer'` set to `'example'`.
   * When not set, no property will be added to features.
   * @property {Array<string>} [layers] Names of the TopoJSON topology's
   * `objects`'s children to read features from.  If not provided, features will
   * be read from all children.
   */

  /**
   * @classdesc
   * Feature format for reading data in the TopoJSON format.
   *
   * @api
   */
  class TopoJSON extends JSONFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @private
       * @type {string|undefined}
       */
      this.layerName_ = options.layerName;

      /**
       * @private
       * @type {?Array<string>}
       */
      this.layers_ = options.layers ? options.layers : null;

      /**
       * @type {import("../proj/Projection.js").default}
       */
      this.dataProjection = get$2(
        options.dataProjection ? options.dataProjection : 'EPSG:4326',
      );
    }

    /**
     * @param {Object} object Object.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<Feature>} Features.
     * @override
     */
    readFeaturesFromObject(object, options) {
      if (object.type == 'Topology') {
        const topoJSONTopology = /** @type {TopoJSONTopology} */ (object);
        let transform,
          scale = null,
          translate = null;
        if (topoJSONTopology['transform']) {
          transform = topoJSONTopology['transform'];
          scale = transform['scale'];
          translate = transform['translate'];
        }
        const arcs = topoJSONTopology['arcs'];
        if (transform) {
          transformArcs(arcs, scale, translate);
        }
        /** @type {Array<Feature>} */
        const features = [];
        const topoJSONFeatures = topoJSONTopology['objects'];
        const property = this.layerName_;
        let feature;
        for (const objectName in topoJSONFeatures) {
          if (this.layers_ && !this.layers_.includes(objectName)) {
            continue;
          }
          if (topoJSONFeatures[objectName].type === 'GeometryCollection') {
            feature = /** @type {TopoJSONGeometryCollection} */ (
              topoJSONFeatures[objectName]
            );
            features.push.apply(
              features,
              readFeaturesFromGeometryCollection(
                feature,
                arcs,
                scale,
                translate,
                property,
                objectName,
                options,
              ),
            );
          } else {
            feature = /** @type {TopoJSONGeometry} */ (
              topoJSONFeatures[objectName]
            );
            features.push(
              readFeatureFromGeometry(
                feature,
                arcs,
                scale,
                translate,
                property,
                objectName,
                options,
              ),
            );
          }
        }
        return features;
      }
      return [];
    }

    /**
     * @param {Object} object Object.
     * @protected
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromObject(object) {
      return this.dataProjection;
    }
  }

  /**
   * @const
   * @type {Object<string, function(TopoJSONGeometry, Array, ...Array=): import("../geom/Geometry.js").default>}
   */
  const GEOMETRY_READERS = {
    'Point': readPointGeometry,
    'LineString': readLineStringGeometry,
    'Polygon': readPolygonGeometry,
    'MultiPoint': readMultiPointGeometry,
    'MultiLineString': readMultiLineStringGeometry,
    'MultiPolygon': readMultiPolygonGeometry,
  };

  /**
   * Concatenate arcs into a coordinate array.
   * @param {Array<number>} indices Indices of arcs to concatenate.  Negative
   *     values indicate arcs need to be reversed.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs (already
   *     transformed).
   * @return {Array<import("../coordinate.js").Coordinate>} Coordinates array.
   */
  function concatenateArcs(indices, arcs) {
    /** @type {Array<import("../coordinate.js").Coordinate>} */
    const coordinates = [];
    let index;
    for (let i = 0, ii = indices.length; i < ii; ++i) {
      index = indices[i];
      if (i > 0) {
        // splicing together arcs, discard last point
        coordinates.pop();
      }
      if (index >= 0) {
        // forward arc
        const arc = arcs[index];
        for (let j = 0, jj = arc.length; j < jj; ++j) {
          coordinates.push(arc[j].slice(0));
        }
      } else {
        // reverse arc
        const arc = arcs[~index];
        for (let j = arc.length - 1; j >= 0; --j) {
          coordinates.push(arc[j].slice(0));
        }
      }
    }
    return coordinates;
  }

  /**
   * Create a point from a TopoJSON geometry object.
   *
   * @param {TopoJSONPoint} object TopoJSON object.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   * @return {Point} Geometry.
   */
  function readPointGeometry(object, scale, translate) {
    const coordinates = object['coordinates'];
    if (scale && translate) {
      transformVertex(coordinates, scale, translate);
    }
    return new Point(coordinates);
  }

  /**
   * Create a multi-point from a TopoJSON geometry object.
   *
   * @param {TopoJSONMultiPoint} object TopoJSON object.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   * @return {MultiPoint} Geometry.
   */
  function readMultiPointGeometry(object, scale, translate) {
    const coordinates = object['coordinates'];
    if (scale && translate) {
      for (let i = 0, ii = coordinates.length; i < ii; ++i) {
        transformVertex(coordinates[i], scale, translate);
      }
    }
    return new MultiPoint(coordinates);
  }

  /**
   * Create a linestring from a TopoJSON geometry object.
   *
   * @param {TopoJSONLineString} object TopoJSON object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @return {LineString} Geometry.
   */
  function readLineStringGeometry(object, arcs) {
    const coordinates = concatenateArcs(object['arcs'], arcs);
    return new LineString(coordinates);
  }

  /**
   * Create a multi-linestring from a TopoJSON geometry object.
   *
   * @param {TopoJSONMultiLineString} object TopoJSON object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @return {MultiLineString} Geometry.
   */
  function readMultiLineStringGeometry(object, arcs) {
    const coordinates = [];
    for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
      coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
    }
    return new MultiLineString(coordinates);
  }

  /**
   * Create a polygon from a TopoJSON geometry object.
   *
   * @param {TopoJSONPolygon} object TopoJSON object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @return {Polygon} Geometry.
   */
  function readPolygonGeometry(object, arcs) {
    const coordinates = [];
    for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
      coordinates[i] = concatenateArcs(object['arcs'][i], arcs);
    }
    return new Polygon(coordinates);
  }

  /**
   * Create a multi-polygon from a TopoJSON geometry object.
   *
   * @param {TopoJSONMultiPolygon} object TopoJSON object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @return {MultiPolygon} Geometry.
   */
  function readMultiPolygonGeometry(object, arcs) {
    const coordinates = [];
    for (let i = 0, ii = object['arcs'].length; i < ii; ++i) {
      // for each polygon
      const polyArray = object['arcs'][i];
      const ringCoords = [];
      for (let j = 0, jj = polyArray.length; j < jj; ++j) {
        // for each ring
        ringCoords[j] = concatenateArcs(polyArray[j], arcs);
      }
      coordinates[i] = ringCoords;
    }
    return new MultiPolygon(coordinates);
  }

  /**
   * Create features from a TopoJSON GeometryCollection object.
   *
   * @param {TopoJSONGeometryCollection} collection TopoJSON Geometry
   *     object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   * @param {string|undefined} property Property to set the `GeometryCollection`'s parent
   *     object to.
   * @param {string} name Name of the `Topology`'s child object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {Array<Feature>} Array of features.
   */
  function readFeaturesFromGeometryCollection(
    collection,
    arcs,
    scale,
    translate,
    property,
    name,
    options,
  ) {
    const geometries = collection['geometries'];
    const features = [];
    for (let i = 0, ii = geometries.length; i < ii; ++i) {
      features[i] = readFeatureFromGeometry(
        geometries[i],
        arcs,
        scale,
        translate,
        property,
        name,
        options,
      );
    }
    return features;
  }

  /**
   * Create a feature from a TopoJSON geometry object.
   *
   * @param {TopoJSONGeometry} object TopoJSON geometry object.
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   * @param {string|undefined} property Property to set the `GeometryCollection`'s parent
   *     object to.
   * @param {string} name Name of the `Topology`'s child object.
   * @param {import("./Feature.js").ReadOptions} [options] Read options.
   * @return {Feature} Feature.
   */
  function readFeatureFromGeometry(
    object,
    arcs,
    scale,
    translate,
    property,
    name,
    options,
  ) {
    let geometry = null;
    const type = object.type;
    if (type) {
      const geometryReader = GEOMETRY_READERS[type];
      if (type === 'Point' || type === 'MultiPoint') {
        geometry = geometryReader(object, scale, translate);
      } else {
        geometry = geometryReader(object, arcs);
      }
      geometry = transformGeometryWithOptions(geometry, false, options);
    }
    const feature = new Feature({geometry: geometry});
    if (object.id !== undefined) {
      feature.setId(object.id);
    }
    let properties = object.properties;
    if (property) {
      if (!properties) {
        properties = {};
      }
      properties[property] = name;
    }
    if (properties) {
      feature.setProperties(properties, true);
    }
    return feature;
  }

  /**
   * Apply a linear transform to array of arcs.  The provided array of arcs is
   * modified in place.
   *
   * @param {Array<Array<import("../coordinate.js").Coordinate>>} arcs Array of arcs.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   */
  function transformArcs(arcs, scale, translate) {
    for (let i = 0, ii = arcs.length; i < ii; ++i) {
      transformArc(arcs[i], scale, translate);
    }
  }

  /**
   * Apply a linear transform to an arc.  The provided arc is modified in place.
   *
   * @param {Array<import("../coordinate.js").Coordinate>} arc Arc.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   */
  function transformArc(arc, scale, translate) {
    let x = 0;
    let y = 0;
    for (let i = 0, ii = arc.length; i < ii; ++i) {
      const vertex = arc[i];
      x += vertex[0];
      y += vertex[1];
      vertex[0] = x;
      vertex[1] = y;
      transformVertex(vertex, scale, translate);
    }
  }

  /**
   * Apply a linear transform to a vertex.  The provided vertex is modified in
   * place.
   *
   * @param {import("../coordinate.js").Coordinate} vertex Vertex.
   * @param {Array<number>} scale Scale for each dimension.
   * @param {Array<number>} translate Translation for each dimension.
   */
  function transformVertex(vertex, scale, translate) {
    vertex[0] = vertex[0] * scale[0] + translate[0];
    vertex[1] = vertex[1] * scale[1] + translate[1];
  }

  /**
   * @module ol/format/GML32
   */

  /**
   * @classdesc Feature format for reading and writing data in the GML format
   *            version 3.2.1.
   * @api
   */
  class GML32 extends GML3 {
    /**
     * @param {import("./GMLBase.js").Options} [options] Optional configuration object.
     */
    constructor(options) {
      options = options ? options : {};

      super(options);

      /**
       * @type {string}
       */
      this.schemaLocation = options.schemaLocation
        ? options.schemaLocation
        : this.namespace + ' http://schemas.opengis.net/gml/3.2.1/gml.xsd';
    }

    /**
     * @param {Node} node Node.
     * @param {import("../geom/Geometry.js").default|import("../extent.js").Extent} geometry Geometry.
     * @param {Array<*>} objectStack Node stack.
     * @override
     */
    writeGeometryElement(node, geometry, objectStack) {
      const context = objectStack[objectStack.length - 1];
      objectStack[objectStack.length - 1] = Object.assign(
        {multiCurve: true, multiSurface: true},
        context,
      );
      super.writeGeometryElement(node, geometry, objectStack);
    }
  }

  GML32.prototype.namespace = 'http://www.opengis.net/gml/3.2';

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.GEOMETRY_FLAT_COORDINATES_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'pos': makeReplacer(GML3.prototype.readFlatPos),
      'posList': makeReplacer(GML3.prototype.readFlatPosList),
      'coordinates': makeReplacer(GML2.prototype.readFlatCoordinates),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.FLAT_LINEAR_RINGS_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'interior': GML3.prototype.interiorParser,
      'exterior': GML3.prototype.exteriorParser,
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.GEOMETRY_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'Point': makeReplacer(GMLBase.prototype.readPoint),
      'MultiPoint': makeReplacer(GMLBase.prototype.readMultiPoint),
      'LineString': makeReplacer(GMLBase.prototype.readLineString),
      'MultiLineString': makeReplacer(GMLBase.prototype.readMultiLineString),
      'LinearRing': makeReplacer(GMLBase.prototype.readLinearRing),
      'Polygon': makeReplacer(GMLBase.prototype.readPolygon),
      'MultiPolygon': makeReplacer(GMLBase.prototype.readMultiPolygon),
      'Surface': makeReplacer(GML32.prototype.readSurface),
      'MultiSurface': makeReplacer(GML3.prototype.readMultiSurface),
      'Curve': makeReplacer(GML32.prototype.readCurve),
      'MultiCurve': makeReplacer(GML3.prototype.readMultiCurve),
      'Envelope': makeReplacer(GML32.prototype.readEnvelope),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.MULTICURVE_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'curveMember': makeArrayPusher(GML3.prototype.curveMemberParser),
      'curveMembers': makeArrayPusher(GML3.prototype.curveMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.MULTISURFACE_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'surfaceMember': makeArrayPusher(GML3.prototype.surfaceMemberParser),
      'surfaceMembers': makeArrayPusher(GML3.prototype.surfaceMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.CURVEMEMBER_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'LineString': makeArrayPusher(GMLBase.prototype.readLineString),
      'Curve': makeArrayPusher(GML3.prototype.readCurve),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.SURFACEMEMBER_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'Polygon': makeArrayPusher(GMLBase.prototype.readPolygon),
      'Surface': makeArrayPusher(GML3.prototype.readSurface),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.SURFACE_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'patches': makeReplacer(GML3.prototype.readPatch),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.CURVE_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'segments': makeReplacer(GML3.prototype.readSegment),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.ENVELOPE_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'lowerCorner': makeArrayPusher(GML3.prototype.readFlatPosList),
      'upperCorner': makeArrayPusher(GML3.prototype.readFlatPosList),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.PATCHES_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'PolygonPatch': makeReplacer(GML3.prototype.readPolygonPatch),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.SEGMENTS_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'LineStringSegment': makeArrayExtender(
        GML3.prototype.readLineStringSegment,
      ),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.MULTIPOINT_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'pointMember': makeArrayPusher(GMLBase.prototype.pointMemberParser),
      'pointMembers': makeArrayPusher(GMLBase.prototype.pointMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.MULTILINESTRING_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'lineStringMember': makeArrayPusher(
        GMLBase.prototype.lineStringMemberParser,
      ),
      'lineStringMembers': makeArrayPusher(
        GMLBase.prototype.lineStringMemberParser,
      ),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.MULTIPOLYGON_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'polygonMember': makeArrayPusher(GMLBase.prototype.polygonMemberParser),
      'polygonMembers': makeArrayPusher(GMLBase.prototype.polygonMemberParser),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.POINTMEMBER_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'Point': makeArrayPusher(GMLBase.prototype.readFlatCoordinatesFromNode),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.LINESTRINGMEMBER_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'LineString': makeArrayPusher(GMLBase.prototype.readLineString),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.POLYGONMEMBER_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'Polygon': makeArrayPusher(GMLBase.prototype.readPolygon),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  GML32.prototype.RING_PARSERS = {
    'http://www.opengis.net/gml/3.2': {
      'LinearRing': makeReplacer(GMLBase.prototype.readFlatLinearRing),
      'Ring': makeReplacer(GML32.prototype.readFlatCurveRing),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.RING_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'exterior': makeChildAppender(GML3.prototype.writeRing),
      'interior': makeChildAppender(GML3.prototype.writeRing),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.ENVELOPE_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'lowerCorner': makeChildAppender(writeStringTextNode),
      'upperCorner': makeChildAppender(writeStringTextNode),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.SURFACEORPOLYGONMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'surfaceMember': makeChildAppender(
        GML3.prototype.writeSurfaceOrPolygonMember,
      ),
      'polygonMember': makeChildAppender(
        GML3.prototype.writeSurfaceOrPolygonMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.POINTMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'pointMember': makeChildAppender(GML3.prototype.writePointMember),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.LINESTRINGORCURVEMEMBER_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'lineStringMember': makeChildAppender(
        GML3.prototype.writeLineStringOrCurveMember,
      ),
      'curveMember': makeChildAppender(
        GML3.prototype.writeLineStringOrCurveMember,
      ),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  GML32.prototype.GEOMETRY_SERIALIZERS = {
    'http://www.opengis.net/gml/3.2': {
      'Curve': makeChildAppender(GML3.prototype.writeCurveOrLineString),
      'MultiCurve': makeChildAppender(GML3.prototype.writeMultiCurveOrLineString),
      'Point': makeChildAppender(GML32.prototype.writePoint),
      'MultiPoint': makeChildAppender(GML3.prototype.writeMultiPoint),
      'LineString': makeChildAppender(GML3.prototype.writeCurveOrLineString),
      'MultiLineString': makeChildAppender(
        GML3.prototype.writeMultiCurveOrLineString,
      ),
      'LinearRing': makeChildAppender(GML3.prototype.writeLinearRing),
      'Polygon': makeChildAppender(GML3.prototype.writeSurfaceOrPolygon),
      'MultiPolygon': makeChildAppender(
        GML3.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Surface': makeChildAppender(GML3.prototype.writeSurfaceOrPolygon),
      'MultiSurface': makeChildAppender(
        GML3.prototype.writeMultiSurfaceOrPolygon,
      ),
      'Envelope': makeChildAppender(GML3.prototype.writeEnvelope),
    },
  };

  /**
   * @module ol/format/filter/Filter
   */

  /**
   * @classdesc
   * Abstract class; normally only used for creating subclasses and not instantiated in apps.
   * Base class for WFS GetFeature filters.
   *
   * @abstract
   */
  class Filter {
    /**
     * @param {!string} tagName The XML tag name for this filter.
     */
    constructor(tagName) {
      /**
       * @private
       * @type {!string}
       */
      this.tagName_ = tagName;
    }

    /**
     * The XML tag name for a filter.
     * @return {!string} Name.
     */
    getTagName() {
      return this.tagName_;
    }
  }

  /**
   * @module ol/format/filter/LogicalNary
   */

  /**
   * @classdesc
   * Abstract class; normally only used for creating subclasses and not instantiated in apps.
   * Base class for WFS GetFeature n-ary logical filters.
   *
   * @abstract
   */
  class LogicalNary extends Filter {
    /**
     * @param {!string} tagName The XML tag name for this filter.
     * @param {Array<import("./Filter.js").default>} conditions Conditions.
     */
    constructor(tagName, conditions) {
      super(tagName);

      /**
       * @type {Array<import("./Filter.js").default>}
       */
      this.conditions = conditions;
      assert(this.conditions.length >= 2, 'At least 2 conditions are required');
    }
  }

  /**
   * @module ol/format/filter/And
   */

  /**
   * @classdesc
   * Represents a logical `<And>` operator between two or more filter conditions.
   *
   * @abstract
   */
  class And extends LogicalNary {
    /**
     * @param {...import("./Filter.js").default} conditions Conditions.
     */
    constructor(conditions) {
      super('And', Array.prototype.slice.call(arguments));
    }
  }

  /**
   * @module ol/format/filter/Bbox
   */

  /**
   * @classdesc
   * Represents a `<BBOX>` operator to test whether a geometry-valued property
   * intersects a fixed bounding box
   *
   * @api
   */
  class Bbox extends Filter {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../extent.js").Extent} extent Extent.
     * @param {string} [srsName] SRS name. No srsName attribute will be set
     * on geometries when this is not provided.
     */
    constructor(geometryName, extent, srsName) {
      super('BBOX');

      /**
       * @type {!string}
       */
      this.geometryName = geometryName;

      /**
       * @type {import("../../extent.js").Extent}
       */
      this.extent = extent;
      if (extent.length !== 4) {
        throw new Error(
          'Expected an extent with four values ([minX, minY, maxX, maxY])',
        );
      }

      /**
       * @type {string|undefined}
       */
      this.srsName = srsName;
    }
  }

  /**
   * @module ol/format/filter/Spatial
   */

  /**
   * @classdesc
   * Abstract class; normally only used for creating subclasses and not instantiated in apps.
   * Represents a spatial operator to test whether a geometry-valued property
   * relates to a given geometry.
   *
   * @abstract
   */
  class Spatial extends Filter {
    /**
     * @param {!string} tagName The XML tag name for this filter.
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(tagName, geometryName, geometry, srsName) {
      super(tagName);

      /**
       * @type {!string}
       */
      this.geometryName = geometryName || 'the_geom';

      /**
       * @type {import("../../geom/Geometry.js").default}
       */
      this.geometry = geometry;

      /**
       * @type {string|undefined}
       */
      this.srsName = srsName;
    }
  }

  /**
   * @module ol/format/filter/Contains
   */

  /**
   * @classdesc
   * Represents a `<Contains>` operator to test whether a geometry-valued property
   * contains a given geometry.
   * @api
   */
  class Contains extends Spatial {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(geometryName, geometry, srsName) {
      super('Contains', geometryName, geometry, srsName);
    }
  }

  /**
   * @module ol/format/filter/DWithin
   */

  /**
   * @classdesc
   * Represents a `<DWithin>` operator to test whether a geometry-valued property
   * is within a distance to a given geometry.
   * @api
   */
  class DWithin extends Spatial {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {!number} distance Distance.
     * @param {!string} unit Unit.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(geometryName, geometry, distance, unit, srsName) {
      super('DWithin', geometryName, geometry, srsName);

      /**
       * @public
       * @type {!number}
       */
      this.distance = distance;

      /**
       * @public
       * @type {!string}
       */
      this.unit = unit;
    }
  }

  /**
   * @module ol/format/filter/Disjoint
   */

  /**
   * @classdesc
   * Represents a `<Disjoint>` operator to test whether a geometry-valued property
   * is disjoint to a given geometry.
   * @api
   */
  class Disjoint extends Spatial {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(geometryName, geometry, srsName) {
      super('Disjoint', geometryName, geometry, srsName);
    }
  }

  /**
   * @module ol/format/filter/Comparison
   */

  /**
   * @classdesc
   * Abstract class; normally only used for creating subclasses and not instantiated in apps.
   * Base class for WFS GetFeature property comparison filters.
   *
   * @abstract
   */
  class Comparison extends Filter {
    /**
     * @param {!string} tagName The XML tag name for this filter.
     * @param {!string} propertyName Name of the context property to compare.
     */
    constructor(tagName, propertyName) {
      super(tagName);

      /**
       * @type {!string}
       */
      this.propertyName = propertyName;
    }
  }

  /**
   * @module ol/format/filter/During
   */

  /**
   * @classdesc
   * Represents a `<During>` comparison operator.
   * @api
   */
  class During extends Comparison {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!string} begin The begin date in ISO-8601 format.
     * @param {!string} end The end date in ISO-8601 format.
     */
    constructor(propertyName, begin, end) {
      super('During', propertyName);

      /**
       * @type {!string}
       */
      this.begin = begin;

      /**
       * @type {!string}
       */
      this.end = end;
    }
  }

  /**
   * @module ol/format/filter/ComparisonBinary
   */

  /**
   * @classdesc
   * Abstract class; normally only used for creating subclasses and not instantiated in apps.
   * Base class for WFS GetFeature property binary comparison filters.
   *
   * @abstract
   */
  class ComparisonBinary extends Comparison {
    /**
     * @param {!string} tagName The XML tag name for this filter.
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!(string|number)} expression The value to compare.
     * @param {boolean} [matchCase] Case-sensitive?
     */
    constructor(tagName, propertyName, expression, matchCase) {
      super(tagName, propertyName);

      /**
       * @type {!(string|number)}
       */
      this.expression = expression;

      /**
       * @type {boolean|undefined}
       */
      this.matchCase = matchCase;
    }
  }

  /**
   * @module ol/format/filter/EqualTo
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsEqualTo>` comparison operator.
   * @api
   */
  class EqualTo extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!(string|number)} expression The value to compare.
     * @param {boolean} [matchCase] Case-sensitive?
     */
    constructor(propertyName, expression, matchCase) {
      super('PropertyIsEqualTo', propertyName, expression, matchCase);
    }
  }

  /**
   * @module ol/format/filter/GreaterThan
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsGreaterThan>` comparison operator.
   * @api
   */
  class GreaterThan extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!number} expression The value to compare.
     */
    constructor(propertyName, expression) {
      super('PropertyIsGreaterThan', propertyName, expression);
    }
  }

  /**
   * @module ol/format/filter/GreaterThanOrEqualTo
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsGreaterThanOrEqualTo>` comparison operator.
   * @api
   */
  class GreaterThanOrEqualTo extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!number} expression The value to compare.
     */
    constructor(propertyName, expression) {
      super('PropertyIsGreaterThanOrEqualTo', propertyName, expression);
    }
  }

  /**
   * @module ol/format/filter/Intersects
   */

  /**
   * @classdesc
   * Represents a `<Intersects>` operator to test whether a geometry-valued property
   * intersects a given geometry.
   * @api
   */
  class Intersects extends Spatial {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(geometryName, geometry, srsName) {
      super('Intersects', geometryName, geometry, srsName);
    }
  }

  /**
   * @module ol/format/filter/IsBetween
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsBetween>` comparison operator.
   * @api
   */
  class IsBetween extends Comparison {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!number} lowerBoundary The lower bound of the range.
     * @param {!number} upperBoundary The upper bound of the range.
     */
    constructor(propertyName, lowerBoundary, upperBoundary) {
      super('PropertyIsBetween', propertyName);

      /**
       * @type {!number}
       */
      this.lowerBoundary = lowerBoundary;

      /**
       * @type {!number}
       */
      this.upperBoundary = upperBoundary;
    }
  }

  /**
   * @module ol/format/filter/IsLike
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsLike>` comparison operator.
   * @api
   */
  class IsLike extends Comparison {
    /**
     * [constructor description]
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!string} pattern Text pattern.
     * @param {string} [wildCard] Pattern character which matches any sequence of
     *    zero or more string characters. Default is '*'.
     * @param {string} [singleChar] pattern character which matches any single
     *    string character. Default is '.'.
     * @param {string} [escapeChar] Escape character which can be used to escape
     *    the pattern characters. Default is '!'.
     * @param {boolean} [matchCase] Case-sensitive?
     */
    constructor(
      propertyName,
      pattern,
      wildCard,
      singleChar,
      escapeChar,
      matchCase,
    ) {
      super('PropertyIsLike', propertyName);

      /**
       * @type {!string}
       */
      this.pattern = pattern;

      /**
       * @type {!string}
       */
      this.wildCard = wildCard !== undefined ? wildCard : '*';

      /**
       * @type {!string}
       */
      this.singleChar = singleChar !== undefined ? singleChar : '.';

      /**
       * @type {!string}
       */
      this.escapeChar = escapeChar !== undefined ? escapeChar : '!';

      /**
       * @type {boolean|undefined}
       */
      this.matchCase = matchCase;
    }
  }

  /**
   * @module ol/format/filter/IsNull
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsNull>` comparison operator.
   * @api
   */
  class IsNull extends Comparison {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     */
    constructor(propertyName) {
      super('PropertyIsNull', propertyName);
    }
  }

  /**
   * @module ol/format/filter/LessThan
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsLessThan>` comparison operator.
   * @api
   */
  class LessThan extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!number} expression The value to compare.
     */
    constructor(propertyName, expression) {
      super('PropertyIsLessThan', propertyName, expression);
    }
  }

  /**
   * @module ol/format/filter/LessThanOrEqualTo
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsLessThanOrEqualTo>` comparison operator.
   * @api
   */
  class LessThanOrEqualTo extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!number} expression The value to compare.
     */
    constructor(propertyName, expression) {
      super('PropertyIsLessThanOrEqualTo', propertyName, expression);
    }
  }

  /**
   * @module ol/format/filter/Not
   */

  /**
   * @classdesc
   * Represents a logical `<Not>` operator for a filter condition.
   * @api
   */
  class Not extends Filter {
    /**
     * @param {!import("./Filter.js").default} condition Filter condition.
     */
    constructor(condition) {
      super('Not');

      /**
       * @type {!import("./Filter.js").default}
       */
      this.condition = condition;
    }
  }

  /**
   * @module ol/format/filter/NotEqualTo
   */

  /**
   * @classdesc
   * Represents a `<PropertyIsNotEqualTo>` comparison operator.
   * @api
   */
  class NotEqualTo extends ComparisonBinary {
    /**
     * @param {!string} propertyName Name of the context property to compare.
     * @param {!(string|number)} expression The value to compare.
     * @param {boolean} [matchCase] Case-sensitive?
     */
    constructor(propertyName, expression, matchCase) {
      super('PropertyIsNotEqualTo', propertyName, expression, matchCase);
    }
  }

  /**
   * @module ol/format/filter/Or
   */

  /**
   * @classdesc
   * Represents a logical `<Or>` operator between two or more filter conditions.
   * @api
   */
  class Or extends LogicalNary {
    /**
     * @param {...import("./Filter.js").default} conditions Conditions.
     */
    constructor(conditions) {
      super('Or', Array.prototype.slice.call(arguments));
    }
  }

  /**
   * @module ol/format/filter/ResourceId
   */

  /**
   * @classdesc
   *
   * @abstract
   */
  class ResourceId extends Filter {
    /**
     * @param {!string} rid Resource ID.
     */
    constructor(rid) {
      super('ResourceId');

      /**
       * @type {!string}
       */
      this.rid = rid;
    }
  }

  /**
   * @module ol/format/filter/Within
   */

  /**
   * @classdesc
   * Represents a `<Within>` operator to test whether a geometry-valued property
   * is within a given geometry.
   * @api
   */
  class Within extends Spatial {
    /**
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../../geom/Geometry.js").default} geometry Geometry.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     */
    constructor(geometryName, geometry, srsName) {
      super('Within', geometryName, geometry, srsName);
    }
  }

  /**
   * @module ol/format/filter
   */

  /**
   * Create a logical `<And>` operator between two or more filter conditions.
   *
   * @param {...import("./filter/Filter.js").default} conditions Filter conditions.
   * @return {!And} `<And>` operator.
   * @api
   */
  function and(conditions) {
    const params = [null].concat(Array.prototype.slice.call(arguments));
    return new (Function.prototype.bind.apply(And, params))();
  }

  /**
   * Create a logical `<Or>` operator between two or more filter conditions.
   *
   * @param {...import("./filter/Filter.js").default} conditions Filter conditions.
   * @return {!Or} `<Or>` operator.
   * @api
   */
  function or(conditions) {
    const params = [null].concat(Array.prototype.slice.call(arguments));
    return new (Function.prototype.bind.apply(Or, params))();
  }

  /**
   * Represents a logical `<Not>` operator for a filter condition.
   *
   * @param {!import("./filter/Filter.js").default} condition Filter condition.
   * @return {!Not} `<Not>` operator.
   * @api
   */
  function not(condition) {
    return new Not(condition);
  }

  /**
   * Create a `<BBOX>` operator to test whether a geometry-valued property
   * intersects a fixed bounding box
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../extent.js").Extent} extent Extent.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!Bbox} `<BBOX>` operator.
   * @api
   */
  function bbox(geometryName, extent, srsName) {
    return new Bbox(geometryName, extent, srsName);
  }

  /**
   * Create a `<Contains>` operator to test whether a geometry-valued property
   * contains a given geometry.
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../geom/Geometry.js").default} geometry Geometry.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!Contains} `<Contains>` operator.
   * @api
   */
  function contains(geometryName, geometry, srsName) {
    return new Contains(geometryName, geometry, srsName);
  }

  /**
   * Create a `<Intersects>` operator to test whether a geometry-valued property
   * intersects a given geometry.
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../geom/Geometry.js").default} geometry Geometry.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!Intersects} `<Intersects>` operator.
   * @api
   */
  function intersects(geometryName, geometry, srsName) {
    return new Intersects(geometryName, geometry, srsName);
  }

  /**
   * Create a `<Disjoint>` operator to test whether a geometry-valued property
   * is disjoint to a given geometry.
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../geom/Geometry.js").default} geometry Geometry.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!Disjoint} `<Disjoint>` operator.
   * @api
   */
  function disjoint(geometryName, geometry, srsName) {
    return new Disjoint(geometryName, geometry, srsName);
  }

  /**
   * Create a `<Within>` operator to test whether a geometry-valued property
   * is within a given geometry.
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../geom/Geometry.js").default} geometry Geometry.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!Within} `<Within>` operator.
   * @api
   */
  function within(geometryName, geometry, srsName) {
    return new Within(geometryName, geometry, srsName);
  }

  /**
   * Create a `<DWithin>` operator to test whether a geometry-valued property
   * is within a distance to a given geometry.
   *
   * @param {!string} geometryName Geometry name to use.
   * @param {!import("../geom/Geometry.js").default} geometry Geometry.
   * @param {!number} distance Distance.
   * @param {!string} unit Unit.
   * @param {string} [srsName] SRS name. No srsName attribute will be
   *    set on geometries when this is not provided.
   * @return {!DWithin} `<DWithin>` operator.
   * @api
   */
  function dwithin(geometryName, geometry, distance, unit, srsName) {
    return new DWithin(geometryName, geometry, distance, unit, srsName);
  }

  /**
   * Creates a `<PropertyIsEqualTo>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!(string|number)} expression The value to compare.
   * @param {boolean} [matchCase] Case-sensitive?
   * @return {!EqualTo} `<PropertyIsEqualTo>` operator.
   * @api
   */
  function equalTo(propertyName, expression, matchCase) {
    return new EqualTo(propertyName, expression, matchCase);
  }

  /**
   * Creates a `<PropertyIsNotEqualTo>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!(string|number)} expression The value to compare.
   * @param {boolean} [matchCase] Case-sensitive?
   * @return {!NotEqualTo} `<PropertyIsNotEqualTo>` operator.
   * @api
   */
  function notEqualTo(propertyName, expression, matchCase) {
    return new NotEqualTo(propertyName, expression, matchCase);
  }

  /**
   * Creates a `<PropertyIsLessThan>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!number} expression The value to compare.
   * @return {!LessThan} `<PropertyIsLessThan>` operator.
   * @api
   */
  function lessThan(propertyName, expression) {
    return new LessThan(propertyName, expression);
  }

  /**
   * Creates a `<PropertyIsLessThanOrEqualTo>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!number} expression The value to compare.
   * @return {!LessThanOrEqualTo} `<PropertyIsLessThanOrEqualTo>` operator.
   * @api
   */
  function lessThanOrEqualTo(propertyName, expression) {
    return new LessThanOrEqualTo(propertyName, expression);
  }

  /**
   * Creates a `<PropertyIsGreaterThan>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!number} expression The value to compare.
   * @return {!GreaterThan} `<PropertyIsGreaterThan>` operator.
   * @api
   */
  function greaterThan(propertyName, expression) {
    return new GreaterThan(propertyName, expression);
  }

  /**
   * Creates a `<PropertyIsGreaterThanOrEqualTo>` comparison operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!number} expression The value to compare.
   * @return {!GreaterThanOrEqualTo} `<PropertyIsGreaterThanOrEqualTo>` operator.
   * @api
   */
  function greaterThanOrEqualTo(propertyName, expression) {
    return new GreaterThanOrEqualTo(propertyName, expression);
  }

  /**
   * Creates a `<PropertyIsNull>` comparison operator to test whether a property value
   * is null.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @return {!IsNull} `<PropertyIsNull>` operator.
   * @api
   */
  function isNull(propertyName) {
    return new IsNull(propertyName);
  }

  /**
   * Creates a `<PropertyIsBetween>` comparison operator to test whether an expression
   * value lies within a range given by a lower and upper bound (inclusive).
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!number} lowerBoundary The lower bound of the range.
   * @param {!number} upperBoundary The upper bound of the range.
   * @return {!IsBetween} `<PropertyIsBetween>` operator.
   * @api
   */
  function between(propertyName, lowerBoundary, upperBoundary) {
    return new IsBetween(propertyName, lowerBoundary, upperBoundary);
  }

  /**
   * Represents a `<PropertyIsLike>` comparison operator that matches a string property
   * value against a text pattern.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!string} pattern Text pattern.
   * @param {string} [wildCard] Pattern character which matches any sequence of
   *    zero or more string characters. Default is '*'.
   * @param {string} [singleChar] pattern character which matches any single
   *    string character. Default is '.'.
   * @param {string} [escapeChar] Escape character which can be used to escape
   *    the pattern characters. Default is '!'.
   * @param {boolean} [matchCase] Case-sensitive?
   * @return {!IsLike} `<PropertyIsLike>` operator.
   * @api
   */
  function like(
    propertyName,
    pattern,
    wildCard,
    singleChar,
    escapeChar,
    matchCase,
  ) {
    return new IsLike(
      propertyName,
      pattern,
      wildCard,
      singleChar,
      escapeChar,
      matchCase,
    );
  }

  /**
   * Create a `<During>` temporal operator.
   *
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!string} begin The begin date in ISO-8601 format.
   * @param {!string} end The end date in ISO-8601 format.
   * @return {!During} `<During>` operator.
   * @api
   */
  function during(propertyName, begin, end) {
    return new During(propertyName, begin, end);
  }

  function resourceId(rid) {
    return new ResourceId(rid);
  }

  var nsFormat_filter = {
    __proto__: null,
    and: and,
    bbox: bbox,
    between: between,
    contains: contains,
    disjoint: disjoint,
    during: during,
    dwithin: dwithin,
    equalTo: equalTo,
    greaterThan: greaterThan,
    greaterThanOrEqualTo: greaterThanOrEqualTo,
    intersects: intersects,
    isNull: isNull,
    lessThan: lessThan,
    lessThanOrEqualTo: lessThanOrEqualTo,
    like: like,
    not: not,
    notEqualTo: notEqualTo,
    or: or,
    resourceId: resourceId,
    within: within
  };

  /**
   * @module ol/format/WFS
   */

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  const FEATURE_COLLECTION_PARSERS = {
    'http://www.opengis.net/gml': {
      'boundedBy': makeObjectPropertySetter(
        GMLBase.prototype.readExtentElement,
        'bounds',
      ),
    },
    'http://www.opengis.net/wfs/2.0': {
      'member': makeArrayPusher(GMLBase.prototype.readFeaturesInternal),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  const TRANSACTION_SUMMARY_PARSERS = {
    'http://www.opengis.net/wfs': {
      'totalInserted': makeObjectPropertySetter(readPositiveInteger),
      'totalUpdated': makeObjectPropertySetter(readPositiveInteger),
      'totalDeleted': makeObjectPropertySetter(readPositiveInteger),
    },
    'http://www.opengis.net/wfs/2.0': {
      'totalInserted': makeObjectPropertySetter(readPositiveInteger),
      'totalUpdated': makeObjectPropertySetter(readPositiveInteger),
      'totalDeleted': makeObjectPropertySetter(readPositiveInteger),
    },
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  const TRANSACTION_RESPONSE_PARSERS = {
    'http://www.opengis.net/wfs': {
      'TransactionSummary': makeObjectPropertySetter(
        readTransactionSummary,
        'transactionSummary',
      ),
      'InsertResults': makeObjectPropertySetter(readInsertResults, 'insertIds'),
    },
    'http://www.opengis.net/wfs/2.0': {
      'TransactionSummary': makeObjectPropertySetter(
        readTransactionSummary,
        'transactionSummary',
      ),
      'InsertResults': makeObjectPropertySetter(readInsertResults, 'insertIds'),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  const QUERY_SERIALIZERS = {
    'http://www.opengis.net/wfs': {
      'PropertyName': makeChildAppender(writeStringTextNode),
    },
    'http://www.opengis.net/wfs/2.0': {
      'PropertyName': makeChildAppender(writeStringTextNode),
    },
  };

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  const TRANSACTION_SERIALIZERS = {
    'http://www.opengis.net/wfs': {
      'Insert': makeChildAppender(writeFeature),
      'Update': makeChildAppender(writeUpdate),
      'Delete': makeChildAppender(writeDelete),
      'Property': makeChildAppender(writeProperty),
      'Native': makeChildAppender(writeNative),
    },
    'http://www.opengis.net/wfs/2.0': {
      'Insert': makeChildAppender(writeFeature),
      'Update': makeChildAppender(writeUpdate),
      'Delete': makeChildAppender(writeDelete),
      'Property': makeChildAppender(writeProperty),
      'Native': makeChildAppender(writeNative),
    },
  };

  /**
   * @typedef {Object} Options
   * @property {Object<string, string>|string} [featureNS] The namespace URI used for features.
   * @property {Array<string>|string} [featureType] The feature type to parse. Only used for read operations.
   * @property {GMLBase} [gmlFormat] The GML format to use to parse the response.
   * Default is `ol/format/GML2` for WFS 1.0.0, `ol/format/GML3` for WFS 1.1.0 and `ol/format/GML32` for WFS 2.0.0.
   * @property {string} [schemaLocation] Optional schemaLocation to use for serialization, this will override the default.
   * @property {string} [version='1.1.0'] WFS version to use. Can be either `1.0.0`, `1.1.0` or `2.0.0`.
   */

  /**
   * @typedef {Object} WriteGetFeatureOptions
   * @property {string} featureNS The namespace URI used for features.
   * @property {string} featurePrefix The prefix for the feature namespace.
   * @property {Array<string|FeatureType>} featureTypes The feature type names or FeatureType objects to
   * define a unique bbox filter per feature type name (in this case, options `bbox` and `geometryName` are
   * ignored.).
   * @property {string} [srsName] SRS name. No srsName attribute will be set on
   * geometries when this is not provided.
   * @property {string} [handle] Handle.
   * @property {string} [outputFormat] Output format.
   * @property {number} [maxFeatures] Maximum number of features to fetch.
   * @property {string} [geometryName] Geometry name to use in a BBOX filter.
   * @property {Array<string>} [propertyNames] Optional list of property names to serialize.
   * @property {string} [viewParams] viewParams GeoServer vendor parameter.
   * @property {number} [startIndex] Start index to use for WFS paging. This is a
   * WFS 2.0 feature backported to WFS 1.1.0 by some Web Feature Services.
   * @property {number} [count] Number of features to retrieve when paging. This is a
   * WFS 2.0 feature backported to WFS 1.1.0 by some Web Feature Services. Please note that some
   * Web Feature Services have repurposed `maxfeatures` instead.
   * @property {import("../extent.js").Extent} [bbox] Extent to use for the BBOX filter. The `geometryName`
   * option must be set.
   * @property {import("./filter/Filter.js").default} [filter] Filter condition. See
   * {@link module:ol/format/filter} for more information.
   * @property {string} [resultType] Indicates what response should be returned,
   * e.g. `hits` only includes the `numberOfFeatures` attribute in the response and no features.
   */

  /**
   * @typedef {Object} FeatureType
   * @property {!string} name The feature type name.
   * @property {!import("../extent.js").Extent} bbox Extent to use for the BBOX filter.
   * @property {!string} geometryName Geometry name to use in the BBOX filter.
   */

  /**
   * @typedef {Object} WriteTransactionOptions
   * @property {string} featureNS The namespace URI used for features.
   * @property {string} featurePrefix The prefix for the feature namespace.
   * @property {string} featureType The feature type name.
   * @property {string} [srsName] SRS name. No srsName attribute will be set on
   * geometries when this is not provided.
   * @property {string} [handle] Handle.
   * @property {boolean} [hasZ] Must be set to true if the transaction is for
   * a 3D layer. This will allow the Z coordinate to be included in the transaction.
   * @property {Array<Object>} nativeElements Native elements. Currently not supported.
   * @property {import("./GMLBase.js").Options} [gmlOptions] GML options for the WFS transaction writer.
   * @property {string} [version='1.1.0'] WFS version to use for the transaction. Can be either `1.0.0`, `1.1.0` or `2.0.0`.
   */

  /**
   * Number of features; bounds/extent.
   * @typedef {Object} FeatureCollectionMetadata
   * @property {number} numberOfFeatures NumberOfFeatures.
   * @property {import("../extent.js").Extent} bounds Bounds.
   */

  /**
   * @typedef {Object} TransactionSummary
   * @property {number} totalDeleted TotalDeleted.
   * @property {number} totalInserted TotalInserted.
   * @property {number} totalUpdated TotalUpdated.
   */

  /**
   * Total deleted; total inserted; total updated; array of insert ids.
   * @typedef {Object} TransactionResponse
   * @property {TransactionSummary} transactionSummary Transaction summary.
   * @property {Array<string>} insertIds InsertIds.
   */

  /**
   * @type {string}
   */
  const FEATURE_PREFIX = 'feature';

  /**
   * @type {string}
   */
  const XMLNS = 'http://www.w3.org/2000/xmlns/';

  /**
   * @type {Object<string, string>}
   */
  const OGCNS = {
    '2.0.0': 'http://www.opengis.net/ogc/1.1',
    '1.1.0': 'http://www.opengis.net/ogc',
    '1.0.0': 'http://www.opengis.net/ogc',
  };

  /**
   * @type {Object<string, string>}
   */
  const WFSNS = {
    '2.0.0': 'http://www.opengis.net/wfs/2.0',
    '1.1.0': 'http://www.opengis.net/wfs',
    '1.0.0': 'http://www.opengis.net/wfs',
  };

  /**
   * @type {Object<string, string>}
   */
  const FESNS = {
    '2.0.0': 'http://www.opengis.net/fes/2.0',
    '1.1.0': 'http://www.opengis.net/fes',
    '1.0.0': 'http://www.opengis.net/fes',
  };

  /**
   * @type {Object<string, string>}
   */
  const SCHEMA_LOCATIONS = {
    '2.0.0':
      'http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd',
    '1.1.0':
      'http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd',
    '1.0.0':
      'http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd',
  };

  /**
   * @type {Object<string, object>}
   */
  const GML_FORMATS = {
    '2.0.0': GML32,
    '1.1.0': GML3,
    '1.0.0': GML2,
  };

  /**
   * @const
   * @type {string}
   */
  const DEFAULT_VERSION$1 = '1.1.0';

  /**
   * @classdesc
   * Feature format for reading and writing data in the WFS format.
   * By default, supports WFS version 1.1.0. You can pass a GML format
   * as option to override the default.
   * Also see {@link module:ol/format/GMLBase~GMLBase} which is used by this format.
   *
   * @api
   */
  class WFS extends XMLFeature {
    /**
     * @param {Options} [options] Optional configuration object.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @private
       * @type {string}
       */
      this.version_ = options.version ? options.version : DEFAULT_VERSION$1;

      /**
       * @private
       * @type {Array<string>|string|undefined}
       */
      this.featureType_ = options.featureType;

      /**
       * @private
       * @type {Object<string, string>|string|undefined}
       */
      this.featureNS_ = options.featureNS;

      /**
       * @private
       * @type {GMLBase}
       */
      this.gmlFormat_ = options.gmlFormat
        ? options.gmlFormat
        : new GML_FORMATS[this.version_]();

      /**
       * @private
       * @type {string}
       */
      this.schemaLocation_ = options.schemaLocation
        ? options.schemaLocation
        : SCHEMA_LOCATIONS[this.version_];
    }

    /**
     * @return {Array<string>|string|undefined} featureType
     */
    getFeatureType() {
      return this.featureType_;
    }

    /**
     * @param {Array<string>|string|undefined} featureType Feature type(s) to parse.
     */
    setFeatureType(featureType) {
      this.featureType_ = featureType;
    }

    /**
     * @protected
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @override
     */
    readFeaturesFromNode(node, options) {
      /** @type {import("../xml.js").NodeStackItem} */
      const context = {
        node,
      };
      Object.assign(context, {
        'featureType': this.featureType_,
        'featureNS': this.featureNS_,
      });

      Object.assign(context, this.getReadOptions(node, options ? options : {}));
      const objectStack = [context];
      let featuresNS;
      if (this.version_ === '2.0.0') {
        featuresNS = FEATURE_COLLECTION_PARSERS;
      } else {
        featuresNS = this.gmlFormat_.FEATURE_COLLECTION_PARSERS;
      }
      let features = pushParseAndPop(
        [],
        featuresNS,
        node,
        objectStack,
        this.gmlFormat_,
      );
      if (!features) {
        features = [];
      }
      return features;
    }

    /**
     * Read transaction response of the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {TransactionResponse|undefined} Transaction response.
     * @api
     */
    readTransactionResponse(source) {
      if (!source) {
        return undefined;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readTransactionResponseFromDocument(doc);
      }
      if (isDocument(source)) {
        return this.readTransactionResponseFromDocument(
          /** @type {Document} */ (source),
        );
      }
      return this.readTransactionResponseFromNode(
        /** @type {Element} */ (source),
      );
    }

    /**
     * Read feature collection metadata of the source.
     *
     * @param {Document|Element|Object|string} source Source.
     * @return {FeatureCollectionMetadata|undefined}
     *     FeatureCollection metadata.
     * @api
     */
    readFeatureCollectionMetadata(source) {
      if (!source) {
        return undefined;
      }
      if (typeof source === 'string') {
        const doc = parse(source);
        return this.readFeatureCollectionMetadataFromDocument(doc);
      }
      if (isDocument(source)) {
        return this.readFeatureCollectionMetadataFromDocument(
          /** @type {Document} */ (source),
        );
      }
      return this.readFeatureCollectionMetadataFromNode(
        /** @type {Element} */ (source),
      );
    }

    /**
     * @param {Document} doc Document.
     * @return {FeatureCollectionMetadata|undefined}
     *     FeatureCollection metadata.
     */
    readFeatureCollectionMetadataFromDocument(doc) {
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          return this.readFeatureCollectionMetadataFromNode(
            /** @type {Element} */ (n),
          );
        }
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @return {FeatureCollectionMetadata|undefined}
     *     FeatureCollection metadata.
     */
    readFeatureCollectionMetadataFromNode(node) {
      const result = {};
      const value = readNonNegativeIntegerString(
        node.getAttribute('numberOfFeatures'),
      );
      result['numberOfFeatures'] = value;
      return pushParseAndPop(
        /** @type {FeatureCollectionMetadata} */ (result),
        FEATURE_COLLECTION_PARSERS,
        node,
        [],
        this.gmlFormat_,
      );
    }

    /**
     * @param {Document} doc Document.
     * @return {TransactionResponse|undefined} Transaction response.
     */
    readTransactionResponseFromDocument(doc) {
      for (let n = /** @type {Node} */ (doc.firstChild); n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          return this.readTransactionResponseFromNode(/** @type {Element} */ (n));
        }
      }
      return undefined;
    }

    /**
     * @param {Element} node Node.
     * @return {TransactionResponse|undefined} Transaction response.
     */
    readTransactionResponseFromNode(node) {
      return pushParseAndPop(
        /** @type {TransactionResponse} */ ({}),
        TRANSACTION_RESPONSE_PARSERS,
        node,
        [],
      );
    }

    /**
     * Encode format as WFS `GetFeature` and return the Node.
     *
     * @param {WriteGetFeatureOptions} options Options.
     * @return {Node} Result.
     * @api
     */
    writeGetFeature(options) {
      const node = createElementNS(WFSNS[this.version_], 'GetFeature');
      node.setAttribute('service', 'WFS');
      node.setAttribute('version', this.version_);
      if (options.handle) {
        node.setAttribute('handle', options.handle);
      }
      if (options.outputFormat) {
        node.setAttribute('outputFormat', options.outputFormat);
      }
      if (options.maxFeatures !== undefined) {
        node.setAttribute('maxFeatures', String(options.maxFeatures));
      }
      if (options.resultType) {
        node.setAttribute('resultType', options.resultType);
      }
      if (options.startIndex !== undefined) {
        node.setAttribute('startIndex', String(options.startIndex));
      }
      if (options.count !== undefined) {
        node.setAttribute('count', String(options.count));
      }
      if (options.viewParams !== undefined) {
        node.setAttribute('viewParams', options.viewParams);
      }
      node.setAttributeNS(
        XML_SCHEMA_INSTANCE_URI,
        'xsi:schemaLocation',
        this.schemaLocation_,
      );
      /** @type {import("../xml.js").NodeStackItem} */
      const context = {
        node,
      };
      Object.assign(context, {
        'version': this.version_,
        'srsName': options.srsName,
        'featureNS': options.featureNS ? options.featureNS : this.featureNS_,
        'featurePrefix': options.featurePrefix,
        'propertyNames': options.propertyNames ? options.propertyNames : [],
      });
      assert(
        Array.isArray(options.featureTypes),
        '`options.featureTypes` must be an Array',
      );
      if (typeof options.featureTypes[0] === 'string') {
        let filter = options.filter;
        if (options.bbox) {
          assert(
            options.geometryName,
            '`options.geometryName` must also be provided when `options.bbox` is set',
          );
          filter = this.combineBboxAndFilter(
            options.geometryName,
            options.bbox,
            options.srsName,
            filter,
          );
        }
        Object.assign(context, {
          'geometryName': options.geometryName,
          'filter': filter,
        });
        writeGetFeature(
          node,
          /** @type {!Array<string>} */ (options.featureTypes),
          [context],
        );
      } else {
        // Write one query node per element in featuresType.
        options.featureTypes.forEach((/** @type {FeatureType} */ featureType) => {
          const completeFilter = this.combineBboxAndFilter(
            featureType.geometryName,
            featureType.bbox,
            options.srsName,
            options.filter,
          );
          Object.assign(context, {
            'geometryName': featureType.geometryName,
            'filter': completeFilter,
          });
          writeGetFeature(node, [featureType.name], [context]);
        });
      }
      return node;
    }

    /**
     * Create a bbox filter and combine it with another optional filter.
     *
     * @param {!string} geometryName Geometry name to use.
     * @param {!import("../extent.js").Extent} extent Extent.
     * @param {string} [srsName] SRS name. No srsName attribute will be
     *    set on geometries when this is not provided.
     * @param {import("./filter/Filter.js").default} [filter] Filter condition.
     * @return {import("./filter/Filter.js").default} The filter.
     */
    combineBboxAndFilter(geometryName, extent, srsName, filter) {
      const bboxFilter = bbox(geometryName, extent, srsName);
      if (filter) {
        // if bbox and filter are both set, combine the two into a single filter
        return and(filter, bboxFilter);
      }
      return bboxFilter;
    }

    /**
     * Encode format as WFS `Transaction` and return the Node.
     *
     * @param {Array<import("../Feature.js").default>} inserts The features to insert.
     * @param {Array<import("../Feature.js").default>} updates The features to update.
     * @param {Array<import("../Feature.js").default>} deletes The features to delete.
     * @param {WriteTransactionOptions} options Write options.
     * @return {Node} Result.
     * @api
     */
    writeTransaction(inserts, updates, deletes, options) {
      const objectStack = [];
      const version = options.version ? options.version : this.version_;
      const node = createElementNS(WFSNS[version], 'Transaction');

      node.setAttribute('service', 'WFS');
      node.setAttribute('version', version);
      let baseObj;
      /** @type {import("../xml.js").NodeStackItem} */
      if (options) {
        baseObj = options.gmlOptions ? options.gmlOptions : {};
        if (options.handle) {
          node.setAttribute('handle', options.handle);
        }
      }
      node.setAttributeNS(
        XML_SCHEMA_INSTANCE_URI,
        'xsi:schemaLocation',
        SCHEMA_LOCATIONS[version],
      );

      const request = createTransactionRequest(node, baseObj, version, options);
      if (inserts) {
        serializeTransactionRequest('Insert', inserts, objectStack, request);
      }
      if (updates) {
        serializeTransactionRequest('Update', updates, objectStack, request);
      }
      if (deletes) {
        serializeTransactionRequest('Delete', deletes, objectStack, request);
      }
      if (options.nativeElements) {
        serializeTransactionRequest(
          'Native',
          options.nativeElements,
          objectStack,
          request,
        );
      }
      return node;
    }

    /**
     * @param {Document} doc Document.
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromDocument(doc) {
      for (let n = doc.firstChild; n; n = n.nextSibling) {
        if (n.nodeType == Node.ELEMENT_NODE) {
          return this.readProjectionFromNode(/** @type {Element} */ (n));
        }
      }
      return null;
    }

    /**
     * @param {Element} node Node.
     * @return {import("../proj/Projection.js").default} Projection.
     * @override
     */
    readProjectionFromNode(node) {
      if (node.firstElementChild && node.firstElementChild.firstElementChild) {
        node = node.firstElementChild.firstElementChild;
        for (let n = node.firstElementChild; n; n = n.nextElementSibling) {
          if (
            !(
              n.childNodes.length === 0 ||
              (n.childNodes.length === 1 && n.firstChild.nodeType === 3)
            )
          ) {
            const objectStack = [{}];
            this.gmlFormat_.readGeometryElement(n, objectStack);
            return get$2(objectStack.pop().srsName);
          }
        }
      }

      return null;
    }
  }

  /**
   * @param {Element} node Node.
   * @param {*} baseObj Base object.
   * @param {string} version Version.
   * @param {WriteTransactionOptions} options Options.
   * @return {Object} Request object.
   */
  function createTransactionRequest(node, baseObj, version, options) {
    const featurePrefix = options.featurePrefix
      ? options.featurePrefix
      : FEATURE_PREFIX;
    let gmlVersion;
    if (version === '1.0.0') {
      gmlVersion = 2;
    } else if (version === '1.1.0') {
      gmlVersion = 3;
    } else if (version === '2.0.0') {
      gmlVersion = 3.2;
    }
    const obj = Object.assign(
      {node},
      {
        version,
        'featureNS': options.featureNS,
        'featureType': options.featureType,
        'featurePrefix': featurePrefix,
        'gmlVersion': gmlVersion,
        'hasZ': options.hasZ,
        'srsName': options.srsName,
      },
      baseObj,
    );
    return obj;
  }

  /**
   * @param {string} type Request type.
   * @param {Array<import("../Feature.js").default>} features Features.
   * @param {Array<*>} objectStack Object stack.
   * @param {Element} request Transaction Request.
   */
  function serializeTransactionRequest(type, features, objectStack, request) {
    pushSerializeAndPop(
      request,
      TRANSACTION_SERIALIZERS,
      makeSimpleNodeFactory(type),
      features,
      objectStack,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Transaction Summary.
   */
  function readTransactionSummary(node, objectStack) {
    return pushParseAndPop({}, TRANSACTION_SUMMARY_PARSERS, node, objectStack);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  const OGC_FID_PARSERS = {
    'http://www.opengis.net/ogc': {
      'FeatureId': makeArrayPusher(function (node, objectStack) {
        return node.getAttribute('fid');
      }),
    },
    'http://www.opengis.net/ogc/1.1': {
      'FeatureId': makeArrayPusher(function (node, objectStack) {
        return node.getAttribute('fid');
      }),
    },
  };

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   */
  function fidParser(node, objectStack) {
    parseNode(OGC_FID_PARSERS, node, objectStack);
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  const INSERT_RESULTS_PARSERS = {
    'http://www.opengis.net/wfs': {
      'Feature': fidParser,
    },
    'http://www.opengis.net/wfs/2.0': {
      'Feature': fidParser,
    },
  };

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<string>|undefined} Insert results.
   */
  function readInsertResults(node, objectStack) {
    return pushParseAndPop([], INSERT_RESULTS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeFeature(node, feature, objectStack) {
    const context = objectStack[objectStack.length - 1];
    const featureType = context['featureType'];
    const featureNS = context['featureNS'];
    const gmlVersion = context['gmlVersion'];
    const child = createElementNS(featureNS, featureType);
    node.appendChild(child);
    if (gmlVersion === 2) {
      GML2.prototype.writeFeatureElement(child, feature, objectStack);
    } else if (gmlVersion === 3) {
      GML3.prototype.writeFeatureElement(child, feature, objectStack);
    } else {
      GML32.prototype.writeFeatureElement(child, feature, objectStack);
    }
  }

  /**
   * @param {Node} node Node.
   * @param {number|string} fid Feature identifier.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeOgcFidFilter(node, fid, objectStack) {
    const context = objectStack[objectStack.length - 1];
    const version = context['version'];
    const ns = OGCNS[version];
    const filter = createElementNS(ns, 'Filter');
    const child = createElementNS(ns, 'FeatureId');
    filter.appendChild(child);
    child.setAttribute('fid', /** @type {string} */ (fid));
    node.appendChild(filter);
  }

  /**
   * @param {string|undefined} featurePrefix The prefix of the feature.
   * @param {string} featureType The type of the feature.
   * @return {string} The value of the typeName property.
   */
  function getTypeName(featurePrefix, featureType) {
    featurePrefix = featurePrefix ? featurePrefix : FEATURE_PREFIX;
    const prefix = featurePrefix + ':';
    // The featureType already contains the prefix.
    if (featureType.startsWith(prefix)) {
      return featureType;
    }
    return prefix + featureType;
  }

  /**
   * @param {Element} node Node.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeDelete(node, feature, objectStack) {
    const context = objectStack[objectStack.length - 1];
    assert(feature.getId() !== undefined, 'Features must have an id set');
    const featureType = context['featureType'];
    const featurePrefix = context['featurePrefix'];
    const featureNS = context['featureNS'];
    const typeName = getTypeName(featurePrefix, featureType);
    node.setAttribute('typeName', typeName);
    node.setAttributeNS(XMLNS, 'xmlns:' + featurePrefix, featureNS);
    const fid = feature.getId();
    if (fid !== undefined) {
      writeOgcFidFilter(node, fid, objectStack);
    }
  }

  /**
   * @param {Element} node Node.
   * @param {import("../Feature.js").default} feature Feature.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeUpdate(node, feature, objectStack) {
    const context = objectStack[objectStack.length - 1];
    assert(feature.getId() !== undefined, 'Features must have an id set');
    const version = context['version'];
    const featureType = context['featureType'];
    const featurePrefix = context['featurePrefix'];
    const featureNS = context['featureNS'];
    const typeName = getTypeName(featurePrefix, featureType);
    const geometryName = feature.getGeometryName();
    node.setAttribute('typeName', typeName);
    node.setAttributeNS(XMLNS, 'xmlns:' + featurePrefix, featureNS);
    const fid = feature.getId();
    if (fid !== undefined) {
      const keys = feature.getKeys();
      const values = [];
      for (let i = 0, ii = keys.length; i < ii; i++) {
        const value = feature.get(keys[i]);
        if (value !== undefined) {
          let name = keys[i];
          if (
            value &&
            typeof (/** @type {?} */ (value).getSimplifiedGeometry) === 'function'
          ) {
            name = geometryName;
          }
          values.push({name: name, value: value});
        }
      }
      pushSerializeAndPop(
        /** @type {import("../xml.js").NodeStackItem} */ ({
          version,
          'gmlVersion': context['gmlVersion'],
          node,
          'hasZ': context['hasZ'],
          'srsName': context['srsName'],
        }),
        TRANSACTION_SERIALIZERS,
        makeSimpleNodeFactory('Property'),
        values,
        objectStack,
      );
      writeOgcFidFilter(node, fid, objectStack);
    }
  }

  /**
   * @param {Node} node Node.
   * @param {Object} pair Property name and value.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeProperty(node, pair, objectStack) {
    const context = objectStack[objectStack.length - 1];
    const version = context['version'];
    const ns = WFSNS[version];
    const tagName = version === '2.0.0' ? 'ValueReference' : 'Name';
    const name = createElementNS(ns, tagName);
    const gmlVersion = context['gmlVersion'];
    node.appendChild(name);
    writeStringTextNode(name, pair.name);
    if (pair.value !== undefined && pair.value !== null) {
      const value = createElementNS(ns, 'Value');
      node.appendChild(value);
      if (
        pair.value &&
        typeof (/** @type {?} */ (pair.value).getSimplifiedGeometry) ===
          'function'
      ) {
        if (gmlVersion === 2) {
          GML2.prototype.writeGeometryElement(value, pair.value, objectStack);
        } else if (gmlVersion === 3) {
          GML3.prototype.writeGeometryElement(value, pair.value, objectStack);
        } else {
          GML32.prototype.writeGeometryElement(value, pair.value, objectStack);
        }
      } else {
        writeStringTextNode(value, pair.value);
      }
    }
  }

  /**
   * @param {Element} node Node.
   * @param {{vendorId: string, safeToIgnore: boolean, value: string}} nativeElement The native element.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeNative(node, nativeElement, objectStack) {
    if (nativeElement.vendorId) {
      node.setAttribute('vendorId', nativeElement.vendorId);
    }
    if (nativeElement.safeToIgnore !== undefined) {
      node.setAttribute('safeToIgnore', String(nativeElement.safeToIgnore));
    }
    if (nativeElement.value !== undefined) {
      writeStringTextNode(node, nativeElement.value);
    }
  }

  /**
   * @type {Object<string, Object<string, import("../xml.js").Serializer>>}
   */
  const GETFEATURE_SERIALIZERS = {
    'http://www.opengis.net/wfs': {
      'Query': makeChildAppender(writeQuery),
    },
    'http://www.opengis.net/wfs/2.0': {
      'Query': makeChildAppender(writeQuery),
    },
    'http://www.opengis.net/ogc': {
      'During': makeChildAppender(writeDuringFilter),
      'And': makeChildAppender(writeLogicalFilter),
      'Or': makeChildAppender(writeLogicalFilter),
      'Not': makeChildAppender(writeNotFilter),
      'BBOX': makeChildAppender(writeBboxFilter),
      'Contains': makeChildAppender(writeSpatialFilter),
      'Intersects': makeChildAppender(writeSpatialFilter),
      'Within': makeChildAppender(writeSpatialFilter),
      'DWithin': makeChildAppender(writeDWithinFilter),
      'PropertyIsEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsNotEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsLessThan': makeChildAppender(writeComparisonFilter),
      'PropertyIsLessThanOrEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsGreaterThan': makeChildAppender(writeComparisonFilter),
      'PropertyIsGreaterThanOrEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsNull': makeChildAppender(writeIsNullFilter),
      'PropertyIsBetween': makeChildAppender(writeIsBetweenFilter),
      'PropertyIsLike': makeChildAppender(writeIsLikeFilter),
    },
    'http://www.opengis.net/fes/2.0': {
      'During': makeChildAppender(writeDuringFilter),
      'And': makeChildAppender(writeLogicalFilter),
      'Or': makeChildAppender(writeLogicalFilter),
      'Not': makeChildAppender(writeNotFilter),
      'BBOX': makeChildAppender(writeBboxFilter),
      'Contains': makeChildAppender(writeSpatialFilter),
      'Disjoint': makeChildAppender(writeSpatialFilter),
      'Intersects': makeChildAppender(writeSpatialFilter),
      'ResourceId': makeChildAppender(writeResourceIdFilter),
      'Within': makeChildAppender(writeSpatialFilter),
      'DWithin': makeChildAppender(writeDWithinFilter),
      'PropertyIsEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsNotEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsLessThan': makeChildAppender(writeComparisonFilter),
      'PropertyIsLessThanOrEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsGreaterThan': makeChildAppender(writeComparisonFilter),
      'PropertyIsGreaterThanOrEqualTo': makeChildAppender(writeComparisonFilter),
      'PropertyIsNull': makeChildAppender(writeIsNullFilter),
      'PropertyIsBetween': makeChildAppender(writeIsBetweenFilter),
      'PropertyIsLike': makeChildAppender(writeIsLikeFilter),
    },
  };

  /**
   * @param {Element} node Node.
   * @param {string} featureType Feature type.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeQuery(node, featureType, objectStack) {
    const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const version = context['version'];
    const featurePrefix = context['featurePrefix'];
    const featureNS = context['featureNS'];
    const propertyNames = context['propertyNames'];
    const srsName = context['srsName'];
    let typeName;
    // If feature prefix is not defined, we must not use the default prefix.
    if (featurePrefix) {
      typeName = getTypeName(featurePrefix, featureType);
    } else {
      typeName = featureType;
    }
    let typeNameAttr;
    if (version === '2.0.0') {
      typeNameAttr = 'typeNames';
    } else {
      typeNameAttr = 'typeName';
    }
    node.setAttribute(typeNameAttr, typeName);
    if (srsName) {
      node.setAttribute('srsName', srsName);
    }
    if (featureNS) {
      node.setAttributeNS(XMLNS, 'xmlns:' + featurePrefix, featureNS);
    }
    const item = /** @type {import("../xml.js").NodeStackItem} */ (
      Object.assign({}, context)
    );
    item.node = node;
    pushSerializeAndPop(
      item,
      QUERY_SERIALIZERS,
      makeSimpleNodeFactory('PropertyName'),
      propertyNames,
      objectStack,
    );
    const filter = context['filter'];
    if (filter) {
      const child = createElementNS(getFilterNS(version), 'Filter');
      node.appendChild(child);
      writeFilterCondition(child, filter, objectStack);
    }
  }

  /**
   * @param {Element} node Node.
   * @param {import("./filter/Filter.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeFilterCondition(node, filter, objectStack) {
    const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    /** @type {import("../xml.js").NodeStackItem} */
    const item = {node};
    Object.assign(item, {context});
    pushSerializeAndPop(
      item,
      GETFEATURE_SERIALIZERS,
      makeSimpleNodeFactory(filter.getTagName()),
      [filter],
      objectStack,
    );
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/Bbox.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeBboxFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    parent['srsName'] = filter.srsName;
    const format = GML_FORMATS[version];

    writePropertyName(version, node, filter.geometryName);
    format.prototype.writeGeometryElement(node, filter.extent, objectStack);
  }

  /**
   * @param {Element} node Element.
   * @param {import("./filter/ResourceId.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeResourceIdFilter(node, filter, objectStack) {
    node.setAttribute('rid', /** @type {string} */ (filter.rid));
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/Spatial.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeSpatialFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    parent['srsName'] = filter.srsName;
    const format = GML_FORMATS[version];

    writePropertyName(version, node, filter.geometryName);
    format.prototype.writeGeometryElement(node, filter.geometry, objectStack);
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/DWithin.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeDWithinFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    writeSpatialFilter(node, filter, objectStack);
    const distance = createElementNS(getFilterNS(version), 'Distance');
    writeStringTextNode(distance, filter.distance.toString());
    if (version === '2.0.0') {
      distance.setAttribute('uom', filter.unit);
    } else {
      distance.setAttribute('units', filter.unit);
    }
    node.appendChild(distance);
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/During.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeDuringFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];

    writeExpression(FESNS[version], 'ValueReference', node, filter.propertyName);
    const timePeriod = createElementNS(GMLNS, 'TimePeriod');

    node.appendChild(timePeriod);

    const begin = createElementNS(GMLNS, 'begin');
    timePeriod.appendChild(begin);
    writeTimeInstant(begin, filter.begin);

    const end = createElementNS(GMLNS, 'end');
    timePeriod.appendChild(end);
    writeTimeInstant(end, filter.end);
  }

  /**
   * @param {Element} node Node.
   * @param {import("./filter/LogicalNary.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeLogicalFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    /** @type {import("../xml.js").NodeStackItem} */
    const item = {node};
    Object.assign(item, {context});
    const conditions = filter.conditions;
    for (let i = 0, ii = conditions.length; i < ii; ++i) {
      const condition = conditions[i];
      pushSerializeAndPop(
        item,
        GETFEATURE_SERIALIZERS,
        makeSimpleNodeFactory(condition.getTagName()),
        [condition],
        objectStack,
      );
    }
  }

  /**
   * @param {Element} node Node.
   * @param {import("./filter/Not.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeNotFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    /** @type {import("../xml.js").NodeStackItem} */
    const item = {node};
    Object.assign(item, {context});
    const condition = filter.condition;
    pushSerializeAndPop(
      item,
      GETFEATURE_SERIALIZERS,
      makeSimpleNodeFactory(condition.getTagName()),
      [condition],
      objectStack,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {import("./filter/ComparisonBinary.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeComparisonFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    if (filter.matchCase !== undefined) {
      node.setAttribute('matchCase', filter.matchCase.toString());
    }
    writePropertyName(version, node, filter.propertyName);
    writeLiteral(version, node, '' + filter.expression);
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/IsNull.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeIsNullFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    writePropertyName(version, node, filter.propertyName);
  }

  /**
   * @param {Node} node Node.
   * @param {import("./filter/IsBetween.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeIsBetweenFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    const ns = getFilterNS(version);

    writePropertyName(version, node, filter.propertyName);

    const lowerBoundary = createElementNS(ns, 'LowerBoundary');
    node.appendChild(lowerBoundary);
    writeLiteral(version, lowerBoundary, '' + filter.lowerBoundary);

    const upperBoundary = createElementNS(ns, 'UpperBoundary');
    node.appendChild(upperBoundary);
    writeLiteral(version, upperBoundary, '' + filter.upperBoundary);
  }

  /**
   * @param {Element} node Node.
   * @param {import("./filter/IsLike.js").default} filter Filter.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeIsLikeFilter(node, filter, objectStack) {
    const parent = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const context = parent['context'];
    const version = context['version'];
    node.setAttribute('wildCard', filter.wildCard);
    node.setAttribute('singleChar', filter.singleChar);
    node.setAttribute('escapeChar', filter.escapeChar);
    if (filter.matchCase !== undefined) {
      node.setAttribute('matchCase', filter.matchCase.toString());
    }
    writePropertyName(version, node, filter.propertyName);
    writeLiteral(version, node, '' + filter.pattern);
  }

  /**
   * @param {string} ns Namespace.
   * @param {string} tagName Tag name.
   * @param {Node} node Node.
   * @param {string} value Value.
   */
  function writeExpression(ns, tagName, node, value) {
    const property = createElementNS(ns, tagName);
    writeStringTextNode(property, value);
    node.appendChild(property);
  }

  /**
   * @param {string} version Version.
   * @param {Node} node Node.
   * @param {string} value PropertyName value.
   */
  function writeLiteral(version, node, value) {
    writeExpression(getFilterNS(version), 'Literal', node, value);
  }

  /**
   * @param {string} version Version.
   * @param {Node} node Node.
   * @param {string} value PropertyName value.
   */
  function writePropertyName(version, node, value) {
    if (version === '2.0.0') {
      writeExpression(FESNS[version], 'ValueReference', node, value);
    } else {
      writeExpression(OGCNS[version], 'PropertyName', node, value);
    }
  }

  /**
   * @param {Node} node Node.
   * @param {string} time PropertyName value.
   */
  function writeTimeInstant(node, time) {
    const timeInstant = createElementNS(GMLNS, 'TimeInstant');
    node.appendChild(timeInstant);

    const timePosition = createElementNS(GMLNS, 'timePosition');
    timeInstant.appendChild(timePosition);
    writeStringTextNode(timePosition, time);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<string>} featureTypes Feature types.
   * @param {Array<*>} objectStack Node stack.
   */
  function writeGetFeature(node, featureTypes, objectStack) {
    const context = /** @type {Object} */ (objectStack[objectStack.length - 1]);
    const item = /** @type {import("../xml.js").NodeStackItem} */ (
      Object.assign({}, context)
    );
    item.node = node;
    pushSerializeAndPop(
      item,
      GETFEATURE_SERIALIZERS,
      makeSimpleNodeFactory('Query'),
      featureTypes,
      objectStack,
    );
  }

  function getFilterNS(version) {
    let ns;
    if (version === '2.0.0') {
      ns = FESNS[version];
    } else {
      ns = OGCNS[version];
    }
    return ns;
  }

  /**
   * @module ol/format/WKB
   */

  // WKB spec: https://www.ogc.org/standards/sfa
  // EWKB spec: https://raw.githubusercontent.com/postgis/postgis/2.1.0/doc/ZMSgeoms.txt

  /**
   * @const
   * @enum {number}
   */
  const WKBGeometryType = {
    POINT: 1,
    LINE_STRING: 2,
    POLYGON: 3,
    MULTI_POINT: 4,
    MULTI_LINE_STRING: 5,
    MULTI_POLYGON: 6,
    GEOMETRY_COLLECTION: 7,

    /*
    CIRCULAR_STRING: 8,
    COMPOUND_CURVE: 9,
    CURVE_POLYGON: 10,

    MULTI_CURVE: 11,
    MULTI_SURFACE: 12,
    CURVE: 13,
    SURFACE: 14,
    */

    POLYHEDRAL_SURFACE: 15,
    TIN: 16,
    TRIANGLE: 17,
  };

  class WkbReader {
    /**
     * @param {DataView} view source to read
     */
    constructor(view) {
      /** @private */
      this.view_ = view;

      /**
       * @type {number}
       * @private
       */
      this.pos_ = 0;

      /**
       * @type {boolean}
       * @private
       */
      this.initialized_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.isLittleEndian_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.hasZ_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.hasM_ = false;

      /**
       * @type {number|null}
       * @private
       */
      this.srid_ = null;

      /**
       * @type {import("../geom/Geometry.js").GeometryLayout}
       * @private
       */
      this.layout_ = 'XY';
    }

    /**
     * @return {number} value
     */
    readUint8() {
      return this.view_.getUint8(this.pos_++);
    }

    /**
     * @param {boolean} [isLittleEndian] Whether read value as little endian
     * @return {number} value
     */
    readUint32(isLittleEndian) {
      return this.view_.getUint32(
        (this.pos_ += 4) - 4,
        isLittleEndian !== undefined ? isLittleEndian : this.isLittleEndian_,
      );
    }

    /**
     * @param {boolean} [isLittleEndian] Whether read value as little endian
     * @return {number} value
     */
    readDouble(isLittleEndian) {
      return this.view_.getFloat64(
        (this.pos_ += 8) - 8,
        isLittleEndian !== undefined ? isLittleEndian : this.isLittleEndian_,
      );
    }

    /**
     * @return {import('../coordinate.js').Coordinate} coords for Point
     */
    readPoint() {
      /** @type {import('../coordinate.js').Coordinate} */
      const coords = [];

      coords.push(this.readDouble());
      coords.push(this.readDouble());
      if (this.hasZ_) {
        coords.push(this.readDouble());
      }
      if (this.hasM_) {
        coords.push(this.readDouble());
      }

      return coords;
    }

    /**
     * @return {Array<import('../coordinate.js').Coordinate>} coords for LineString / LinearRing
     */
    readLineString() {
      const numPoints = this.readUint32();

      /** @type {Array<import('../coordinate.js').Coordinate>} */
      const coords = [];
      for (let i = 0; i < numPoints; i++) {
        coords.push(this.readPoint());
      }

      return coords;
    }

    /**
     * @return {Array<Array<import('../coordinate.js').Coordinate>>} coords for Polygon like
     */
    readPolygon() {
      const numRings = this.readUint32();

      /** @type {Array<Array<import('../coordinate.js').Coordinate>>} */
      const rings = [];
      for (let i = 0; i < numRings; i++) {
        rings.push(this.readLineString()); // as a LinearRing
      }

      return rings;
    }

    /**
     * @param {number} [expectedTypeId] Expected WKB Type ID
     * @return {number} WKB Type ID
     */
    readWkbHeader(expectedTypeId) {
      const byteOrder = this.readUint8();
      const isLittleEndian = byteOrder > 0;

      const wkbType = this.readUint32(isLittleEndian);
      const wkbTypeThousandth = Math.floor((wkbType & 0x0fffffff) / 1000);
      const hasZ =
        Boolean(wkbType & 0x80000000) ||
        wkbTypeThousandth === 1 ||
        wkbTypeThousandth === 3;
      const hasM =
        Boolean(wkbType & 0x40000000) ||
        wkbTypeThousandth === 2 ||
        wkbTypeThousandth === 3;
      const hasSRID = Boolean(wkbType & 0x20000000);
      const typeId = (wkbType & 0x0fffffff) % 1000; // Assume 1000 is an upper limit for type ID
      const layout = /** @type {import("../geom/Geometry.js").GeometryLayout} */ (
        ['XY', hasZ ? 'Z' : '', hasM ? 'M' : ''].join('')
      );

      const srid = hasSRID ? this.readUint32(isLittleEndian) : null;

      if (expectedTypeId !== undefined && expectedTypeId !== typeId) {
        throw new Error('Unexpected WKB geometry type ' + typeId);
      }

      if (this.initialized_) {
        // sanity checks
        if (this.isLittleEndian_ !== isLittleEndian) {
          throw new Error('Inconsistent endian');
        }
        if (this.layout_ !== layout) {
          throw new Error('Inconsistent geometry layout');
        }
        if (srid && this.srid_ !== srid) {
          throw new Error('Inconsistent coordinate system (SRID)');
        }
      } else {
        this.isLittleEndian_ = isLittleEndian;
        this.hasZ_ = hasZ;
        this.hasM_ = hasM;
        this.layout_ = layout;
        this.srid_ = srid;
        this.initialized_ = true;
      }

      return typeId;
    }

    /**
     * @param {number} typeId WKB Type ID
     * @return {any} values read
     */
    readWkbPayload(typeId) {
      switch (typeId) {
        case WKBGeometryType.POINT:
          return this.readPoint();

        case WKBGeometryType.LINE_STRING:
          return this.readLineString();

        case WKBGeometryType.POLYGON:
        case WKBGeometryType.TRIANGLE:
          return this.readPolygon();

        case WKBGeometryType.MULTI_POINT:
          return this.readMultiPoint();

        case WKBGeometryType.MULTI_LINE_STRING:
          return this.readMultiLineString();

        case WKBGeometryType.MULTI_POLYGON:
        case WKBGeometryType.POLYHEDRAL_SURFACE:
        case WKBGeometryType.TIN:
          return this.readMultiPolygon();

        case WKBGeometryType.GEOMETRY_COLLECTION:
          return this.readGeometryCollection();

        default:
          throw new Error(
            'Unsupported WKB geometry type ' + typeId + ' is found',
          );
      }
    }

    /**
     * @param {number} expectedTypeId Expected WKB Type ID
     * @return {any} values read
     */
    readWkbBlock(expectedTypeId) {
      return this.readWkbPayload(this.readWkbHeader(expectedTypeId));
    }

    /**
     * @param {Function} reader reader function for each item
     * @param {number} [expectedTypeId] Expected WKB Type ID
     * @return {any} values read
     */
    readWkbCollection(reader, expectedTypeId) {
      const num = this.readUint32();

      const items = [];
      for (let i = 0; i < num; i++) {
        const result = reader.call(this, expectedTypeId);
        if (result) {
          items.push(result);
        }
      }

      return items;
    }

    /**
     * @return {Array<import('../coordinate.js').Coordinate>} coords for MultiPoint
     */
    readMultiPoint() {
      return this.readWkbCollection(this.readWkbBlock, WKBGeometryType.POINT);
    }

    /**
     * @return {Array<Array<import('../coordinate.js').Coordinate>>} coords for MultiLineString like
     */
    readMultiLineString() {
      return this.readWkbCollection(
        this.readWkbBlock,
        WKBGeometryType.LINE_STRING,
      );
    }

    /**
     * @return {Array<Array<Array<import('../coordinate.js').Coordinate>>>} coords for MultiPolygon like
     */
    readMultiPolygon() {
      return this.readWkbCollection(this.readWkbBlock, WKBGeometryType.POLYGON);
    }

    /**
     * @return {Array<import('../geom/Geometry.js').default>} array of geometries
     */
    readGeometryCollection() {
      return this.readWkbCollection(this.readGeometry);
    }

    /**
     * @return {import('../geom/Geometry.js').default} geometry
     */
    readGeometry() {
      const typeId = this.readWkbHeader();
      const result = this.readWkbPayload(typeId);

      switch (typeId) {
        case WKBGeometryType.POINT:
          return new Point(
            /** @type {import('../coordinate.js').Coordinate} */ (result),
            this.layout_,
          );

        case WKBGeometryType.LINE_STRING:
          return new LineString(
            /** @type {Array<import('../coordinate.js').Coordinate>} */ (result),
            this.layout_,
          );

        case WKBGeometryType.POLYGON:
        case WKBGeometryType.TRIANGLE:
          return new Polygon(
            /** @type {Array<Array<import('../coordinate.js').Coordinate>>} */ (
              result
            ),
            this.layout_,
          );

        case WKBGeometryType.MULTI_POINT:
          return new MultiPoint(
            /** @type {Array<import('../coordinate.js').Coordinate>} */ (result),
            this.layout_,
          );

        case WKBGeometryType.MULTI_LINE_STRING:
          return new MultiLineString(
            /** @type {Array<Array<import('../coordinate.js').Coordinate>>} */ (
              result
            ),
            this.layout_,
          );

        case WKBGeometryType.MULTI_POLYGON:
        case WKBGeometryType.POLYHEDRAL_SURFACE:
        case WKBGeometryType.TIN:
          return new MultiPolygon(
            /** @type {Array<Array<Array<import('../coordinate.js').Coordinate>>>} */ (
              result
            ),
            this.layout_,
          );

        case WKBGeometryType.GEOMETRY_COLLECTION:
          return new GeometryCollection(
            /** @type {Array<import('../geom/Geometry.js').default>} */ (result),
          );

        default:
          return null;
      }
    }

    /**
     * @return {number|null} SRID in the EWKB. `null` if not defined.
     */
    getSrid() {
      return this.srid_;
    }
  }

  class WkbWriter {
    /**
     * @type {Object}
     * @property {string} [layout] geometryLayout
     * @property {boolean} [littleEndian=true] littleEndian
     * @property {boolean} [ewkb=true] Whether writes in EWKB format
     * @property {Object} [nodata] NoData value for each axes
     * @param {Object} opts options
     */
    constructor(opts) {
      opts = opts || {};

      /** @type {string} */
      this.layout_ = opts.layout;
      this.isLittleEndian_ = opts.littleEndian !== false;

      this.isEWKB_ = opts.ewkb !== false;

      /** @type {Array<Array<number>>} */
      this.writeQueue_ = [];

      /**
       * @type {Object}
       * @property {number} X NoData value for X
       * @property {number} Y NoData value for Y
       * @property {number} Z NoData value for Z
       * @property {number} M NoData value for M
       */
      this.nodata_ = Object.assign({X: 0, Y: 0, Z: 0, M: 0}, opts.nodata);
    }

    /**
     * @param {number} value value
     */
    writeUint8(value) {
      this.writeQueue_.push([1, value]);
    }

    /**
     * @param {number} value value
     */
    writeUint32(value) {
      this.writeQueue_.push([4, value]);
    }

    /**
     * @param {number} value value
     */
    writeDouble(value) {
      this.writeQueue_.push([8, value]);
    }

    /**
     * @param {import('../coordinate.js').Coordinate} coords coords
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writePoint(coords, layout) {
      /**
       * @type {Object}
       * @property {number} X NoData value for X
       * @property {number} Y NoData value for Y
       * @property {number} [Z] NoData value for Z
       * @property {number} [M] NoData value for M
       */
      const coordsObj = Object.assign.apply(
        null,
        layout.split('').map((axis, idx) => ({[axis]: coords[idx]})),
      );

      for (const axis of this.layout_) {
        this.writeDouble(
          axis in coordsObj ? coordsObj[axis] : this.nodata_[axis],
        );
      }
    }

    /**
     * @param {Array<import('../coordinate.js').Coordinate>} coords coords
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writeLineString(coords, layout) {
      this.writeUint32(coords.length); // numPoints
      for (let i = 0; i < coords.length; i++) {
        this.writePoint(coords[i], layout);
      }
    }

    /**
     * @param {Array<Array<import('../coordinate.js').Coordinate>>} rings rings
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writePolygon(rings, layout) {
      this.writeUint32(rings.length); // numRings
      for (let i = 0; i < rings.length; i++) {
        this.writeLineString(rings[i], layout); // as a LinearRing
      }
    }

    /**
     * @param {number} wkbType WKB Type ID
     * @param {number} [srid] SRID
     */
    writeWkbHeader(wkbType, srid) {
      wkbType %= 1000; // Assume 1000 is an upper limit for type ID
      if (this.layout_.includes('Z')) {
        wkbType += this.isEWKB_ ? 0x80000000 : 1000;
      }
      if (this.layout_.includes('M')) {
        wkbType += this.isEWKB_ ? 0x40000000 : 2000;
      }
      if (this.isEWKB_ && Number.isInteger(srid)) {
        wkbType |= 0x20000000;
      }

      this.writeUint8(this.isLittleEndian_ ? 1 : 0);
      this.writeUint32(wkbType);
      if (this.isEWKB_ && Number.isInteger(srid)) {
        this.writeUint32(srid);
      }
    }

    /**
     * @param {Array<import('../coordinate.js').Coordinate>} coords coords
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writeMultiPoint(coords, layout) {
      this.writeUint32(coords.length); // numItems
      for (let i = 0; i < coords.length; i++) {
        this.writeWkbHeader(1);
        this.writePoint(coords[i], layout);
      }
    }

    /**
     * @param {Array<Array<import('../coordinate.js').Coordinate>>} coords coords
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writeMultiLineString(coords, layout) {
      this.writeUint32(coords.length); // numItems
      for (let i = 0; i < coords.length; i++) {
        this.writeWkbHeader(2);
        this.writeLineString(coords[i], layout);
      }
    }

    /**
     * @param {Array<Array<Array<import('../coordinate.js').Coordinate>>>} coords coords
     * @param {import("../geom/Geometry.js").GeometryLayout} layout layout
     */
    writeMultiPolygon(coords, layout) {
      this.writeUint32(coords.length); // numItems
      for (let i = 0; i < coords.length; i++) {
        this.writeWkbHeader(3);
        this.writePolygon(coords[i], layout);
      }
    }

    /**
     * @param {Array<import('../geom/Geometry.js').default>} geometries geometries
     */
    writeGeometryCollection(geometries) {
      this.writeUint32(geometries.length); // numItems

      for (let i = 0; i < geometries.length; i++) {
        this.writeGeometry(geometries[i]);
      }
    }

    /**
     * @param {import("../geom/Geometry.js").default} geom geometry
     * @param {import("../geom/Geometry.js").GeometryLayout} [layout] layout
     * @return {import("../geom/Geometry.js").GeometryLayout} minimum layout made by common axes
     */
    findMinimumLayout(geom, layout = 'XYZM') {
      /**
       * @param {import("../geom/Geometry.js").GeometryLayout} a A
       * @param {import("../geom/Geometry.js").GeometryLayout} b B
       * @return {import("../geom/Geometry.js").GeometryLayout} minimum layout made by common axes
       */
      const GeometryLayout_min = (a, b) => {
        if (a === b) {
          return a;
        }

        if (a === 'XYZM') {
          // anything `b` is minimum
          return b;
        }
        if (b === 'XYZM') {
          // anything `a` is minimum
          return a;
        }

        // otherwise, incompatible
        return 'XY';
      };

      if (geom instanceof SimpleGeometry) {
        return GeometryLayout_min(geom.getLayout(), layout);
      }

      if (geom instanceof GeometryCollection) {
        const geoms = geom.getGeometriesArray();
        for (let i = 0; i < geoms.length && layout !== 'XY'; i++) {
          layout = this.findMinimumLayout(geoms[i], layout);
        }
      }

      return layout;
    }

    /**
     * @param {import("../geom/Geometry.js").default} geom geometry
     * @param {number} [srid] SRID
     */
    writeGeometry(geom, srid) {
      /**
       * @type {Object<import("../geom/Geometry.js").Type, WKBGeometryType>}
       */
      const wkblut = {
        Point: WKBGeometryType.POINT,
        LineString: WKBGeometryType.LINE_STRING,
        Polygon: WKBGeometryType.POLYGON,
        MultiPoint: WKBGeometryType.MULTI_POINT,
        MultiLineString: WKBGeometryType.MULTI_LINE_STRING,
        MultiPolygon: WKBGeometryType.MULTI_POLYGON,
        GeometryCollection: WKBGeometryType.GEOMETRY_COLLECTION,
      };
      const geomType = geom.getType();
      const typeId = wkblut[geomType];

      if (!typeId) {
        throw new Error('GeometryType ' + geomType + ' is not supported');
      }

      // first call of writeGeometry() traverse whole geometries to determine its output layout if not specified on constructor.
      if (!this.layout_) {
        this.layout_ = this.findMinimumLayout(geom);
      }

      this.writeWkbHeader(typeId, srid);

      if (geom instanceof SimpleGeometry) {
        const writerLUT = {
          Point: this.writePoint,
          LineString: this.writeLineString,
          Polygon: this.writePolygon,
          MultiPoint: this.writeMultiPoint,
          MultiLineString: this.writeMultiLineString,
          MultiPolygon: this.writeMultiPolygon,
        };
        writerLUT[geomType].call(this, geom.getCoordinates(), geom.getLayout());
      } else if (geom instanceof GeometryCollection) {
        this.writeGeometryCollection(geom.getGeometriesArray());
      }
    }

    getBuffer() {
      const byteLength = this.writeQueue_.reduce((acc, item) => acc + item[0], 0);
      const buffer = new ArrayBuffer(byteLength);
      const view = new DataView(buffer);

      let pos = 0;
      this.writeQueue_.forEach((item) => {
        switch (item[0]) {
          case 1:
            view.setUint8(pos, item[1]);
            break;
          case 4:
            view.setUint32(pos, item[1], this.isLittleEndian_);
            break;
          case 8:
            view.setFloat64(pos, item[1], this.isLittleEndian_);
            break;
        }

        pos += item[0];
      });

      return buffer;
    }
  }

  /**
   * @typedef {Object} Options
   * @property {boolean} [splitCollection=false] Whether to split GeometryCollections into multiple features on reading.
   * @property {boolean} [hex=true] Returns hex string instead of ArrayBuffer for output. This also is used as a hint internally whether it should load contents as text or ArrayBuffer on reading.
   * @property {boolean} [littleEndian=true] Use littleEndian for output.
   * @property {boolean} [ewkb=true] Use EWKB format for output.
   * @property {import("../geom/Geometry.js").GeometryLayout} [geometryLayout=null] Use specific coordinate layout for output features (null: auto detect)
   * @property {number} [nodataZ=0] If the `geometryLayout` doesn't match with geometry to be output, this value is used to fill missing coordinate value of Z.
   * @property {number} [nodataM=0] If the `geometryLayout` doesn't match with geometry to be output, this value is used to fill missing coordinate value of M.
   * @property {number|boolean} [srid=true] SRID for output. Specify integer value to enforce the value as a SRID. Specify `true` to extract from `dataProjection`. `false` to suppress the output. This option only takes effect when `ewkb` is `true`.
   */

  /**
   * @classdesc
   * Geometry format for reading and writing data in the `Well-Known Binary` (WKB) format.
   * Also supports `Extended Well-Known Binary` (EWKB) format, used in PostGIS for example.
   *
   * @api
   */
  class WKB extends FeatureFormat {
    /**
     * @param {Options} [options] Optional configuration object.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      this.splitCollection = Boolean(options.splitCollection);

      this.viewCache_ = null;

      this.hex_ = options.hex !== false;
      this.littleEndian_ = options.littleEndian !== false;
      this.ewkb_ = options.ewkb !== false;

      this.layout_ = options.geometryLayout; // null for auto detect
      this.nodataZ_ = options.nodataZ || 0;
      this.nodataM_ = options.nodataM || 0;

      this.srid_ = options.srid;
    }

    /**
     * @return {import("./Feature.js").Type} Format.
     * @override
     */
    getType() {
      return this.hex_ ? 'text' : 'arraybuffer';
    }

    /**
     * Read a single feature from a source.
     *
     * @param {string|ArrayBuffer|ArrayBufferView} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @api
     * @override
     */
    readFeature(source, options) {
      return new Feature({
        geometry: this.readGeometry(source, options),
      });
    }

    /**
     * Read all features from a source.
     *
     * @param {string|ArrayBuffer|ArrayBufferView} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @api
     * @override
     */
    readFeatures(source, options) {
      let geometries = [];
      const geometry = this.readGeometry(source, options);
      if (this.splitCollection && geometry instanceof GeometryCollection) {
        geometries = geometry.getGeometriesArray();
      } else {
        geometries = [geometry];
      }
      return geometries.map((geometry) => new Feature({geometry}));
    }

    /**
     * Read a single geometry from a source.
     *
     * @param {string|ArrayBuffer|ArrayBufferView} source Source.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @api
     * @override
     */
    readGeometry(source, options) {
      const view = getDataView(source);
      if (!view) {
        return null;
      }

      const reader = new WkbReader(view);
      const geometry = reader.readGeometry();

      this.viewCache_ = view; // cache for internal subsequent call of readProjection()
      options = this.getReadOptions(source, options);
      this.viewCache_ = null; // release

      return transformGeometryWithOptions(geometry, false, options);
    }

    /**
     * Read the projection from a source.
     *
     * @param {string|ArrayBuffer|ArrayBufferView} source Source.
     * @return {import("../proj/Projection.js").default|undefined} Projection.
     * @api
     * @override
     */
    readProjection(source) {
      const view = this.viewCache_ || getDataView(source);
      if (!view) {
        return undefined;
      }

      const reader = new WkbReader(view);
      reader.readWkbHeader();

      return (
        (reader.getSrid() && get$2('EPSG:' + reader.getSrid())) ||
        undefined
      );
    }

    /**
     * Encode a feature in this format.
     *
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     * @api
     * @override
     */
    writeFeature(feature, options) {
      return this.writeGeometry(feature.getGeometry(), options);
    }

    /**
     * Encode an array of features in this format.
     *
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     * @api
     * @override
     */
    writeFeatures(features, options) {
      return this.writeGeometry(
        new GeometryCollection(features.map((f) => f.getGeometry())),
        options,
      );
    }

    /**
     * Write a single geometry in this format.
     *
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @return {string|ArrayBuffer} Result.
     * @api
     * @override
     */
    writeGeometry(geometry, options) {
      options = this.adaptOptions(options);

      const writer = new WkbWriter({
        layout: this.layout_,
        littleEndian: this.littleEndian_,
        ewkb: this.ewkb_,

        nodata: {
          Z: this.nodataZ_,
          M: this.nodataM_,
        },
      });

      // extract SRID from `dataProjection`
      let srid = Number.isInteger(this.srid_) ? Number(this.srid_) : null;
      if (this.srid_ !== false && !Number.isInteger(this.srid_)) {
        const dataProjection =
          options.dataProjection && get$2(options.dataProjection);
        if (dataProjection) {
          const code = dataProjection.getCode();
          if (code.startsWith('EPSG:')) {
            srid = Number(code.substring(5));
          }
        }
      }

      writer.writeGeometry(
        transformGeometryWithOptions(geometry, true, options),
        srid,
      );
      const buffer = writer.getBuffer();

      return this.hex_ ? encodeHexString(buffer) : buffer;
    }
  }

  /**
   * @param {ArrayBuffer} buffer source buffer
   * @return {string} encoded hex string
   */
  function encodeHexString(buffer) {
    const view = new Uint8Array(buffer);
    return Array.from(view.values())
      .map((x) => (x < 16 ? '0' : '') + Number(x).toString(16).toUpperCase())
      .join('');
  }

  /**
   * @param {string} text source text
   * @return {DataView} decoded binary buffer
   */
  function decodeHexString(text) {
    const buffer = new Uint8Array(text.length / 2);
    for (let i = 0; i < text.length / 2; i++) {
      buffer[i] = parseInt(text.substr(i * 2, 2), 16);
    }
    return new DataView(buffer.buffer);
  }

  /**
   * @param {string | ArrayBuffer | ArrayBufferView} source source
   * @return {DataView} data view
   */
  function getDataView(source) {
    if (typeof source === 'string') {
      return decodeHexString(source);
    }
    if (ArrayBuffer.isView(source)) {
      if (source instanceof DataView) {
        return source;
      }
      return new DataView(source.buffer, source.byteOffset, source.byteLength);
    }
    if (source instanceof ArrayBuffer) {
      return new DataView(source);
    }
    return null;
  }

  /**
   * @module ol/format/WKT
   */

  /**
   * Geometry constructors
   * @enum {function (new:import("../geom/Geometry.js").default, Array, import("../geom/Geometry.js").GeometryLayout)}
   */
  const GeometryConstructor = {
    'POINT': Point,
    'LINESTRING': LineString,
    'POLYGON': Polygon,
    'MULTIPOINT': MultiPoint,
    'MULTILINESTRING': MultiLineString,
    'MULTIPOLYGON': MultiPolygon,
  };

  /**
   * @typedef {Object} Options
   * @property {boolean} [splitCollection=false] Whether to split GeometryCollections into
   * multiple features on reading.
   */

  /**
   * @typedef {Object} Token
   * @property {number} type Type.
   * @property {number|string} [value] Value.
   * @property {number} position Position.
   */

  /**
   * @const
   * @type {string}
   */
  const EMPTY = 'EMPTY';

  /**
   * @const
   * @type {string}
   */
  const Z = 'Z';

  /**
   * @const
   * @type {string}
   */
  const M = 'M';

  /**
   * @const
   * @type {string}
   */
  const ZM = 'ZM';

  /**
   * @const
   * @enum {number}
   */
  const TokenType = {
    START: 0,
    TEXT: 1,
    LEFT_PAREN: 2,
    RIGHT_PAREN: 3,
    NUMBER: 4,
    COMMA: 5,
    EOF: 6,
  };

  /**
   * @type {Object<import("../geom/Geometry.js").Type, string>}
   */
  const wktTypeLookup = {
    Point: 'POINT',
    LineString: 'LINESTRING',
    Polygon: 'POLYGON',
    MultiPoint: 'MULTIPOINT',
    MultiLineString: 'MULTILINESTRING',
    MultiPolygon: 'MULTIPOLYGON',
    GeometryCollection: 'GEOMETRYCOLLECTION',
    Circle: 'CIRCLE',
  };

  /**
   * Class to tokenize a WKT string.
   */
  class Lexer {
    /**
     * @param {string} wkt WKT string.
     */
    constructor(wkt) {
      /**
       * @type {string}
       */
      this.wkt = wkt;

      /**
       * @type {number}
       * @private
       */
      this.index_ = -1;
    }

    /**
     * @param {string} c Character.
     * @return {boolean} Whether the character is alphabetic.
     * @private
     */
    isAlpha_(c) {
      return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    /**
     * @param {string} c Character.
     * @param {boolean} [decimal] Whether the string number
     *     contains a dot, i.e. is a decimal number.
     * @return {boolean} Whether the character is numeric.
     * @private
     */
    isNumeric_(c, decimal) {
      decimal = decimal !== undefined ? decimal : false;
      return (c >= '0' && c <= '9') || (c == '.' && !decimal);
    }

    /**
     * @param {string} c Character.
     * @return {boolean} Whether the character is whitespace.
     * @private
     */
    isWhiteSpace_(c) {
      return c == ' ' || c == '\t' || c == '\r' || c == '\n';
    }

    /**
     * @return {string} Next string character.
     * @private
     */
    nextChar_() {
      return this.wkt.charAt(++this.index_);
    }

    /**
     * Fetch and return the next token.
     * @return {Token} Next string token.
     */
    nextToken() {
      const c = this.nextChar_();
      const position = this.index_;
      /** @type {number|string} */
      let value = c;
      let type;

      if (c == '(') {
        type = TokenType.LEFT_PAREN;
      } else if (c == ',') {
        type = TokenType.COMMA;
      } else if (c == ')') {
        type = TokenType.RIGHT_PAREN;
      } else if (this.isNumeric_(c) || c == '-') {
        type = TokenType.NUMBER;
        value = this.readNumber_();
      } else if (this.isAlpha_(c)) {
        type = TokenType.TEXT;
        value = this.readText_();
      } else if (this.isWhiteSpace_(c)) {
        return this.nextToken();
      } else if (c === '') {
        type = TokenType.EOF;
      } else {
        throw new Error('Unexpected character: ' + c);
      }

      return {position: position, value: value, type: type};
    }

    /**
     * @return {number} Numeric token value.
     * @private
     */
    readNumber_() {
      let c;
      const index = this.index_;
      let decimal = false;
      let scientificNotation = false;
      do {
        if (c == '.') {
          decimal = true;
        } else if (c == 'e' || c == 'E') {
          scientificNotation = true;
        }
        c = this.nextChar_();
      } while (
        this.isNumeric_(c, decimal) ||
        // if we haven't detected a scientific number before, 'e' or 'E'
        // hint that we should continue to read
        (!scientificNotation && (c == 'e' || c == 'E')) ||
        // once we know that we have a scientific number, both '-' and '+'
        // are allowed
        (scientificNotation && (c == '-' || c == '+'))
      );
      return parseFloat(this.wkt.substring(index, this.index_--));
    }

    /**
     * @return {string} String token value.
     * @private
     */
    readText_() {
      let c;
      const index = this.index_;
      do {
        c = this.nextChar_();
      } while (this.isAlpha_(c));
      return this.wkt.substring(index, this.index_--).toUpperCase();
    }
  }

  /**
   * Class to parse the tokens from the WKT string.
   */
  class Parser {
    /**
     * @param {Lexer} lexer The lexer.
     */
    constructor(lexer) {
      /**
       * @type {Lexer}
       * @private
       */
      this.lexer_ = lexer;

      /**
       * @type {Token}
       * @private
       */
      this.token_ = {
        position: 0,
        type: TokenType.START,
      };

      /**
       * @type {import("../geom/Geometry.js").GeometryLayout}
       * @private
       */
      this.layout_ = 'XY';
    }

    /**
     * Fetch the next token form the lexer and replace the active token.
     * @private
     */
    consume_() {
      this.token_ = this.lexer_.nextToken();
    }

    /**
     * Tests if the given type matches the type of the current token.
     * @param {TokenType} type Token type.
     * @return {boolean} Whether the token matches the given type.
     */
    isTokenType(type) {
      return this.token_.type == type;
    }

    /**
     * If the given type matches the current token, consume it.
     * @param {TokenType} type Token type.
     * @return {boolean} Whether the token matches the given type.
     */
    match(type) {
      const isMatch = this.isTokenType(type);
      if (isMatch) {
        this.consume_();
      }
      return isMatch;
    }

    /**
     * Try to parse the tokens provided by the lexer.
     * @return {import("../geom/Geometry.js").default} The geometry.
     */
    parse() {
      this.consume_();
      return this.parseGeometry_();
    }

    /**
     * Try to parse the dimensional info.
     * @return {import("../geom/Geometry.js").GeometryLayout} The layout.
     * @private
     */
    parseGeometryLayout_() {
      /** @type {import("../geom/Geometry.js").GeometryLayout} */
      let layout = 'XY';
      const dimToken = this.token_;
      if (this.isTokenType(TokenType.TEXT)) {
        const dimInfo = dimToken.value;
        if (dimInfo === Z) {
          layout = 'XYZ';
        } else if (dimInfo === M) {
          layout = 'XYM';
        } else if (dimInfo === ZM) {
          layout = 'XYZM';
        }
        if (layout !== 'XY') {
          this.consume_();
        }
      }
      return layout;
    }

    /**
     * @return {Array<import("../geom/Geometry.js").default>} A collection of geometries.
     * @private
     */
    parseGeometryCollectionText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const geometries = [];
        do {
          geometries.push(this.parseGeometry_());
        } while (this.match(TokenType.COMMA));
        if (this.match(TokenType.RIGHT_PAREN)) {
          return geometries;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<number>} All values in a point.
     * @private
     */
    parsePointText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const coordinates = this.parsePoint_();
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<number>>} All points in a linestring.
     * @private
     */
    parseLineStringText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const coordinates = this.parsePointList_();
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<Array<number>>>} All points in a polygon.
     * @private
     */
    parsePolygonText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const coordinates = this.parseLineStringTextList_();
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<number>>} All points in a multipoint.
     * @private
     */
    parseMultiPointText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        let coordinates;
        if (this.token_.type == TokenType.LEFT_PAREN) {
          coordinates = this.parsePointTextList_();
        } else {
          coordinates = this.parsePointList_();
        }
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<Array<number>>>} All linestring points
     *                                          in a multilinestring.
     * @private
     */
    parseMultiLineStringText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const coordinates = this.parseLineStringTextList_();
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<Array<Array<number>>>>} All polygon points in a multipolygon.
     * @private
     */
    parseMultiPolygonText_() {
      if (this.match(TokenType.LEFT_PAREN)) {
        const coordinates = this.parsePolygonTextList_();
        if (this.match(TokenType.RIGHT_PAREN)) {
          return coordinates;
        }
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<number>} A point.
     * @private
     */
    parsePoint_() {
      const coordinates = [];
      const dimensions = this.layout_.length;
      for (let i = 0; i < dimensions; ++i) {
        const token = this.token_;
        if (this.match(TokenType.NUMBER)) {
          coordinates.push(/** @type {number} */ (token.value));
        } else {
          break;
        }
      }
      if (coordinates.length == dimensions) {
        return coordinates;
      }
      throw new Error(this.formatErrorMessage_());
    }

    /**
     * @return {Array<Array<number>>} An array of points.
     * @private
     */
    parsePointList_() {
      const coordinates = [this.parsePoint_()];
      while (this.match(TokenType.COMMA)) {
        coordinates.push(this.parsePoint_());
      }
      return coordinates;
    }

    /**
     * @return {Array<Array<number>>} An array of points.
     * @private
     */
    parsePointTextList_() {
      const coordinates = [this.parsePointText_()];
      while (this.match(TokenType.COMMA)) {
        coordinates.push(this.parsePointText_());
      }
      return coordinates;
    }

    /**
     * @return {Array<Array<Array<number>>>} An array of points.
     * @private
     */
    parseLineStringTextList_() {
      const coordinates = [this.parseLineStringText_()];
      while (this.match(TokenType.COMMA)) {
        coordinates.push(this.parseLineStringText_());
      }
      return coordinates;
    }

    /**
     * @return {Array<Array<Array<Array<number>>>>} An array of points.
     * @private
     */
    parsePolygonTextList_() {
      const coordinates = [this.parsePolygonText_()];
      while (this.match(TokenType.COMMA)) {
        coordinates.push(this.parsePolygonText_());
      }
      return coordinates;
    }

    /**
     * @return {boolean} Whether the token implies an empty geometry.
     * @private
     */
    isEmptyGeometry_() {
      const isEmpty =
        this.isTokenType(TokenType.TEXT) && this.token_.value == EMPTY;
      if (isEmpty) {
        this.consume_();
      }
      return isEmpty;
    }

    /**
     * Create an error message for an unexpected token error.
     * @return {string} Error message.
     * @private
     */
    formatErrorMessage_() {
      return (
        'Unexpected `' +
        this.token_.value +
        '` at position ' +
        this.token_.position +
        ' in `' +
        this.lexer_.wkt +
        '`'
      );
    }

    /**
     * @return {import("../geom/Geometry.js").default} The geometry.
     * @private
     */
    parseGeometry_() {
      const token = this.token_;
      if (this.match(TokenType.TEXT)) {
        const geomType = /** @type {string} */ (token.value);
        this.layout_ = this.parseGeometryLayout_();
        const isEmpty = this.isEmptyGeometry_();
        if (geomType == 'GEOMETRYCOLLECTION') {
          if (isEmpty) {
            return new GeometryCollection([]);
          }
          const geometries = this.parseGeometryCollectionText_();
          return new GeometryCollection(geometries);
        }
        const ctor = GeometryConstructor[geomType];
        if (!ctor) {
          throw new Error('Invalid geometry type: ' + geomType);
        }

        let coordinates;

        if (isEmpty) {
          if (geomType == 'POINT') {
            coordinates = [NaN, NaN];
          } else {
            coordinates = [];
          }
        } else {
          switch (geomType) {
            case 'POINT': {
              coordinates = this.parsePointText_();
              break;
            }
            case 'LINESTRING': {
              coordinates = this.parseLineStringText_();
              break;
            }
            case 'POLYGON': {
              coordinates = this.parsePolygonText_();
              break;
            }
            case 'MULTIPOINT': {
              coordinates = this.parseMultiPointText_();
              break;
            }
            case 'MULTILINESTRING': {
              coordinates = this.parseMultiLineStringText_();
              break;
            }
            case 'MULTIPOLYGON': {
              coordinates = this.parseMultiPolygonText_();
              break;
            }
          }
        }

        return new ctor(coordinates, this.layout_);
      }
      throw new Error(this.formatErrorMessage_());
    }
  }

  /**
   * @classdesc
   * Geometry format for reading and writing data in the `WellKnownText` (WKT)
   * format.
   *
   * @api
   */
  class WKT extends TextFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * Split GeometryCollection into multiple features.
       * @type {boolean}
       * @private
       */
      this.splitCollection_ =
        options.splitCollection !== undefined ? options.splitCollection : false;
    }

    /**
     * Parse a WKT string.
     * @param {string} wkt WKT string.
     * @return {import("../geom/Geometry.js").default}
     *     The geometry created.
     * @private
     */
    parse_(wkt) {
      const lexer = new Lexer(wkt);
      const parser = new Parser(lexer);
      return parser.parse();
    }

    /**
     * @protected
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @return {import("../Feature.js").default} Feature.
     * @override
     */
    readFeatureFromText(text, options) {
      const geom = this.readGeometryFromText(text, options);
      const feature = new Feature();
      feature.setGeometry(geom);
      return feature;
    }

    /**
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {Array<Feature>} Features.
     * @override
     */
    readFeaturesFromText(text, options) {
      let geometries = [];
      const geometry = this.readGeometryFromText(text, options);
      if (this.splitCollection_ && geometry.getType() == 'GeometryCollection') {
        geometries = /** @type {GeometryCollection} */ (
          geometry
        ).getGeometriesArray();
      } else {
        geometries = [geometry];
      }
      const features = [];
      for (let i = 0, ii = geometries.length; i < ii; ++i) {
        const feature = new Feature();
        feature.setGeometry(geometries[i]);
        features.push(feature);
      }
      return features;
    }

    /**
     * @param {string} text Text.
     * @param {import("./Feature.js").ReadOptions} [options] Read options.
     * @protected
     * @return {import("../geom/Geometry.js").default} Geometry.
     * @override
     */
    readGeometryFromText(text, options) {
      const geometry = this.parse_(text);
      return transformGeometryWithOptions(geometry, false, options);
    }

    /**
     * @param {import("../Feature.js").default} feature Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeFeatureText(feature, options) {
      const geometry = feature.getGeometry();
      if (geometry) {
        return this.writeGeometryText(geometry, options);
      }
      return '';
    }

    /**
     * @param {Array<import("../Feature.js").default>} features Features.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeFeaturesText(features, options) {
      if (features.length == 1) {
        return this.writeFeatureText(features[0], options);
      }
      const geometries = [];
      for (let i = 0, ii = features.length; i < ii; ++i) {
        geometries.push(features[i].getGeometry());
      }
      const collection = new GeometryCollection(geometries);
      return this.writeGeometryText(collection, options);
    }

    /**
     * @param {import("../geom/Geometry.js").default} geometry Geometry.
     * @param {import("./Feature.js").WriteOptions} [options] Write options.
     * @protected
     * @return {string} Text.
     * @override
     */
    writeGeometryText(geometry, options) {
      return encode(transformGeometryWithOptions(geometry, true, options));
    }
  }

  /**
   * @param {Point} geom Point geometry.
   * @return {string} Coordinates part of Point as WKT.
   */
  function encodePointGeometry(geom) {
    const coordinates = geom.getCoordinates();
    if (coordinates.length === 0) {
      return '';
    }
    return coordinates.join(' ');
  }

  /**
   * @param {MultiPoint} geom MultiPoint geometry.
   * @return {string} Coordinates part of MultiPoint as WKT.
   */
  function encodeMultiPointGeometry(geom) {
    const array = [];
    const components = geom.getPoints();
    for (let i = 0, ii = components.length; i < ii; ++i) {
      array.push('(' + encodePointGeometry(components[i]) + ')');
    }
    return array.join(',');
  }

  /**
   * @param {GeometryCollection} geom GeometryCollection geometry.
   * @return {string} Coordinates part of GeometryCollection as WKT.
   */
  function encodeGeometryCollectionGeometry(geom) {
    const array = [];
    const geoms = geom.getGeometries();
    for (let i = 0, ii = geoms.length; i < ii; ++i) {
      array.push(encode(geoms[i]));
    }
    return array.join(',');
  }

  /**
   * @param {LineString|import("../geom/LinearRing.js").default} geom LineString geometry.
   * @return {string} Coordinates part of LineString as WKT.
   */
  function encodeLineStringGeometry(geom) {
    const coordinates = geom.getCoordinates();
    const array = [];
    for (let i = 0, ii = coordinates.length; i < ii; ++i) {
      array.push(coordinates[i].join(' '));
    }
    return array.join(',');
  }

  /**
   * @param {MultiLineString} geom MultiLineString geometry.
   * @return {string} Coordinates part of MultiLineString as WKT.
   */
  function encodeMultiLineStringGeometry(geom) {
    const array = [];
    const components = geom.getLineStrings();
    for (let i = 0, ii = components.length; i < ii; ++i) {
      array.push('(' + encodeLineStringGeometry(components[i]) + ')');
    }
    return array.join(',');
  }

  /**
   * @param {Polygon} geom Polygon geometry.
   * @return {string} Coordinates part of Polygon as WKT.
   */
  function encodePolygonGeometry(geom) {
    const array = [];
    const rings = geom.getLinearRings();
    for (let i = 0, ii = rings.length; i < ii; ++i) {
      array.push('(' + encodeLineStringGeometry(rings[i]) + ')');
    }
    return array.join(',');
  }

  /**
   * @param {MultiPolygon} geom MultiPolygon geometry.
   * @return {string} Coordinates part of MultiPolygon as WKT.
   */
  function encodeMultiPolygonGeometry(geom) {
    const array = [];
    const components = geom.getPolygons();
    for (let i = 0, ii = components.length; i < ii; ++i) {
      array.push('(' + encodePolygonGeometry(components[i]) + ')');
    }
    return array.join(',');
  }

  /**
   * @param {import("../geom/SimpleGeometry.js").default} geom SimpleGeometry geometry.
   * @return {string} Potential dimensional information for WKT type.
   */
  function encodeGeometryLayout(geom) {
    const layout = geom.getLayout();
    let dimInfo = '';
    if (layout === 'XYZ' || layout === 'XYZM') {
      dimInfo += Z;
    }
    if (layout === 'XYM' || layout === 'XYZM') {
      dimInfo += M;
    }
    return dimInfo;
  }

  /**
   * @const
   * @type {Object<string, function(import("../geom/Geometry.js").default): string>}
   */
  const GeometryEncoder = {
    'Point': encodePointGeometry,
    'LineString': encodeLineStringGeometry,
    'Polygon': encodePolygonGeometry,
    'MultiPoint': encodeMultiPointGeometry,
    'MultiLineString': encodeMultiLineStringGeometry,
    'MultiPolygon': encodeMultiPolygonGeometry,
    'GeometryCollection': encodeGeometryCollectionGeometry,
  };

  /**
   * Encode a geometry as WKT.
   * @param {import("../geom/Geometry.js").default} geom The geometry to encode.
   * @return {string} WKT string for the geometry.
   */
  function encode(geom) {
    const type = geom.getType();
    const geometryEncoder = GeometryEncoder[type];
    const enc = geometryEncoder(geom);
    let wktType = wktTypeLookup[type];
    if (typeof (/** @type {?} */ (geom).getFlatCoordinates) === 'function') {
      const dimInfo = encodeGeometryLayout(
        /** @type {import("../geom/SimpleGeometry.js").default} */ (geom),
      );
      if (dimInfo.length > 0) {
        wktType += ' ' + dimInfo;
      }
    }
    if (enc.length === 0) {
      return wktType + ' ' + EMPTY;
    }
    return wktType + '(' + enc + ')';
  }

  /**
   * @module ol/format/WMSCapabilities
   */

  /**
   * @const
   * @type {Array<null|string>}
   */
  const NAMESPACE_URIS$1 = [
    null,
    'http://www.opengis.net/wms',
    'http://www.opengis.net/sld',
  ];

  function isV13(objectStack) {
    return compareVersions(objectStack[0].version, '1.3') >= 0;
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PARSERS$1 = makeStructureNS(NAMESPACE_URIS$1, {
    'Service': makeObjectPropertySetter(readService),
    'Capability': makeObjectPropertySetter(readCapability),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CAPABILITY_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Request': makeObjectPropertySetter(readRequest),
    'Exception': makeObjectPropertySetter(readException),
    'Layer': makeObjectPropertySetter(readCapabilityLayer),
    'UserDefinedSymbolization': makeObjectPropertySetter(
      readUserDefinedSymbolization,
    ),
  });

  /**
   * @typedef {Object} RootObject
   * @property {string} version Version
   * @property {boolean} v13 Whether version is 1.3 or higher
   */

  /**
   * @classdesc
   * Format for reading WMS capabilities data
   *
   * @api
   */
  class WMSCapabilities extends XML {
    constructor() {
      super();

      /**
       * @type {string|undefined}
       */
      this.version = undefined;
    }

    /**
     * @param {Element} node Node.
     * @return {Object|null} Object
     * @override
     */
    readFromNode(node) {
      this.version = node.getAttribute('version').trim();
      const wmsCapabilityObject = pushParseAndPop(
        {
          'version': this.version,
        },
        PARSERS$1,
        node,
        [],
      );
      return wmsCapabilityObject ? wmsCapabilityObject : null;
    }
  }

  const COMMON_SERVICE_PARSERS = {
    'Name': makeObjectPropertySetter(readString),
    'Title': makeObjectPropertySetter(readString),
    'Abstract': makeObjectPropertySetter(readString),
    'KeywordList': makeObjectPropertySetter(readKeywordList),
    'OnlineResource': makeObjectPropertySetter(readHref),
    'ContactInformation': makeObjectPropertySetter(readContactInformation),
    'Fees': makeObjectPropertySetter(readString),
    'AccessConstraints': makeObjectPropertySetter(readString),
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SERVICE_PARSERS = makeStructureNS(NAMESPACE_URIS$1, COMMON_SERVICE_PARSERS);

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const SERVICE_PARSERS_V13 = makeStructureNS(NAMESPACE_URIS$1, {
    ...COMMON_SERVICE_PARSERS,
    'LayerLimit': makeObjectPropertySetter(readPositiveInteger),
    'MaxWidth': makeObjectPropertySetter(readPositiveInteger),
    'MaxHeight': makeObjectPropertySetter(readPositiveInteger),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONTACT_INFORMATION_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'ContactPersonPrimary': makeObjectPropertySetter(readContactPersonPrimary),
    'ContactPosition': makeObjectPropertySetter(readString),
    'ContactAddress': makeObjectPropertySetter(readContactAddress),
    'ContactVoiceTelephone': makeObjectPropertySetter(readString),
    'ContactFacsimileTelephone': makeObjectPropertySetter(readString),
    'ContactElectronicMailAddress': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONTACT_PERSON_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'ContactPerson': makeObjectPropertySetter(readString),
    'ContactOrganization': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONTACT_ADDRESS_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'AddressType': makeObjectPropertySetter(readString),
    'Address': makeObjectPropertySetter(readString),
    'City': makeObjectPropertySetter(readString),
    'StateOrProvince': makeObjectPropertySetter(readString),
    'PostCode': makeObjectPropertySetter(readString),
    'Country': makeObjectPropertySetter(readString),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const EXCEPTION_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Format': makeArrayPusher(readString),
  });

  const COMMON_LAYER_PARSERS = {
    'Name': makeObjectPropertySetter(readString),
    'Title': makeObjectPropertySetter(readString),
    'Abstract': makeObjectPropertySetter(readString),
    'KeywordList': makeObjectPropertySetter(readKeywordList),
    'BoundingBox': makeObjectPropertyPusher(readBoundingBox$1),
    'Dimension': makeObjectPropertyPusher(readDimension),
    'Attribution': makeObjectPropertySetter(readAttribution),
    'AuthorityURL': makeObjectPropertyPusher(readAuthorityURL),
    'Identifier': makeObjectPropertyPusher(readString),
    'MetadataURL': makeObjectPropertyPusher(readMetadataURL),
    'DataURL': makeObjectPropertyPusher(readFormatOnlineresource),
    'FeatureListURL': makeObjectPropertyPusher(readFormatOnlineresource),
    'Style': makeObjectPropertyPusher(readStyle$1),
    'Layer': makeObjectPropertyPusher(readLayer$1),
  };

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LAYER_PARSERS$1 = makeStructureNS(NAMESPACE_URIS$1, {
    ...COMMON_LAYER_PARSERS,
    'SRS': makeObjectPropertyPusher(readString),
    'Extent': makeObjectPropertySetter(readExtent),
    'ScaleHint': makeObjectPropertyPusher(readScaleHint),
    'LatLonBoundingBox': makeObjectPropertySetter((node, objectStack) =>
      readBoundingBox$1(node, objectStack, false),
    ),
    'Layer': makeObjectPropertyPusher(readLayer$1),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LAYER_PARSERS_V13 = makeStructureNS(NAMESPACE_URIS$1, {
    ...COMMON_LAYER_PARSERS,
    'CRS': makeObjectPropertyPusher(readString),
    'EX_GeographicBoundingBox': makeObjectPropertySetter(
      readEXGeographicBoundingBox,
    ),
    'MinScaleDenominator': makeObjectPropertySetter(readDecimal),
    'MaxScaleDenominator': makeObjectPropertySetter(readDecimal),
    'Layer': makeObjectPropertyPusher(readLayer$1),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const ATTRIBUTION_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Title': makeObjectPropertySetter(readString),
    'OnlineResource': makeObjectPropertySetter(readHref),
    'LogoURL': makeObjectPropertySetter(readSizedFormatOnlineresource),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'westBoundLongitude': makeObjectPropertySetter(readDecimal),
    'eastBoundLongitude': makeObjectPropertySetter(readDecimal),
    'southBoundLatitude': makeObjectPropertySetter(readDecimal),
    'northBoundLatitude': makeObjectPropertySetter(readDecimal),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const REQUEST_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'GetCapabilities': makeObjectPropertySetter(readOperationType),
    'GetMap': makeObjectPropertySetter(readOperationType),
    'GetFeatureInfo': makeObjectPropertySetter(readOperationType),
    'DescribeLayer': makeObjectPropertySetter(readOperationType),
    'GetLegendGraphic': makeObjectPropertySetter(readOperationType),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const OPERATIONTYPE_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Format': makeObjectPropertyPusher(readString),
    'DCPType': makeObjectPropertyPusher(readDCPType),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const DCPTYPE_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'HTTP': makeObjectPropertySetter(readHTTP),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const HTTP_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Get': makeObjectPropertySetter(readFormatOnlineresource),
    'Post': makeObjectPropertySetter(readFormatOnlineresource),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const STYLE_PARSERS$1 = makeStructureNS(NAMESPACE_URIS$1, {
    'Name': makeObjectPropertySetter(readString),
    'Title': makeObjectPropertySetter(readString),
    'Abstract': makeObjectPropertySetter(readString),
    'LegendURL': makeObjectPropertyPusher(readSizedFormatOnlineresource),
    'StyleSheetURL': makeObjectPropertySetter(readFormatOnlineresource),
    'StyleURL': makeObjectPropertySetter(readFormatOnlineresource),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const FORMAT_ONLINERESOURCE_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Format': makeObjectPropertySetter(readString),
    'OnlineResource': makeObjectPropertySetter(readHref),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const KEYWORDLIST_PARSERS = makeStructureNS(NAMESPACE_URIS$1, {
    'Keyword': makeArrayPusher(readString),
  });

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Attribution object.
   */
  function readAttribution(node, objectStack) {
    return pushParseAndPop({}, ATTRIBUTION_PARSERS, node, objectStack);
  }

  function readUserDefinedSymbolization(node, objectStack) {
    return {
      'SupportSLD': !!readBooleanString(node.getAttribute('SupportSLD')),
      'UserLayer': !!readBooleanString(node.getAttribute('UserLayer')),
      'UserStyle': !!readBooleanString(node.getAttribute('UserStyle')),
      'RemoteWFS': !!readBooleanString(node.getAttribute('RemoteWFS')),
      'InlineFeatureData': !!readBooleanString(
        node.getAttribute('InlineFeatureData'),
      ),
      'RemoteWCS': !!readBooleanString(node.getAttribute('RemoteWCS')),
    };
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @param {boolean} withCrs Whether to include the CRS attribute.
   * @return {Object} Bounding box object.
   */
  function readBoundingBox$1(node, objectStack, withCrs = true) {
    const extent = [
      readDecimalString(node.getAttribute('minx')),
      readDecimalString(node.getAttribute('miny')),
      readDecimalString(node.getAttribute('maxx')),
      readDecimalString(node.getAttribute('maxy')),
    ];

    const resolutions = [
      readDecimalString(node.getAttribute('resx')),
      readDecimalString(node.getAttribute('resy')),
    ];

    const result = {
      extent,
      res: resolutions,
    };
    if (!withCrs) {
      return result;
    }

    /** @type {RootObject} */
    if (isV13(objectStack)) {
      result.crs = node.getAttribute('CRS');
    } else {
      result.srs = node.getAttribute('SRS');
    }

    return result;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {import("../extent.js").Extent|undefined} Bounding box object.
   */
  function readEXGeographicBoundingBox(node, objectStack) {
    const geographicBoundingBox = pushParseAndPop(
      {},
      EX_GEOGRAPHIC_BOUNDING_BOX_PARSERS,
      node,
      objectStack,
    );
    if (!geographicBoundingBox) {
      return undefined;
    }
    const westBoundLongitude =
      /** @type {number|undefined} */
      (geographicBoundingBox['westBoundLongitude']);
    const southBoundLatitude =
      /** @type {number|undefined} */
      (geographicBoundingBox['southBoundLatitude']);
    const eastBoundLongitude =
      /** @type {number|undefined} */
      (geographicBoundingBox['eastBoundLongitude']);
    const northBoundLatitude =
      /** @type {number|undefined} */
      (geographicBoundingBox['northBoundLatitude']);
    if (
      westBoundLongitude === undefined ||
      southBoundLatitude === undefined ||
      eastBoundLongitude === undefined ||
      northBoundLatitude === undefined
    ) {
      return undefined;
    }
    return [
      westBoundLongitude,
      southBoundLatitude,
      eastBoundLongitude,
      northBoundLatitude,
    ];
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Capability object.
   */
  //ts-ignore
  function readCapability(node, objectStack) {
    return pushParseAndPop({}, CAPABILITY_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Service object.
   */
  function readService(node, objectStack) {
    return pushParseAndPop(
      {},
      isV13(objectStack) ? SERVICE_PARSERS_V13 : SERVICE_PARSERS,
      node,
      objectStack,
    );
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Contact information object.
   */
  function readContactInformation(node, objectStack) {
    return pushParseAndPop({}, CONTACT_INFORMATION_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Contact person object.
   */
  function readContactPersonPrimary(node, objectStack) {
    return pushParseAndPop({}, CONTACT_PERSON_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Contact address object.
   */
  function readContactAddress(node, objectStack) {
    return pushParseAndPop({}, CONTACT_ADDRESS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<string>|undefined} Format array.
   */
  function readException(node, objectStack) {
    return pushParseAndPop([], EXCEPTION_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Layer object.
   */
  function readCapabilityLayer(node, objectStack) {
    const layerObject = pushParseAndPop(
      {},
      isV13(objectStack) ? LAYER_PARSERS_V13 : LAYER_PARSERS$1,
      node,
      objectStack,
    );

    if (layerObject['Layer'] === undefined) {
      return Object.assign(layerObject, readLayer$1(node, objectStack));
    }

    return layerObject;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Layer object.
   */
  function readLayer$1(node, objectStack) {
    const v13 = isV13(objectStack);

    const parentLayerObject = /**  @type {!Object<string,*>} */ (
      objectStack[objectStack.length - 1]
    );

    const layerObject = pushParseAndPop(
      {},
      v13 ? LAYER_PARSERS_V13 : LAYER_PARSERS$1,
      node,
      objectStack,
    );

    if (!layerObject) {
      return undefined;
    }
    let queryable = readBooleanString(node.getAttribute('queryable'));
    if (queryable === undefined) {
      queryable = parentLayerObject['queryable'];
    }
    layerObject['queryable'] = queryable !== undefined ? queryable : false;

    let cascaded = readNonNegativeIntegerString(node.getAttribute('cascaded'));
    if (cascaded === undefined) {
      cascaded = parentLayerObject['cascaded'];
    }
    layerObject['cascaded'] = cascaded;

    let opaque = readBooleanString(node.getAttribute('opaque'));
    if (opaque === undefined) {
      opaque = parentLayerObject['opaque'];
    }
    layerObject['opaque'] = opaque !== undefined ? opaque : false;

    let noSubsets = readBooleanString(node.getAttribute('noSubsets'));
    if (noSubsets === undefined) {
      noSubsets = parentLayerObject['noSubsets'];
    }
    layerObject['noSubsets'] = noSubsets !== undefined ? noSubsets : false;

    let fixedWidth = readDecimalString(node.getAttribute('fixedWidth'));
    if (!fixedWidth) {
      fixedWidth = parentLayerObject['fixedWidth'];
    }
    layerObject['fixedWidth'] = fixedWidth;

    let fixedHeight = readDecimalString(node.getAttribute('fixedHeight'));
    if (!fixedHeight) {
      fixedHeight = parentLayerObject['fixedHeight'];
    }
    layerObject['fixedHeight'] = fixedHeight;

    // See 7.2.4.8
    const addKeys = ['Style', 'AuthorityURL'];
    if (v13) {
      addKeys.push('CRS');
    } else {
      addKeys.push('SRS', 'Dimension');
    }
    addKeys.forEach(function (key) {
      if (key in parentLayerObject) {
        const childValue = layerObject[key] || [];
        layerObject[key] = childValue.concat(parentLayerObject[key]);
      }
    });

    const replaceKeys = ['BoundingBox', 'Attribution'];
    if (v13) {
      replaceKeys.push(
        'Dimension',
        'EX_GeographicBoundingBox',
        'MinScaleDenominator',
        'MaxScaleDenominator',
      );
    } else {
      replaceKeys.push('LatLonBoundingBox', 'ScaleHint', 'Extent');
    }
    replaceKeys.forEach(function (key) {
      if (!(key in layerObject)) {
        const parentValue = parentLayerObject[key];
        layerObject[key] = parentValue;
      }
    });

    return layerObject;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object} Dimension object.
   */
  function readDimension(node, objectStack) {
    const dimensionObject = {
      'name': node.getAttribute('name'),
      'units': node.getAttribute('units'),
      'unitSymbol': node.getAttribute('unitSymbol'),
    };

    if (isV13(objectStack)) {
      Object.assign(dimensionObject, {
        'default': node.getAttribute('default'),
        'multipleValues': readBooleanString(node.getAttribute('multipleValues')),
        'nearestValue': readBooleanString(node.getAttribute('nearestValue')),
        'current': readBooleanString(node.getAttribute('current')),
        'values': readString(node),
      });
    }
    return dimensionObject;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object} Extent object.
   */
  function readExtent(node, objectStack) {
    return {
      'name': node.getAttribute('name'),
      'default': node.getAttribute('default'),
      'nearestValue': readBooleanString(node.getAttribute('nearestValue')),
    };
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object} ScaleHint object.
   */
  function readScaleHint(node, objectStack) {
    return {
      'min': readDecimalString(node.getAttribute('min')),
      'max': readDecimalString(node.getAttribute('max')),
    };
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Online resource object.
   */
  function readFormatOnlineresource(node, objectStack) {
    return pushParseAndPop({}, FORMAT_ONLINERESOURCE_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Request object.
   */
  function readRequest(node, objectStack) {
    return pushParseAndPop({}, REQUEST_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} DCP type object.
   */
  function readDCPType(node, objectStack) {
    return pushParseAndPop({}, DCPTYPE_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} HTTP object.
   */
  function readHTTP(node, objectStack) {
    return pushParseAndPop({}, HTTP_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Operation type object.
   */
  function readOperationType(node, objectStack) {
    return pushParseAndPop({}, OPERATIONTYPE_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Online resource object.
   */
  function readSizedFormatOnlineresource(node, objectStack) {
    const formatOnlineresource = readFormatOnlineresource(node, objectStack);
    if (formatOnlineresource) {
      const size = [
        readNonNegativeIntegerString(node.getAttribute('width')),
        readNonNegativeIntegerString(node.getAttribute('height')),
      ];
      formatOnlineresource['size'] = size;
      return formatOnlineresource;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Authority URL object.
   */
  function readAuthorityURL(node, objectStack) {
    const authorityObject = readFormatOnlineresource(node, objectStack);
    if (authorityObject) {
      authorityObject['name'] = node.getAttribute('name');
      return authorityObject;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Metadata URL object.
   */
  function readMetadataURL(node, objectStack) {
    const metadataObject = readFormatOnlineresource(node, objectStack);
    if (metadataObject) {
      metadataObject['type'] = node.getAttribute('type');
      return metadataObject;
    }
    return undefined;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Style object.
   */
  function readStyle$1(node, objectStack) {
    return pushParseAndPop({}, STYLE_PARSERS$1, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Array<string>|undefined} Keyword list.
   */
  function readKeywordList(node, objectStack) {
    return pushParseAndPop([], KEYWORDLIST_PARSERS, node, objectStack);
  }

  /**
   * @module ol/format/WMSGetFeatureInfo
   */

  /**
   * @typedef {Object} Options
   * @property {Array<string>} [layers] If set, only features of the given layers will be returned by the format when read.
   */

  /**
   * @const
   * @type {string}
   */
  const featureIdentifier = '_feature';

  /**
   * @const
   * @type {string}
   */
  const layerIdentifier = '_layer';

  /**
   * @classdesc
   * Format for reading WMSGetFeatureInfo format. It uses
   * {@link module:ol/format/GML2~GML2} to read features.
   *
   * @api
   */
  class WMSGetFeatureInfo extends XMLFeature {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      options = options ? options : {};

      /**
       * @private
       * @type {string}
       */
      this.featureNS_ = 'http://mapserver.gis.umn.edu/mapserver';

      /**
       * @private
       * @type {GML2}
       */
      this.gmlFormat_ = new GML2();

      /**
       * @private
       * @type {Array<string>|null}
       */
      this.layers_ = options.layers ? options.layers : null;
    }

    /**
     * @return {Array<string>|null} layers
     */
    getLayers() {
      return this.layers_;
    }

    /**
     * @param {Array<string>|null} layers Layers to parse.
     */
    setLayers(layers) {
      this.layers_ = layers;
    }

    /**
     * @param {Element} node Node.
     * @param {Array<*>} objectStack Object stack.
     * @return {Array<import("../Feature.js").default>} Features.
     * @private
     */
    readFeatures_(node, objectStack) {
      node.setAttribute('namespaceURI', this.featureNS_);
      const localName = node.localName;
      /** @type {Array<import("../Feature.js").default>} */
      let features = [];
      if (node.childNodes.length === 0) {
        return features;
      }
      if (localName == 'msGMLOutput') {
        for (let i = 0, ii = node.childNodes.length; i < ii; i++) {
          const layer = node.childNodes[i];
          if (layer.nodeType !== Node.ELEMENT_NODE) {
            continue;
          }

          const layerElement = /** @type {Element} */ (layer);
          const context = objectStack[0];

          const toRemove = layerIdentifier;
          const layerName = layerElement.localName.replace(toRemove, '');

          if (this.layers_ && !this.layers_.includes(layerName)) {
            continue;
          }

          const featureType = layerName + featureIdentifier;

          context['featureType'] = featureType;
          context['featureNS'] = this.featureNS_;

          /** @type {Object<string, import("../xml.js").Parser>} */
          const parsers = {};
          parsers[featureType] = makeArrayPusher(
            this.gmlFormat_.readFeatureElement,
            this.gmlFormat_,
          );
          const parsersNS = makeStructureNS(
            [context['featureNS'], null],
            parsers,
          );
          layerElement.setAttribute('namespaceURI', this.featureNS_);
          const layerFeatures = pushParseAndPop(
            [],
            // @ts-ignore
            parsersNS,
            layerElement,
            objectStack,
            this.gmlFormat_,
          );
          if (layerFeatures) {
            extend$2(features, layerFeatures);
          }
        }
      }
      if (localName == 'FeatureCollection') {
        const gmlFeatures = pushParseAndPop(
          [],
          this.gmlFormat_.FEATURE_COLLECTION_PARSERS,
          node,
          [{}],
          this.gmlFormat_,
        );
        if (gmlFeatures) {
          features = gmlFeatures;
        }
      }
      return features;
    }

    /**
     * @protected
     * @param {Element} node Node.
     * @param {import("./Feature.js").ReadOptions} [options] Options.
     * @return {Array<import("../Feature.js").default>} Features.
     * @override
     */
    readFeaturesFromNode(node, options) {
      const internalOptions = {};
      if (options) {
        Object.assign(internalOptions, this.getReadOptions(node, options));
      }
      return this.readFeatures_(node, [internalOptions]);
    }
  }

  /**
   * @module ol/format/WMTSCapabilities
   */

  /**
   * @const
   * @type {Array<null|string>}
   */
  const NAMESPACE_URIS = [null, 'http://www.opengis.net/wmts/1.0'];

  /**
   * @const
   * @type {Array<null|string>}
   */
  const OWS_NAMESPACE_URIS = [null, 'http://www.opengis.net/ows/1.1'];

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const PARSERS = makeStructureNS(NAMESPACE_URIS, {
    'Contents': makeObjectPropertySetter(readContents),
  });

  /**
   * @classdesc
   * Format for reading WMTS capabilities data.
   *
   * @api
   */
  class WMTSCapabilities extends XML {
    constructor() {
      super();

      /**
       * @type {OWS}
       * @private
       */
      this.owsParser_ = new OWS();
    }

    /**
     * @param {Element} node Node.
     * @return {Object|null} Object
     * @override
     */
    readFromNode(node) {
      let version = node.getAttribute('version');
      if (version) {
        version = version.trim();
      }
      let WMTSCapabilityObject = this.owsParser_.readFromNode(node);
      if (!WMTSCapabilityObject) {
        return null;
      }
      WMTSCapabilityObject['version'] = version;
      WMTSCapabilityObject = pushParseAndPop(
        WMTSCapabilityObject,
        PARSERS,
        node,
        [],
      );
      return WMTSCapabilityObject ? WMTSCapabilityObject : null;
    }
  }

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const CONTENTS_PARSERS = makeStructureNS(NAMESPACE_URIS, {
    'Layer': makeObjectPropertyPusher(readLayer),
    'TileMatrixSet': makeObjectPropertyPusher(readTileMatrixSet),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const LAYER_PARSERS = makeStructureNS(
    NAMESPACE_URIS,
    {
      'Style': makeObjectPropertyPusher(readStyle),
      'Format': makeObjectPropertyPusher(readString),
      'TileMatrixSetLink': makeObjectPropertyPusher(readTileMatrixSetLink),
      'Dimension': makeObjectPropertyPusher(readDimensions),
      'ResourceURL': makeObjectPropertyPusher(readResourceUrl),
    },
    makeStructureNS(OWS_NAMESPACE_URIS, {
      'Title': makeObjectPropertySetter(readString),
      'Abstract': makeObjectPropertySetter(readString),
      'WGS84BoundingBox': makeObjectPropertySetter(readBoundingBox),
      'BoundingBox': makeObjectPropertyPusher(readBoundingBoxWithCrs),
      'Identifier': makeObjectPropertySetter(readString),
    }),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const STYLE_PARSERS = makeStructureNS(
    NAMESPACE_URIS,
    {
      'LegendURL': makeObjectPropertyPusher(readLegendUrl),
    },
    makeStructureNS(OWS_NAMESPACE_URIS, {
      'Title': makeObjectPropertySetter(readString),
      'Identifier': makeObjectPropertySetter(readString),
    }),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TMS_LINKS_PARSERS = makeStructureNS(NAMESPACE_URIS, {
    'TileMatrixSet': makeObjectPropertySetter(readString),
    'TileMatrixSetLimits': makeObjectPropertySetter(readTileMatrixLimitsList),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TMS_LIMITS_LIST_PARSERS = makeStructureNS(NAMESPACE_URIS, {
    'TileMatrixLimits': makeArrayPusher(readTileMatrixLimits),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TMS_LIMITS_PARSERS = makeStructureNS(NAMESPACE_URIS, {
    'TileMatrix': makeObjectPropertySetter(readString),
    'MinTileRow': makeObjectPropertySetter(readPositiveInteger),
    'MaxTileRow': makeObjectPropertySetter(readPositiveInteger),
    'MinTileCol': makeObjectPropertySetter(readPositiveInteger),
    'MaxTileCol': makeObjectPropertySetter(readPositiveInteger),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const DIMENSION_PARSERS = makeStructureNS(
    NAMESPACE_URIS,
    {
      'Default': makeObjectPropertySetter(readString),
      'Value': makeObjectPropertyPusher(readString),
    },
    makeStructureNS(OWS_NAMESPACE_URIS, {
      'Identifier': makeObjectPropertySetter(readString),
    }),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const WGS84_BBOX_READERS = makeStructureNS(OWS_NAMESPACE_URIS, {
    'LowerCorner': makeArrayPusher(readCoordinates),
    'UpperCorner': makeArrayPusher(readCoordinates),
  });

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TMS_PARSERS = makeStructureNS(
    NAMESPACE_URIS,
    {
      'WellKnownScaleSet': makeObjectPropertySetter(readString),
      'TileMatrix': makeObjectPropertyPusher(readTileMatrix),
    },
    makeStructureNS(OWS_NAMESPACE_URIS, {
      'SupportedCRS': makeObjectPropertySetter(readString),
      'Identifier': makeObjectPropertySetter(readString),
      'BoundingBox': makeObjectPropertySetter(readBoundingBox),
    }),
  );

  /**
   * @const
   * @type {Object<string, Object<string, import("../xml.js").Parser>>}
   */
  // @ts-ignore
  const TM_PARSERS = makeStructureNS(
    NAMESPACE_URIS,
    {
      'TopLeftCorner': makeObjectPropertySetter(readCoordinates),
      'ScaleDenominator': makeObjectPropertySetter(readDecimal),
      'TileWidth': makeObjectPropertySetter(readPositiveInteger),
      'TileHeight': makeObjectPropertySetter(readPositiveInteger),
      'MatrixWidth': makeObjectPropertySetter(readPositiveInteger),
      'MatrixHeight': makeObjectPropertySetter(readPositiveInteger),
    },
    makeStructureNS(OWS_NAMESPACE_URIS, {
      'Identifier': makeObjectPropertySetter(readString),
    }),
  );

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Attribution object.
   */
  function readContents(node, objectStack) {
    return pushParseAndPop({}, CONTENTS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Layers object.
   */
  function readLayer(node, objectStack) {
    return pushParseAndPop({}, LAYER_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Tile Matrix Set object.
   */
  function readTileMatrixSet(node, objectStack) {
    return pushParseAndPop({}, TMS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Style object.
   */
  function readStyle(node, objectStack) {
    const style = pushParseAndPop({}, STYLE_PARSERS, node, objectStack);
    if (!style) {
      return undefined;
    }
    const isDefault = node.getAttribute('isDefault') === 'true';
    style['isDefault'] = isDefault;
    return style;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Tile Matrix Set Link object.
   */
  function readTileMatrixSetLink(node, objectStack) {
    return pushParseAndPop({}, TMS_LINKS_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Dimension object.
   */
  function readDimensions(node, objectStack) {
    return pushParseAndPop({}, DIMENSION_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Resource URL object.
   */
  function readResourceUrl(node, objectStack) {
    const format = node.getAttribute('format');
    const template = node.getAttribute('template');
    const resourceType = node.getAttribute('resourceType');
    const resource = {};
    if (format) {
      resource['format'] = format;
    }
    if (template) {
      resource['template'] = template;
    }
    if (resourceType) {
      resource['resourceType'] = resourceType;
    }
    return resource;
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} BBox object.
   */
  function readBoundingBox(node, objectStack) {
    const coordinates = pushParseAndPop(
      [],
      WGS84_BBOX_READERS,
      node,
      objectStack,
    );
    if (coordinates.length != 2) {
      return undefined;
    }
    return boundingExtent(coordinates);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} BBox object.
   */
  function readBoundingBoxWithCrs(node, objectStack) {
    const crs = node.getAttribute('crs');
    const coordinates = pushParseAndPop(
      [],
      WGS84_BBOX_READERS,
      node,
      objectStack,
    );
    if (coordinates.length != 2) {
      return undefined;
    }
    return {extent: boundingExtent(coordinates), crs: crs};
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Legend object.
   */
  function readLegendUrl(node, objectStack) {
    const legend = {};
    legend['format'] = node.getAttribute('format');
    legend['href'] = readHref(node);
    return legend;
  }

  /**
   * @param {Node} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} Coordinates object.
   */
  function readCoordinates(node, objectStack) {
    const coordinates = readString(node).split(/\s+/);
    if (!coordinates || coordinates.length != 2) {
      return undefined;
    }
    const x = +coordinates[0];
    const y = +coordinates[1];
    if (isNaN(x) || isNaN(y)) {
      return undefined;
    }
    return [x, y];
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} TileMatrix object.
   */
  function readTileMatrix(node, objectStack) {
    return pushParseAndPop({}, TM_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} TileMatrixSetLimits Object.
   */
  function readTileMatrixLimitsList(node, objectStack) {
    return pushParseAndPop([], TMS_LIMITS_LIST_PARSERS, node, objectStack);
  }

  /**
   * @param {Element} node Node.
   * @param {Array<*>} objectStack Object stack.
   * @return {Object|undefined} TileMatrixLimits Array.
   */
  function readTileMatrixLimits(node, objectStack) {
    return pushParseAndPop({}, TMS_LIMITS_PARSERS, node, objectStack);
  }

  /**
   * @module ol/interaction/DblClickDragZoom
   */

  /**
   * @typedef {Object} Options
   * @property {number} [duration=400] Animation duration in milliseconds. *
   * @property {number} [delta=1] The zoom delta applied on move of one pixel. *
   * @property {function(boolean):boolean} [stopDown]
   * Should the down event be propagated to other interactions, or should be
   * stopped?
   */

  /**
   * @classdesc
   * Allows the user to zoom the map by double tap/click then drag up/down
   * with one finger/left mouse.
   * @api
   */
  class DblClickDragZoom extends Interaction {
    /**
     * @param {Options} [opt_options] Options.
     */
    constructor(opt_options) {
      const options = opt_options ? opt_options : {};

      super(
        /** @type {import("./Interaction.js").InteractionOptions} */ (options),
      );

      if (options.stopDown) {
        this.stopDown = options.stopDown;
      }

      /**
       * @private
       * @type {number}
       */
      this.scaleDeltaByPixel_ = options.delta ? options.delta : 0.01;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 250;

      /**
       * @type {boolean}
       * @private
       */
      this.handlingDownUpSequence_ = false;

      /**
       * @type {boolean}
       * @private
       */
      this.handlingDoubleDownSequence_ = false;

      /**
       * @type {ReturnType<typeof setTimeout>}
       * @private
       */
      this.doubleTapTimeoutId_ = undefined;

      /**
       * @type {!Object<string, PointerEvent>}
       * @private
       */
      this.trackedPointers_ = {};

      /**
       * @type {PointerEvent|null}
       * @private
       */
      this.down_ = null;

      /**
       * @type {Array<PointerEvent>}
       * @protected
       */
      this.targetPointers = [];
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent  map browser event} and may call into
     * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are
     * detected.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!mapBrowserEvent.originalEvent) {
        return true;
      }

      let stopEvent = false;
      this.updateTrackedPointers_(mapBrowserEvent);
      if (this.handlingDownUpSequence_) {
        if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) {
          this.handleDragEvent(mapBrowserEvent);
          // prevent page scrolling during dragging
          mapBrowserEvent.originalEvent.preventDefault();
        } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {
          const handledUp = this.handleUpEvent(mapBrowserEvent);
          this.handlingDownUpSequence_ = handledUp;
        }
      } else {
        if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {
          if (this.handlingDoubleDownSequence_) {
            this.handlingDoubleDownSequence_ = false;
            const handled = this.handleDownEvent(mapBrowserEvent);
            this.handlingDownUpSequence_ = handled;
            stopEvent = this.stopDown(handled);
          } else {
            stopEvent = this.stopDown(false);
            this.waitForDblTap_();
          }
        }
      }
      return !stopEvent;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} mapBrowserEvent Event.
     */
    handleDragEvent(mapBrowserEvent) {
      let scaleDelta = 1.0;

      const touch0 = this.targetPointers[0];
      const touch1 = this.down_;
      const distance = touch0.clientY - touch1.clientY;

      if (this.lastDistance_ !== undefined) {
        scaleDelta =
          1 - (this.lastDistance_ - distance) * this.scaleDeltaByPixel_;
      }
      this.lastDistance_ = distance;

      if (scaleDelta != 1.0) {
        this.lastScaleDelta_ = scaleDelta;
      }

      // scale, bypass the resolution constraint
      const map = mapBrowserEvent.map;
      const view = map.getView();
      map.render();
      view.adjustResolutionInternal(scaleDelta);
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     */
    handleDownEvent(mapBrowserEvent) {
      if (this.targetPointers.length == 1) {
        const map = mapBrowserEvent.map;
        this.anchor_ = null;
        this.lastDistance_ = undefined;
        this.lastScaleDelta_ = 1;
        this.down_ = mapBrowserEvent.originalEvent;
        if (!this.handlingDownUpSequence_) {
          map.getView().beginInteraction();
        }
        return true;
      }
      return false;
    }

    /**
     * Handle pointer up events zooming out.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     */
    handleUpEvent(mapBrowserEvent) {
      if (this.targetPointers.length == 0) {
        const map = mapBrowserEvent.map;
        const view = map.getView();
        const direction = this.lastScaleDelta_ > 1 ? 1 : -1;
        view.endInteraction(this.duration_, direction);
        this.handlingDownUpSequence_ = false;
        this.handlingDoubleDownSequence_ = false;
        return false;
      }
      return true;
    }

    /**
     * This function is used to determine if "down" events should be propagated
     * to other interactions or should be stopped.
     * @param {boolean} handled Was the event handled by the interaction?
     * @return {boolean} Should the `down` event be stopped?
     */
    stopDown(handled) {
      return handled;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} mapBrowserEvent Event.
     * @private
     */
    updateTrackedPointers_(mapBrowserEvent) {
      if (isPointerDraggingEvent(mapBrowserEvent)) {
        const event = mapBrowserEvent.originalEvent;

        const id = event.pointerId.toString();
        if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {
          delete this.trackedPointers_[id];
        } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {
          this.trackedPointers_[id] = event;
        } else if (id in this.trackedPointers_) {
          // update only when there was a pointerdown event for this pointer
          this.trackedPointers_[id] = event;
        }
        this.targetPointers = Object.values(this.trackedPointers_);
      }
    }

    /**
     * Wait the second double finger tap.
     * @private
     */
    waitForDblTap_() {
      if (this.doubleTapTimeoutId_ !== undefined) {
        // double-click
        clearTimeout(this.doubleTapTimeoutId_);
        this.doubleTapTimeoutId_ = undefined;
      } else {
        this.handlingDoubleDownSequence_ = true;
        this.doubleTapTimeoutId_ = setTimeout(
          this.endInteraction_.bind(this),
          250,
        );
      }
    }

    /**
     * @private
     */
    endInteraction_() {
      this.handlingDoubleDownSequence_ = false;
      this.doubleTapTimeoutId_ = undefined;
    }
  }

  /**
   * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
   * @return {boolean} Whether the event is a pointerdown, pointerdrag
   *     or pointerup event.
   */
  function isPointerDraggingEvent(mapBrowserEvent) {
    const type = mapBrowserEvent.type;
    return (
      type === MapBrowserEventType.POINTERDOWN ||
      type === MapBrowserEventType.POINTERDRAG ||
      type === MapBrowserEventType.POINTERUP
    );
  }

  /**
   * @module ol/interaction/DragAndDrop
   */
  // FIXME should handle all geo-referenced data, not just vector data


  /**
   * @typedef {Object} Options
   * @property {Array<typeof import("../format/Feature.js").default|import("../format/Feature.js").default>} [formatConstructors] Format constructors
   * (and/or formats pre-constructed with options).
   * @property {import("../source/Vector.js").default} [source] Optional vector source where features will be added.  If a source is provided
   * all existing features will be removed and new features will be added when
   * they are dropped on the target.  If you want to add features to a vector
   * source without removing the existing features (append only), instead of
   * providing the source option listen for the "addfeatures" event.
   * @property {import("../proj.js").ProjectionLike} [projection] Target projection. By default, the map's view's projection is used.
   * @property {HTMLElement} [target] The element that is used as the drop target, default is the viewport element.
   */

  /**
   * @enum {string}
   */
  const DragAndDropEventType = {
    /**
     * Triggered when features are added
     * @event DragAndDropEvent#addfeatures
     * @api
     */
    ADD_FEATURES: 'addfeatures',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/DragAndDrop~DragAndDrop} instances are instances
   * of this type.
   */
  class DragAndDropEvent extends BaseEvent {
    /**
     * @param {DragAndDropEventType} type Type.
     * @param {File} file File.
     * @param {Array<import("../Feature.js").default>} [features] Features.
     * @param {import("../proj/Projection.js").default} [projection] Projection.
     */
    constructor(type, file, features, projection) {
      super(type);

      /**
       * The features parsed from dropped data.
       * @type {Array<import("../Feature.js").FeatureLike>|undefined}
       * @api
       */
      this.features = features;

      /**
       * The dropped file.
       * @type {File}
       * @api
       */
      this.file = file;

      /**
       * The feature projection.
       * @type {import("../proj/Projection.js").default|undefined}
       * @api
       */
      this.projection = projection;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'addfeatures', DragAndDropEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'addfeatures', Return>} DragAndDropOnSignature
   */

  /**
   * @classdesc
   * Handles input of vector data by drag and drop.
   *
   * @api
   *
   * @fires DragAndDropEvent
   */
  class DragAndDrop extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        handleEvent: TRUE,
      });

      /***
       * @type {DragAndDropOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {DragAndDropOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {DragAndDropOnSignature<void>}
       */
      this.un;

      /**
       * @private
       * @type {boolean}
       */
      this.readAsBuffer_ = false;

      /**
       * @private
       * @type {Array<import("../format/Feature.js").default>}
       */
      this.formats_ = [];
      const formatConstructors = options.formatConstructors
        ? options.formatConstructors
        : [];
      for (let i = 0, ii = formatConstructors.length; i < ii; ++i) {
        let format = formatConstructors[i];
        if (typeof format === 'function') {
          format = new format();
        }
        this.formats_.push(format);
        this.readAsBuffer_ =
          this.readAsBuffer_ || format.getType() === 'arraybuffer';
      }

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.projection_ = options.projection
        ? get$2(options.projection)
        : null;

      /**
       * @private
       * @type {?Array<import("../events.js").EventsKey>}
       */
      this.dropListenKeys_ = null;

      /**
       * @private
       * @type {import("../source/Vector.js").default}
       */
      this.source_ = options.source || null;

      /**
       * @private
       * @type {HTMLElement|null}
       */
      this.target = options.target ? options.target : null;
    }

    /**
     * @param {File} file File.
     * @param {Event} event Load event.
     * @private
     */
    handleResult_(file, event) {
      const result = event.target.result;
      const map = this.getMap();
      let projection = this.projection_;
      if (!projection) {
        projection = getUserProjection();
        if (!projection) {
          const view = map.getView();
          projection = view.getProjection();
        }
      }

      let text;
      const formats = this.formats_;
      for (let i = 0, ii = formats.length; i < ii; ++i) {
        const format = formats[i];
        let input = result;
        if (this.readAsBuffer_ && format.getType() !== 'arraybuffer') {
          if (text === undefined) {
            text = new TextDecoder().decode(result);
          }
          input = text;
        }
        const features = this.tryReadFeatures_(format, input, {
          featureProjection: projection,
        });
        if (features && features.length > 0) {
          if (this.source_) {
            this.source_.clear();
            this.source_.addFeatures(features);
          }
          this.dispatchEvent(
            new DragAndDropEvent(
              DragAndDropEventType.ADD_FEATURES,
              file,
              features,
              projection,
            ),
          );
          break;
        }
      }
    }

    /**
     * @private
     */
    registerListeners_() {
      const map = this.getMap();
      if (map) {
        const dropArea = this.target ? this.target : map.getViewport();
        this.dropListenKeys_ = [
          listen(dropArea, EventType.DROP, this.handleDrop, this),
          listen(dropArea, EventType.DRAGENTER, this.handleStop, this),
          listen(dropArea, EventType.DRAGOVER, this.handleStop, this),
          listen(dropArea, EventType.DROP, this.handleStop, this),
        ];
      }
    }

    /**
     * Activate or deactivate the interaction.
     * @param {boolean} active Active.
     * @observable
     * @api
     * @override
     */
    setActive(active) {
      if (!this.getActive() && active) {
        this.registerListeners_();
      }
      if (this.getActive() && !active) {
        this.unregisterListeners_();
      }
      super.setActive(active);
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      this.unregisterListeners_();
      super.setMap(map);
      if (this.getActive()) {
        this.registerListeners_();
      }
    }

    /**
     * @param {import("../format/Feature.js").default} format Format.
     * @param {string} text Text.
     * @param {import("../format/Feature.js").ReadOptions} options Read options.
     * @private
     * @return {Array<import("../Feature.js").default>} Features.
     */
    tryReadFeatures_(format, text, options) {
      try {
        return (
          /** @type {Array<import("../Feature.js").default>} */
          (format.readFeatures(text, options))
        );
      } catch {
        return null;
      }
    }

    /**
     * @private
     */
    unregisterListeners_() {
      if (this.dropListenKeys_) {
        this.dropListenKeys_.forEach(unlistenByKey);
        this.dropListenKeys_ = null;
      }
    }

    /**
     * @param {DragEvent} event Event.
     */
    handleDrop(event) {
      const files = event.dataTransfer.files;
      for (let i = 0, ii = files.length; i < ii; ++i) {
        const file = files.item(i);
        const reader = new FileReader();
        reader.addEventListener(
          EventType.LOAD,
          this.handleResult_.bind(this, file),
        );
        if (this.readAsBuffer_) {
          reader.readAsArrayBuffer(file);
        } else {
          reader.readAsText(file);
        }
      }
    }

    /**
     * @param {DragEvent} event Event.
     */
    handleStop(event) {
      event.stopPropagation();
      event.preventDefault();
      event.dataTransfer.dropEffect = 'copy';
    }
  }

  /**
   * @module ol/interaction/DragRotateAndZoom
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.shiftKeyOnly}.
   * @property {number} [duration=400] Animation duration in milliseconds.
   */

  /**
   * @classdesc
   * Allows the user to zoom and rotate the map by clicking and dragging
   * on the map.  By default, this interaction is limited to when the shift
   * key is held down.
   *
   * This interaction is only supported for mouse devices.
   *
   * And this interaction is not included in the default interactions.
   * @api
   */
  class DragRotateAndZoom extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super(/** @type {import("./Pointer.js").Options} */ (options));

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : shiftKeyOnly;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lastAngle_ = undefined;

      /**
       * @private
       * @type {number|undefined}
       */
      this.lastMagnitude_ = undefined;

      /**
       * @private
       * @type {number}
       */
      this.lastScaleDelta_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.duration_ = options.duration !== undefined ? options.duration : 400;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return;
      }

      const map = mapBrowserEvent.map;
      const size = map.getSize();
      const offset = mapBrowserEvent.pixel;
      const deltaX = offset[0] - size[0] / 2;
      const deltaY = size[1] / 2 - offset[1];
      const theta = Math.atan2(deltaY, deltaX);
      const magnitude = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
      const view = map.getView();
      if (this.lastAngle_ !== undefined) {
        const angleDelta = this.lastAngle_ - theta;
        view.adjustRotationInternal(angleDelta);
      }
      this.lastAngle_ = theta;
      if (this.lastMagnitude_ !== undefined) {
        view.adjustResolutionInternal(this.lastMagnitude_ / magnitude);
      }
      if (this.lastMagnitude_ !== undefined) {
        this.lastScaleDelta_ = this.lastMagnitude_ / magnitude;
      }
      this.lastMagnitude_ = magnitude;
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return true;
      }

      const map = mapBrowserEvent.map;
      const view = map.getView();
      const direction = this.lastScaleDelta_ > 1 ? 1 : -1;
      view.endInteraction(this.duration_, direction);
      this.lastScaleDelta_ = 0;
      return false;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      if (!mouseOnly(mapBrowserEvent)) {
        return false;
      }

      if (this.condition_(mapBrowserEvent)) {
        mapBrowserEvent.map.getView().beginInteraction();
        this.lastAngle_ = undefined;
        this.lastMagnitude_ = undefined;
        return true;
      }
      return false;
    }
  }

  /**
   * @module ol/interaction/Draw
   */

  /**
   * @typedef {Object} Options
   * @property {import("../geom/Geometry.js").Type} type Geometry type of
   * the geometries being drawn with this instance.
   * @property {number} [clickTolerance=6] The maximum distance in pixels between
   * "down" and "up" for a "up" event to be considered a "click" event and
   * actually add a point/vertex to the geometry being drawn.  The default of `6`
   * was chosen for the draw interaction to behave correctly on mouse as well as
   * on touch devices.
   * @property {import("../Collection.js").default<Feature>} [features]
   * Destination collection for the drawn features.
   * @property {VectorSource} [source] Destination source for
   * the drawn features.
   * @property {number} [dragVertexDelay=500] Delay in milliseconds after pointerdown
   * before the current vertex can be dragged to its exact position.
   * @property {number} [snapTolerance=12] Pixel distance for snapping to the
   * drawing finish. Must be greater than `0`.
   * @property {boolean} [stopClick=false] Stop click, singleclick, and
   * doubleclick events from firing during drawing.
   * @property {number} [maxPoints] The number of points that can be drawn before
   * a polygon ring or line string is finished. By default there is no
   * restriction.
   * @property {number} [minPoints] The number of points that must be drawn
   * before a polygon ring or line string can be finished. Default is `3` for
   * polygon rings and `2` for line strings.
   * @property {import("../events/condition.js").Condition} [finishCondition] A function
   * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether the drawing can be finished. Not used when drawing
   * POINT or MULTI_POINT geometries.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike} [style]
   * Style for sketch features. The draw interaction can have up to three sketch features, depending on the mode.
   * It will always contain a feature with a `Point` geometry that corresponds to the current cursor position.
   * If the mode is `LineString` or `Polygon`, and there is at least one drawn point, it will also contain a feature with
   * a `LineString` geometry that corresponds to the line between the already drawn points and the current cursor position.
   * If the mode is `Polygon`, and there is at least one drawn point, it will also contain a feature with a `Polygon`
   * geometry that corresponds to the polygon between the already drawn points and the current cursor position
   * (note that this polygon has only two points if only one point is drawn).
   * If the mode is `Circle`, and there is one point drawn, it will also contain a feature with a `Circle` geometry whose
   * center is the drawn point and the radius is determined by the distance between the drawn point and the cursor.
   * @property {GeometryFunction} [geometryFunction]
   * Function that is called when a geometry's coordinates are updated.
   * @property {string} [geometryName] Geometry name to use for features created
   * by the draw interaction.
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * By default {@link module:ol/events/condition.noModifierKeys}, i.e. a click,
   * adds a vertex or deactivates freehand drawing.
   * @property {boolean} [freehand=false] Operate in freehand mode for lines,
   * polygons, and circles.  This makes the interaction always operate in freehand
   * mode and takes precedence over any `freehandCondition` option.
   * @property {import("../events/condition.js").Condition} [freehandCondition]
   * Condition that activates freehand drawing for lines and polygons. This
   * function takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and
   * returns a boolean to indicate whether that event should be handled. The
   * default is {@link module:ol/events/condition.shiftKeyOnly}, meaning that the
   * Shift key activates freehand drawing.
   * @property {boolean|import("../events/condition.js").Condition} [trace=false] Trace a portion of another geometry.
   * Ignored when in freehand mode.
   * @property {VectorSource} [traceSource] Source for features to trace.  If tracing is active and a `traceSource` is
   * not provided, the interaction's `source` will be used.  Tracing requires that the interaction is configured with
   * either a `traceSource` or a `source`.
   * @property {boolean} [wrapX=false] Wrap the world horizontally on the sketch
   * overlay.
   * @property {import("../geom/Geometry.js").GeometryLayout} [geometryLayout='XY'] Layout of the
   * feature geometries created by the draw interaction.
   */

  /**
   * Coordinate type when drawing points.
   * @typedef {import("../coordinate.js").Coordinate} PointCoordType
   */

  /**
   * Coordinate type when drawing lines.
   * @typedef {Array<import("../coordinate.js").Coordinate>} LineCoordType
   */

  /**
   * Coordinate type when drawing polygons.
   * @typedef {Array<Array<import("../coordinate.js").Coordinate>>} PolyCoordType
   */

  /**
   * Types used for drawing coordinates.
   * @typedef {PointCoordType|LineCoordType|PolyCoordType} SketchCoordType
   */

  /**
   * @typedef {Object} TraceState
   * @property {boolean} active Tracing active.
   * @property {import("../pixel.js").Pixel} [startPx] The initially clicked pixel location.
   * @property {Array<TraceTarget>} [targets] Targets available for tracing.
   * @property {number} [targetIndex] The index of the currently traced target.  A value of -1 indicates
   * that no trace target is active.
   */

  /**
   * @typedef {Object} TraceTarget
   * @property {Array<import("../coordinate.js").Coordinate>} coordinates Target coordinates.
   * @property {boolean} ring The target coordinates are a linear ring.
   * @property {number} startIndex The index of first traced coordinate.  A fractional index represents an
   * edge intersection.  Index values for rings will wrap (may be negative or larger than coordinates length).
   * @property {number} endIndex The index of last traced coordinate.  Details from startIndex also apply here.
   */

  /**
   * Function that takes an array of coordinates and an optional existing geometry
   * and a projection as arguments, and returns a geometry. The optional existing
   * geometry is the geometry that is returned when the function is called without
   * a second argument.
   * @typedef {function(!SketchCoordType, import("../geom/SimpleGeometry.js").default,
   *     import("../proj/Projection.js").default):
   *     import("../geom/SimpleGeometry.js").default} GeometryFunction
   */

  /**
   * @typedef {'Point' | 'LineString' | 'Polygon' | 'Circle'} Mode
   * Draw mode.  This collapses multi-part geometry types with their single-part
   * cousins.
   */

  /**
   * @enum {string}
   */
  const DrawEventType = {
    /**
     * Triggered upon feature draw start
     * @event DrawEvent#drawstart
     * @api
     */
    DRAWSTART: 'drawstart',
    /**
     * Triggered upon feature draw end
     * @event DrawEvent#drawend
     * @api
     */
    DRAWEND: 'drawend',
    /**
     * Triggered upon feature draw abortion
     * @event DrawEvent#drawabort
     * @api
     */
    DRAWABORT: 'drawabort',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Draw~Draw} instances are
   * instances of this type.
   */
  class DrawEvent extends BaseEvent {
    /**
     * @param {DrawEventType} type Type.
     * @param {Feature} feature The feature drawn.
     */
    constructor(type, feature) {
      super(type);

      /**
       * The feature being drawn.
       * @type {Feature}
       * @api
       */
      this.feature = feature;
    }
  }

  /**
   * @param {import("../coordinate.js").Coordinate} coordinate The coordinate.
   * @param {Array<Feature>} features The candidate features.
   * @return {Array<TraceTarget>} The trace targets.
   */
  function getTraceTargets(coordinate, features) {
    /**
     * @type {Array<TraceTarget>}
     */
    const targets = [];

    for (let i = 0; i < features.length; ++i) {
      const feature = features[i];
      const geometry = feature.getGeometry();
      appendGeometryTraceTargets(coordinate, geometry, targets);
    }

    return targets;
  }

  /**
   * @param {import("../coordinate.js").Coordinate} a One coordinate.
   * @param {import("../coordinate.js").Coordinate} b Another coordinate.
   * @return {number} The squared distance between the two coordinates.
   */
  function getSquaredDistance(a, b) {
    return squaredDistance$1(a[0], a[1], b[0], b[1]);
  }

  /**
   * @param {LineCoordType} coordinates The ring coordinates.
   * @param {number} index The index.  May be wrapped.
   * @return {import("../coordinate.js").Coordinate} The coordinate.
   */
  function getCoordinate(coordinates, index) {
    const count = coordinates.length;
    if (index < 0) {
      return coordinates[index + count];
    }
    if (index >= count) {
      return coordinates[index - count];
    }
    return coordinates[index];
  }

  /**
   * Get the cumulative squared distance along a ring path.  The end index index may be "wrapped" and it may
   * be less than the start index to indicate the direction of travel.  The start and end index may have
   * a fractional part to indicate a point between two coordinates.
   * @param {LineCoordType} coordinates Ring coordinates.
   * @param {number} startIndex The start index.
   * @param {number} endIndex The end index.
   * @return {number} The cumulative squared distance along the ring path.
   */
  function getCumulativeSquaredDistance(coordinates, startIndex, endIndex) {
    let lowIndex, highIndex;
    if (startIndex < endIndex) {
      lowIndex = startIndex;
      highIndex = endIndex;
    } else {
      lowIndex = endIndex;
      highIndex = startIndex;
    }
    const lowWholeIndex = Math.ceil(lowIndex);
    const highWholeIndex = Math.floor(highIndex);

    if (lowWholeIndex > highWholeIndex) {
      // both start and end are on the same segment
      const start = interpolateCoordinate(coordinates, lowIndex);
      const end = interpolateCoordinate(coordinates, highIndex);
      return getSquaredDistance(start, end);
    }

    let sd = 0;

    if (lowIndex < lowWholeIndex) {
      const start = interpolateCoordinate(coordinates, lowIndex);
      const end = getCoordinate(coordinates, lowWholeIndex);
      sd += getSquaredDistance(start, end);
    }

    if (highWholeIndex < highIndex) {
      const start = getCoordinate(coordinates, highWholeIndex);
      const end = interpolateCoordinate(coordinates, highIndex);
      sd += getSquaredDistance(start, end);
    }

    for (let i = lowWholeIndex; i < highWholeIndex - 1; ++i) {
      const start = getCoordinate(coordinates, i);
      const end = getCoordinate(coordinates, i + 1);
      sd += getSquaredDistance(start, end);
    }

    return sd;
  }

  /**
   * @param {import("../coordinate.js").Coordinate} coordinate The coordinate.
   * @param {import("../geom/Geometry.js").default} geometry The candidate geometry.
   * @param {Array<TraceTarget>} targets The trace targets.
   */
  function appendGeometryTraceTargets(coordinate, geometry, targets) {
    if (geometry instanceof LineString) {
      appendTraceTarget(coordinate, geometry.getCoordinates(), false, targets);
      return;
    }
    if (geometry instanceof MultiLineString) {
      const coordinates = geometry.getCoordinates();
      for (let i = 0, ii = coordinates.length; i < ii; ++i) {
        appendTraceTarget(coordinate, coordinates[i], false, targets);
      }
      return;
    }
    if (geometry instanceof Polygon) {
      const coordinates = geometry.getCoordinates();
      for (let i = 0, ii = coordinates.length; i < ii; ++i) {
        appendTraceTarget(coordinate, coordinates[i], true, targets);
      }
      return;
    }
    if (geometry instanceof MultiPolygon) {
      const polys = geometry.getCoordinates();
      for (let i = 0, ii = polys.length; i < ii; ++i) {
        const coordinates = polys[i];
        for (let j = 0, jj = coordinates.length; j < jj; ++j) {
          appendTraceTarget(coordinate, coordinates[j], true, targets);
        }
      }
      return;
    }
    if (geometry instanceof GeometryCollection) {
      const geometries = geometry.getGeometries();
      for (let i = 0; i < geometries.length; ++i) {
        appendGeometryTraceTargets(coordinate, geometries[i], targets);
      }
      return;
    }
    // other types cannot be traced
  }

  /**
   * @typedef {Object} TraceTargetUpdateInfo
   * @property {number} index The new target index.
   * @property {number} endIndex The new segment end index.
   */

  /**
   * @type {TraceTargetUpdateInfo}
   */
  const sharedUpdateInfo = {index: -1, endIndex: NaN};

  /**
   * @param {import("../coordinate.js").Coordinate} coordinate The coordinate.
   * @param {TraceState} traceState The trace state.
   * @param {import("../Map.js").default} map The map.
   * @param {number} snapTolerance The snap tolerance.
   * @return {TraceTargetUpdateInfo} Information about the new trace target.  The returned
   * object is reused between calls and must not be modified by the caller.
   */
  function getTraceTargetUpdate(coordinate, traceState, map, snapTolerance) {
    const x = coordinate[0];
    const y = coordinate[1];

    let closestTargetDistance = Infinity;

    let newTargetIndex = -1;
    let newEndIndex = NaN;

    for (
      let targetIndex = 0;
      targetIndex < traceState.targets.length;
      ++targetIndex
    ) {
      const target = traceState.targets[targetIndex];
      const coordinates = target.coordinates;

      let minSegmentDistance = Infinity;
      let endIndex;
      for (
        let coordinateIndex = 0;
        coordinateIndex < coordinates.length - 1;
        ++coordinateIndex
      ) {
        const start = coordinates[coordinateIndex];
        const end = coordinates[coordinateIndex + 1];
        const rel = getPointSegmentRelationship(x, y, start, end);
        if (rel.squaredDistance < minSegmentDistance) {
          minSegmentDistance = rel.squaredDistance;
          endIndex = coordinateIndex + rel.along;
        }
      }

      if (minSegmentDistance < closestTargetDistance) {
        closestTargetDistance = minSegmentDistance;
        if (target.ring && traceState.targetIndex === targetIndex) {
          // same target, maintain the same trace direction
          if (target.endIndex > target.startIndex) {
            // forward trace
            if (endIndex < target.startIndex) {
              endIndex += coordinates.length;
            }
          } else if (target.endIndex < target.startIndex) {
            // reverse trace
            if (endIndex > target.startIndex) {
              endIndex -= coordinates.length;
            }
          }
        }
        newEndIndex = endIndex;
        newTargetIndex = targetIndex;
      }
    }

    const newTarget = traceState.targets[newTargetIndex];
    let considerBothDirections = newTarget.ring;
    if (traceState.targetIndex === newTargetIndex && considerBothDirections) {
      // only consider switching trace direction if close to the start
      const newCoordinate = interpolateCoordinate(
        newTarget.coordinates,
        newEndIndex,
      );
      const pixel = map.getPixelFromCoordinate(newCoordinate);
      if (distance(pixel, traceState.startPx) > snapTolerance) {
        considerBothDirections = false;
      }
    }

    if (considerBothDirections) {
      const coordinates = newTarget.coordinates;
      const count = coordinates.length;
      const startIndex = newTarget.startIndex;
      const endIndex = newEndIndex;
      if (startIndex < endIndex) {
        const forwardDistance = getCumulativeSquaredDistance(
          coordinates,
          startIndex,
          endIndex,
        );
        const reverseDistance = getCumulativeSquaredDistance(
          coordinates,
          startIndex,
          endIndex - count,
        );
        if (reverseDistance < forwardDistance) {
          newEndIndex -= count;
        }
      } else {
        const reverseDistance = getCumulativeSquaredDistance(
          coordinates,
          startIndex,
          endIndex,
        );
        const forwardDistance = getCumulativeSquaredDistance(
          coordinates,
          startIndex,
          endIndex + count,
        );
        if (forwardDistance < reverseDistance) {
          newEndIndex += count;
        }
      }
    }

    sharedUpdateInfo.index = newTargetIndex;
    sharedUpdateInfo.endIndex = newEndIndex;
    return sharedUpdateInfo;
  }

  /**
   * @param {import("../coordinate.js").Coordinate} coordinate The clicked coordinate.
   * @param {Array<import("../coordinate.js").Coordinate>} coordinates The geometry component coordinates.
   * @param {boolean} ring The coordinates represent a linear ring.
   * @param {Array<TraceTarget>} targets The trace targets.
   */
  function appendTraceTarget(coordinate, coordinates, ring, targets) {
    const x = coordinate[0];
    const y = coordinate[1];
    for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {
      const start = coordinates[i];
      const end = coordinates[i + 1];
      const rel = getPointSegmentRelationship(x, y, start, end);
      if (rel.squaredDistance === 0) {
        const index = i + rel.along;
        targets.push({
          coordinates: coordinates,
          ring: ring,
          startIndex: index,
          endIndex: index,
        });
        return;
      }
    }
  }

  /**
   * @typedef {Object} PointSegmentRelationship
   * @property {number} along The closest point expressed as a fraction along the segment length.
   * @property {number} squaredDistance The squared distance of the point to the segment.
   */

  /**
   * @type {PointSegmentRelationship}
   */
  const sharedRel = {along: 0, squaredDistance: 0};

  /**
   * @param {number} x The point x.
   * @param {number} y The point y.
   * @param {import("../coordinate.js").Coordinate} start The segment start.
   * @param {import("../coordinate.js").Coordinate} end The segment end.
   * @return {PointSegmentRelationship} The point segment relationship.  The returned object is
   * shared between calls and must not be modified by the caller.
   */
  function getPointSegmentRelationship(x, y, start, end) {
    const x1 = start[0];
    const y1 = start[1];
    const x2 = end[0];
    const y2 = end[1];
    const dx = x2 - x1;
    const dy = y2 - y1;
    let along = 0;
    let px = x1;
    let py = y1;
    if (dx !== 0 || dy !== 0) {
      along = clamp$1(((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy), 0, 1);
      px += dx * along;
      py += dy * along;
    }

    sharedRel.along = along;
    sharedRel.squaredDistance = toFixed(squaredDistance$1(x, y, px, py), 10);
    return sharedRel;
  }

  /**
   * @param {LineCoordType} coordinates The coordinates.
   * @param {number} index The index.  May be fractional and may wrap.
   * @return {import("../coordinate.js").Coordinate} The interpolated coordinate.
   */
  function interpolateCoordinate(coordinates, index) {
    const count = coordinates.length;

    let startIndex = Math.floor(index);
    const along = index - startIndex;
    if (startIndex >= count) {
      startIndex -= count;
    } else if (startIndex < 0) {
      startIndex += count;
    }

    let endIndex = startIndex + 1;
    if (endIndex >= count) {
      endIndex -= count;
    }

    const start = coordinates[startIndex];
    const x0 = start[0];
    const y0 = start[1];
    const end = coordinates[endIndex];
    const dx = end[0] - x0;
    const dy = end[1] - y0;

    return [x0 + dx * along, y0 + dy * along];
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'drawabort'|'drawend'|'drawstart', DrawEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'drawabort'|'drawend'|'drawstart', Return>} DrawOnSignature
   */

  /**
   * @classdesc
   * Interaction for drawing feature geometries.
   *
   * @fires DrawEvent
   * @api
   */
  class Draw extends PointerInteraction {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      const pointerOptions = /** @type {import("./Pointer.js").Options} */ (
        options
      );
      if (!pointerOptions.stopDown) {
        pointerOptions.stopDown = FALSE;
      }

      super(pointerOptions);

      /***
       * @type {DrawOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {DrawOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {DrawOnSignature<void>}
       */
      this.un;

      /**
       * @type {boolean}
       * @private
       */
      this.shouldHandle_ = false;

      /**
       * @type {import("../pixel.js").Pixel}
       * @private
       */
      this.downPx_ = null;

      /**
       * @type {ReturnType<typeof setTimeout>}
       * @private
       */
      this.downTimeout_;

      /**
       * @type {number|undefined}
       * @private
       */
      this.lastDragTime_;

      /**
       * Pointer type of the last pointermove event
       * @type {string}
       * @private
       */
      this.pointerType_;

      /**
       * @type {boolean}
       * @private
       */
      this.freehand_ = false;

      /**
       * Target source for drawn features.
       * @type {VectorSource|null}
       * @private
       */
      this.source_ = options.source ? options.source : null;

      /**
       * Target collection for drawn features.
       * @type {import("../Collection.js").default<Feature>|null}
       * @private
       */
      this.features_ = options.features ? options.features : null;

      /**
       * Pixel distance for snapping.
       * @type {number}
       * @private
       */
      this.snapTolerance_ = options.snapTolerance ? options.snapTolerance : 12;

      /**
       * Geometry type.
       * @type {import("../geom/Geometry.js").Type}
       * @private
       */
      this.type_ = /** @type {import("../geom/Geometry.js").Type} */ (
        options.type
      );

      /**
       * Drawing mode (derived from geometry type.
       * @type {Mode}
       * @private
       */
      this.mode_ = getMode(this.type_);

      /**
       * Stop click, singleclick, and doubleclick events from firing during drawing.
       * Default is `false`.
       * @type {boolean}
       * @private
       */
      this.stopClick_ = !!options.stopClick;

      /**
       * The number of points that must be drawn before a polygon ring or line
       * string can be finished.  The default is 3 for polygon rings and 2 for
       * line strings.
       * @type {number}
       * @private
       */
      this.minPoints_ = options.minPoints
        ? options.minPoints
        : this.mode_ === 'Polygon'
          ? 3
          : 2;

      /**
       * The number of points that can be drawn before a polygon ring or line string
       * is finished. The default is no restriction.
       * @type {number}
       * @private
       */
      this.maxPoints_ =
        this.mode_ === 'Circle'
          ? 2
          : options.maxPoints
            ? options.maxPoints
            : Infinity;

      /**
       * A function to decide if a potential finish coordinate is permissible
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.finishCondition_ = options.finishCondition
        ? options.finishCondition
        : TRUE;

      /**
       * @private
       * @type {import("../geom/Geometry.js").GeometryLayout}
       */
      this.geometryLayout_ = options.geometryLayout
        ? options.geometryLayout
        : 'XY';

      let geometryFunction = options.geometryFunction;
      if (!geometryFunction) {
        const mode = this.mode_;
        if (mode === 'Circle') {
          /**
           * @param {!LineCoordType} coordinates The coordinates.
           * @param {import("../geom/SimpleGeometry.js").default|undefined} geometry Optional geometry.
           * @param {import("../proj/Projection.js").default} projection The view projection.
           * @return {import("../geom/SimpleGeometry.js").default} A geometry.
           */
          geometryFunction = (coordinates, geometry, projection) => {
            const circle = geometry
              ? /** @type {Circle} */ (geometry)
              : new Circle([NaN, NaN]);
            const center = fromUserCoordinate(coordinates[0], projection);
            const squaredLength = squaredDistance(
              center,
              fromUserCoordinate(coordinates[coordinates.length - 1], projection),
            );
            circle.setCenterAndRadius(
              center,
              Math.sqrt(squaredLength),
              this.geometryLayout_,
            );
            const userProjection = getUserProjection();
            if (userProjection) {
              circle.transform(projection, userProjection);
            }
            return circle;
          };
        } else {
          let Constructor;
          if (mode === 'Point') {
            Constructor = Point;
          } else if (mode === 'LineString') {
            Constructor = LineString;
          } else if (mode === 'Polygon') {
            Constructor = Polygon;
          }
          /**
           * @param {!LineCoordType} coordinates The coordinates.
           * @param {import("../geom/SimpleGeometry.js").default|undefined} geometry Optional geometry.
           * @param {import("../proj/Projection.js").default} projection The view projection.
           * @return {import("../geom/SimpleGeometry.js").default} A geometry.
           */
          geometryFunction = (coordinates, geometry, projection) => {
            if (geometry) {
              if (mode === 'Polygon') {
                if (coordinates[0].length) {
                  // Add a closing coordinate to match the first
                  geometry.setCoordinates(
                    [coordinates[0].concat([coordinates[0][0]])],
                    this.geometryLayout_,
                  );
                } else {
                  geometry.setCoordinates([], this.geometryLayout_);
                }
              } else {
                geometry.setCoordinates(coordinates, this.geometryLayout_);
              }
            } else {
              geometry = new Constructor(coordinates, this.geometryLayout_);
            }
            return geometry;
          };
        }
      }

      /**
       * @type {GeometryFunction}
       * @private
       */
      this.geometryFunction_ = geometryFunction;

      /**
       * @type {number}
       * @private
       */
      this.dragVertexDelay_ =
        options.dragVertexDelay !== undefined ? options.dragVertexDelay : 500;

      /**
       * Finish coordinate for the feature (first point for polygons, last point for
       * linestrings).
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.finishCoordinate_ = null;

      /**
       * Sketch feature.
       * @type {Feature<import('../geom/SimpleGeometry.js').default>}
       * @private
       */
      this.sketchFeature_ = null;

      /**
       * Sketch point.
       * @type {Feature<Point>}
       * @private
       */
      this.sketchPoint_ = null;

      /**
       * Sketch coordinates. Used when drawing a line or polygon.
       * @type {SketchCoordType}
       * @private
       */
      this.sketchCoords_ = null;

      /**
       * Sketch line. Used when drawing polygon.
       * @type {Feature<LineString>}
       * @private
       */
      this.sketchLine_ = null;

      /**
       * Sketch line coordinates. Used when drawing a polygon or circle.
       * @type {LineCoordType}
       * @private
       */
      this.sketchLineCoords_ = null;

      /**
       * Squared tolerance for handling up events.  If the squared distance
       * between a down and up event is greater than this tolerance, up events
       * will not be handled.
       * @type {number}
       * @private
       */
      this.squaredClickTolerance_ = options.clickTolerance
        ? options.clickTolerance * options.clickTolerance
        : 36;

      /**
       * Draw overlay where our sketch features are drawn.
       * @type {VectorLayer}
       * @private
       */
      this.overlay_ = new VectorLayer({
        source: new VectorSource({
          useSpatialIndex: false,
          wrapX: options.wrapX ? options.wrapX : false,
        }),
        style: options.style ? options.style : getDefaultStyleFunction$2(),
        updateWhileInteracting: true,
      });

      /**
       * Name of the geometry attribute for newly created features.
       * @type {string|undefined}
       * @private
       */
      this.geometryName_ = options.geometryName;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : noModifierKeys;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.freehandCondition_;
      if (options.freehand) {
        this.freehandCondition_ = always;
      } else {
        this.freehandCondition_ = options.freehandCondition
          ? options.freehandCondition
          : shiftKeyOnly;
      }

      /**
       * @type {import("../events/condition.js").Condition}
       * @private
       */
      this.traceCondition_;
      this.setTrace(options.trace || false);

      /**
       * @type {TraceState}
       * @private
       */
      this.traceState_ = {active: false};

      /**
       * @type {VectorSource|null}
       * @private
       */
      this.traceSource_ = options.traceSource || options.source || null;

      this.addChangeListener(InteractionProperty.ACTIVE, this.updateState_);
    }

    /**
     * Toggle tracing mode or set a tracing condition.
     *
     * @param {boolean|import("../events/condition.js").Condition} trace A boolean to toggle tracing mode or an event
     *     condition that will be checked when a feature is clicked to determine if tracing should be active.
     */
    setTrace(trace) {
      let condition;
      if (!trace) {
        condition = never;
      } else if (trace === true) {
        condition = always;
      } else {
        condition = trace;
      }
      this.traceCondition_ = condition;
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      super.setMap(map);
      this.updateState_();
    }

    /**
     * Get the overlay layer that this interaction renders sketch features to.
     * @return {VectorLayer} Overlay layer.
     * @api
     */
    getOverlay() {
      return this.overlay_;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may actually draw or finish the drawing.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} event Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     * @override
     */
    handleEvent(event) {
      if (event.originalEvent.type === EventType.CONTEXTMENU) {
        // Avoid context menu for long taps when drawing on mobile
        event.originalEvent.preventDefault();
      }
      this.freehand_ = this.mode_ !== 'Point' && this.freehandCondition_(event);
      let move = event.type === MapBrowserEventType.POINTERMOVE;
      let pass = true;
      if (
        !this.freehand_ &&
        this.lastDragTime_ &&
        event.type === MapBrowserEventType.POINTERDRAG
      ) {
        const now = Date.now();
        if (now - this.lastDragTime_ >= this.dragVertexDelay_) {
          this.downPx_ = event.pixel;
          this.shouldHandle_ = !this.freehand_;
          move = true;
        } else {
          this.lastDragTime_ = undefined;
        }
        if (this.shouldHandle_ && this.downTimeout_ !== undefined) {
          clearTimeout(this.downTimeout_);
          this.downTimeout_ = undefined;
        }
      }
      if (
        this.freehand_ &&
        event.type === MapBrowserEventType.POINTERDRAG &&
        this.sketchFeature_ !== null
      ) {
        this.addToDrawing_(event.coordinate);
        pass = false;
      } else if (
        this.freehand_ &&
        event.type === MapBrowserEventType.POINTERDOWN
      ) {
        pass = false;
      } else if (move && this.getPointerCount() < 2) {
        pass = event.type === MapBrowserEventType.POINTERMOVE;
        if (pass && this.freehand_) {
          this.handlePointerMove_(event);
          if (this.shouldHandle_) {
            // Avoid page scrolling when freehand drawing on mobile
            event.originalEvent.preventDefault();
          }
        } else if (
          event.originalEvent.pointerType === 'mouse' ||
          (event.type === MapBrowserEventType.POINTERDRAG &&
            this.downTimeout_ === undefined)
        ) {
          this.handlePointerMove_(event);
        }
      } else if (event.type === MapBrowserEventType.DBLCLICK) {
        pass = false;
      }

      return super.handleEvent(event) && pass;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} event Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(event) {
      this.shouldHandle_ = !this.freehand_;

      if (this.freehand_) {
        this.downPx_ = event.pixel;
        if (!this.finishCoordinate_) {
          this.startDrawing_(event.coordinate);
        }
        return true;
      }

      if (!this.condition_(event)) {
        this.lastDragTime_ = undefined;
        return false;
      }

      this.lastDragTime_ = Date.now();
      this.downTimeout_ = setTimeout(() => {
        this.handlePointerMove_(
          new MapBrowserEvent(
            MapBrowserEventType.POINTERMOVE,
            event.map,
            event.originalEvent,
            false,
            event.frameState,
          ),
        );
      }, this.dragVertexDelay_);
      this.downPx_ = event.pixel;
      return true;
    }

    /**
     * @private
     */
    deactivateTrace_() {
      this.traceState_ = {active: false};
    }

    /**
     * Activate or deactivate trace state based on a browser event.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @private
     */
    toggleTraceState_(event) {
      if (!this.traceSource_ || !this.traceCondition_(event)) {
        return;
      }

      if (this.traceState_.active) {
        this.deactivateTrace_();
        return;
      }

      const map = this.getMap();
      const lowerLeft = map.getCoordinateFromPixel([
        event.pixel[0] - this.snapTolerance_,
        event.pixel[1] + this.snapTolerance_,
      ]);
      const upperRight = map.getCoordinateFromPixel([
        event.pixel[0] + this.snapTolerance_,
        event.pixel[1] - this.snapTolerance_,
      ]);
      const extent = boundingExtent([lowerLeft, upperRight]);
      const features = this.traceSource_.getFeaturesInExtent(extent);
      if (features.length === 0) {
        return;
      }

      const targets = getTraceTargets(event.coordinate, features);
      if (targets.length) {
        this.traceState_ = {
          active: true,
          startPx: event.pixel.slice(),
          targets: targets,
          targetIndex: -1,
        };
      }
    }

    /**
     * @param {TraceTarget} target The trace target.
     * @param {number} endIndex The new end index of the trace.
     * @private
     */
    addOrRemoveTracedCoordinates_(target, endIndex) {
      // three cases to handle:
      //  1. traced in the same direction and points need adding
      //  2. traced in the same direction and points need removing
      //  3. traced in a new direction
      const previouslyForward = target.startIndex <= target.endIndex;
      const currentlyForward = target.startIndex <= endIndex;
      if (previouslyForward === currentlyForward) {
        // same direction
        if (
          (previouslyForward && endIndex > target.endIndex) ||
          (!previouslyForward && endIndex < target.endIndex)
        ) {
          // case 1 - add new points
          this.addTracedCoordinates_(target, target.endIndex, endIndex);
        } else if (
          (previouslyForward && endIndex < target.endIndex) ||
          (!previouslyForward && endIndex > target.endIndex)
        ) {
          // case 2 - remove old points
          this.removeTracedCoordinates_(endIndex, target.endIndex);
        }
      } else {
        // case 3 - remove old points, add new points
        this.removeTracedCoordinates_(target.startIndex, target.endIndex);
        this.addTracedCoordinates_(target, target.startIndex, endIndex);
      }
    }

    /**
     * @param {number} fromIndex The start index.
     * @param {number} toIndex The end index.
     * @private
     */
    removeTracedCoordinates_(fromIndex, toIndex) {
      if (fromIndex === toIndex) {
        return;
      }

      let remove = 0;
      if (fromIndex < toIndex) {
        const start = Math.ceil(fromIndex);
        let end = Math.floor(toIndex);
        if (end === toIndex) {
          end -= 1;
        }
        remove = end - start + 1;
      } else {
        const start = Math.floor(fromIndex);
        let end = Math.ceil(toIndex);
        if (end === toIndex) {
          end += 1;
        }
        remove = start - end + 1;
      }

      if (remove > 0) {
        this.removeLastPoints_(remove);
      }
    }

    /**
     * @param {TraceTarget} target The trace target.
     * @param {number} fromIndex The start index.
     * @param {number} toIndex The end index.
     * @private
     */
    addTracedCoordinates_(target, fromIndex, toIndex) {
      if (fromIndex === toIndex) {
        return;
      }

      const coordinates = [];
      if (fromIndex < toIndex) {
        // forward trace
        const start = Math.ceil(fromIndex);
        let end = Math.floor(toIndex);
        if (end === toIndex) {
          // if end is snapped to a vertex, it will be added later
          end -= 1;
        }
        for (let i = start; i <= end; ++i) {
          coordinates.push(getCoordinate(target.coordinates, i));
        }
      } else {
        // reverse trace
        const start = Math.floor(fromIndex);
        let end = Math.ceil(toIndex);
        if (end === toIndex) {
          end += 1;
        }
        for (let i = start; i >= end; --i) {
          coordinates.push(getCoordinate(target.coordinates, i));
        }
      }
      if (coordinates.length) {
        this.appendCoordinates(coordinates);
      }
    }

    /**
     * Update the trace.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @private
     */
    updateTrace_(event) {
      const traceState = this.traceState_;
      if (!traceState.active) {
        return;
      }

      if (traceState.targetIndex === -1) {
        // check if we are ready to pick a target
        if (distance(traceState.startPx, event.pixel) < this.snapTolerance_) {
          return;
        }
      }

      const updatedTraceTarget = getTraceTargetUpdate(
        event.coordinate,
        traceState,
        this.getMap(),
        this.snapTolerance_,
      );

      if (traceState.targetIndex !== updatedTraceTarget.index) {
        // target changed
        if (traceState.targetIndex !== -1) {
          // remove points added during previous trace
          const oldTarget = traceState.targets[traceState.targetIndex];
          this.removeTracedCoordinates_(oldTarget.startIndex, oldTarget.endIndex);
        }
        // add points for the new target
        const newTarget = traceState.targets[updatedTraceTarget.index];
        this.addTracedCoordinates_(
          newTarget,
          newTarget.startIndex,
          updatedTraceTarget.endIndex,
        );
      } else {
        // target stayed the same
        const target = traceState.targets[traceState.targetIndex];
        this.addOrRemoveTracedCoordinates_(target, updatedTraceTarget.endIndex);
      }

      // modify the state with updated info
      traceState.targetIndex = updatedTraceTarget.index;
      const target = traceState.targets[traceState.targetIndex];
      target.endIndex = updatedTraceTarget.endIndex;

      // update event coordinate and pixel to match end point of final segment
      const coordinate = interpolateCoordinate(
        target.coordinates,
        target.endIndex,
      );
      const pixel = this.getMap().getPixelFromCoordinate(coordinate);
      event.coordinate = coordinate;
      event.pixel = [Math.round(pixel[0]), Math.round(pixel[1])];
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} event Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(event) {
      let pass = true;

      if (this.getPointerCount() === 0) {
        if (this.downTimeout_) {
          clearTimeout(this.downTimeout_);
          this.downTimeout_ = undefined;
        }

        this.handlePointerMove_(event);
        const tracing = this.traceState_.active;
        this.toggleTraceState_(event);

        if (this.shouldHandle_) {
          const startingToDraw = !this.finishCoordinate_;
          if (startingToDraw) {
            this.startDrawing_(event.coordinate);
          }
          if (!startingToDraw && this.freehand_) {
            this.finishDrawing();
          } else if (
            !this.freehand_ &&
            (!startingToDraw || this.mode_ === 'Point')
          ) {
            if (this.atFinish_(event.pixel, tracing)) {
              if (this.finishCondition_(event)) {
                this.finishDrawing();
              }
            } else {
              this.addToDrawing_(event.coordinate);
            }
          }
          pass = false;
        } else if (this.freehand_) {
          this.abortDrawing();
        }
      }

      if (!pass && this.stopClick_) {
        event.preventDefault();
      }
      return pass;
    }

    /**
     * Handle move events.
     * @param {import("../MapBrowserEvent.js").default<PointerEvent>} event A move event.
     * @private
     */
    handlePointerMove_(event) {
      this.pointerType_ = event.originalEvent.pointerType;
      if (
        this.downPx_ &&
        ((!this.freehand_ && this.shouldHandle_) ||
          (this.freehand_ && !this.shouldHandle_))
      ) {
        const downPx = this.downPx_;
        const clickPx = event.pixel;
        const dx = downPx[0] - clickPx[0];
        const dy = downPx[1] - clickPx[1];
        const squaredDistance = dx * dx + dy * dy;
        this.shouldHandle_ = this.freehand_
          ? squaredDistance > this.squaredClickTolerance_
          : squaredDistance <= this.squaredClickTolerance_;
        if (!this.shouldHandle_) {
          return;
        }
      }

      if (!this.finishCoordinate_) {
        this.createOrUpdateSketchPoint_(event.coordinate.slice());
        return;
      }

      this.updateTrace_(event);
      this.modifyDrawing_(event.coordinate);
    }

    /**
     * Determine if an event is within the snapping tolerance of the start coord.
     * @param {import("../pixel.js").Pixel} pixel Pixel.
     * @param {boolean} [tracing] Drawing in trace mode (only stop if at the starting point).
     * @return {boolean} The event is within the snapping tolerance of the start.
     * @private
     */
    atFinish_(pixel, tracing) {
      let at = false;
      if (this.sketchFeature_) {
        let potentiallyDone = false;
        let potentiallyFinishCoordinates = [this.finishCoordinate_];
        const mode = this.mode_;
        if (mode === 'Point') {
          at = true;
        } else if (mode === 'Circle') {
          at = this.sketchCoords_.length === 2;
        } else if (mode === 'LineString') {
          potentiallyDone =
            !tracing && this.sketchCoords_.length > this.minPoints_;
        } else if (mode === 'Polygon') {
          const sketchCoords = /** @type {PolyCoordType} */ (this.sketchCoords_);
          potentiallyDone = sketchCoords[0].length > this.minPoints_;
          potentiallyFinishCoordinates = [
            sketchCoords[0][0],
            sketchCoords[0][sketchCoords[0].length - 2],
          ];
          if (tracing) {
            potentiallyFinishCoordinates = [sketchCoords[0][0]];
          } else {
            potentiallyFinishCoordinates = [
              sketchCoords[0][0],
              sketchCoords[0][sketchCoords[0].length - 2],
            ];
          }
        }
        if (potentiallyDone) {
          const map = this.getMap();
          for (let i = 0, ii = potentiallyFinishCoordinates.length; i < ii; i++) {
            const finishCoordinate = potentiallyFinishCoordinates[i];
            const finishPixel = map.getPixelFromCoordinate(finishCoordinate);
            const dx = pixel[0] - finishPixel[0];
            const dy = pixel[1] - finishPixel[1];
            const snapTolerance = this.freehand_ ? 1 : this.snapTolerance_;
            at = Math.sqrt(dx * dx + dy * dy) <= snapTolerance;
            if (at) {
              this.finishCoordinate_ = finishCoordinate;
              break;
            }
          }
        }
      }
      return at;
    }

    /**
     * @param {import("../coordinate").Coordinate} coordinates Coordinate.
     * @private
     */
    createOrUpdateSketchPoint_(coordinates) {
      if (!this.sketchPoint_) {
        this.sketchPoint_ = new Feature(new Point(coordinates));
        this.updateSketchFeatures_();
      } else {
        const sketchPointGeom = this.sketchPoint_.getGeometry();
        sketchPointGeom.setCoordinates(coordinates);
      }
    }

    /**
     * @param {import("../geom/Polygon.js").default} geometry Polygon geometry.
     * @private
     */
    createOrUpdateCustomSketchLine_(geometry) {
      if (!this.sketchLine_) {
        this.sketchLine_ = new Feature();
      }
      const ring = geometry.getLinearRing(0);
      let sketchLineGeom = this.sketchLine_.getGeometry();
      if (!sketchLineGeom) {
        sketchLineGeom = new LineString(
          ring.getFlatCoordinates(),
          ring.getLayout(),
        );
        this.sketchLine_.setGeometry(sketchLineGeom);
      } else {
        sketchLineGeom.setFlatCoordinates(
          ring.getLayout(),
          ring.getFlatCoordinates(),
        );
        sketchLineGeom.changed();
      }
    }

    /**
     * Start the drawing.
     * @param {import("../coordinate.js").Coordinate} start Start coordinate.
     * @private
     */
    startDrawing_(start) {
      const projection = this.getMap().getView().getProjection();
      const stride = getStrideForLayout(this.geometryLayout_);
      while (start.length < stride) {
        start.push(0);
      }
      this.finishCoordinate_ = start;
      if (this.mode_ === 'Point') {
        this.sketchCoords_ = start.slice();
      } else if (this.mode_ === 'Polygon') {
        this.sketchCoords_ = [[start.slice(), start.slice()]];
        this.sketchLineCoords_ = this.sketchCoords_[0];
      } else {
        this.sketchCoords_ = [start.slice(), start.slice()];
      }
      if (this.sketchLineCoords_) {
        this.sketchLine_ = new Feature(new LineString(this.sketchLineCoords_));
      }
      const geometry = this.geometryFunction_(
        this.sketchCoords_,
        undefined,
        projection,
      );
      this.sketchFeature_ = new Feature();
      if (this.geometryName_) {
        this.sketchFeature_.setGeometryName(this.geometryName_);
      }
      this.sketchFeature_.setGeometry(geometry);
      this.updateSketchFeatures_();
      this.dispatchEvent(
        new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_),
      );
    }

    /**
     * Modify the drawing.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @private
     */
    modifyDrawing_(coordinate) {
      const map = this.getMap();
      const geometry = this.sketchFeature_.getGeometry();
      const projection = map.getView().getProjection();
      const stride = getStrideForLayout(this.geometryLayout_);
      let coordinates, last;
      while (coordinate.length < stride) {
        coordinate.push(0);
      }
      if (this.mode_ === 'Point') {
        last = this.sketchCoords_;
      } else if (this.mode_ === 'Polygon') {
        coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
        last = coordinates[coordinates.length - 1];
        if (this.atFinish_(map.getPixelFromCoordinate(coordinate))) {
          // snap to finish
          coordinate = this.finishCoordinate_.slice();
        }
      } else {
        coordinates = this.sketchCoords_;
        last = coordinates[coordinates.length - 1];
      }
      last[0] = coordinate[0];
      last[1] = coordinate[1];
      this.geometryFunction_(
        /** @type {!LineCoordType} */ (this.sketchCoords_),
        geometry,
        projection,
      );
      if (this.sketchPoint_) {
        const sketchPointGeom = this.sketchPoint_.getGeometry();
        sketchPointGeom.setCoordinates(coordinate);
      }
      if (geometry.getType() === 'Polygon' && this.mode_ !== 'Polygon') {
        this.createOrUpdateCustomSketchLine_(/** @type {Polygon} */ (geometry));
      } else if (this.sketchLineCoords_) {
        const sketchLineGeom = this.sketchLine_.getGeometry();
        sketchLineGeom.setCoordinates(this.sketchLineCoords_);
      }
      this.updateSketchFeatures_();
    }

    /**
     * Add a new coordinate to the drawing.
     * @param {!PointCoordType} coordinate Coordinate
     * @return {Feature<import("../geom/SimpleGeometry.js").default>} The sketch feature.
     * @private
     */
    addToDrawing_(coordinate) {
      const geometry = this.sketchFeature_.getGeometry();
      const projection = this.getMap().getView().getProjection();
      let done;
      let coordinates;
      const mode = this.mode_;
      if (mode === 'LineString' || mode === 'Circle') {
        this.finishCoordinate_ = coordinate.slice();
        coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);
        if (coordinates.length >= this.maxPoints_) {
          if (this.freehand_) {
            coordinates.pop();
          } else {
            done = true;
          }
        }
        coordinates.push(coordinate.slice());
        this.geometryFunction_(coordinates, geometry, projection);
      } else if (mode === 'Polygon') {
        coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
        if (coordinates.length >= this.maxPoints_) {
          if (this.freehand_) {
            coordinates.pop();
          } else {
            done = true;
          }
        }
        coordinates.push(coordinate.slice());
        if (done) {
          this.finishCoordinate_ = coordinates[0];
        }
        this.geometryFunction_(this.sketchCoords_, geometry, projection);
      }
      this.createOrUpdateSketchPoint_(coordinate.slice());
      this.updateSketchFeatures_();
      if (done) {
        return this.finishDrawing();
      }
      return this.sketchFeature_;
    }

    /**
     * @param {number} n The number of points to remove.
     */
    removeLastPoints_(n) {
      if (!this.sketchFeature_) {
        return;
      }
      const geometry = this.sketchFeature_.getGeometry();
      const projection = this.getMap().getView().getProjection();
      const mode = this.mode_;
      for (let i = 0; i < n; ++i) {
        let coordinates;
        if (mode === 'LineString' || mode === 'Circle') {
          coordinates = /** @type {LineCoordType} */ (this.sketchCoords_);
          coordinates.splice(-2, 1);
          if (coordinates.length >= 2) {
            this.finishCoordinate_ = coordinates[coordinates.length - 2].slice();
            const finishCoordinate = this.finishCoordinate_.slice();
            coordinates[coordinates.length - 1] = finishCoordinate;
            this.createOrUpdateSketchPoint_(finishCoordinate);
          }
          this.geometryFunction_(coordinates, geometry, projection);
          if (geometry.getType() === 'Polygon' && this.sketchLine_) {
            this.createOrUpdateCustomSketchLine_(
              /** @type {Polygon} */ (geometry),
            );
          }
        } else if (mode === 'Polygon') {
          coordinates = /** @type {PolyCoordType} */ (this.sketchCoords_)[0];
          coordinates.splice(-2, 1);
          const sketchLineGeom = this.sketchLine_.getGeometry();
          if (coordinates.length >= 2) {
            const finishCoordinate = coordinates[coordinates.length - 2].slice();
            coordinates[coordinates.length - 1] = finishCoordinate;
            this.createOrUpdateSketchPoint_(finishCoordinate);
          }
          sketchLineGeom.setCoordinates(coordinates);
          this.geometryFunction_(this.sketchCoords_, geometry, projection);
        }

        if (coordinates.length === 1) {
          this.abortDrawing();
          break;
        }
      }

      this.updateSketchFeatures_();
    }

    /**
     * Remove last point of the feature currently being drawn. Does not do anything when
     * drawing POINT or MULTI_POINT geometries.
     * @api
     */
    removeLastPoint() {
      this.removeLastPoints_(1);
    }

    /**
     * Stop drawing and add the sketch feature to the target layer.
     * The {@link module:ol/interaction/Draw~DrawEventType.DRAWEND} event is
     * dispatched before inserting the feature.
     * @return {Feature<import("../geom/SimpleGeometry.js").default>|null} The drawn feature.
     * @api
     */
    finishDrawing() {
      const sketchFeature = this.abortDrawing_();
      if (!sketchFeature) {
        return null;
      }
      let coordinates = this.sketchCoords_;
      const geometry = sketchFeature.getGeometry();
      const projection = this.getMap().getView().getProjection();
      if (this.mode_ === 'LineString') {
        // remove the redundant last point
        coordinates.pop();
        this.geometryFunction_(coordinates, geometry, projection);
      } else if (this.mode_ === 'Polygon') {
        // remove the redundant last point in ring
        /** @type {PolyCoordType} */ (coordinates)[0].pop();
        this.geometryFunction_(coordinates, geometry, projection);
        coordinates = geometry.getCoordinates();
      }

      // cast multi-part geometries
      if (this.type_ === 'MultiPoint') {
        sketchFeature.setGeometry(
          new MultiPoint([/** @type {PointCoordType} */ (coordinates)]),
        );
      } else if (this.type_ === 'MultiLineString') {
        sketchFeature.setGeometry(
          new MultiLineString([/** @type {LineCoordType} */ (coordinates)]),
        );
      } else if (this.type_ === 'MultiPolygon') {
        sketchFeature.setGeometry(
          new MultiPolygon([/** @type {PolyCoordType} */ (coordinates)]),
        );
      }

      // First dispatch event to allow full set up of feature
      this.dispatchEvent(new DrawEvent(DrawEventType.DRAWEND, sketchFeature));

      // Then insert feature
      if (this.features_) {
        this.features_.push(sketchFeature);
      }
      if (this.source_) {
        this.source_.addFeature(sketchFeature);
      }
      return sketchFeature;
    }

    /**
     * Stop drawing without adding the sketch feature to the target layer.
     * @return {Feature<import("../geom/SimpleGeometry.js").default>|null} The sketch feature (or null if none).
     * @private
     */
    abortDrawing_() {
      this.finishCoordinate_ = null;
      const sketchFeature = this.sketchFeature_;
      this.sketchFeature_ = null;
      this.sketchPoint_ = null;
      this.sketchLine_ = null;
      this.overlay_.getSource().clear(true);
      this.deactivateTrace_();
      return sketchFeature;
    }

    /**
     * Stop drawing without adding the sketch feature to the target layer.
     * @api
     */
    abortDrawing() {
      const sketchFeature = this.abortDrawing_();
      if (sketchFeature) {
        this.dispatchEvent(new DrawEvent(DrawEventType.DRAWABORT, sketchFeature));
      }
    }

    /**
     * Append coordinates to the end of the geometry that is currently being drawn.
     * This can be used when drawing LineStrings or Polygons. Coordinates will
     * either be appended to the current LineString or the outer ring of the current
     * Polygon. If no geometry is being drawn, a new one will be created.
     * @param {!LineCoordType} coordinates Linear coordinates to be appended to
     * the coordinate array.
     * @api
     */
    appendCoordinates(coordinates) {
      const mode = this.mode_;
      const newDrawing = !this.sketchFeature_;
      if (newDrawing) {
        this.startDrawing_(coordinates[0]);
      }
      /** @type {LineCoordType} */
      let sketchCoords;
      if (mode === 'LineString' || mode === 'Circle') {
        sketchCoords = /** @type {LineCoordType} */ (this.sketchCoords_);
      } else if (mode === 'Polygon') {
        sketchCoords =
          this.sketchCoords_ && this.sketchCoords_.length
            ? /** @type {PolyCoordType} */ (this.sketchCoords_)[0]
            : [];
      } else {
        return;
      }

      if (newDrawing) {
        sketchCoords.shift();
      }

      // Remove last coordinate from sketch drawing (this coordinate follows cursor position)
      sketchCoords.pop();

      // Append coordinate list
      for (let i = 0; i < coordinates.length; i++) {
        this.addToDrawing_(coordinates[i]);
      }

      const ending = coordinates[coordinates.length - 1];
      // Duplicate last coordinate for sketch drawing (cursor position)
      this.sketchFeature_ = this.addToDrawing_(ending);
      this.modifyDrawing_(ending);
    }

    /**
     * Initiate draw mode by starting from an existing geometry which will
     * receive new additional points. This only works on features with
     * `LineString` geometries, where the interaction will extend lines by adding
     * points to the end of the coordinates array.
     * This will change the original feature, instead of drawing a copy.
     *
     * The function will dispatch a `drawstart` event.
     *
     * @param {!Feature<LineString>} feature Feature to be extended.
     * @api
     */
    extend(feature) {
      const geometry = feature.getGeometry();
      const lineString = geometry;
      this.sketchFeature_ = feature;
      this.sketchCoords_ = lineString.getCoordinates();
      const last = this.sketchCoords_[this.sketchCoords_.length - 1];
      this.finishCoordinate_ = last.slice();
      this.sketchCoords_.push(last.slice());
      this.sketchPoint_ = new Feature(new Point(last));
      this.updateSketchFeatures_();
      this.dispatchEvent(
        new DrawEvent(DrawEventType.DRAWSTART, this.sketchFeature_),
      );
    }

    /**
     * Redraw the sketch features.
     * @private
     */
    updateSketchFeatures_() {
      const sketchFeatures = [];
      if (this.sketchFeature_) {
        sketchFeatures.push(this.sketchFeature_);
      }
      if (this.sketchLine_) {
        sketchFeatures.push(this.sketchLine_);
      }
      if (this.sketchPoint_) {
        sketchFeatures.push(this.sketchPoint_);
      }
      const overlaySource = this.overlay_.getSource();
      overlaySource.clear(true);
      overlaySource.addFeatures(sketchFeatures);
    }

    /**
     * @private
     */
    updateState_() {
      const map = this.getMap();
      const active = this.getActive();
      if (!map || !active) {
        this.abortDrawing();
      }
      this.overlay_.setMap(active ? map : null);
    }
  }

  /**
   * @return {import("../style/Style.js").StyleFunction} Styles.
   */
  function getDefaultStyleFunction$2() {
    const styles = createEditingStyle();
    return function (feature, resolution) {
      return styles[feature.getGeometry().getType()];
    };
  }

  /**
   * Create a `geometryFunction` that will create a box-shaped polygon (aligned
   * with the coordinate system axes).  Use this with the draw interaction and
   * `type: 'Circle'` to return a box instead of a circle geometry.
   * @return {GeometryFunction} Function that draws a box-shaped polygon.
   * @api
   */
  function createBox() {
    return function (coordinates, geometry, projection) {
      const extent = boundingExtent(
        /** @type {LineCoordType} */ ([
          coordinates[0],
          coordinates[coordinates.length - 1],
        ]).map(function (coordinate) {
          return fromUserCoordinate(coordinate, projection);
        }),
      );
      const boxCoordinates = [
        [
          getBottomLeft(extent),
          getBottomRight(extent),
          getTopRight(extent),
          getTopLeft(extent),
          getBottomLeft(extent),
        ],
      ];
      if (geometry) {
        geometry.setCoordinates(boxCoordinates);
      } else {
        geometry = new Polygon(boxCoordinates);
      }
      const userProjection = getUserProjection();
      if (userProjection) {
        geometry.transform(projection, userProjection);
      }
      return geometry;
    };
  }

  /**
   * Get the drawing mode.  The mode for multi-part geometries is the same as for
   * their single-part cousins.
   * @param {import("../geom/Geometry.js").Type} type Geometry type.
   * @return {Mode} Drawing mode.
   */
  function getMode(type) {
    switch (type) {
      case 'Point':
      case 'MultiPoint':
        return 'Point';
      case 'LineString':
      case 'MultiLineString':
        return 'LineString';
      case 'Polygon':
      case 'MultiPolygon':
        return 'Polygon';
      case 'Circle':
        return 'Circle';
      default:
        throw new Error('Invalid type: ' + type);
    }
  }

  /**
   * @module ol/interaction/Extent
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.always}.
   * @property {import("../extent.js").Extent} [extent] Initial extent. Defaults to no
   * initial extent.
   * @property {import("../style/Style.js").StyleLike} [boxStyle]
   * Style for the drawn extent box. Defaults to the `Polygon` editing style
   * documented in {@link module:ol/style/Style~Style}
   * @property {number} [pixelTolerance=10] Pixel tolerance for considering the
   * pointer close enough to a segment or vertex for editing.
   * @property {import("../style/Style.js").StyleLike} [pointerStyle]
   * Style for the cursor used to draw the extent. Defaults to the `Point` editing style
   * documented in {@link module:ol/style/Style~Style}
   * @property {boolean} [wrapX=false] Wrap the drawn extent across multiple maps
   * in the X direction? Only affects visuals, not functionality.
   */

  /**
   * @enum {string}
   */
  const ExtentEventType = {
    /**
     * Triggered after the extent is changed
     * @event ExtentEvent#extentchanged
     * @api
     */
    EXTENTCHANGED: 'extentchanged',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Extent~Extent} instances are
   * instances of this type.
   */
  class ExtentEvent extends BaseEvent {
    /**
     * @param {import("../extent.js").Extent} extent the new extent
     */
    constructor(extent) {
      super(ExtentEventType.EXTENTCHANGED);

      /**
       * The current extent.
       * @type {import("../extent.js").Extent}
       * @api
       */
      this.extent = extent;
    }
  }

  /**
   * @typedef {function (import("../coordinate.js").Coordinate): import("../extent.js").Extent} PointerHandler
   */

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'extentchanged', ExtentEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'extentchanged', Return>} ExtentOnSignature
   */

  /**
   * @classdesc
   * Allows the user to draw a vector box by clicking and dragging on the map.
   * Once drawn, the vector box can be modified by dragging its vertices or edges.
   * This interaction is only supported for mouse devices.
   *
   * @fires ExtentEvent
   * @api
   */
  class Extent extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options || {};

      super(/** @type {import("./Pointer.js").Options} */ (options));

      /***
       * @type {ExtentOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {ExtentOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {ExtentOnSignature<void>}
       */
      this.un;

      /**
       * Condition
       * @type {import("../events/condition.js").Condition}
       * @private
       */
      this.condition_ = options.condition ? options.condition : always;

      /**
       * Extent of the drawn box
       * @type {import("../extent.js").Extent}
       * @private
       */
      this.extent_ = null;

      /**
       * Handler for pointer move events
       * @type {PointerHandler|null}
       * @private
       */
      this.pointerHandler_ = null;

      /**
       * Pixel threshold to snap to extent
       * @type {number}
       * @private
       */
      this.pixelTolerance_ =
        options.pixelTolerance !== undefined ? options.pixelTolerance : 10;

      /**
       * Is the pointer snapped to an extent vertex
       * @type {boolean}
       * @private
       */
      this.snappedToVertex_ = false;

      /**
       * Feature for displaying the visible extent
       * @type {Feature}
       * @private
       */
      this.extentFeature_ = null;

      /**
       * Feature for displaying the visible pointer
       * @type {Feature<Point>}
       * @private
       */
      this.vertexFeature_ = null;

      if (!options) {
        options = {};
      }

      /**
       * Layer for the extentFeature
       * @type {VectorLayer}
       * @private
       */
      this.extentOverlay_ = new VectorLayer({
        source: new VectorSource({
          useSpatialIndex: false,
          wrapX: !!options.wrapX,
        }),
        style: options.boxStyle
          ? options.boxStyle
          : getDefaultExtentStyleFunction(),
        updateWhileAnimating: true,
        updateWhileInteracting: true,
      });

      /**
       * Layer for the vertexFeature
       * @type {VectorLayer}
       * @private
       */
      this.vertexOverlay_ = new VectorLayer({
        source: new VectorSource({
          useSpatialIndex: false,
          wrapX: !!options.wrapX,
        }),
        style: options.pointerStyle
          ? options.pointerStyle
          : getDefaultPointerStyleFunction(),
        updateWhileAnimating: true,
        updateWhileInteracting: true,
      });

      if (options.extent) {
        this.setExtent(options.extent);
      }
    }

    /**
     * @param {import("../pixel.js").Pixel} pixel cursor location
     * @param {import("../Map.js").default} map map
     * @return {import("../coordinate.js").Coordinate|null} snapped vertex on extent
     * @private
     */
    snapToVertex_(pixel, map) {
      const pixelCoordinate = map.getCoordinateFromPixelInternal(pixel);
      const sortByDistance = function (a, b) {
        return (
          squaredDistanceToSegment(pixelCoordinate, a) -
          squaredDistanceToSegment(pixelCoordinate, b)
        );
      };
      const extent = this.getExtentInternal();
      if (extent) {
        //convert extents to line segments and find the segment closest to pixelCoordinate
        const segments = getSegments(extent);
        segments.sort(sortByDistance);
        const closestSegment = segments[0];

        let vertex = closestOnSegment(pixelCoordinate, closestSegment);
        const vertexPixel = map.getPixelFromCoordinateInternal(vertex);

        //if the distance is within tolerance, snap to the segment
        if (distance(pixel, vertexPixel) <= this.pixelTolerance_) {
          //test if we should further snap to a vertex
          const pixel1 = map.getPixelFromCoordinateInternal(closestSegment[0]);
          const pixel2 = map.getPixelFromCoordinateInternal(closestSegment[1]);
          const squaredDist1 = squaredDistance(vertexPixel, pixel1);
          const squaredDist2 = squaredDistance(vertexPixel, pixel2);
          const dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));
          this.snappedToVertex_ = dist <= this.pixelTolerance_;
          if (this.snappedToVertex_) {
            vertex =
              squaredDist1 > squaredDist2 ? closestSegment[1] : closestSegment[0];
          }
          return vertex;
        }
      }
      return null;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent pointer move event
     * @private
     */
    handlePointerMove_(mapBrowserEvent) {
      const pixel = mapBrowserEvent.pixel;
      const map = mapBrowserEvent.map;

      let vertex = this.snapToVertex_(pixel, map);
      if (!vertex) {
        vertex = map.getCoordinateFromPixelInternal(pixel);
      }
      this.createOrUpdatePointerFeature_(vertex);
    }

    /**
     * @param {import("../extent.js").Extent} extent extent
     * @return {Feature} extent as featrue
     * @private
     */
    createOrUpdateExtentFeature_(extent) {
      let extentFeature = this.extentFeature_;

      if (!extentFeature) {
        if (!extent) {
          extentFeature = new Feature({});
        } else {
          extentFeature = new Feature(fromExtent(extent));
        }
        this.extentFeature_ = extentFeature;
        this.extentOverlay_.getSource().addFeature(extentFeature);
      } else {
        if (!extent) {
          extentFeature.setGeometry(undefined);
        } else {
          extentFeature.setGeometry(fromExtent(extent));
        }
      }
      return extentFeature;
    }

    /**
     * @param {import("../coordinate.js").Coordinate} vertex location of feature
     * @return {Feature} vertex as feature
     * @private
     */
    createOrUpdatePointerFeature_(vertex) {
      let vertexFeature = this.vertexFeature_;
      if (!vertexFeature) {
        vertexFeature = new Feature(new Point(vertex));
        this.vertexFeature_ = vertexFeature;
        this.vertexOverlay_.getSource().addFeature(vertexFeature);
      } else {
        const geometry = vertexFeature.getGeometry();
        geometry.setCoordinates(vertex);
      }
      return vertexFeature;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!mapBrowserEvent.originalEvent || !this.condition_(mapBrowserEvent)) {
        return true;
      }
      //display pointer (if not dragging)
      if (
        mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE &&
        !this.handlingDownUpSequence
      ) {
        this.handlePointerMove_(mapBrowserEvent);
      }
      //call pointer to determine up/down/drag
      super.handleEvent(mapBrowserEvent);
      //return false to stop propagation
      return false;
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(mapBrowserEvent) {
      const pixel = mapBrowserEvent.pixel;
      const map = mapBrowserEvent.map;

      const extent = this.getExtentInternal();
      let vertex = this.snapToVertex_(pixel, map);

      //find the extent corner opposite the passed corner
      const getOpposingPoint = function (point) {
        let x_ = null;
        let y_ = null;
        if (point[0] == extent[0]) {
          x_ = extent[2];
        } else if (point[0] == extent[2]) {
          x_ = extent[0];
        }
        if (point[1] == extent[1]) {
          y_ = extent[3];
        } else if (point[1] == extent[3]) {
          y_ = extent[1];
        }
        if (x_ !== null && y_ !== null) {
          return [x_, y_];
        }
        return null;
      };
      if (vertex && extent) {
        const x =
          vertex[0] == extent[0] || vertex[0] == extent[2] ? vertex[0] : null;
        const y =
          vertex[1] == extent[1] || vertex[1] == extent[3] ? vertex[1] : null;

        //snap to point
        if (x !== null && y !== null) {
          this.pointerHandler_ = getPointHandler(getOpposingPoint(vertex));
          //snap to edge
        } else if (x !== null) {
          this.pointerHandler_ = getEdgeHandler(
            getOpposingPoint([x, extent[1]]),
            getOpposingPoint([x, extent[3]]),
          );
        } else if (y !== null) {
          this.pointerHandler_ = getEdgeHandler(
            getOpposingPoint([extent[0], y]),
            getOpposingPoint([extent[2], y]),
          );
        }
        //no snap - new bbox
      } else {
        vertex = map.getCoordinateFromPixelInternal(pixel);
        this.setExtent([vertex[0], vertex[1], vertex[0], vertex[1]]);
        this.pointerHandler_ = getPointHandler(vertex);
      }
      return true; //event handled; start downup sequence
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @override
     */
    handleDragEvent(mapBrowserEvent) {
      if (this.pointerHandler_) {
        const pixelCoordinate = mapBrowserEvent.coordinate;
        this.setExtent(this.pointerHandler_(pixelCoordinate));
        this.createOrUpdatePointerFeature_(pixelCoordinate);
      }
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(mapBrowserEvent) {
      this.pointerHandler_ = null;
      //If bbox is zero area, set to null;
      const extent = this.getExtentInternal();
      if (!extent || getArea$1(extent) === 0) {
        this.setExtent(null);
      }
      return false; //Stop handling downup sequence
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      this.extentOverlay_.setMap(map);
      this.vertexOverlay_.setMap(map);
      super.setMap(map);
    }

    /**
     * Returns the current drawn extent in the view projection (or user projection if set)
     *
     * @return {import("../extent.js").Extent} Drawn extent in the view projection.
     * @api
     */
    getExtent() {
      return toUserExtent(
        this.getExtentInternal(),
        this.getMap().getView().getProjection(),
      );
    }

    /**
     * Returns the current drawn extent in the view projection
     *
     * @return {import("../extent.js").Extent} Drawn extent in the view projection.
     * @api
     */
    getExtentInternal() {
      return this.extent_;
    }

    /**
     * Manually sets the drawn extent, using the view projection.
     *
     * @param {import("../extent.js").Extent} extent Extent
     * @api
     */
    setExtent(extent) {
      //Null extent means no bbox
      this.extent_ = extent ? extent : null;
      this.createOrUpdateExtentFeature_(extent);
      this.dispatchEvent(new ExtentEvent(this.extent_));
    }
  }

  /**
   * Returns the default style for the drawn bbox
   *
   * @return {import("../style/Style.js").StyleFunction} Default Extent style
   */
  function getDefaultExtentStyleFunction() {
    const style = createEditingStyle();
    return function (feature, resolution) {
      return style['Polygon'];
    };
  }

  /**
   * Returns the default style for the pointer
   *
   * @return {import("../style/Style.js").StyleFunction} Default pointer style
   */
  function getDefaultPointerStyleFunction() {
    const style = createEditingStyle();
    return function (feature, resolution) {
      return style['Point'];
    };
  }

  /**
   * @param {import("../coordinate.js").Coordinate} fixedPoint corner that will be unchanged in the new extent
   * @return {function (import("../coordinate.js").Coordinate): import("../extent.js").Extent} event handler
   */
  function getPointHandler(fixedPoint) {
    return function (point) {
      return boundingExtent([fixedPoint, point]);
    };
  }

  /**
   * @param {import("../coordinate.js").Coordinate} fixedP1 first corner that will be unchanged in the new extent
   * @param {import("../coordinate.js").Coordinate} fixedP2 second corner that will be unchanged in the new extent
   * @return {PointerHandler|null} event handler
   */
  function getEdgeHandler(fixedP1, fixedP2) {
    if (fixedP1[0] == fixedP2[0]) {
      return function (point) {
        return boundingExtent([fixedP1, [point[0], fixedP2[1]]]);
      };
    }
    if (fixedP1[1] == fixedP2[1]) {
      return function (point) {
        return boundingExtent([fixedP1, [fixedP2[0], point[1]]]);
      };
    }
    return null;
  }

  /**
   * @param {import("../extent.js").Extent} extent extent
   * @return {Array<Array<import("../coordinate.js").Coordinate>>} extent line segments
   */
  function getSegments(extent) {
    return [
      [
        [extent[0], extent[1]],
        [extent[0], extent[3]],
      ],
      [
        [extent[0], extent[3]],
        [extent[2], extent[3]],
      ],
      [
        [extent[2], extent[3]],
        [extent[2], extent[1]],
      ],
      [
        [extent[2], extent[1]],
        [extent[0], extent[1]],
      ],
    ];
  }

  /**
   * @module ol/interaction/Link
   */

  /**
   * @param {number} number A number.
   * @return {number} A number with at most 5 decimal places.
   */
  function to5(number) {
    return toFixed(number, 5);
  }

  /**
   * @param {string} string A string.
   * @return {number} A number representing the string.
   */
  function readNumber(string) {
    return parseFloat(string);
  }

  /**
   * @param {number} number A number.
   * @return {string} A string representing the number.
   */
  function writeNumber(number) {
    return to5(number).toString();
  }

  /**
   * @param {number} a A number.
   * @param {number} b A number.
   * @return {boolean} The numbers are different.
   */
  function differentNumber(a, b) {
    if (isNaN(a)) {
      return false;
    }
    return a !== readNumber(writeNumber(b));
  }

  /**
   * @param {Array<number>} a An array of two numbers.
   * @param {Array<number>} b An array of two numbers.
   * @return {boolean} The arrays are different.
   */
  function differentArray(a, b) {
    return differentNumber(a[0], b[0]) || differentNumber(a[1], b[1]);
  }

  /** @typedef {'x'|'y'|'z'|'r'|'l'} Params */

  /**
   * @typedef {function(string):void} Callback
   */

  /**
   * @typedef {Object} Options
   * @property {boolean|import('../View.js').AnimationOptions} [animate=true] Animate view transitions.
   * @property {Array<Params>} [params=['x', 'y', 'z', 'r', 'l']] Properties to track. Default is to track
   * `x` (center x), `y` (center y), `z` (zoom), `r` (rotation) and `l` (layers).
   * @property {boolean} [replace=false] Replace the current URL without creating the new entry in browser history.
   * By default, changes in the map state result in a new entry being added to the browser history.
   * @property {string} [prefix=''] By default, the URL will be updated with search parameters x, y, z, and r.  To
   * avoid collisions with existing search parameters that your application uses, you can supply a custom prefix for
   * the ones used by this interaction (e.g. 'ol:').
   */

  /**
   * @classdesc
   * An interaction that synchronizes the map state with the URL.
   *
   * @api
   */
  class Link extends Interaction {
    /**
     * @param {Options} [options] Link options.
     */
    constructor(options) {
      super();

      options = Object.assign(
        {
          animate: true,
          params: ['x', 'y', 'z', 'r', 'l'],
          replace: false,
          prefix: '',
        },
        options || {},
      );

      let animationOptions;
      if (options.animate === true) {
        animationOptions = {duration: 250};
      } else if (!options.animate) {
        animationOptions = null;
      } else {
        animationOptions = options.animate;
      }

      /**
       * @type {import('../View.js').AnimationOptions|null}
       * @private
       */
      this.animationOptions_ = animationOptions;

      /**
       * @type {Object<Params, boolean>}
       * @private
       */
      this.params_ = options.params.reduce((acc, value) => {
        acc[value] = true;
        return acc;
      }, {});

      /**
       * @private
       * @type {boolean}
       */
      this.replace_ = options.replace;

      /**
       * @private
       * @type {string}
       */
      this.prefix_ = options.prefix;

      /**
       * @private
       * @type {!Array<import("../events.js").EventsKey>}
       */
      this.listenerKeys_ = [];

      /**
       * @private
       * @type {boolean}
       */
      this.initial_ = true;

      /**
       * @private
       */
      this.updateState_ = this.updateState_.bind(this);

      /**
       * The tracked parameter callbacks.
       * @private
       * @type {Object<string, Callback>}
       */
      this.trackedCallbacks_ = {};

      /**
       * The tracked parameter values.
       * @private
       * @type {Object<string, string|null>}
       */
      this.trackedValues_ = {};
    }

    /**
     * @private
     * @param {string} name A parameter name.
     * @return {string} A name with the prefix applied.
     */
    getParamName_(name) {
      if (!this.prefix_) {
        return name;
      }
      return this.prefix_ + name;
    }

    /**
     * @private
     * @param {URLSearchParams} params The search params.
     * @param {string} name The unprefixed parameter name.
     * @return {string|null} The parameter value.
     */
    get_(params, name) {
      return params.get(this.getParamName_(name));
    }

    /**
     * @private
     * @param {URLSearchParams} params The search params.
     * @param {string} name The unprefixed parameter name.
     * @param {string} value The param value.
     */
    set_(params, name, value) {
      if (!(name in this.params_)) {
        return;
      }
      params.set(this.getParamName_(name), value);
    }

    /**
     * @private
     * @param {URLSearchParams} params The search params.
     * @param {string} name The unprefixed parameter name.
     */
    delete_(params, name) {
      if (!(name in this.params_)) {
        return;
      }
      params.delete(this.getParamName_(name));
    }

    /**
     * @param {import("../Map.js").default|null} map Map.
     * @override
     */
    setMap(map) {
      const oldMap = this.getMap();
      super.setMap(map);
      if (map === oldMap) {
        return;
      }
      if (oldMap) {
        this.unregisterListeners_(oldMap);
      }
      if (map) {
        this.initial_ = true;
        this.updateState_();
        this.registerListeners_(map);
      }
    }

    /**
     * @param {import("../Map.js").default} map Map.
     * @private
     */
    registerListeners_(map) {
      this.listenerKeys_.push(
        listen(map, MapEventType.MOVEEND, this.updateUrl_, this),
        listen(map.getLayerGroup(), EventType.CHANGE, this.updateUrl_, this),
        listen(map, 'change:layergroup', this.handleChangeLayerGroup_, this),
      );

      if (!this.replace_) {
        addEventListener('popstate', this.updateState_);
      }
    }

    /**
     * @param {import("../Map.js").default} map Map.
     * @private
     */
    unregisterListeners_(map) {
      for (let i = 0, ii = this.listenerKeys_.length; i < ii; ++i) {
        unlistenByKey(this.listenerKeys_[i]);
      }
      this.listenerKeys_.length = 0;

      if (!this.replace_) {
        removeEventListener('popstate', this.updateState_);
      }

      const url = new URL(window.location.href);
      const params = url.searchParams;
      this.delete_(params, 'x');
      this.delete_(params, 'y');
      this.delete_(params, 'z');
      this.delete_(params, 'r');
      this.delete_(params, 'l');
      window.history.replaceState(null, '', url);
    }

    /**
     * @private
     */
    handleChangeLayerGroup_() {
      const map = this.getMap();
      if (!map) {
        return;
      }
      this.unregisterListeners_(map);
      this.registerListeners_(map);
      this.initial_ = true;
      this.updateUrl_();
    }

    /**
     * @private
     */
    updateState_() {
      const url = new URL(window.location.href);
      const params = url.searchParams;
      for (const key in this.trackedCallbacks_) {
        const value = params.get(key);
        if (key in this.trackedCallbacks_ && value !== this.trackedValues_[key]) {
          this.trackedValues_[key] = value;
          this.trackedCallbacks_[key](value);
        }
      }

      const map = this.getMap();
      if (!map) {
        return;
      }
      const view = map.getView();
      if (!view) {
        return;
      }

      let updateView = false;

      /**
       * @type {import('../View.js').AnimationOptions}
       */
      const viewProperties = {};

      const zoom = readNumber(this.get_(params, 'z'));
      if ('z' in this.params_ && differentNumber(zoom, view.getZoom())) {
        updateView = true;
        viewProperties.zoom = zoom;
      }

      const rotation = readNumber(this.get_(params, 'r'));
      if ('r' in this.params_ && differentNumber(rotation, view.getRotation())) {
        updateView = true;
        viewProperties.rotation = rotation;
      }

      const center = [
        readNumber(this.get_(params, 'x')),
        readNumber(this.get_(params, 'y')),
      ];
      if (
        ('x' in this.params_ || 'y' in this.params_) &&
        differentArray(center, view.getCenter())
      ) {
        updateView = true;
        viewProperties.center = center;
      }

      if (updateView) {
        if (!this.initial_ && this.animationOptions_) {
          view.animate(Object.assign(viewProperties, this.animationOptions_));
        } else {
          if (viewProperties.center) {
            view.setCenter(viewProperties.center);
          }
          if ('zoom' in viewProperties) {
            view.setZoom(viewProperties.zoom);
          }
          if ('rotation' in viewProperties) {
            view.setRotation(viewProperties.rotation);
          }
        }
      }

      const layers = map.getAllLayers();
      const layersParam = this.get_(params, 'l');
      if (
        'l' in this.params_ &&
        layersParam &&
        layersParam.length === layers.length
      ) {
        for (let i = 0, ii = layers.length; i < ii; ++i) {
          const value = parseInt(layersParam[i]);
          if (!isNaN(value)) {
            const visible = Boolean(value);
            const layer = layers[i];
            if (layer.getVisible() !== visible) {
              layer.setVisible(visible);
            }
          }
        }
      }
    }

    /**
     * Register a listener for a URL search parameter.  The callback will be called with a new value
     * when the corresponding search parameter changes due to history events (e.g. browser navigation).
     *
     * @param {string} key The URL search parameter.
     * @param {Callback} callback The function to call when the search parameter changes.
     * @return {string|null} The initial value of the search parameter (or null if absent from the URL).
     * @api
     */
    track(key, callback) {
      this.trackedCallbacks_[key] = callback;
      const url = new URL(window.location.href);
      const params = url.searchParams;
      const value = params.get(key);
      this.trackedValues_[key] = value;
      return value;
    }

    /**
     * Update the URL with a new search parameter value.  If the value is null, it will be
     * deleted from the search parameters.
     *
     * @param {string} key The URL search parameter.
     * @param {string|null} value The updated value (or null to remove it from the URL).
     * @api
     */
    update(key, value) {
      const url = new URL(window.location.href);
      const params = url.searchParams;
      if (value === null) {
        params.delete(key);
      } else {
        params.set(key, value);
      }
      if (key in this.trackedValues_) {
        this.trackedValues_[key] = value;
      }
      this.updateHistory_(url);
    }

    /**
     * @private
     */
    updateUrl_() {
      const map = this.getMap();
      if (!map) {
        return;
      }
      const view = map.getView();
      if (!view) {
        return;
      }

      const center = view.getCenter();
      const zoom = view.getZoom();
      const rotation = view.getRotation();

      const layers = map.getAllLayers();
      const visibilities = new Array(layers.length);
      for (let i = 0, ii = layers.length; i < ii; ++i) {
        visibilities[i] = layers[i].getVisible() ? '1' : '0';
      }

      const url = new URL(window.location.href);
      const params = url.searchParams;

      this.set_(params, 'x', writeNumber(center[0]));
      this.set_(params, 'y', writeNumber(center[1]));
      this.set_(params, 'z', writeNumber(zoom));
      this.set_(params, 'r', writeNumber(rotation));
      this.set_(params, 'l', visibilities.join(''));

      this.updateHistory_(url);
      this.initial_ = false;
    }

    /**
     * @private
     * @param {URL} url The URL.
     */
    updateHistory_(url) {
      if (url.href !== window.location.href) {
        if (this.initial_ || this.replace_) {
          window.history.replaceState(history.state, '', url);
        } else {
          window.history.pushState(null, '', url);
        }
      }
    }
  }

  /**
   * @module ol/interaction/Modify
   */

  /**
   * The segment index assigned to a circle's center when
   * breaking up a circle into ModifySegmentDataType segments.
   * @type {number}
   */
  const CIRCLE_CENTER_INDEX = 0;

  /**
   * The segment index assigned to a circle's circumference when
   * breaking up a circle into ModifySegmentDataType segments.
   * @type {number}
   */
  const CIRCLE_CIRCUMFERENCE_INDEX = 1;

  const tempExtent = [0, 0, 0, 0];
  const tempSegment$1 = [];

  /**
   * @enum {string}
   */
  const ModifyEventType = {
    /**
     * Triggered upon feature modification start
     * @event ModifyEvent#modifystart
     * @api
     */
    MODIFYSTART: 'modifystart',
    /**
     * Triggered upon feature modification end
     * @event ModifyEvent#modifyend
     * @api
     */
    MODIFYEND: 'modifyend',
  };

  /**
   * @typedef {Object} SegmentData
   * @property {Array<number>} [depth] Depth.
   * @property {Feature} feature Feature.
   * @property {import("../geom/SimpleGeometry.js").default} geometry Geometry.
   * @property {number} [index] Index.
   * @property {Array<Array<number>>} segment Segment.
   * @property {Array<SegmentData>} [featureSegments] FeatureSegments.
   */

  /**
   * @typedef {[SegmentData, number]} DragSegment
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event will be considered to add or move a
   * vertex to the sketch. Default is
   * {@link module:ol/events/condition.primaryAction}.
   * @property {import("../events/condition.js").Condition} [deleteCondition] A function
   * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. By default,
   * {@link module:ol/events/condition.singleClick} with
   * {@link module:ol/events/condition.altKeyOnly} results in a vertex deletion.
   * @property {import("../events/condition.js").Condition} [insertVertexCondition] A
   * function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and
   * returns a boolean to indicate whether a new vertex should be added to the sketch
   * features. Default is {@link module:ol/events/condition.always}.
   * @property {number} [pixelTolerance=10] Pixel tolerance for considering the
   * pointer close enough to a segment or vertex for editing.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike} [style]
   * Style used for the modification point or vertex. For linestrings and polygons, this will
   * be the affected vertex, for circles a point along the circle, and for points the actual
   * point. If not configured, the default edit style is used (see {@link module:ol/style/Style~Style}).
   * When using a style function, the point feature passed to the function will have an `existing` property -
   * indicating whether there is an existing vertex underneath or not, a `features`
   * property - an array whose entries are the features that are being modified, and a `geometries`
   * property - an array whose entries are the geometries that are being modified. Both arrays are
   * in the same order. The `geometries` are only useful when modifying geometry collections, where
   * the geometry will be the particular geometry from the collection that is being modified.
   * @property {VectorSource} [source] The vector source with
   * features to modify.  If a vector source is not provided, a feature collection
   * must be provided with the `features` option.
   * @property {boolean|import("../layer/BaseVector").default} [hitDetection] When configured, point
   * features will be considered for modification based on their visual appearance, instead of being within
   * the `pixelTolerance` from the pointer location. When a {@link module:ol/layer/BaseVector~BaseVectorLayer} is
   * provided, only the rendered representation of the features on that layer will be considered.
   * @property {Collection<Feature>} [features]
   * The features the interaction works on.  If a feature collection is not
   * provided, a vector source must be provided with the `source` option.
   * @property {boolean} [wrapX=false] Wrap the world horizontally on the sketch
   * overlay.
   * @property {boolean} [snapToPointer=!hitDetection] The vertex, point or segment being modified snaps to the
   * pointer coordinate when clicked within the `pixelTolerance`.
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Modify~Modify} instances are
   * instances of this type.
   */
  class ModifyEvent extends BaseEvent {
    /**
     * @param {ModifyEventType} type Type.
     * @param {Collection<Feature>} features
     * The features modified.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent
     * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
     */
    constructor(type, features, mapBrowserEvent) {
      super(type);

      /**
       * The features being modified.
       * @type {Collection<Feature>}
       * @api
       */
      this.features = features;

      /**
       * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
       * @type {import("../MapBrowserEvent.js").default}
       * @api
       */
      this.mapBrowserEvent = mapBrowserEvent;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'modifyend'|'modifystart', ModifyEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'modifyend'|'modifystart', Return>} ModifyOnSignature
   */

  /**
   * @classdesc
   * Interaction for modifying feature geometries.  To modify features that have
   * been added to an existing source, construct the modify interaction with the
   * `source` option.  If you want to modify features in a collection (for example,
   * the collection used by a select interaction), construct the interaction with
   * the `features` option.  The interaction must be constructed with either a
   * `source` or `features` option.
   *
   * Cartesian distance from the pointer is used to determine the features that
   * will be modified. This means that geometries will only be considered for
   * modification when they are within the configured `pixelTolerance`. For point
   * geometries, the `hitDetection` option can be used to match their visual
   * appearance.
   *
   * By default, the interaction will allow deletion of vertices when the `alt`
   * key is pressed.  To configure the interaction with a different condition
   * for deletion, use the `deleteCondition` option.
   * @fires ModifyEvent
   * @api
   */
  class Modify extends PointerInteraction {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      super(/** @type {import("./Pointer.js").Options} */ (options));

      /***
       * @type {ModifyOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {ModifyOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {ModifyOnSignature<void>}
       */
      this.un;

      /** @private */
      this.boundHandleFeatureChange_ = this.handleFeatureChange_.bind(this);

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : primaryAction;

      /**
       * @private
       * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Browser event.
       * @return {boolean} Combined condition result.
       */
      this.defaultDeleteCondition_ = function (mapBrowserEvent) {
        return altKeyOnly(mapBrowserEvent) && singleClick(mapBrowserEvent);
      };

      /**
       * @type {import("../events/condition.js").Condition}
       * @private
       */
      this.deleteCondition_ = options.deleteCondition
        ? options.deleteCondition
        : this.defaultDeleteCondition_;

      /**
       * @type {import("../events/condition.js").Condition}
       * @private
       */
      this.insertVertexCondition_ = options.insertVertexCondition
        ? options.insertVertexCondition
        : always;

      /**
       * Editing vertex.
       * @type {Feature<Point>}
       * @private
       */
      this.vertexFeature_ = null;

      /**
       * Segments intersecting {@link this.vertexFeature_} by segment uid.
       * @type {Object<string, boolean>}
       * @private
       */
      this.vertexSegments_ = null;

      /**
       * @type {import("../pixel.js").Pixel}
       * @private
       */
      this.lastPixel_ = [0, 0];

      /**
       * Tracks if the next `singleclick` event should be ignored to prevent
       * accidental deletion right after vertex creation.
       * @type {boolean}
       * @private
       */
      this.ignoreNextSingleClick_ = false;

      /**
       * @type {Collection<Feature>}
       * @private
       */
      this.featuresBeingModified_ = null;

      /**
       * Segment RTree for each layer
       * @type {RBush<SegmentData>}
       * @private
       */
      this.rBush_ = new RBush();

      /**
       * @type {number}
       * @private
       */
      this.pixelTolerance_ =
        options.pixelTolerance !== undefined ? options.pixelTolerance : 10;

      /**
       * @type {boolean}
       * @private
       */
      this.snappedToVertex_ = false;

      /**
       * Indicate whether the interaction is currently changing a feature's
       * coordinates.
       * @type {boolean}
       * @private
       */
      this.changingFeature_ = false;

      /**
       * @type {Array<DragSegment>}
       * @private
       */
      this.dragSegments_ = [];

      /**
       * Draw overlay where sketch features are drawn.
       * @type {VectorLayer}
       * @private
       */
      this.overlay_ = new VectorLayer({
        source: new VectorSource({
          useSpatialIndex: false,
          wrapX: !!options.wrapX,
        }),
        style: options.style ? options.style : getDefaultStyleFunction$1(),
        updateWhileAnimating: true,
        updateWhileInteracting: true,
      });

      /**
       * @const
       * @private
       * @type {!Object<string, function(Feature, import("../geom/Geometry.js").default): void>}
       */
      this.SEGMENT_WRITERS_ = {
        'Point': this.writePointGeometry_.bind(this),
        'LineString': this.writeLineStringGeometry_.bind(this),
        'LinearRing': this.writeLineStringGeometry_.bind(this),
        'Polygon': this.writePolygonGeometry_.bind(this),
        'MultiPoint': this.writeMultiPointGeometry_.bind(this),
        'MultiLineString': this.writeMultiLineStringGeometry_.bind(this),
        'MultiPolygon': this.writeMultiPolygonGeometry_.bind(this),
        'Circle': this.writeCircleGeometry_.bind(this),
        'GeometryCollection': this.writeGeometryCollectionGeometry_.bind(this),
      };

      /**
       * @type {VectorSource}
       * @private
       */
      this.source_ = null;

      /**
       * @type {boolean|import("../layer/BaseVector").default}
       * @private
       */
      this.hitDetection_ = null;

      /** @type {Collection<Feature>} */
      let features;
      if (options.features) {
        features = options.features;
      } else if (options.source) {
        this.source_ = options.source;
        features = new Collection(this.source_.getFeatures());
        this.source_.addEventListener(
          VectorEventType.ADDFEATURE,
          this.handleSourceAdd_.bind(this),
        );
        this.source_.addEventListener(
          VectorEventType.REMOVEFEATURE,
          this.handleSourceRemove_.bind(this),
        );
      }
      if (!features) {
        throw new Error(
          'The modify interaction requires features, a source or a layer',
        );
      }
      if (options.hitDetection) {
        this.hitDetection_ = options.hitDetection;
      }

      /**
       * @type {Collection<Feature>}
       * @private
       */
      this.features_ = features;

      this.features_.forEach(this.addFeature_.bind(this));
      this.features_.addEventListener(
        CollectionEventType.ADD,
        this.handleFeatureAdd_.bind(this),
      );
      this.features_.addEventListener(
        CollectionEventType.REMOVE,
        this.handleFeatureRemove_.bind(this),
      );

      /**
       * @type {import("../MapBrowserEvent.js").default}
       * @private
       */
      this.lastPointerEvent_ = null;

      /**
       * Delta (x, y in map units) between matched rtree vertex and pointer vertex.
       * @type {Array<number>}
       * @private
       */
      this.delta_ = [0, 0];

      /**
       * @private
       */
      this.snapToPointer_ =
        options.snapToPointer === undefined
          ? !this.hitDetection_
          : options.snapToPointer;
    }

    /**
     * @param {Feature} feature Feature.
     * @private
     */
    addFeature_(feature) {
      const geometry = feature.getGeometry();
      if (geometry) {
        const writer = this.SEGMENT_WRITERS_[geometry.getType()];
        if (writer) {
          writer(feature, geometry);
        }
      }
      const map = this.getMap();
      if (map && map.isRendered() && this.getActive()) {
        this.handlePointerAtPixel_(map.getCoordinateFromPixel(this.lastPixel_));
      }
      feature.addEventListener(EventType.CHANGE, this.boundHandleFeatureChange_);
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} evt Map browser event.
     * @param {Array<SegmentData>} segments The segments subject to modification.
     * @private
     */
    willModifyFeatures_(evt, segments) {
      if (!this.featuresBeingModified_) {
        this.featuresBeingModified_ = new Collection();
        const features = this.featuresBeingModified_.getArray();
        for (let i = 0, ii = segments.length; i < ii; ++i) {
          const feature = segments[i].feature;
          if (feature && !features.includes(feature)) {
            this.featuresBeingModified_.push(feature);
          }
        }
        if (this.featuresBeingModified_.getLength() === 0) {
          this.featuresBeingModified_ = null;
        } else {
          this.dispatchEvent(
            new ModifyEvent(
              ModifyEventType.MODIFYSTART,
              this.featuresBeingModified_,
              evt,
            ),
          );
        }
      }
    }

    /**
     * @param {Feature} feature Feature.
     * @private
     */
    removeFeature_(feature) {
      this.removeFeatureSegmentData_(feature);
      // Remove the vertex feature if the collection of candidate features is empty.
      if (this.vertexFeature_ && this.features_.getLength() === 0) {
        this.overlay_.getSource().removeFeature(this.vertexFeature_);
        this.vertexFeature_ = null;
      }
      feature.removeEventListener(
        EventType.CHANGE,
        this.boundHandleFeatureChange_,
      );
    }

    /**
     * @param {Feature} feature Feature.
     * @private
     */
    removeFeatureSegmentData_(feature) {
      const rBush = this.rBush_;
      /** @type {Array<SegmentData>} */
      const nodesToRemove = [];
      rBush.forEach(
        /**
         * @param {SegmentData} node RTree node.
         */
        function (node) {
          if (feature === node.feature) {
            nodesToRemove.push(node);
          }
        },
      );
      for (let i = nodesToRemove.length - 1; i >= 0; --i) {
        const nodeToRemove = nodesToRemove[i];
        for (let j = this.dragSegments_.length - 1; j >= 0; --j) {
          if (this.dragSegments_[j][0] === nodeToRemove) {
            this.dragSegments_.splice(j, 1);
          }
        }
        rBush.remove(nodeToRemove);
      }
    }

    /**
     * Activate or deactivate the interaction.
     * @param {boolean} active Active.
     * @observable
     * @api
     * @override
     */
    setActive(active) {
      if (this.vertexFeature_ && !active) {
        this.overlay_.getSource().removeFeature(this.vertexFeature_);
        this.vertexFeature_ = null;
      }
      super.setActive(active);
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      this.overlay_.setMap(map);
      super.setMap(map);
    }

    /**
     * Get the overlay layer that this interaction renders the modification point or vertex to.
     * @return {VectorLayer} Overlay layer.
     * @api
     */
    getOverlay() {
      return this.overlay_;
    }

    /**
     * @param {import("../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceAdd_(event) {
      if (event.feature) {
        this.features_.push(event.feature);
      }
    }

    /**
     * @param {import("../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceRemove_(event) {
      if (event.feature) {
        this.features_.remove(event.feature);
      }
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<Feature>} evt Event.
     * @private
     */
    handleFeatureAdd_(evt) {
      this.addFeature_(evt.element);
    }

    /**
     * @param {import("../events/Event.js").default} evt Event.
     * @private
     */
    handleFeatureChange_(evt) {
      if (!this.changingFeature_) {
        const feature = /** @type {Feature} */ (evt.target);
        this.removeFeature_(feature);
        this.addFeature_(feature);
      }
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<Feature>} evt Event.
     * @private
     */
    handleFeatureRemove_(evt) {
      this.removeFeature_(evt.element);
    }

    /**
     * @param {Feature} feature Feature
     * @param {Point} geometry Geometry.
     * @private
     */
    writePointGeometry_(feature, geometry) {
      const coordinates = geometry.getCoordinates();

      /** @type {SegmentData} */
      const segmentData = {
        feature: feature,
        geometry: geometry,
        segment: [coordinates, coordinates],
      };

      this.rBush_.insert(geometry.getExtent(), segmentData);
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/MultiPoint.js").default} geometry Geometry.
     * @private
     */
    writeMultiPointGeometry_(feature, geometry) {
      const points = geometry.getCoordinates();
      for (let i = 0, ii = points.length; i < ii; ++i) {
        const coordinates = points[i];

        /** @type {SegmentData} */
        const segmentData = {
          feature: feature,
          geometry: geometry,
          depth: [i],
          index: i,
          segment: [coordinates, coordinates],
        };

        this.rBush_.insert(geometry.getExtent(), segmentData);
      }
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/LineString.js").default} geometry Geometry.
     * @private
     */
    writeLineStringGeometry_(feature, geometry) {
      const coordinates = geometry.getCoordinates();
      for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {
        const segment = coordinates.slice(i, i + 2);

        /** @type {SegmentData} */
        const segmentData = {
          feature: feature,
          geometry: geometry,
          index: i,
          segment: segment,
        };

        this.rBush_.insert(boundingExtent(segment), segmentData);
      }
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/MultiLineString.js").default} geometry Geometry.
     * @private
     */
    writeMultiLineStringGeometry_(feature, geometry) {
      const lines = geometry.getCoordinates();
      for (let j = 0, jj = lines.length; j < jj; ++j) {
        const coordinates = lines[j];
        for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {
          const segment = coordinates.slice(i, i + 2);

          /** @type {SegmentData} */
          const segmentData = {
            feature: feature,
            geometry: geometry,
            depth: [j],
            index: i,
            segment: segment,
          };

          this.rBush_.insert(boundingExtent(segment), segmentData);
        }
      }
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/Polygon.js").default} geometry Geometry.
     * @private
     */
    writePolygonGeometry_(feature, geometry) {
      const rings = geometry.getCoordinates();
      for (let j = 0, jj = rings.length; j < jj; ++j) {
        const coordinates = rings[j];
        for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {
          const segment = coordinates.slice(i, i + 2);

          /** @type {SegmentData} */
          const segmentData = {
            feature: feature,
            geometry: geometry,
            depth: [j],
            index: i,
            segment: segment,
          };

          this.rBush_.insert(boundingExtent(segment), segmentData);
        }
      }
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/MultiPolygon.js").default} geometry Geometry.
     * @private
     */
    writeMultiPolygonGeometry_(feature, geometry) {
      const polygons = geometry.getCoordinates();
      for (let k = 0, kk = polygons.length; k < kk; ++k) {
        const rings = polygons[k];
        for (let j = 0, jj = rings.length; j < jj; ++j) {
          const coordinates = rings[j];
          for (let i = 0, ii = coordinates.length - 1; i < ii; ++i) {
            const segment = coordinates.slice(i, i + 2);

            /** @type {SegmentData} */
            const segmentData = {
              feature: feature,
              geometry: geometry,
              depth: [j, k],
              index: i,
              segment: segment,
            };

            this.rBush_.insert(boundingExtent(segment), segmentData);
          }
        }
      }
    }

    /**
     * We convert a circle into two segments.  The segment at index
     * {@link CIRCLE_CENTER_INDEX} is the
     * circle's center (a point).  The segment at index
     * {@link CIRCLE_CIRCUMFERENCE_INDEX} is
     * the circumference, and is not a line segment.
     *
     * @param {Feature} feature Feature.
     * @param {import("../geom/Circle.js").default} geometry Geometry.
     * @private
     */
    writeCircleGeometry_(feature, geometry) {
      const coordinates = geometry.getCenter();

      /** @type {SegmentData} */
      const centerSegmentData = {
        feature: feature,
        geometry: geometry,
        index: CIRCLE_CENTER_INDEX,
        segment: [coordinates, coordinates],
      };

      /** @type {SegmentData} */
      const circumferenceSegmentData = {
        feature: feature,
        geometry: geometry,
        index: CIRCLE_CIRCUMFERENCE_INDEX,
        segment: [coordinates, coordinates],
      };

      const featureSegments = [centerSegmentData, circumferenceSegmentData];
      centerSegmentData.featureSegments = featureSegments;
      circumferenceSegmentData.featureSegments = featureSegments;
      this.rBush_.insert(createOrUpdateFromCoordinate(coordinates), centerSegmentData);
      let circleGeometry = /** @type {import("../geom/Geometry.js").default} */ (
        geometry
      );
      const userProjection = getUserProjection();
      if (userProjection && this.getMap()) {
        const projection = this.getMap().getView().getProjection();
        circleGeometry = circleGeometry
          .clone()
          .transform(userProjection, projection);
        circleGeometry = fromCircle(
          /** @type {import("../geom/Circle.js").default} */ (circleGeometry),
        ).transform(projection, userProjection);
      }
      this.rBush_.insert(circleGeometry.getExtent(), circumferenceSegmentData);
    }

    /**
     * @param {Feature} feature Feature
     * @param {import("../geom/GeometryCollection.js").default} geometry Geometry.
     * @private
     */
    writeGeometryCollectionGeometry_(feature, geometry) {
      const geometries = geometry.getGeometriesArray();
      for (let i = 0; i < geometries.length; ++i) {
        const geometry = geometries[i];
        const writer = this.SEGMENT_WRITERS_[geometry.getType()];
        writer(feature, geometry);
      }
    }

    /**
     * @param {import("../coordinate.js").Coordinate} coordinates Coordinates.
     * @param {Array<Feature>} features The features being modified.
     * @param {Array<import("../geom/SimpleGeometry.js").default>} geometries The geometries being modified.
     * @param {boolean} existing The vertex represents an existing vertex.
     * @return {Feature} Vertex feature.
     * @private
     */
    createOrUpdateVertexFeature_(coordinates, features, geometries, existing) {
      let vertexFeature = this.vertexFeature_;
      if (!vertexFeature) {
        vertexFeature = new Feature(new Point(coordinates));
        this.vertexFeature_ = vertexFeature;
        this.overlay_.getSource().addFeature(vertexFeature);
      } else {
        const geometry = vertexFeature.getGeometry();
        geometry.setCoordinates(coordinates);
      }
      vertexFeature.set('features', features);
      vertexFeature.set('geometries', geometries);
      vertexFeature.set('existing', existing);
      return vertexFeature;
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may modify the geometry.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!mapBrowserEvent.originalEvent) {
        return true;
      }
      this.lastPointerEvent_ = mapBrowserEvent;

      let handled;
      if (
        !mapBrowserEvent.map.getView().getInteracting() &&
        mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE &&
        !this.handlingDownUpSequence
      ) {
        this.handlePointerMove_(mapBrowserEvent);
      }
      if (this.vertexFeature_ && this.deleteCondition_(mapBrowserEvent)) {
        if (
          mapBrowserEvent.type != MapBrowserEventType.SINGLECLICK ||
          !this.ignoreNextSingleClick_
        ) {
          handled = this.removePoint();
        } else {
          handled = true;
        }
      }

      if (mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK) {
        this.ignoreNextSingleClick_ = false;
      }

      return super.handleEvent(mapBrowserEvent) && !handled;
    }

    findInsertVerticesAndUpdateDragSegments_(pixelCoordinate) {
      this.handlePointerAtPixel_(pixelCoordinate);
      this.dragSegments_.length = 0;
      this.featuresBeingModified_ = null;
      const vertexFeature = this.vertexFeature_;
      if (!vertexFeature) {
        return;
      }

      const projection = this.getMap().getView().getProjection();
      const insertVertices = [];
      const vertex = vertexFeature.getGeometry().getCoordinates();
      const vertexExtent = boundingExtent([vertex]);
      const segmentDataMatches = this.rBush_.getInExtent(vertexExtent);
      const componentSegments = {};
      segmentDataMatches.sort(compareIndexes);
      for (let i = 0, ii = segmentDataMatches.length; i < ii; ++i) {
        const segmentDataMatch = segmentDataMatches[i];
        const segment = segmentDataMatch.segment;
        let uid = getUid(segmentDataMatch.geometry);
        const depth = segmentDataMatch.depth;
        if (depth) {
          uid += '-' + depth.join('-'); // separate feature components
        }
        if (!componentSegments[uid]) {
          componentSegments[uid] = new Array(2);
        }

        if (
          segmentDataMatch.geometry.getType() === 'Circle' &&
          segmentDataMatch.index === CIRCLE_CIRCUMFERENCE_INDEX
        ) {
          const closestVertex = closestOnSegmentData(
            pixelCoordinate,
            segmentDataMatch,
            projection,
          );
          if (
            equals(closestVertex, vertex) &&
            !componentSegments[uid][0]
          ) {
            this.dragSegments_.push([segmentDataMatch, 0]);
            componentSegments[uid][0] = segmentDataMatch;
          }
          continue;
        }

        if (equals(segment[0], vertex) && !componentSegments[uid][0]) {
          this.dragSegments_.push([segmentDataMatch, 0]);
          componentSegments[uid][0] = segmentDataMatch;
          continue;
        }

        if (equals(segment[1], vertex) && !componentSegments[uid][1]) {
          if (
            componentSegments[uid][0] &&
            componentSegments[uid][0].index === 0
          ) {
            let coordinates = segmentDataMatch.geometry.getCoordinates();
            switch (segmentDataMatch.geometry.getType()) {
              // prevent dragging closed linestrings by the connecting node
              case 'LineString':
              case 'MultiLineString':
                continue;
              // if dragging the first vertex of a polygon, ensure the other segment
              // belongs to the closing vertex of the linear ring
              case 'MultiPolygon':
                coordinates = coordinates[depth[1]];
              /* falls through */
              case 'Polygon':
                if (segmentDataMatch.index !== coordinates[depth[0]].length - 2) {
                  continue;
                }
                break;
              // pass
            }
          }

          this.dragSegments_.push([segmentDataMatch, 1]);
          componentSegments[uid][1] = segmentDataMatch;
          continue;
        }

        if (
          getUid(segment) in this.vertexSegments_ &&
          !componentSegments[uid][0] &&
          !componentSegments[uid][1]
        ) {
          insertVertices.push(segmentDataMatch);
        }
      }

      return insertVertices;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} evt Event.
     * @override
     */
    handleDragEvent(evt) {
      this.ignoreNextSingleClick_ = false;
      this.willModifyFeatures_(
        evt,
        this.dragSegments_.map(([segment]) => segment),
      );

      const vertex = [
        evt.coordinate[0] + this.delta_[0],
        evt.coordinate[1] + this.delta_[1],
      ];
      const features = [];
      const geometries = [];
      for (let i = 0, ii = this.dragSegments_.length; i < ii; ++i) {
        const dragSegment = this.dragSegments_[i];
        const segmentData = dragSegment[0];
        const feature = segmentData.feature;
        if (!features.includes(feature)) {
          features.push(feature);
        }
        const geometry = segmentData.geometry;
        if (!geometries.includes(geometry)) {
          geometries.push(geometry);
        }
        const depth = segmentData.depth;
        let coordinates;
        const segment = segmentData.segment;
        const index = dragSegment[1];

        while (vertex.length < geometry.getStride()) {
          vertex.push(segment[index][vertex.length]);
        }

        switch (geometry.getType()) {
          case 'Point':
            coordinates = vertex;
            segment[0] = vertex;
            segment[1] = vertex;
            break;
          case 'MultiPoint':
            coordinates = geometry.getCoordinates();
            coordinates[segmentData.index] = vertex;
            segment[0] = vertex;
            segment[1] = vertex;
            break;
          case 'LineString':
            coordinates = geometry.getCoordinates();
            coordinates[segmentData.index + index] = vertex;
            segment[index] = vertex;
            break;
          case 'MultiLineString':
            coordinates = geometry.getCoordinates();
            coordinates[depth[0]][segmentData.index + index] = vertex;
            segment[index] = vertex;
            break;
          case 'Polygon':
            coordinates = geometry.getCoordinates();
            coordinates[depth[0]][segmentData.index + index] = vertex;
            segment[index] = vertex;
            break;
          case 'MultiPolygon':
            coordinates = geometry.getCoordinates();
            coordinates[depth[1]][depth[0]][segmentData.index + index] = vertex;
            segment[index] = vertex;
            break;
          case 'Circle':
            const circle = /** @type {import("../geom/Circle.js").default} */ (
              geometry
            );
            segment[0] = vertex;
            segment[1] = vertex;
            if (segmentData.index === CIRCLE_CENTER_INDEX) {
              this.changingFeature_ = true;
              circle.setCenter(vertex);
              this.changingFeature_ = false;
            } else {
              // We're dragging the circle's circumference:
              this.changingFeature_ = true;
              const projection = evt.map.getView().getProjection();
              let radius = distance(
                fromUserCoordinate(circle.getCenter(), projection),
                fromUserCoordinate(vertex, projection),
              );
              const userProjection = getUserProjection();
              if (userProjection) {
                const circleGeometry = circle
                  .clone()
                  .transform(userProjection, projection);
                circleGeometry.setRadius(radius);
                radius = circleGeometry
                  .transform(projection, userProjection)
                  .getRadius();
              }
              circle.setRadius(radius);
              this.changingFeature_ = false;
            }
            break;
          // pass
        }

        if (coordinates) {
          this.setGeometryCoordinates_(geometry, coordinates);
        }
      }
      this.createOrUpdateVertexFeature_(vertex, features, geometries, true);
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} evt Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(evt) {
      if (!this.condition_(evt)) {
        return false;
      }
      const pixelCoordinate = evt.coordinate;
      const insertVertices =
        this.findInsertVerticesAndUpdateDragSegments_(pixelCoordinate);

      if (insertVertices?.length && this.insertVertexCondition_(evt)) {
        this.willModifyFeatures_(evt, insertVertices);

        if (this.vertexFeature_) {
          const vertex = this.vertexFeature_.getGeometry().getCoordinates();
          for (let j = insertVertices.length - 1; j >= 0; --j) {
            this.insertVertex_(insertVertices[j], vertex);
          }
          this.ignoreNextSingleClick_ = true;
        }
      }

      return !!this.vertexFeature_;
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} evt Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(evt) {
      for (let i = this.dragSegments_.length - 1; i >= 0; --i) {
        const segmentData = this.dragSegments_[i][0];
        const geometry = segmentData.geometry;
        if (geometry.getType() === 'Circle') {
          const circle = /** @type {import("../geom/Circle.js").default} */ (
            geometry
          );
          // Update a circle object in the R* bush:
          const coordinates = circle.getCenter();
          const centerSegmentData = segmentData.featureSegments[0];
          const circumferenceSegmentData = segmentData.featureSegments[1];
          centerSegmentData.segment[0] = coordinates;
          centerSegmentData.segment[1] = coordinates;
          circumferenceSegmentData.segment[0] = coordinates;
          circumferenceSegmentData.segment[1] = coordinates;
          this.rBush_.update(createOrUpdateFromCoordinate(coordinates), centerSegmentData);
          /** @type {import("../geom/Circle.js").default | import("../geom/Polygon.js").default} */
          let circleGeometry = circle;
          const userProjection = getUserProjection();
          if (userProjection) {
            const projection = evt.map.getView().getProjection();
            circleGeometry = circleGeometry
              .clone()
              .transform(userProjection, projection);
            circleGeometry = fromCircle(circleGeometry).transform(
              projection,
              userProjection,
            );
          }
          this.rBush_.update(
            circleGeometry.getExtent(),
            circumferenceSegmentData,
          );
        } else {
          this.rBush_.update(boundingExtent(segmentData.segment), segmentData);
        }
      }
      if (this.featuresBeingModified_) {
        this.dispatchEvent(
          new ModifyEvent(
            ModifyEventType.MODIFYEND,
            this.featuresBeingModified_,
            evt,
          ),
        );
        this.featuresBeingModified_ = null;
      }
      return false;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} evt Event.
     * @private
     */
    handlePointerMove_(evt) {
      this.lastPixel_ = evt.pixel;
      this.handlePointerAtPixel_(evt.coordinate);
    }

    /**
     * @param {import("../coordinate.js").Coordinate} pixelCoordinate The pixel Coordinate.
     * @private
     */
    handlePointerAtPixel_(pixelCoordinate) {
      const map = this.getMap();
      const pixel = map.getPixelFromCoordinate(pixelCoordinate);
      const projection = map.getView().getProjection();
      const sortByDistance = function (a, b) {
        return (
          projectedDistanceToSegmentDataSquared(pixelCoordinate, a, projection) -
          projectedDistanceToSegmentDataSquared(pixelCoordinate, b, projection)
        );
      };

      /** @type {Array<SegmentData>|undefined} */
      let nodes;
      /** @type {Point|undefined} */
      let hitPointGeometry;
      if (this.hitDetection_) {
        const layerFilter =
          typeof this.hitDetection_ === 'object'
            ? (layer) => layer === this.hitDetection_
            : undefined;
        map.forEachFeatureAtPixel(
          pixel,
          (feature, layer, geometry) => {
            if (geometry && geometry.getType() === 'Point') {
              geometry = new Point(
                toUserCoordinate(geometry.getCoordinates(), projection),
              );
            }
            const geom = geometry || feature.getGeometry();

            if (
              geom &&
              geom.getType() === 'Point' &&
              feature instanceof Feature &&
              this.features_.getArray().includes(feature)
            ) {
              hitPointGeometry = /** @type {Point} */ (geom);
              const coordinate = /** @type {Point} */ (feature.getGeometry())
                .getFlatCoordinates()
                .slice(0, 2);
              nodes = [
                {
                  feature,
                  geometry: hitPointGeometry,
                  segment: [coordinate, coordinate],
                },
              ];
            }
            return true;
          },
          {layerFilter},
        );
      }
      if (!nodes) {
        const viewExtent = fromUserExtent(
          createOrUpdateFromCoordinate(pixelCoordinate, tempExtent),
          projection,
        );
        const buffer = map.getView().getResolution() * this.pixelTolerance_;
        const box = toUserExtent(
          buffer$1(viewExtent, buffer, tempExtent),
          projection,
        );
        nodes = this.rBush_.getInExtent(box);
      }

      if (nodes && nodes.length > 0) {
        const node = nodes.sort(sortByDistance)[0];
        const closestSegment = node.segment;
        let vertex = closestOnSegmentData(pixelCoordinate, node, projection);
        const vertexPixel = map.getPixelFromCoordinate(vertex);
        let dist = distance(pixel, vertexPixel);
        if (hitPointGeometry || dist <= this.pixelTolerance_) {
          /** @type {Object<string, boolean>} */
          const vertexSegments = {};
          vertexSegments[getUid(closestSegment)] = true;

          if (!this.snapToPointer_) {
            this.delta_[0] = vertex[0] - pixelCoordinate[0];
            this.delta_[1] = vertex[1] - pixelCoordinate[1];
          }
          if (
            node.geometry.getType() === 'Circle' &&
            node.index === CIRCLE_CIRCUMFERENCE_INDEX
          ) {
            this.snappedToVertex_ = true;
            this.createOrUpdateVertexFeature_(
              vertex,
              [node.feature],
              [node.geometry],
              this.snappedToVertex_,
            );
          } else {
            const pixel1 = map.getPixelFromCoordinate(closestSegment[0]);
            const pixel2 = map.getPixelFromCoordinate(closestSegment[1]);
            const squaredDist1 = squaredDistance(vertexPixel, pixel1);
            const squaredDist2 = squaredDistance(vertexPixel, pixel2);
            dist = Math.sqrt(Math.min(squaredDist1, squaredDist2));
            this.snappedToVertex_ = dist <= this.pixelTolerance_;
            // Stop and cleanup overlay vertex feature if a segment was hit and new vertex creation is not allowed by the insertVertexCondition
            if (
              !this.snappedToVertex_ &&
              !this.insertVertexCondition_(this.lastPointerEvent_)
            ) {
              if (this.vertexFeature_) {
                this.overlay_.getSource().removeFeature(this.vertexFeature_);
                this.vertexFeature_ = null;
              }
              return;
            }
            if (this.snappedToVertex_) {
              vertex =
                squaredDist1 > squaredDist2
                  ? closestSegment[1]
                  : closestSegment[0];
            }
            this.createOrUpdateVertexFeature_(
              vertex,
              [node.feature],
              [node.geometry],
              this.snappedToVertex_,
            );
            const geometries = {};
            geometries[getUid(node.geometry)] = true;
            for (let i = 1, ii = nodes.length; i < ii; ++i) {
              const segment = nodes[i].segment;
              if (
                (equals(closestSegment[0], segment[0]) &&
                  equals(closestSegment[1], segment[1])) ||
                (equals(closestSegment[0], segment[1]) &&
                  equals(closestSegment[1], segment[0]))
              ) {
                const geometryUid = getUid(nodes[i].geometry);
                if (!(geometryUid in geometries)) {
                  geometries[geometryUid] = true;
                  vertexSegments[getUid(segment)] = true;
                }
              } else {
                break;
              }
            }
          }

          this.vertexSegments_ = vertexSegments;
          return;
        }
      }
      if (this.vertexFeature_) {
        this.overlay_.getSource().removeFeature(this.vertexFeature_);
        this.vertexFeature_ = null;
      }
    }

    /**
     * @param {SegmentData} segmentData Segment data.
     * @param {import("../coordinate.js").Coordinate} vertex Vertex.
     * @return {boolean} A vertex was inserted.
     * @private
     */
    insertVertex_(segmentData, vertex) {
      const segment = segmentData.segment;
      const feature = segmentData.feature;
      const geometry = segmentData.geometry;
      const depth = segmentData.depth;
      const index = segmentData.index;
      let coordinates;

      while (vertex.length < geometry.getStride()) {
        vertex.push(0);
      }

      switch (geometry.getType()) {
        case 'MultiLineString':
          coordinates = geometry.getCoordinates();
          coordinates[depth[0]].splice(index + 1, 0, vertex);
          break;
        case 'Polygon':
          coordinates = geometry.getCoordinates();
          coordinates[depth[0]].splice(index + 1, 0, vertex);
          break;
        case 'MultiPolygon':
          coordinates = geometry.getCoordinates();
          coordinates[depth[1]][depth[0]].splice(index + 1, 0, vertex);
          break;
        case 'LineString':
          coordinates = geometry.getCoordinates();
          coordinates.splice(index + 1, 0, vertex);
          break;
        default:
          return false;
      }

      this.setGeometryCoordinates_(geometry, coordinates);
      const rTree = this.rBush_;
      rTree.remove(segmentData);
      this.updateSegmentIndices_(geometry, index, depth, 1);

      /** @type {SegmentData} */
      const newSegmentData = {
        segment: [segment[0], vertex],
        feature: feature,
        geometry: geometry,
        depth: depth,
        index: index,
      };

      rTree.insert(boundingExtent(newSegmentData.segment), newSegmentData);
      this.dragSegments_.push([newSegmentData, 1]);

      /** @type {SegmentData} */
      const newSegmentData2 = {
        segment: [vertex, segment[1]],
        feature: feature,
        geometry: geometry,
        depth: depth,
        index: index + 1,
      };

      rTree.insert(boundingExtent(newSegmentData2.segment), newSegmentData2);
      this.dragSegments_.push([newSegmentData2, 0]);
      return true;
    }

    updatePointer_(coordinate) {
      if (coordinate) {
        this.findInsertVerticesAndUpdateDragSegments_(coordinate);
      }
      return this.vertexFeature_?.getGeometry().getCoordinates();
    }

    /**
     * Get the current pointer position.
     * @return {import("../coordinate.js").Coordinate | null} The current pointer coordinate.
     */
    getPoint() {
      const coordinate = this.vertexFeature_?.getGeometry().getCoordinates();
      if (!coordinate) {
        return null;
      }
      return toUserCoordinate(
        coordinate,
        this.getMap().getView().getProjection(),
      );
    }

    /**
     * Check if a point can be removed from the current linestring or polygon at the current
     * pointer position.
     * @return {boolean} A point can be deleted at the current pointer position.
     * @api
     */
    canRemovePoint() {
      if (!this.vertexFeature_) {
        return false;
      }
      if (
        this.vertexFeature_
          .get('geometries')
          .every(
            (geometry) =>
              geometry.getType() === 'Circle' ||
              geometry.getType().endsWith('Point'),
          )
      ) {
        return false;
      }
      const coordinate = this.vertexFeature_.getGeometry().getCoordinates();
      const segments = this.rBush_.getInExtent(boundingExtent([coordinate]));
      return segments.some(
        ({segment}) =>
          equals(segment[0], coordinate) ||
          equals(segment[1], coordinate),
      );
    }

    /**
     * Removes the vertex currently being pointed from the current linestring or polygon.
     * @param {import('../coordinate.js').Coordinate} [coordinate] If provided, the pointer
     * will be set to the provided coordinate. If not, the current pointer coordinate will be used.
     * @return {boolean} True when a vertex was removed.
     * @api
     */
    removePoint(coordinate) {
      if (coordinate) {
        coordinate = fromUserCoordinate(
          coordinate,
          this.getMap().getView().getProjection(),
        );
        this.updatePointer_(coordinate);
      }
      if (
        !this.lastPointerEvent_ ||
        (this.lastPointerEvent_ &&
          this.lastPointerEvent_.type != MapBrowserEventType.POINTERDRAG)
      ) {
        const evt = this.lastPointerEvent_;
        this.willModifyFeatures_(
          evt,
          this.dragSegments_.map(([segment]) => segment),
        );
        const removed = this.removeVertex_();
        if (this.featuresBeingModified_) {
          this.dispatchEvent(
            new ModifyEvent(
              ModifyEventType.MODIFYEND,
              this.featuresBeingModified_,
              evt,
            ),
          );
        }

        this.featuresBeingModified_ = null;
        return removed;
      }
      return false;
    }

    /**
     * Removes a vertex from all matching features.
     * @return {boolean} True when a vertex was removed.
     * @private
     */
    removeVertex_() {
      const dragSegments = this.dragSegments_;
      const segmentsByFeature = {};
      let deleted = false;
      let component, coordinates, dragSegment, geometry, i, index, left;
      let newIndex, right, segmentData, uid;
      for (i = dragSegments.length - 1; i >= 0; --i) {
        dragSegment = dragSegments[i];
        segmentData = dragSegment[0];
        uid = getUid(segmentData.feature);
        if (segmentData.depth) {
          // separate feature components
          uid += '-' + segmentData.depth.join('-');
        }
        if (!(uid in segmentsByFeature)) {
          segmentsByFeature[uid] = {};
        }
        if (dragSegment[1] === 0) {
          segmentsByFeature[uid].right = segmentData;
          segmentsByFeature[uid].index = segmentData.index;
        } else if (dragSegment[1] == 1) {
          segmentsByFeature[uid].left = segmentData;
          segmentsByFeature[uid].index = segmentData.index + 1;
        }
      }
      for (uid in segmentsByFeature) {
        right = segmentsByFeature[uid].right;
        left = segmentsByFeature[uid].left;
        index = segmentsByFeature[uid].index;
        newIndex = index - 1;
        if (left !== undefined) {
          segmentData = left;
        } else {
          segmentData = right;
        }
        if (newIndex < 0) {
          newIndex = 0;
        }
        geometry = segmentData.geometry;
        coordinates = geometry.getCoordinates();
        component = coordinates;
        deleted = false;
        switch (geometry.getType()) {
          case 'MultiLineString':
            if (coordinates[segmentData.depth[0]].length > 2) {
              coordinates[segmentData.depth[0]].splice(index, 1);
              deleted = true;
            }
            break;
          case 'LineString':
            if (coordinates.length > 2) {
              coordinates.splice(index, 1);
              deleted = true;
            }
            break;
          case 'MultiPolygon':
            component = component[segmentData.depth[1]];
          /* falls through */
          case 'Polygon':
            component = component[segmentData.depth[0]];
            if (component.length > 4) {
              if (index == component.length - 1) {
                index = 0;
              }
              component.splice(index, 1);
              deleted = true;
              if (index === 0) {
                // close the ring again
                component.pop();
                component.push(component[0]);
                newIndex = component.length - 1;
              }
            }
            break;
          // pass
        }

        if (deleted) {
          this.setGeometryCoordinates_(geometry, coordinates);
          const segments = [];
          if (left !== undefined) {
            this.rBush_.remove(left);
            segments.push(left.segment[0]);
          }
          if (right !== undefined) {
            this.rBush_.remove(right);
            segments.push(right.segment[1]);
          }
          if (left !== undefined && right !== undefined) {
            /** @type {SegmentData} */
            const newSegmentData = {
              depth: segmentData.depth,
              feature: segmentData.feature,
              geometry: segmentData.geometry,
              index: newIndex,
              segment: segments,
            };

            this.rBush_.insert(
              boundingExtent(newSegmentData.segment),
              newSegmentData,
            );
          }
          this.updateSegmentIndices_(geometry, index, segmentData.depth, -1);
          if (this.vertexFeature_) {
            this.overlay_.getSource().removeFeature(this.vertexFeature_);
            this.vertexFeature_ = null;
          }
          dragSegments.length = 0;
        }
      }
      return deleted;
    }

    /**
     * Check if a point can be inserted to the current linestring or polygon at the current
     * pointer position.
     * @return {boolean} A point can be inserted at the current pointer position.
     * @api
     */
    canInsertPoint() {
      if (!this.vertexFeature_) {
        return false;
      }
      if (
        this.vertexFeature_
          .get('geometries')
          .every(
            (geometry) =>
              geometry.getType() === 'Circle' ||
              geometry.getType().endsWith('Point'),
          )
      ) {
        return false;
      }
      const coordinate = this.vertexFeature_.getGeometry().getCoordinates();
      const segments = this.rBush_.getInExtent(boundingExtent([coordinate]));
      return segments.some(
        ({segment}) =>
          !(
            equals(segment[0], coordinate) ||
            equals(segment[1], coordinate)
          ),
      );
    }

    /**
     * Inserts the vertex currently being pointed to the current linestring or polygon.
     * @param {import('../coordinate.js').Coordinate} [coordinate] If provided, the pointer
     * will be set to the provided coordinate. If not, the current pointer coordinate will be used.
     * @return {boolean} A vertex was inserted.
     * @api
     */
    insertPoint(coordinate) {
      const pixelCoordinate = coordinate
        ? fromUserCoordinate(coordinate, this.getMap().getView().getProjection())
        : this.vertexFeature_?.getGeometry().getCoordinates();
      if (!pixelCoordinate) {
        return false;
      }
      const insertVertices =
        this.findInsertVerticesAndUpdateDragSegments_(pixelCoordinate);
      return insertVertices.reduce(
        (prev, segmentData) =>
          prev || this.insertVertex_(segmentData, pixelCoordinate),
        false,
      );
    }

    /**
     * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry.
     * @param {Array} coordinates Coordinates.
     * @private
     */
    setGeometryCoordinates_(geometry, coordinates) {
      this.changingFeature_ = true;
      geometry.setCoordinates(coordinates);
      this.changingFeature_ = false;
    }

    /**
     * @param {import("../geom/SimpleGeometry.js").default} geometry Geometry.
     * @param {number} index Index.
     * @param {Array<number>|undefined} depth Depth.
     * @param {number} delta Delta (1 or -1).
     * @private
     */
    updateSegmentIndices_(geometry, index, depth, delta) {
      this.rBush_.forEachInExtent(
        geometry.getExtent(),
        function (segmentDataMatch) {
          if (
            segmentDataMatch.geometry === geometry &&
            (depth === undefined ||
              segmentDataMatch.depth === undefined ||
              equals$2(segmentDataMatch.depth, depth)) &&
            segmentDataMatch.index > index
          ) {
            segmentDataMatch.index += delta;
          }
        },
      );
    }
  }

  /**
   * @param {SegmentData} a The first segment data.
   * @param {SegmentData} b The second segment data.
   * @return {number} The difference in indexes.
   */
  function compareIndexes(a, b) {
    return a.index - b.index;
  }

  /**
   * Returns the distance from a point to a line segment.
   *
   * @param {import("../coordinate.js").Coordinate} pointCoordinates The coordinates of the point from
   *        which to calculate the distance.
   * @param {SegmentData} segmentData The object describing the line
   *        segment we are calculating the distance to.
   * @param {import("../proj/Projection.js").default} projection The view projection.
   * @return {number} The square of the distance between a point and a line segment.
   */
  function projectedDistanceToSegmentDataSquared(
    pointCoordinates,
    segmentData,
    projection,
  ) {
    const geometry = segmentData.geometry;

    if (geometry.getType() === 'Circle') {
      let circleGeometry = /** @type {import("../geom/Circle.js").default} */ (
        geometry
      );

      if (segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX) {
        const userProjection = getUserProjection();
        if (userProjection) {
          circleGeometry = circleGeometry
            .clone()
            .transform(userProjection, projection);
        }
        const distanceToCenterSquared = squaredDistance(
          circleGeometry.getCenter(),
          fromUserCoordinate(pointCoordinates, projection),
        );
        const distanceToCircumference =
          Math.sqrt(distanceToCenterSquared) - circleGeometry.getRadius();
        return distanceToCircumference * distanceToCircumference;
      }
    }

    const coordinate = fromUserCoordinate(pointCoordinates, projection);
    tempSegment$1[0] = fromUserCoordinate(segmentData.segment[0], projection);
    tempSegment$1[1] = fromUserCoordinate(segmentData.segment[1], projection);
    return squaredDistanceToSegment(coordinate, tempSegment$1);
  }

  /**
   * Returns the point closest to a given line segment.
   *
   * @param {import("../coordinate.js").Coordinate} pointCoordinates The point to which a closest point
   *        should be found.
   * @param {SegmentData} segmentData The object describing the line
   *        segment which should contain the closest point.
   * @param {import("../proj/Projection.js").default} projection The view projection.
   * @return {import("../coordinate.js").Coordinate} The point closest to the specified line segment.
   */
  function closestOnSegmentData(pointCoordinates, segmentData, projection) {
    const geometry = segmentData.geometry;

    if (
      geometry.getType() === 'Circle' &&
      segmentData.index === CIRCLE_CIRCUMFERENCE_INDEX
    ) {
      let circleGeometry = /** @type {import("../geom/Circle.js").default} */ (
        geometry
      );
      const userProjection = getUserProjection();
      if (userProjection) {
        circleGeometry = circleGeometry
          .clone()
          .transform(userProjection, projection);
      }
      return toUserCoordinate(
        circleGeometry.getClosestPoint(
          fromUserCoordinate(pointCoordinates, projection),
        ),
        projection,
      );
    }
    const coordinate = fromUserCoordinate(pointCoordinates, projection);
    tempSegment$1[0] = fromUserCoordinate(segmentData.segment[0], projection);
    tempSegment$1[1] = fromUserCoordinate(segmentData.segment[1], projection);
    return toUserCoordinate(
      closestOnSegment(coordinate, tempSegment$1),
      projection,
    );
  }

  /**
   * @return {import("../style/Style.js").StyleFunction} Styles.
   */
  function getDefaultStyleFunction$1() {
    const style = createEditingStyle();
    return function (feature, resolution) {
      return style['Point'];
    };
  }

  /**
   * @module ol/interaction/Select
   */

  /**
   * @enum {string}
   */
  const SelectEventType = {
    /**
     * Triggered when feature(s) has been (de)selected.
     * @event SelectEvent#select
     * @api
     */
    SELECT: 'select',
  };

  /**
   * A function that takes a {@link module:ol/Feature~Feature} and returns `true` if the feature may be
   * selected or `false` otherwise.
   * @typedef {function(import("../Feature.js").default, import("../layer/Layer.js").default<import("../source/Source").default>):boolean} FilterFunction
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [addCondition] A function
   * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * By default, this is {@link module:ol/events/condition.never}. Use this if you
   * want to use different events for add and remove instead of `toggle`.
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. This is the event
   * for the selected features as a whole. By default, this is
   * {@link module:ol/events/condition.singleClick}. Clicking on a feature selects that
   * feature and removes any that were in the selection. Clicking outside any
   * feature removes all from the selection.
   * See `toggle`, `add`, `remove` options for adding/removing extra features to/
   * from the selection.
   * @property {Array<import("../layer/Layer.js").default>|function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean} [layers]
   * A list of layers from which features should be selected. Alternatively, a
   * filter function can be provided. The function will be called for each layer
   * in the map and should return `true` for layers that you want to be
   * selectable. If the option is absent, all visible layers will be considered
   * selectable.
   * @property {import("../style/Style.js").StyleLike|null} [style]
   * Style for the selected features. By default the default edit style is used
   * (see {@link module:ol/style/Style~Style}). Set to `null` if this interaction should not apply
   * any style changes for selected features.
   * If set to a falsey value, the selected feature's style will not change.
   * @property {import("../events/condition.js").Condition} [removeCondition] A function
   * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * By default, this is {@link module:ol/events/condition.never}. Use this if you
   * want to use different events for add and remove instead of `toggle`.
   * @property {import("../events/condition.js").Condition} [toggleCondition] A function
   * that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled. This is in addition
   * to the `condition` event. By default,
   * {@link module:ol/events/condition.shiftKeyOnly}, i.e. pressing `shift` as
   * well as the `condition` event, adds that feature to the current selection if
   * it is not currently selected, and removes it if it is. See `add` and `remove`
   * if you want to use different events instead of a toggle.
   * @property {boolean} [multi=false] A boolean that determines if the default
   * behaviour should select only single features or all (overlapping) features at
   * the clicked map position. The default of `false` means single select.
   * @property {Collection<Feature>} [features]
   * Collection where the interaction will place selected features. Optional. If
   * not set the interaction will create a collection. In any case the collection
   * used by the interaction is returned by
   * {@link module:ol/interaction/Select~Select#getFeatures}.
   * @property {FilterFunction} [filter] A function
   * that takes a {@link module:ol/Feature~Feature} and a
   * {@link module:ol/layer/Layer~Layer} and returns `true` if the feature may be
   * selected or `false` otherwise.
   * @property {number} [hitTolerance=0] Hit-detection tolerance. Pixels inside
   * the radius around the given position will be checked for features.
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Select~Select} instances are instances of
   * this type.
   */
  class SelectEvent extends BaseEvent {
    /**
     * @param {SelectEventType} type The event type.
     * @param {Array<import("../Feature.js").default>} selected Selected features.
     * @param {Array<import("../Feature.js").default>} deselected Deselected features.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Associated
     *     {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
     */
    constructor(type, selected, deselected, mapBrowserEvent) {
      super(type);

      /**
       * Selected features array.
       * @type {Array<import("../Feature.js").default>}
       * @api
       */
      this.selected = selected;

      /**
       * Deselected features array.
       * @type {Array<import("../Feature.js").default>}
       * @api
       */
      this.deselected = deselected;

      /**
       * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
       * @type {import("../MapBrowserEvent.js").default}
       * @api
       */
      this.mapBrowserEvent = mapBrowserEvent;
    }
  }

  /**
   * Original feature styles to reset to when features are no longer selected.
   * @type {Object<number, import("../style/Style.js").default|Array<import("../style/Style.js").default>|import("../style/Style.js").StyleFunction>}
   */
  const originalFeatureStyles = {};

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'select', SelectEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'select', Return>} SelectOnSignature
   */

  /**
   * @classdesc
   * Interaction for selecting vector features. By default, selected features are
   * styled differently, so this interaction can be used for visual highlighting,
   * as well as selecting features for other actions, such as modification or
   * output. There are three ways of controlling which features are selected:
   * using the browser event as defined by the `condition` and optionally the
   * `toggle`, `add`/`remove`, and `multi` options; a `layers` filter; and a
   * further feature filter using the `filter` option.
   *
   * @fires SelectEvent
   * @api
   */
  class Select extends Interaction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      super();

      /***
       * @type {SelectOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {SelectOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {SelectOnSignature<void>}
       */
      this.un;

      options = options ? options : {};

      /**
       * @private
       */
      this.boundAddFeature_ = this.addFeature_.bind(this);

      /**
       * @private
       */
      this.boundRemoveFeature_ = this.removeFeature_.bind(this);

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : singleClick;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.addCondition_ = options.addCondition ? options.addCondition : never;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.removeCondition_ = options.removeCondition
        ? options.removeCondition
        : never;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.toggleCondition_ = options.toggleCondition
        ? options.toggleCondition
        : shiftKeyOnly;

      /**
       * @private
       * @type {boolean}
       */
      this.multi_ = options.multi ? options.multi : false;

      /**
       * @private
       * @type {FilterFunction}
       */
      this.filter_ = options.filter ? options.filter : TRUE;

      /**
       * @private
       * @type {number}
       */
      this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0;

      /**
       * @private
       * @type {import("../style/Style.js").default|Array<import("../style/Style.js").default>|import("../style/Style.js").StyleFunction|null}
       */
      this.style_ =
        options.style !== undefined ? options.style : getDefaultStyleFunction();

      /**
       * @private
       * @type {Collection<Feature>}
       */
      this.features_ = options.features || new Collection();

      /** @type {function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean} */
      let layerFilter;
      if (options.layers) {
        if (typeof options.layers === 'function') {
          layerFilter = options.layers;
        } else {
          const layers = options.layers;
          layerFilter = function (layer) {
            return layers.includes(layer);
          };
        }
      } else {
        layerFilter = TRUE;
      }

      /**
       * @private
       * @type {function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean}
       */
      this.layerFilter_ = layerFilter;

      /**
       * An association between selected feature (key)
       * and layer (value)
       * @private
       * @type {Object<string, import("../layer/Layer.js").default>}
       */
      this.featureLayerAssociation_ = {};
    }

    /**
     * @param {import("../Feature.js").default} feature Feature.
     * @param {import("../layer/Layer.js").default} layer Layer.
     * @private
     */
    addFeatureLayerAssociation_(feature, layer) {
      this.featureLayerAssociation_[getUid(feature)] = layer;
    }

    /**
     * Get the selected features.
     * @return {Collection<Feature>} Features collection.
     * @api
     */
    getFeatures() {
      return this.features_;
    }

    /**
     * Returns the Hit-detection tolerance.
     * @return {number} Hit tolerance in pixels.
     * @api
     */
    getHitTolerance() {
      return this.hitTolerance_;
    }

    /**
     * Returns the associated {@link module:ol/layer/Vector~VectorLayer vector layer} of
     * a selected feature.
     * @param {import("../Feature.js").default} feature Feature
     * @return {import('../layer/Vector.js').default} Layer.
     * @api
     */
    getLayer(feature) {
      return /** @type {import('../layer/Vector.js').default} */ (
        this.featureLayerAssociation_[getUid(feature)]
      );
    }

    /**
     * Hit-detection tolerance. Pixels inside the radius around the given position
     * will be checked for features.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @api
     */
    setHitTolerance(hitTolerance) {
      this.hitTolerance_ = hitTolerance;
    }

    /**
     * Remove the interaction from its current map, if any,  and attach it to a new
     * map, if any. Pass `null` to just remove the interaction from the current map.
     * @param {import("../Map.js").default|null} map Map.
     * @api
     * @override
     */
    setMap(map) {
      const currentMap = this.getMap();
      if (currentMap && this.style_) {
        this.features_.forEach(this.restorePreviousStyle_.bind(this));
      }
      super.setMap(map);
      if (map) {
        this.features_.addEventListener(
          CollectionEventType.ADD,
          this.boundAddFeature_,
        );
        this.features_.addEventListener(
          CollectionEventType.REMOVE,
          this.boundRemoveFeature_,
        );

        if (this.style_) {
          this.features_.forEach(this.applySelectedStyle_.bind(this));
        }
      } else {
        this.features_.removeEventListener(
          CollectionEventType.ADD,
          this.boundAddFeature_,
        );
        this.features_.removeEventListener(
          CollectionEventType.REMOVE,
          this.boundRemoveFeature_,
        );
      }
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<Feature>} evt Event.
     * @private
     */
    addFeature_(evt) {
      const feature = evt.element;
      if (this.style_) {
        this.applySelectedStyle_(feature);
      }
      if (!this.getLayer(feature)) {
        const layer = /** @type {VectorLayer} */ (
          this.getMap()
            .getAllLayers()
            .find(function (layer) {
              if (
                layer instanceof VectorLayer &&
                layer.getSource() &&
                layer.getSource().hasFeature(feature)
              ) {
                return layer;
              }
            })
        );
        if (layer) {
          this.addFeatureLayerAssociation_(feature, layer);
        }
      }
    }

    /**
     * @param {import("../Collection.js").CollectionEvent<Feature>} evt Event.
     * @private
     */
    removeFeature_(evt) {
      if (this.style_) {
        this.restorePreviousStyle_(evt.element);
      }
    }

    /**
     * @return {import("../style/Style.js").StyleLike|null} Select style.
     */
    getStyle() {
      return this.style_;
    }

    /**
     * @param {Feature} feature Feature
     * @private
     */
    applySelectedStyle_(feature) {
      const key = getUid(feature);
      if (!(key in originalFeatureStyles)) {
        originalFeatureStyles[key] = feature.getStyle();
      }
      feature.setStyle(this.style_);
    }

    /**
     * @param {Feature} feature Feature
     * @private
     */
    restorePreviousStyle_(feature) {
      const interactions = this.getMap().getInteractions().getArray();
      for (let i = interactions.length - 1; i >= 0; --i) {
        const interaction = interactions[i];
        if (
          interaction !== this &&
          interaction instanceof Select &&
          interaction.getStyle() &&
          interaction.getFeatures().getArray().lastIndexOf(feature) !== -1
        ) {
          feature.setStyle(interaction.getStyle());
          return;
        }
      }

      const key = getUid(feature);
      feature.setStyle(originalFeatureStyles[key]);
      delete originalFeatureStyles[key];
    }

    /**
     * @param {Feature} feature Feature.
     * @private
     */
    removeFeatureLayerAssociation_(feature) {
      delete this.featureLayerAssociation_[getUid(feature)];
    }

    /**
     * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may change the
     * selected state of features.
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @override
     */
    handleEvent(mapBrowserEvent) {
      if (!this.condition_(mapBrowserEvent)) {
        return true;
      }
      const add = this.addCondition_(mapBrowserEvent);
      const remove = this.removeCondition_(mapBrowserEvent);
      const toggle = this.toggleCondition_(mapBrowserEvent);
      const set = !add && !remove && !toggle;
      const map = mapBrowserEvent.map;
      const features = this.getFeatures();

      /**
       * @type {Array<Feature>}
       */
      const deselected = [];

      /**
       * @type {Array<Feature>}
       */
      const selected = [];

      if (set) {
        // Replace the currently selected feature(s) with the feature(s) at the
        // pixel, or clear the selected feature(s) if there is no feature at
        // the pixel.
        clear$2(this.featureLayerAssociation_);
        map.forEachFeatureAtPixel(
          mapBrowserEvent.pixel,
          /**
           * @param {import("../Feature.js").FeatureLike} feature Feature.
           * @param {import("../layer/Layer.js").default} layer Layer.
           * @return {boolean|undefined} Continue to iterate over the features.
           */
          (feature, layer) => {
            if (!(feature instanceof Feature) || !this.filter_(feature, layer)) {
              return;
            }
            this.addFeatureLayerAssociation_(feature, layer);
            selected.push(feature);
            return !this.multi_;
          },
          {
            layerFilter: this.layerFilter_,
            hitTolerance: this.hitTolerance_,
          },
        );
        for (let i = features.getLength() - 1; i >= 0; --i) {
          const feature = features.item(i);
          const index = selected.indexOf(feature);
          if (index > -1) {
            // feature is already selected
            selected.splice(index, 1);
          } else {
            features.remove(feature);
            deselected.push(feature);
          }
        }
        if (selected.length !== 0) {
          features.extend(selected);
        }
      } else {
        // Modify the currently selected feature(s).
        map.forEachFeatureAtPixel(
          mapBrowserEvent.pixel,
          /**
           * @param {import("../Feature.js").FeatureLike} feature Feature.
           * @param {import("../layer/Layer.js").default} layer Layer.
           * @return {boolean|undefined} Continue to iterate over the features.
           */
          (feature, layer) => {
            if (!(feature instanceof Feature) || !this.filter_(feature, layer)) {
              return;
            }
            if ((add || toggle) && !features.getArray().includes(feature)) {
              this.addFeatureLayerAssociation_(feature, layer);
              selected.push(feature);
            } else if (
              (remove || toggle) &&
              features.getArray().includes(feature)
            ) {
              deselected.push(feature);
              this.removeFeatureLayerAssociation_(feature);
            }
            return !this.multi_;
          },
          {
            layerFilter: this.layerFilter_,
            hitTolerance: this.hitTolerance_,
          },
        );
        for (let j = deselected.length - 1; j >= 0; --j) {
          features.remove(deselected[j]);
        }
        features.extend(selected);
      }
      if (selected.length > 0 || deselected.length > 0) {
        this.dispatchEvent(
          new SelectEvent(
            SelectEventType.SELECT,
            selected,
            deselected,
            mapBrowserEvent,
          ),
        );
      }
      return true;
    }
  }

  /**
   * @return {import("../style/Style.js").StyleFunction} Styles.
   */
  function getDefaultStyleFunction() {
    const styles = createEditingStyle();
    extend$2(styles['Polygon'], styles['LineString']);
    extend$2(styles['GeometryCollection'], styles['LineString']);

    return function (feature) {
      if (!feature.getGeometry()) {
        return null;
      }
      return styles[feature.getGeometry().getType()];
    };
  }

  /**
   * @module ol/events/SnapEvent
   */

  /**
   * @enum {string}
   */
  const SnapEventType = {
    /**
     * Triggered upon snapping to vertex or edge
     * @event SnapEvent#snap
     * @api
     */
    SNAP: 'snap',
    UNSNAP: 'unsnap',
  };

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Snap~Snap} instances are instances of this
   */
  class SnapEvent extends BaseEvent {
    /**
     * @param {SnapEventType} type Type.
     * @param {Object} options Options.
     * @param {import("../coordinate.js").Coordinate} options.vertex The snapped vertex.
     * @param {import("../coordinate.js").Coordinate} options.vertexPixel The pixel of the snapped vertex.
     * @param {import("../Feature.js").default} options.feature The feature being snapped.
     * @param {Array<import("../coordinate.js").Coordinate>|null} options.segment Segment, or `null` if snapped to a vertex.
     */
    constructor(type, options) {
      super(type);
      /**
       * The Map coordinate of the snapped point.
       * @type {import("../coordinate.js").Coordinate}
       * @api
       */
      this.vertex = options.vertex;
      /**
       * The Map pixel of the snapped point.
       * @type {Array<number>&Array<number>}
       * @api
       */
      this.vertexPixel = options.vertexPixel;
      /**
       * The feature closest to the snapped point.
       * @type {import("../Feature.js").default<import("../geom/Geometry.js").default>}
       * @api
       */
      this.feature = options.feature;
      /**
       * The segment closest to the snapped point, if snapped to a segment.
       * @type {Array<import("../coordinate.js").Coordinate>|null}
       * @api
       */
      this.segment = options.segment;
    }
  }

  /**
   * @module ol/interaction/Snap
   */

  /**
   * @typedef {Array<import("../coordinate.js").Coordinate>} Segment
   * An array of two coordinates representing a line segment, or an array of one
   * coordinate representing a point.
   */

  /**
   * @typedef {Object} SegmentData
   * @property {import("../Feature.js").default} feature Feature.
   * @property {Segment} segment Segment.
   * @property {boolean} [isIntersection] Is intersection.
   */

  /**
   * @template {import("../geom/Geometry.js").default} [GeometryType=import("../geom/Geometry.js").default]
   * @typedef {(geometry: GeometryType, projection?: import("../proj/Projection.js").default) => Array<Segment>} Segmenter
   * A function taking a {@link module:ol/geom/Geometry~Geometry} as argument and returning an array of {@link Segment}s.
   */

  /**
   * Each segmenter specified here will override the default segmenter for the
   * corresponding geometry type. To exclude all geometries of a specific geometry type from being snapped to,
   * set the segmenter to `null`.
   * @typedef {Object} Segmenters
   * @property {Segmenter<import("../geom/Point.js").default>|null} [Point] Point segmenter.
   * @property {Segmenter<import("../geom/LineString.js").default>|null} [LineString] LineString segmenter.
   * @property {Segmenter<import("../geom/Polygon.js").default>|null} [Polygon] Polygon segmenter.
   * @property {Segmenter<import("../geom/Circle.js").default>|null} [Circle] Circle segmenter.
   * @property {Segmenter<import("../geom/GeometryCollection.js").default>|null} [GeometryCollection] GeometryCollection segmenter.
   * @property {Segmenter<import("../geom/MultiPoint.js").default>|null} [MultiPoint] MultiPoint segmenter.
   * @property {Segmenter<import("../geom/MultiLineString.js").default>|null} [MultiLineString] MultiLineString segmenter.
   * @property {Segmenter<import("../geom/MultiPolygon.js").default>|null} [MultiPolygon] MultiPolygon segmenter.
   */

  /**
   * @typedef {Object} Options
   * @property {import("../Collection.js").default<import("../Feature.js").default>} [features] Snap to these features. Either this option or source should be provided.
   * @property {import("../source/Vector.js").default} [source] Snap to features from this source. Either this option or features should be provided
   * @property {boolean} [edge=true] Snap to edges.
   * @property {boolean} [vertex=true] Snap to vertices.
   * @property {boolean} [intersection=false] Snap to intersections between segments.
   * @property {number} [pixelTolerance=10] Pixel tolerance for considering the pointer close enough to a segment or
   * vertex for snapping.
   * @property {Segmenters} [segmenters] Custom segmenters by {@link module:ol/geom/Geometry~Type}. By default, the
   * following segmenters are used:
   *   - `Point`: A one-dimensional segment (e.g. `[[10, 20]]`) representing the point.
   *   - `LineString`: One two-dimensional segment (e.g. `[[10, 20], [30, 40]]`) for each segment of the linestring.
   *   - `Polygon`: One two-dimensional segment for each segment of the exterior ring and the interior rings.
   *   - `Circle`: One two-dimensional segment for each segment of a regular polygon with 32 points representing the circle circumference.
   *   - `GeometryCollection`: All segments of the contained geometries.
   *   - `MultiPoint`: One one-dimensional segment for each point.
   *   - `MultiLineString`: One two-dimensional segment for each segment of the linestrings.
   *   - `MultiPolygon`: One two-dimensional segment for each segment of the polygons.
   */

  /**
   * Information about the last snapped state.
   * @typedef {Object} SnappedInfo
   * @property {import("../coordinate.js").Coordinate|null} vertex - The snapped vertex.
   * @property {import("../pixel.js").Pixel|null} vertexPixel - The pixel of the snapped vertex.
   * @property {import("../Feature.js").default|null} feature - The feature being snapped.
   * @property {Segment|null} segment - Segment, or `null` if snapped to a vertex.
   */

  /***
   * @type {Object<string, Segmenter>}
   */
  const GEOMETRY_SEGMENTERS = {
    /**
     * @param {import("../geom/Circle.js").default} geometry Geometry.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {Array<Segment>} Segments
     */
    Circle(geometry, projection) {
      let circleGeometry = geometry;
      const userProjection = getUserProjection();
      if (userProjection) {
        circleGeometry = circleGeometry
          .clone()
          .transform(userProjection, projection);
      }
      const polygon = fromCircle(circleGeometry);
      if (userProjection) {
        polygon.transform(projection, userProjection);
      }
      return GEOMETRY_SEGMENTERS.Polygon(polygon);
    },

    /**
     * @param {import("../geom/GeometryCollection.js").default} geometry Geometry.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {Array<Segment>} Segments
     */
    GeometryCollection(geometry, projection) {
      /** @type {Array<Array<Segment>>} */
      const segments = [];
      const geometries = geometry.getGeometriesArray();
      for (let i = 0; i < geometries.length; ++i) {
        const segmenter = GEOMETRY_SEGMENTERS[geometries[i].getType()];
        if (segmenter) {
          segments.push(segmenter(geometries[i], projection));
        }
      }
      return segments.flat();
    },

    /**
     * @param {import("../geom/LineString.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    LineString(geometry) {
      /** @type {Array<Segment>} */
      const segments = [];
      const coordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      for (let i = 0, ii = coordinates.length - stride; i < ii; i += stride) {
        segments.push([
          coordinates.slice(i, i + 2),
          coordinates.slice(i + stride, i + stride + 2),
        ]);
      }
      return segments;
    },

    /**
     * @param {import("../geom/MultiLineString.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    MultiLineString(geometry) {
      /** @type {Array<Segment>} */
      const segments = [];
      const coordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      const ends = geometry.getEnds();
      let offset = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        for (let j = offset, jj = end - stride; j < jj; j += stride) {
          segments.push([
            coordinates.slice(j, j + 2),
            coordinates.slice(j + stride, j + stride + 2),
          ]);
        }
        offset = end;
      }
      return segments;
    },

    /**
     * @param {import("../geom/MultiPoint.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    MultiPoint(geometry) {
      /** @type {Array<Segment>} */
      const segments = [];
      const coordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      for (let i = 0, ii = coordinates.length; i < ii; i += stride) {
        segments.push([coordinates.slice(i, i + 2)]);
      }
      return segments;
    },

    /**
     * @param {import("../geom/MultiPolygon.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    MultiPolygon(geometry) {
      /** @type {Array<Segment>} */
      const segments = [];
      const coordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      const endss = geometry.getEndss();
      let offset = 0;
      for (let i = 0, ii = endss.length; i < ii; ++i) {
        const ends = endss[i];
        for (let j = 0, jj = ends.length; j < jj; ++j) {
          const end = ends[j];
          for (let k = offset, kk = end - stride; k < kk; k += stride) {
            segments.push([
              coordinates.slice(k, k + 2),
              coordinates.slice(k + stride, k + stride + 2),
            ]);
          }
          offset = end;
        }
      }
      return segments;
    },

    /**
     * @param {import("../geom/Point.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    Point(geometry) {
      return [[geometry.getFlatCoordinates().slice(0, 2)]];
    },

    /**
     * @param {import("../geom/Polygon.js").default} geometry Geometry.
     * @return {Array<Segment>} Segments
     */
    Polygon(geometry) {
      /** @type {Array<Segment>} */
      const segments = [];
      const coordinates = geometry.getFlatCoordinates();
      const stride = geometry.getStride();
      const ends = geometry.getEnds();
      let offset = 0;
      for (let i = 0, ii = ends.length; i < ii; ++i) {
        const end = ends[i];
        for (let j = offset, jj = end - stride; j < jj; j += stride) {
          segments.push([
            coordinates.slice(j, j + 2),
            coordinates.slice(j + stride, j + stride + 2),
          ]);
        }
        offset = end;
      }
      return segments;
    },
  };

  /**
   * @param  {import("../source/Vector.js").VectorSourceEvent|import("../Collection.js").CollectionEvent<import("../Feature.js").default>} evt Event.
   * @return {import("../Feature.js").default|null} Feature.
   */
  function getFeatureFromEvent(evt) {
    if (
      /** @type {import("../source/Vector.js").VectorSourceEvent} */ (evt).feature
    ) {
      return /** @type {import("../source/Vector.js").VectorSourceEvent} */ (evt)
        .feature;
    }
    if (
      /** @type {import("../Collection.js").CollectionEvent<import("../Feature.js").default>} */ (
        evt
      ).element
    ) {
      return /** @type {import("../Collection.js").CollectionEvent<import("../Feature.js").default>} */ (
        evt
      ).element;
    }
    return null;
  }

  const tempSegment = [];
  /** @type {Array<import('../extent.js').Extent>} */
  const tempExtents = [];
  /** @type {Array<SegmentData>} */
  const tempSegmentData = [];

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'snap'|'unsnap', SnapEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'snap'|'unsnap', Return>} SnapOnSignature
   */

  /**
   * @classdesc
   * Handles snapping of vector features while modifying or drawing them.  The
   * features can come from a {@link module:ol/source/Vector~VectorSource} or {@link module:ol/Collection~Collection}
   * Any interaction object that allows the user to interact
   * with the features using the mouse can benefit from the snapping, as long
   * as it is added before.
   *
   * The snap interaction modifies map browser event `coordinate` and `pixel`
   * properties to force the snap to occur to any interaction that uses them.
   *
   * Example:
   *
   *     import Snap from 'ol/interaction/Snap.js';
   *
   *     const snap = new Snap({
   *       source: source
   *     });
   *
   *     map.addInteraction(snap);
   *
   * @fires SnapEvent
   * @api
   */
  class Snap extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const pointerOptions = /** @type {import("./Pointer.js").Options} */ (
        options
      );

      if (!pointerOptions.handleDownEvent) {
        pointerOptions.handleDownEvent = TRUE;
      }

      if (!pointerOptions.stopDown) {
        pointerOptions.stopDown = FALSE;
      }

      super(pointerOptions);

      /***
       * @type {SnapOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {SnapOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {SnapOnSignature<void>}
       */
      this.un;

      /**
       * @type {import("../source/Vector.js").default|null}
       * @private
       */
      this.source_ = options.source ? options.source : null;

      /**
       * @private
       * @type {boolean}
       */
      this.vertex_ = options.vertex !== undefined ? options.vertex : true;

      /**
       * @private
       * @type {boolean}
       */
      this.edge_ = options.edge !== undefined ? options.edge : true;

      /**
       * @private
       * @type {boolean}
       */
      this.intersection_ =
        options.intersection !== undefined ? options.intersection : false;

      /**
       * @type {import("../Collection.js").default<import("../Feature.js").default>|null}
       * @private
       */
      this.features_ = options.features ? options.features : null;

      /**
       * @type {Array<import("../events.js").EventsKey>}
       * @private
       */
      this.featuresListenerKeys_ = [];

      /**
       * @type {Object<string, import("../events.js").EventsKey>}
       * @private
       */
      this.featureChangeListenerKeys_ = {};

      /**
       * Extents are preserved so indexed segment can be quickly removed
       * when its feature geometry changes
       * @type {Object<string, import("../extent.js").Extent>}
       * @private
       */
      this.indexedFeaturesExtents_ = {};

      /**
       * If a feature geometry changes while a pointer drag|move event occurs, the
       * feature doesn't get updated right away.  It will be at the next 'pointerup'
       * event fired.
       * @type {!Object<string, import("../Feature.js").default>}
       * @private
       */
      this.pendingFeatures_ = {};

      /**
       * @type {number}
       * @private
       */
      this.pixelTolerance_ =
        options.pixelTolerance !== undefined ? options.pixelTolerance : 10;

      /**
       * Segment RTree for each layer
       * @type {import("../structs/RBush.js").default<SegmentData>}
       * @private
       */
      this.rBush_ = new RBush();

      /**
       * Holds information about the last snapped state.
       * @type {SnappedInfo|null}
       * @private
       */
      this.snapped_ = null;

      /**
       * @type {Object<string, Segmenter>}
       * @private
       */
      this.segmenters_ = Object.assign(
        {},
        GEOMETRY_SEGMENTERS,
        options.segmenters,
      );
    }

    /**
     * Add a feature to the collection of features that we may snap to.
     * @param {import("../Feature.js").default} feature Feature.
     * @param {boolean} [register] Whether to listen to the feature change or not
     *     Defaults to `true`.
     * @api
     */
    addFeature(feature, register) {
      register = register !== undefined ? register : true;
      const feature_uid = getUid(feature);
      const geometry = feature.getGeometry();
      if (geometry) {
        const segmenter = this.segmenters_[geometry.getType()];
        if (segmenter) {
          this.indexedFeaturesExtents_[feature_uid] =
            geometry.getExtent(createEmpty());
          const segments = segmenter(
            geometry,
            this.getMap().getView().getProjection(),
          );
          let segmentCount = segments.length;
          for (let i = 0; i < segmentCount; ++i) {
            const segment = segments[i];
            tempExtents[i] = boundingExtent(segment);
            tempSegmentData[i] = {
              feature: feature,
              segment: segment,
            };
          }
          tempExtents.length = segmentCount;
          tempSegmentData.length = segmentCount;

          if (this.intersection_) {
            for (let j = 0, jj = segments.length; j < jj; ++j) {
              const segment = segments[j];
              if (segment.length === 1) {
                continue;
              }
              const extent = tempExtents[j];
              // Calculate intersections with own segments
              for (let k = 0, kk = segments.length; k < kk; ++k) {
                if (j === k || j - 1 === k || j + 1 === k) {
                  // Exclude self and neighbours
                  continue;
                }
                const otherSegment = segments[k];
                if (!intersects$2(extent, tempExtents[k])) {
                  continue;
                }
                const intersection = getIntersectionPoint(segment, otherSegment);
                if (!intersection) {
                  continue;
                }
                const intersectionSegment = [intersection];
                tempExtents[segmentCount] = boundingExtent(intersectionSegment);
                tempSegmentData[segmentCount++] = {
                  feature,
                  segment: intersectionSegment,
                  isIntersection: true,
                };
              }
              // Calculate intersections with existing segments
              const otherSegments = this.rBush_.getInExtent(tempExtents[j]);
              for (const {segment: otherSegment} of otherSegments) {
                if (otherSegment.length === 1) {
                  continue;
                }
                const intersection = getIntersectionPoint(segment, otherSegment);
                if (!intersection) {
                  continue;
                }
                const intersectionSegment = [intersection];
                tempExtents[segmentCount] = boundingExtent(intersectionSegment);
                tempSegmentData[segmentCount++] = {
                  feature,
                  segment: intersectionSegment,
                  isIntersection: true,
                };
              }
            }
          }

          if (segmentCount === 1) {
            this.rBush_.insert(tempExtents[0], tempSegmentData[0]);
          } else {
            this.rBush_.load(tempExtents, tempSegmentData);
          }
        }
      }

      if (register) {
        this.featureChangeListenerKeys_[feature_uid] = listen(
          feature,
          EventType.CHANGE,
          this.handleFeatureChange_,
          this,
        );
      }
    }

    /**
     * @return {import("../Collection.js").default<import("../Feature.js").default>|Array<import("../Feature.js").default>} Features.
     * @private
     */
    getFeatures_() {
      /** @type {import("../Collection.js").default<import("../Feature.js").default>|Array<import("../Feature.js").default>} */
      let features;
      if (this.features_) {
        features = this.features_;
      } else if (this.source_) {
        features = this.source_.getFeatures();
      }
      return features;
    }

    /**
     * Checks if two snap data sets are equal.
     * Compares the segment and the feature.
     *
     * @param {SnappedInfo} data1 The first snap data set.
     * @param {SnappedInfo} data2 The second snap data set.
     * @return {boolean} `true` if the data sets are equal, otherwise `false`.
     * @private
     */
    areSnapDataEqual_(data1, data2) {
      return data1.segment === data2.segment && data1.feature === data2.feature;
    }

    /**
     * @param {import("../MapBrowserEvent.js").default} evt Map browser event.
     * @return {boolean} `false` to stop event propagation.
     * @api
     * @override
     */
    handleEvent(evt) {
      const result = this.snapTo(evt.pixel, evt.coordinate, evt.map);

      if (result) {
        evt.coordinate = result.vertex.slice(0, 2);
        evt.pixel = result.vertexPixel;

        // Dispatch UNSNAP event if already snapped
        if (this.snapped_ && !this.areSnapDataEqual_(this.snapped_, result)) {
          this.dispatchEvent(new SnapEvent(SnapEventType.UNSNAP, this.snapped_));
        }

        this.snapped_ = {
          vertex: evt.coordinate,
          vertexPixel: evt.pixel,
          feature: result.feature,
          segment: result.segment,
        };
        this.dispatchEvent(new SnapEvent(SnapEventType.SNAP, this.snapped_));
      } else if (this.snapped_) {
        // Dispatch UNSNAP event if no longer snapped
        this.dispatchEvent(new SnapEvent(SnapEventType.UNSNAP, this.snapped_));
        this.snapped_ = null;
      }

      return super.handleEvent(evt);
    }

    /**
     * @param {import("../source/Vector.js").VectorSourceEvent|import("../Collection.js").CollectionEvent<import("../Feature.js").default>} evt Event.
     * @private
     */
    handleFeatureAdd_(evt) {
      const feature = getFeatureFromEvent(evt);
      if (feature) {
        this.addFeature(feature);
      }
    }

    /**
     * @param {import("../source/Vector.js").VectorSourceEvent|import("../Collection.js").CollectionEvent<import("../Feature.js").default>} evt Event.
     * @private
     */
    handleFeatureRemove_(evt) {
      const feature = getFeatureFromEvent(evt);
      if (feature) {
        this.removeFeature(feature);
      }
    }

    /**
     * @param {import("../events/Event.js").default} evt Event.
     * @private
     */
    handleFeatureChange_(evt) {
      const feature = /** @type {import("../Feature.js").default} */ (evt.target);
      if (this.handlingDownUpSequence) {
        const uid = getUid(feature);
        if (!(uid in this.pendingFeatures_)) {
          this.pendingFeatures_[uid] = feature;
        }
      } else {
        this.updateFeature_(feature);
      }
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} evt Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(evt) {
      const featuresToUpdate = Object.values(this.pendingFeatures_);
      if (featuresToUpdate.length) {
        for (const feature of featuresToUpdate) {
          this.updateFeature_(feature);
        }
      }
      return false;
    }

    /**
     * Remove a feature from the collection of features that we may snap to.
     * @param {import("../Feature.js").default} feature Feature
     * @param {boolean} [unlisten] Whether to unlisten to the feature change
     *     or not. Defaults to `true`.
     * @api
     */
    removeFeature(feature, unlisten) {
      const unregister = unlisten !== undefined ? unlisten : true;
      const feature_uid = getUid(feature);
      const extent = this.indexedFeaturesExtents_[feature_uid];
      if (extent) {
        const rBush = this.rBush_;
        const nodesToRemove = [];
        rBush.forEachInExtent(extent, function (node) {
          if (feature === node.feature) {
            nodesToRemove.push(node);
          }
        });
        for (let i = nodesToRemove.length - 1; i >= 0; --i) {
          rBush.remove(nodesToRemove[i]);
        }
      }

      if (unregister) {
        unlistenByKey(this.featureChangeListenerKeys_[feature_uid]);
        delete this.featureChangeListenerKeys_[feature_uid];
      }
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      const currentMap = this.getMap();
      const keys = this.featuresListenerKeys_;
      let features = this.getFeatures_();
      if (!Array.isArray(features)) {
        features = features.getArray();
      }

      if (currentMap) {
        keys.forEach(unlistenByKey);
        keys.length = 0;
        this.rBush_.clear();
        Object.values(this.featureChangeListenerKeys_).forEach(unlistenByKey);
        this.featureChangeListenerKeys_ = {};
      }
      super.setMap(map);

      if (map) {
        if (this.features_) {
          keys.push(
            listen(
              this.features_,
              CollectionEventType.ADD,
              this.handleFeatureAdd_,
              this,
            ),
            listen(
              this.features_,
              CollectionEventType.REMOVE,
              this.handleFeatureRemove_,
              this,
            ),
          );
        } else if (this.source_) {
          keys.push(
            listen(
              this.source_,
              VectorEventType.ADDFEATURE,
              this.handleFeatureAdd_,
              this,
            ),
            listen(
              this.source_,
              VectorEventType.REMOVEFEATURE,
              this.handleFeatureRemove_,
              this,
            ),
          );
        }
        for (const feature of features) {
          this.addFeature(feature);
        }
      }
    }

    /**
     * @param {import("../pixel.js").Pixel} pixel Pixel
     * @param {import("../coordinate.js").Coordinate} pixelCoordinate Coordinate
     * @param {import("../Map.js").default} map Map.
     * @return {SnappedInfo|null} Snap result
     */
    snapTo(pixel, pixelCoordinate, map) {
      const projection = map.getView().getProjection();
      const projectedCoordinate = fromUserCoordinate(pixelCoordinate, projection);

      const box = toUserExtent(
        buffer$1(
          boundingExtent([projectedCoordinate]),
          map.getView().getResolution() * this.pixelTolerance_,
        ),
        projection,
      );

      const segments = this.rBush_.getInExtent(box);
      const segmentsLength = segments.length;
      if (segmentsLength === 0) {
        return null;
      }

      let closestVertex;
      let minSquaredDistance = Infinity;
      let closestFeature;
      let closestSegment = null;
      let isIntersection;

      const squaredPixelTolerance = this.pixelTolerance_ * this.pixelTolerance_;
      const getResult = () => {
        if (closestVertex) {
          const vertexPixel = map.getPixelFromCoordinate(closestVertex);
          const squaredPixelDistance = squaredDistance(pixel, vertexPixel);
          if (
            squaredPixelDistance <= squaredPixelTolerance &&
            ((isIntersection && this.intersection_) ||
              (!isIntersection && (this.vertex_ || this.edge_)))
          ) {
            return {
              vertex: closestVertex,
              vertexPixel: [
                Math.round(vertexPixel[0]),
                Math.round(vertexPixel[1]),
              ],
              feature: closestFeature,
              segment: closestSegment,
            };
          }
        }
        return null;
      };

      if (this.vertex_ || this.intersection_) {
        for (let i = 0; i < segmentsLength; ++i) {
          const segmentData = segments[i];
          if (segmentData.feature.getGeometry().getType() !== 'Circle') {
            for (const vertex of segmentData.segment) {
              const tempVertexCoord = fromUserCoordinate(vertex, projection);
              const delta = squaredDistance(projectedCoordinate, tempVertexCoord);
              if (delta < minSquaredDistance) {
                closestVertex = vertex;
                minSquaredDistance = delta;
                closestFeature = segmentData.feature;
                isIntersection = segmentData.isIntersection;
              }
            }
          }
        }
        const result = getResult();
        if (result) {
          return result;
        }
      }

      if (this.edge_) {
        for (let i = 0; i < segmentsLength; ++i) {
          let vertex = null;
          const segmentData = segments[i];
          if (segmentData.feature.getGeometry().getType() === 'Circle') {
            let circleGeometry = segmentData.feature.getGeometry();
            const userProjection = getUserProjection();
            if (userProjection) {
              circleGeometry = circleGeometry
                .clone()
                .transform(userProjection, projection);
            }
            vertex = closestOnCircle(
              projectedCoordinate,
              /** @type {import("../geom/Circle.js").default} */ (circleGeometry),
            );
          } else {
            const [segmentStart, segmentEnd] = segmentData.segment;
            // points have only one coordinate
            if (segmentEnd) {
              tempSegment[0] = fromUserCoordinate(segmentStart, projection);
              tempSegment[1] = fromUserCoordinate(segmentEnd, projection);
              vertex = closestOnSegment(projectedCoordinate, tempSegment);
            }
          }
          if (vertex) {
            const delta = squaredDistance(projectedCoordinate, vertex);
            if (delta < minSquaredDistance) {
              closestVertex = toUserCoordinate(vertex, projection);
              closestSegment =
                segmentData.feature.getGeometry().getType() === 'Circle'
                  ? null
                  : segmentData.segment;
              minSquaredDistance = delta;
              closestFeature = segmentData.feature;
            }
          }
        }

        const result = getResult();
        if (result) {
          return result;
        }
      }

      return null;
    }

    /**
     * @param {import("../Feature.js").default} feature Feature
     * @private
     */
    updateFeature_(feature) {
      this.removeFeature(feature, false);
      this.addFeature(feature, false);
    }
  }

  /**
   * @module ol/interaction/Translate
   */

  /**
   * @enum {string}
   */
  const TranslateEventType = {
    /**
     * Triggered upon feature translation start.
     * @event TranslateEvent#translatestart
     * @api
     */
    TRANSLATESTART: 'translatestart',
    /**
     * Triggered upon feature translation.
     * @event TranslateEvent#translating
     * @api
     */
    TRANSLATING: 'translating',
    /**
     * Triggered upon feature translation end.
     * @event TranslateEvent#translateend
     * @api
     */
    TRANSLATEEND: 'translateend',
  };

  /**
   * A function that takes a {@link module:ol/Feature~Feature} or
   * {@link module:ol/render/Feature~RenderFeature} and a
   * {@link module:ol/layer/Layer~Layer} and returns `true` if the feature may be
   * translated or `false` otherwise.
   * @typedef {function(Feature, import("../layer/Layer.js").default<import("../source/Source").default>):boolean} FilterFunction
   */

  /**
   * @typedef {Object} Options
   * @property {import("../events/condition.js").Condition} [condition] A function that
   * takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a
   * boolean to indicate whether that event should be handled.
   * Default is {@link module:ol/events/condition.always}.
   * @property {Collection<Feature>} [features] Features contained in this collection will be able to be translated together.
   * @property {Array<import("../layer/Layer.js").default>|function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean} [layers] A list of layers from which features should be
   * translated. Alternatively, a filter function can be provided. The
   * function will be called for each layer in the map and should return
   * `true` for layers that you want to be translatable. If the option is
   * absent, all visible layers will be considered translatable.
   * Not used if `features` is provided.
   * @property {FilterFunction} [filter] A function
   * that takes a {@link module:ol/Feature~Feature} and an
   * {@link module:ol/layer/Layer~Layer} and returns `true` if the feature may be
   * translated or `false` otherwise. Not used if `features` is provided.
   * @property {number} [hitTolerance=0] Hit-detection tolerance. Pixels inside the radius around the given position
   * will be checked for features.
   */

  /**
   * @classdesc
   * Events emitted by {@link module:ol/interaction/Translate~Translate} instances
   * are instances of this type.
   */
  class TranslateEvent extends BaseEvent {
    /**
     * @param {TranslateEventType} type Type.
     * @param {Collection<Feature>} features The features translated.
     * @param {import("../coordinate.js").Coordinate} coordinate The event coordinate.
     * @param {import("../coordinate.js").Coordinate} startCoordinate The original coordinates before.translation started
     * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event.
     */
    constructor(type, features, coordinate, startCoordinate, mapBrowserEvent) {
      super(type);

      /**
       * The features being translated.
       * @type {Collection<Feature>}
       * @api
       */
      this.features = features;

      /**
       * The coordinate of the drag event.
       * @const
       * @type {import("../coordinate.js").Coordinate}
       * @api
       */
      this.coordinate = coordinate;

      /**
       * The coordinate of the start position before translation started.
       * @const
       * @type {import("../coordinate.js").Coordinate}
       * @api
       */
      this.startCoordinate = startCoordinate;

      /**
       * Associated {@link module:ol/MapBrowserEvent~MapBrowserEvent}.
       * @type {import("../MapBrowserEvent.js").default}
       * @api
       */
      this.mapBrowserEvent = mapBrowserEvent;
    }
  }

  /***
   * @template Return
   * @typedef {import("../Observable").OnSignature<import("../Observable").EventTypes, import("../events/Event.js").default, Return> &
   *   import("../Observable").OnSignature<import("../ObjectEventType").Types|
   *     'change:active', import("../Object").ObjectEvent, Return> &
   *   import("../Observable").OnSignature<'translateend'|'translatestart'|'translating', TranslateEvent, Return> &
   *   import("../Observable").CombinedOnSignature<import("../Observable").EventTypes|import("../ObjectEventType").Types|
   *     'change:active'|'translateend'|'translatestart'|'translating', Return>} TranslateOnSignature
   */

  /**
   * @classdesc
   * Interaction for translating (moving) features.
   * If you want to translate multiple features in a single action (for example,
   * the collection used by a select interaction), construct the interaction with
   * the `features` option.
   *
   * @fires TranslateEvent
   * @api
   */
  class Translate extends PointerInteraction {
    /**
     * @param {Options} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      super(/** @type {import("./Pointer.js").Options} */ (options));

      /***
       * @type {TranslateOnSignature<import("../events").EventsKey>}
       */
      this.on;

      /***
       * @type {TranslateOnSignature<import("../events").EventsKey>}
       */
      this.once;

      /***
       * @type {TranslateOnSignature<void>}
       */
      this.un;

      /**
       * The last position we translated to.
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.lastCoordinate_ = null;

      /**
       * The start position before translation started.
       * @type {import("../coordinate.js").Coordinate}
       * @private
       */
      this.startCoordinate_ = null;

      /**
       * @type {Collection<Feature>|null}
       * @private
       */
      this.features_ = options.features !== undefined ? options.features : null;

      /** @type {function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean} */
      let layerFilter;
      if (options.layers && !this.features_) {
        if (typeof options.layers === 'function') {
          layerFilter = options.layers;
        } else {
          const layers = options.layers;
          layerFilter = function (layer) {
            return layers.includes(layer);
          };
        }
      } else {
        layerFilter = TRUE;
      }

      /**
       * @private
       * @type {function(import("../layer/Layer.js").default<import("../source/Source").default>): boolean}
       */
      this.layerFilter_ = layerFilter;

      /**
       * @private
       * @type {FilterFunction}
       */
      this.filter_ = options.filter && !this.features_ ? options.filter : TRUE;

      /**
       * @private
       * @type {number}
       */
      this.hitTolerance_ = options.hitTolerance ? options.hitTolerance : 0;

      /**
       * @private
       * @type {import("../events/condition.js").Condition}
       */
      this.condition_ = options.condition ? options.condition : always;

      /**
       * @type {Feature}
       * @private
       */
      this.lastFeature_ = null;

      this.addChangeListener(
        InteractionProperty.ACTIVE,
        this.handleActiveChanged_,
      );
    }

    /**
     * Handle pointer down events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleDownEvent(event) {
      if (!event.originalEvent || !this.condition_(event)) {
        return false;
      }
      this.lastFeature_ = this.featuresAtPixel_(event.pixel, event.map);
      if (!this.lastCoordinate_ && this.lastFeature_) {
        this.startCoordinate_ = event.coordinate;
        this.lastCoordinate_ = event.coordinate;
        this.handleMoveEvent(event);

        const features = this.features_ || new Collection([this.lastFeature_]);

        this.dispatchEvent(
          new TranslateEvent(
            TranslateEventType.TRANSLATESTART,
            features,
            event.coordinate,
            this.startCoordinate_,
            event,
          ),
        );
        return true;
      }
      return false;
    }

    /**
     * Handle pointer up events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @return {boolean} If the event was consumed.
     * @override
     */
    handleUpEvent(event) {
      if (this.lastCoordinate_) {
        this.lastCoordinate_ = null;
        this.handleMoveEvent(event);

        const features = this.features_ || new Collection([this.lastFeature_]);

        this.dispatchEvent(
          new TranslateEvent(
            TranslateEventType.TRANSLATEEND,
            features,
            event.coordinate,
            this.startCoordinate_,
            event,
          ),
        );
        // cleanup
        this.startCoordinate_ = null;
        return true;
      }
      return false;
    }

    /**
     * Handle pointer drag events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @override
     */
    handleDragEvent(event) {
      if (this.lastCoordinate_) {
        const newCoordinate = event.coordinate;
        const projection = event.map.getView().getProjection();

        const newViewCoordinate = fromUserCoordinate(newCoordinate, projection);
        const lastViewCoordinate = fromUserCoordinate(
          this.lastCoordinate_,
          projection,
        );
        const deltaX = newViewCoordinate[0] - lastViewCoordinate[0];
        const deltaY = newViewCoordinate[1] - lastViewCoordinate[1];

        const features = this.features_ || new Collection([this.lastFeature_]);
        const userProjection = getUserProjection();

        features.forEach(function (feature) {
          const geom = feature.getGeometry();
          if (userProjection) {
            geom.transform(userProjection, projection);
            geom.translate(deltaX, deltaY);
            geom.transform(projection, userProjection);
          } else {
            geom.translate(deltaX, deltaY);
          }
          feature.setGeometry(geom);
        });

        this.lastCoordinate_ = newCoordinate;

        this.dispatchEvent(
          new TranslateEvent(
            TranslateEventType.TRANSLATING,
            features,
            newCoordinate,
            this.startCoordinate_,
            event,
          ),
        );
      }
    }

    /**
     * Handle pointer move events.
     * @param {import("../MapBrowserEvent.js").default} event Event.
     * @override
     */
    handleMoveEvent(event) {
      const elem = event.map.getViewport();

      // Change the cursor to grab/grabbing if hovering any of the features managed
      // by the interaction
      if (this.featuresAtPixel_(event.pixel, event.map)) {
        elem.classList.remove(this.lastCoordinate_ ? 'ol-grab' : 'ol-grabbing');
        elem.classList.add(this.lastCoordinate_ ? 'ol-grabbing' : 'ol-grab');
      } else {
        elem.classList.remove('ol-grab', 'ol-grabbing');
      }
    }

    /**
     * Tests to see if the given coordinates intersects any of our selected
     * features.
     * @param {import("../pixel.js").Pixel} pixel Pixel coordinate to test for intersection.
     * @param {import("../Map.js").default} map Map to test the intersection on.
     * @return {Feature} Returns the feature found at the specified pixel
     * coordinates.
     * @private
     */
    featuresAtPixel_(pixel, map) {
      return map.forEachFeatureAtPixel(
        pixel,
        (feature, layer) => {
          if (!(feature instanceof Feature) || !this.filter_(feature, layer)) {
            return undefined;
          }
          if (this.features_ && !this.features_.getArray().includes(feature)) {
            return undefined;
          }
          return feature;
        },
        {
          layerFilter: this.layerFilter_,
          hitTolerance: this.hitTolerance_,
        },
      );
    }

    /**
     * Returns the Hit-detection tolerance.
     * @return {number} Hit tolerance in pixels.
     * @api
     */
    getHitTolerance() {
      return this.hitTolerance_;
    }

    /**
     * Hit-detection tolerance. Pixels inside the radius around the given position
     * will be checked for features.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @api
     */
    setHitTolerance(hitTolerance) {
      this.hitTolerance_ = hitTolerance;
    }

    /**
     * Remove the interaction from its current map and attach it to the new map.
     * Subclasses may set up event handlers to get notified about changes to
     * the map here.
     * @param {import("../Map.js").default} map Map.
     * @override
     */
    setMap(map) {
      const oldMap = this.getMap();
      super.setMap(map);
      this.updateState_(oldMap);
    }

    /**
     * @private
     */
    handleActiveChanged_() {
      this.updateState_(null);
    }

    /**
     * @param {import("../Map.js").default} oldMap Old map.
     * @private
     */
    updateState_(oldMap) {
      let map = this.getMap();
      const active = this.getActive();
      if (!map || !active) {
        map = map || oldMap;
        if (map) {
          const elem = map.getViewport();
          elem.classList.remove('ol-grab', 'ol-grabbing');
        }
      }
    }
  }

  /**
   * @module ol/interaction
   */

  var interaction0 = {
    __proto__: null,
    DblClickDragZoom: DblClickDragZoom,
    DoubleClickZoom: DoubleClickZoom,
    DragAndDrop: DragAndDrop,
    DragBox: DragBox,
    DragPan: DragPan,
    DragRotate: DragRotate,
    DragRotateAndZoom: DragRotateAndZoom,
    DragZoom: DragZoom,
    Draw: Draw,
    Extent: Extent,
    Interaction: Interaction,
    KeyboardPan: KeyboardPan,
    KeyboardZoom: KeyboardZoom,
    Link: Link,
    Modify: Modify,
    MouseWheelZoom: MouseWheelZoom,
    PinchRotate: PinchRotate,
    PinchZoom: PinchZoom,
    Pointer: PointerInteraction,
    Select: Select,
    Snap: Snap,
    Translate: Translate,
    defaults: defaults
  };

  /**
   * @module ol/source/wms
   */


  /**
   * Default WMS version.
   * @type {string}
   */
  const DEFAULT_VERSION = '1.3.0';

  /**
   * @const
   * @type {import("../size.js").Size}
   */
  const GETFEATUREINFO_IMAGE_SIZE = [101, 101];

  /**
   * @api
   * @typedef {'carmentaserver' | 'geoserver' | 'mapserver' | 'qgis'} ServerType
   * Set the server type to use implementation-specific parameters beyond the WMS specification.
   *  - `'carmentaserver'`: HiDPI support for [Carmenta Server](https://www.carmenta.com/en/products/carmenta-server)
   *  - `'geoserver'`: HiDPI support for [GeoServer](https://geoserver.org/)
   *  - `'mapserver'`: HiDPI support for [MapServer](https://mapserver.org/)
   *  - `'qgis'`: HiDPI support for [QGIS](https://qgis.org/)
   */

  /**
   * @param {string} baseUrl Base URL.
   * @param {import("../extent.js").Extent} extent Extent.
   * @param {import("../size.js").Size} size Size.
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @param {Object} params WMS params. Will be modified in place.
   * @return {string} Request URL.
   */
  function getRequestUrl$1(baseUrl, extent, size, projection, params) {
    params['WIDTH'] = size[0];
    params['HEIGHT'] = size[1];

    const axisOrientation = projection.getAxisOrientation();
    const v13 = compareVersions(params['VERSION'], '1.3') >= 0;
    params[v13 ? 'CRS' : 'SRS'] = projection.getCode();
    const bbox =
      v13 && axisOrientation.startsWith('ne')
        ? [extent[1], extent[0], extent[3], extent[2]]
        : extent;
    params['BBOX'] = bbox.join(',');

    return appendParams(baseUrl, params);
  }

  /**
   * @param {import("../extent").Extent} extent Extent.
   * @param {number} resolution Resolution.
   * @param {number} pixelRatio pixel ratio.
   * @param {import("../proj.js").Projection} projection Projection.
   * @param {string} url WMS service url.
   * @param {Object} params WMS params.
   * @param {import("./wms.js").ServerType} serverType The type of the remote WMS server.
   * @return {string} Image src.
   */
  function getImageSrc(
    extent,
    resolution,
    pixelRatio,
    projection,
    url,
    params,
    serverType,
  ) {
    params = Object.assign({REQUEST: 'GetMap'}, params);

    const imageResolution = resolution / pixelRatio;

    const imageSize = [
      round(getWidth(extent) / imageResolution, DECIMALS$1),
      round(getHeight(extent) / imageResolution, DECIMALS$1),
    ];

    if (pixelRatio != 1) {
      switch (serverType) {
        case 'geoserver':
          const dpi = (90 * pixelRatio + 0.5) | 0;
          if ('FORMAT_OPTIONS' in params) {
            params['FORMAT_OPTIONS'] += ';dpi:' + dpi;
          } else {
            params['FORMAT_OPTIONS'] = 'dpi:' + dpi;
          }
          break;
        case 'mapserver':
          params['MAP_RESOLUTION'] = 90 * pixelRatio;
          break;
        case 'carmentaserver':
        case 'qgis':
          params['DPI'] = 90 * pixelRatio;
          break;
        default:
          throw new Error('Unknown `serverType` configured');
      }
    }

    const src = getRequestUrl$1(url, extent, imageSize, projection, params);
    return src;
  }

  /**
   * @param {Object} params WMS params.
   * @param {string} request WMS `REQUEST`.
   * @return {Object} WMS params with required properties set.
   */
  function getRequestParams(params, request) {
    return Object.assign(
      {
        'REQUEST': request,
        'SERVICE': 'WMS',
        'VERSION': DEFAULT_VERSION,
        'FORMAT': 'image/png',
        'STYLES': '',
        'TRANSPARENT': 'TRUE',
      },
      params,
    );
  }

  /**
   * @typedef {Object} LoaderOptions
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {Object<string,*>} [params] WMS request parameters.
   * At least a `LAYERS` param is required. `STYLES` is
   * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT` and `BBOX` will be set
   * dynamically. `CRS` (`SRS` for WMS version < 1.3.0) will is derived from the `proection` config.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is 'EPSG:3857'.
   * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport, `2` means
   * twice the width and height of the map viewport, and so on. Must be `1` or higher.
   * @property {import("./wms.js").ServerType} [serverType] The type of
   * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.
   * Only needed if `hidpi` is `true`.
   * @property {string} url WMS service URL.
   * @property {function(HTMLImageElement, string): Promise<import('../DataTile.js').ImageLike>} [load] Function
   * to perform loading of the image. Receives the created `HTMLImageElement` and the desired `src` as argument and
   * returns a promise resolving to the loaded or decoded image. Default is {@link module:ol/Image.decode}.
   */

  /**
   * Creates a loader for WMS images.
   * @param {LoaderOptions} options Loader options.
   * @return {import("../Image.js").ImageObjectPromiseLoader} Loader.
   * @api
   */
  function createLoader$3(options) {
    const hidpi = options.hidpi === undefined ? true : options.hidpi;
    const projection = get$2(options.projection || 'EPSG:3857');
    const ratio = options.ratio || 1.5;
    const load = options.load || decode;
    const crossOrigin = options.crossOrigin ?? null;

    return (extent, resolution, pixelRatio) => {
      extent = getRequestExtent(extent, resolution, pixelRatio, ratio);
      if (pixelRatio != 1 && (!hidpi || options.serverType === undefined)) {
        pixelRatio = 1;
      }
      const src = getImageSrc(
        extent,
        resolution,
        pixelRatio,
        projection,
        options.url,
        getRequestParams(options.params, 'GetMap'),
        options.serverType,
      );
      const image = new Image();
      image.crossOrigin = crossOrigin;
      return load(image, src).then((image) => ({image, extent, pixelRatio}));
    };
  }

  /**
   * Get the GetFeatureInfo URL for the passed coordinate and resolution. Returns `undefined` if the
   * GetFeatureInfo URL cannot be constructed.
   * @param {LoaderOptions} options Options passed the `createWMSLoader()` function. In addition to
   * the params required by the loader, `INFO_FORMAT` should be specified, it defaults to
   * `application/json`. If `QUERY_LAYERS` is not provided, then the layers specified in the `LAYERS`
   * parameter will be used.
   * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
   * @param {number} resolution Resolution.
   * @return {string|undefined} GetFeatureInfo URL.
   * @api
   */
  function getFeatureInfoUrl(options, coordinate, resolution) {
    if (options.url === undefined) {
      return undefined;
    }

    const projectionObj = get$2(options.projection || 'EPSG:3857');

    const extent = getForViewAndSize(
      coordinate,
      resolution,
      0,
      GETFEATUREINFO_IMAGE_SIZE,
    );

    const baseParams = {
      'QUERY_LAYERS': options.params['LAYERS'],
      'INFO_FORMAT': 'application/json',
    };
    Object.assign(
      baseParams,
      getRequestParams(options.params, 'GetFeatureInfo'),
      options.params,
    );

    const x = floor((coordinate[0] - extent[0]) / resolution, DECIMALS$1);
    const y = floor((extent[3] - coordinate[1]) / resolution, DECIMALS$1);
    const v13 = compareVersions(baseParams['VERSION'], '1.3') >= 0;
    baseParams[v13 ? 'I' : 'X'] = x;
    baseParams[v13 ? 'J' : 'Y'] = y;

    return getRequestUrl$1(
      options.url,
      extent,
      GETFEATUREINFO_IMAGE_SIZE,
      projectionObj,
      baseParams,
    );
  }

  /**
   * Get the GetLegendGraphic URL, optionally optimized for the passed resolution and possibly
   * including any passed specific parameters. Returns `undefined` if the GetLegendGraphic URL
   * cannot be constructed.
   *
   * @param {LoaderOptions} options Options passed the `createWMSLoader()` function.
   * @param {number} [resolution] Resolution. If not provided, `SCALE` will not be calculated and
   * included in URL.
   * @return {string|undefined} GetLegendGraphic URL.
   * @api
   */
  function getLegendUrl(options, resolution) {
    if (options.url === undefined) {
      return undefined;
    }

    const baseParams = {
      'SERVICE': 'WMS',
      'VERSION': DEFAULT_VERSION,
      'REQUEST': 'GetLegendGraphic',
      'FORMAT': 'image/png',
    };

    if (resolution !== undefined) {
      const mpu =
        get$2(options.projection || 'EPSG:3857').getMetersPerUnit() || 1;
      const pixelSize = 0.00028;
      baseParams['SCALE'] = (resolution * mpu) / pixelSize;
    }

    Object.assign(baseParams, options.params);

    if (options.params !== undefined && baseParams['LAYER'] === undefined) {
      const layers = baseParams['LAYERS'];
      const isSingleLayer = !Array.isArray(layers) || layers.length !== 1;
      if (!isSingleLayer) {
        return undefined;
      }
      baseParams['LAYER'] = layers;
    }

    return appendParams(options.url, baseParams);
  }

  /**
   * Compute world params
   * @param {import("../../Map.js").FrameState} frameState Frame state.
   * @param {any} layer The layer
   * @return {Array<number>} The world start, end and width.
   */
  function getWorldParameters(frameState, layer) {
    const projection = frameState.viewState.projection;

    const vectorSource = layer.getSource();
    const multiWorld = vectorSource.getWrapX() && projection.canWrapX();
    const projectionExtent = projection.getExtent();

    const extent = frameState.extent;
    const worldWidth = multiWorld ? getWidth(projectionExtent) : null;
    const endWorld = multiWorld
      ? Math.ceil((extent[2] - projectionExtent[2]) / worldWidth) + 1
      : 1;

    const startWorld = multiWorld
      ? Math.floor((extent[0] - projectionExtent[0]) / worldWidth)
      : 0;

    return [startWorld, endWorld, worldWidth];
  }

  /**
   * @module ol/renderer/webgl/VectorLayer
   */

  const Uniforms = {
    ...DefaultUniform,
    RENDER_EXTENT: 'u_renderExtent', // intersection of layer, source, and view extent
    PATTERN_ORIGIN: 'u_patternOrigin',
    GLOBAL_ALPHA: 'u_globalAlpha',
  };

  /**
   * @typedef {import('../../render/webgl/VectorStyleRenderer.js').AsShaders} StyleAsShaders
   */
  /**
   * @typedef {import('../../render/webgl/VectorStyleRenderer.js').AsRule} StyleAsRule
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the canvas element.
   * @property {import('../../style/flat.js').FlatStyleLike | Array<StyleAsShaders> | StyleAsShaders} style Flat vector style; also accepts shaders
   * @property {Object<string, number|Array<number>|string|boolean>} variables Style variables
   * @property {boolean} [disableHitDetection=false] Setting this to true will provide a slight performance boost, but will
   * prevent all hit detection on the layer.
   * @property {Array<import("./Layer").PostProcessesOptions>} [postProcesses] Post-processes definitions
   */

  /**
   * @classdesc
   * Experimental WebGL vector renderer. Supports polygons, lines and points:
   *  Polygons are broken down into triangles
   *  Lines are rendered as strips of quads
   *  Points are rendered as quads
   *
   * You need to provide vertex and fragment shaders as well as custom attributes for each type of geometry. All shaders
   * can access the uniforms in the {@link module:ol/webgl/Helper~DefaultUniform} enum.
   * The vertex shaders can access the following attributes depending on the geometry type:
   *  For polygons: {@link module:ol/render/webgl/PolygonBatchRenderer~Attributes}
   *  For line strings: {@link module:ol/render/webgl/LineStringBatchRenderer~Attributes}
   *  For points: {@link module:ol/render/webgl/PointBatchRenderer~Attributes}
   *
   * Please note that the fragment shaders output should have premultiplied alpha, otherwise visual anomalies may occur.
   *
   * Note: this uses {@link module:ol/webgl/Helper~WebGLHelper} internally.
   */
  class WebGLVectorLayerRenderer extends WebGLLayerRenderer {
    /**
     * @param {import("../../layer/Layer.js").default} layer Layer.
     * @param {Options} options Options.
     */
    constructor(layer, options) {
      const uniforms = {
        [Uniforms.RENDER_EXTENT]: [0, 0, 0, 0],
        [Uniforms.PATTERN_ORIGIN]: [0, 0],
        [Uniforms.GLOBAL_ALPHA]: 1,
      };

      super(layer, {
        uniforms: uniforms,
        postProcesses: options.postProcesses,
      });

      /**
       * @type {boolean}
       * @private
       */
      this.hitDetectionEnabled_ = !options.disableHitDetection;

      /**
       * @type {WebGLRenderTarget}
       * @private
       */
      this.hitRenderTarget_;

      /**
       * @private
       */
      this.sourceRevision_ = -1;

      /**
       * @private
       */
      this.previousExtent_ = createEmpty();

      /**
       * This transform is updated on every frame and is the composition of:
       * - invert of the world->screen transform that was used when rebuilding buffers (see `this.renderTransform_`)
       * - current world->screen transform
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.currentTransform_ = create$3();

      /**
       * @private
       */
      this.tmpCoords_ = [0, 0];
      /**
       * @private
       */
      this.tmpTransform_ = create$3();
      /**
       * @private
       */
      this.tmpMat4_ = create$2();

      /**
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.currentFrameStateTransform_ = create$3();

      /**
       * @type {import('../../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = {};

      /**
       * @type {Array<StyleAsRule | StyleAsShaders>}
       * @private
       */
      this.styles_ = [];

      /**
       * @type {Array<VectorStyleRenderer>}
       * @private
       */
      this.styleRenderers_ = [];

      /**
       * @type {Array<import('../../render/webgl/VectorStyleRenderer.js').WebGLBuffers>}
       * @private
       */
      this.buffers_ = [];

      this.applyOptions_(options);

      /**
       * @private
       */
      this.batch_ = new MixedGeometryBatch();

      /**
       * @private
       * @type {boolean}
       */
      this.initialFeaturesAdded_ = false;

      /**
       * @private
       * @type {Array<import("../../events.js").EventsKey|null>}
       */
      this.sourceListenKeys_ = null;
    }

    /**
     * @private
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     */
    addInitialFeatures_(frameState) {
      const source = this.getLayer().getSource();
      const userProjection = getUserProjection();
      let projectionTransform;
      if (userProjection) {
        projectionTransform = getTransformFromProjections(
          userProjection,
          frameState.viewState.projection,
        );
      }
      this.batch_.addFeatures(source.getFeatures(), projectionTransform);
      this.sourceListenKeys_ = [
        listen(
          source,
          VectorEventType.ADDFEATURE,
          this.handleSourceFeatureAdded_.bind(this, projectionTransform),
        ),
        listen(
          source,
          VectorEventType.CHANGEFEATURE,
          this.handleSourceFeatureChanged_.bind(this, projectionTransform),
          this,
        ),
        listen(
          source,
          VectorEventType.REMOVEFEATURE,
          this.handleSourceFeatureDelete_,
          this,
        ),
        listen(
          source,
          VectorEventType.CLEAR,
          this.handleSourceFeatureClear_,
          this,
        ),
      ];
    }

    /**
     * @param {Options} options Options.
     * @private
     */
    applyOptions_(options) {
      this.styleVariables_ = options.variables;
      this.styles_ = breakDownFlatStyle(options.style);
    }

    /**
     * @private
     */
    createRenderers_() {
      this.buffers_ = [];
      this.styleRenderers_ = this.styles_.map(
        (style) =>
          new VectorStyleRenderer(
            style,
            this.styleVariables_,
            this.helper,
            this.hitDetectionEnabled_,
            'filter' in style ? style.filter : null,
          ),
      );
    }

    /**
     * @override
     */
    reset(options) {
      this.applyOptions_(options);
      if (this.helper) {
        this.createRenderers_();
      }
      super.reset(options);
    }

    /**
     * @override
     */
    afterHelperCreated() {
      if (this.styleRenderers_.length) {
        // To reuse buffers
        this.styleRenderers_.forEach((renderer, i) =>
          renderer.setHelper(this.helper, this.buffers_[i]),
        );
      } else {
        this.createRenderers_();
      }

      if (this.hitDetectionEnabled_) {
        this.hitRenderTarget_ = new WebGLRenderTarget(this.helper);
      }
    }

    /**
     * @param {import("../../proj.js").TransformFunction} projectionTransform Transform function.
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureAdded_(projectionTransform, event) {
      const feature = event.feature;
      this.batch_.addFeature(feature, projectionTransform);
    }

    /**
     * @param {import("../../proj.js").TransformFunction} projectionTransform Transform function.
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureChanged_(projectionTransform, event) {
      const feature = event.feature;
      this.batch_.changeFeature(feature, projectionTransform);
    }

    /**
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureDelete_(event) {
      const feature = event.feature;
      this.batch_.removeFeature(feature);
    }

    /**
     * @private
     */
    handleSourceFeatureClear_() {
      this.batch_.clear();
    }

    /**
     * @param {import("../../transform.js").Transform} batchInvertTransform Inverse of the transformation in which geometries are expressed
     * @private
     */
    applyUniforms_(batchInvertTransform) {
      // world to screen matrix
      setFromArray(this.tmpTransform_, this.currentFrameStateTransform_);
      multiply(this.tmpTransform_, batchInvertTransform);
      this.helper.setUniformMatrixValue(
        Uniforms.PROJECTION_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );

      // screen to world matrix
      makeInverse(this.tmpTransform_, this.tmpTransform_);
      this.helper.setUniformMatrixValue(
        Uniforms.SCREEN_TO_WORLD_MATRIX,
        fromTransform(this.tmpMat4_, this.tmpTransform_),
      );

      // pattern origin should always be [0, 0] in world coordinates
      this.tmpCoords_[0] = 0;
      this.tmpCoords_[1] = 0;
      makeInverse(this.tmpTransform_, batchInvertTransform);
      apply(this.tmpTransform_, this.tmpCoords_);
      this.helper.setUniformFloatVec2(Uniforms.PATTERN_ORIGIN, this.tmpCoords_);
    }

    /**
     * Render the layer.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState) {
      const gl = this.helper.getGL();
      this.preRender(gl, frameState);

      const [startWorld, endWorld, worldWidth] = getWorldParameters(
        frameState,
        this.getLayer(),
      );

      // draw the normal canvas
      this.helper.prepareDraw(frameState);
      this.renderWorlds(frameState, false, startWorld, endWorld, worldWidth);
      this.helper.finalizeDraw(
        frameState,
        this.dispatchPreComposeEvent,
        this.dispatchPostComposeEvent,
      );

      const canvas = this.helper.getCanvas();

      if (this.hitDetectionEnabled_) {
        this.renderWorlds(frameState, true, startWorld, endWorld, worldWidth);
        this.hitRenderTarget_.clearCachedData();
      }

      this.postRender(gl, frameState);

      return canvas;
    }

    /**
     * Determine whether renderFrame should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrameInternal(frameState) {
      if (!this.initialFeaturesAdded_) {
        this.addInitialFeatures_(frameState);
        this.initialFeaturesAdded_ = true;
      }

      const layer = this.getLayer();
      const vectorSource = layer.getSource();
      const viewState = frameState.viewState;
      const viewNotMoving =
        !frameState.viewHints[ViewHint.ANIMATING] &&
        !frameState.viewHints[ViewHint.INTERACTING];
      const extentChanged = !equals$1(this.previousExtent_, frameState.extent);
      const sourceChanged = this.sourceRevision_ < vectorSource.getRevision();

      if (sourceChanged) {
        this.sourceRevision_ = vectorSource.getRevision();
      }

      if (viewNotMoving && (extentChanged || sourceChanged)) {
        const projection = viewState.projection;
        const resolution = viewState.resolution;

        const renderBuffer =
          layer instanceof BaseVectorLayer ? layer.getRenderBuffer() : 0;
        const extent = buffer$1(frameState.extent, renderBuffer * resolution);

        const userProjection = getUserProjection();
        if (userProjection) {
          vectorSource.loadFeatures(
            toUserExtent(extent, userProjection),
            toUserResolution(resolution, projection),
            userProjection,
          );
        } else {
          vectorSource.loadFeatures(extent, resolution, projection);
        }

        this.ready = false;

        const transform = this.helper.makeProjectionTransform(
          frameState,
          create$3(),
        );

        const generatePromises = this.styleRenderers_.map((renderer, i) =>
          renderer.generateBuffers(this.batch_, transform).then((buffers) => {
            if (this.buffers_[i]) {
              this.disposeBuffers(this.buffers_[i]);
            }
            this.buffers_[i] = buffers;
          }),
        );
        Promise.all(generatePromises).then(() => {
          this.ready = true;
          this.getLayer().changed();
        });

        this.previousExtent_ = frameState.extent.slice();
      }

      return true;
    }

    /**
     * Render the world, either to the main framebuffer or to the hit framebuffer
     * @param {import("../../Map.js").FrameState} frameState current frame state
     * @param {boolean} forHitDetection whether the rendering is for hit detection
     * @param {number} startWorld the world to render in the first iteration
     * @param {number} endWorld the last world to render
     * @param {number} worldWidth the width of the worlds being rendered
     */
    renderWorlds(frameState, forHitDetection, startWorld, endWorld, worldWidth) {
      let world = startWorld;

      if (forHitDetection) {
        this.hitRenderTarget_.setSize([
          Math.floor(frameState.size[0] / 2),
          Math.floor(frameState.size[1] / 2),
        ]);
        this.helper.prepareDrawToRenderTarget(
          frameState,
          this.hitRenderTarget_,
          true,
        );
      }

      do {
        this.helper.makeProjectionTransform(
          frameState,
          this.currentFrameStateTransform_,
        );
        translate$2(
          this.currentFrameStateTransform_,
          world * worldWidth,
          0,
        );
        for (let i = 0, ii = this.styleRenderers_.length; i < ii; i++) {
          const renderer = this.styleRenderers_[i];
          const buffers = this.buffers_[i];
          if (!buffers) {
            continue;
          }
          renderer.render(buffers, frameState, () => {
            this.applyUniforms_(buffers.invertVerticesTransform);
            this.helper.applyHitDetectionUniform(forHitDetection);
          });
        }
      } while (++world < endWorld);
    }

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("../vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("../Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     * @override
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      assert(
        this.hitDetectionEnabled_,
        '`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has been disabled using the `disableHitDetection: true` option.',
      );
      if (!this.styleRenderers_.length || !this.hitDetectionEnabled_) {
        return undefined;
      }

      const pixel = apply(
        frameState.coordinateToPixelTransform,
        coordinate.slice(),
      );

      const data = this.hitRenderTarget_.readPixel(pixel[0] / 2, pixel[1] / 2);
      const color = [data[0] / 255, data[1] / 255, data[2] / 255, data[3] / 255];
      const ref = colorDecodeId(color);
      const feature = this.batch_.getFeatureFromRef(ref);
      if (feature) {
        return callback(feature, this.getLayer(), null);
      }
      return undefined;
    }

    /**
     * Will release a set of Webgl buffers
     * @param {import('../../render/webgl/VectorStyleRenderer.js').WebGLBuffers} buffers Buffers
     */
    disposeBuffers(buffers) {
      /**
       * @param {Array<import('../../webgl/Buffer.js').default>} typeBuffers Buffers
       */
      const disposeBuffersOfType = (typeBuffers) => {
        for (const buffer of typeBuffers) {
          if (buffer) {
            this.helper.deleteBuffer(buffer);
          }
        }
      };
      if (buffers.pointBuffers) {
        disposeBuffersOfType(buffers.pointBuffers);
      }
      if (buffers.lineStringBuffers) {
        disposeBuffersOfType(buffers.lineStringBuffers);
      }
      if (buffers.polygonBuffers) {
        disposeBuffersOfType(buffers.polygonBuffers);
      }
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.buffers_.forEach((buffers) => {
        if (buffers) {
          this.disposeBuffers(buffers);
        }
      });
      if (this.sourceListenKeys_) {
        this.sourceListenKeys_.forEach(function (key) {
          unlistenByKey(key);
        });
        this.sourceListenKeys_ = null;
      }
      super.disposeInternal();
    }

    renderDeclutter() {}
  }

  /**
   * @module ol/layer/Heatmap
   */

  /**
   * @typedef {import("../style/flat.js").NumberExpression|string|function(import("../Feature.js").default):number} WeightExpression
   */

  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<FeatureType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {Array<string>} [gradient=['#00f', '#0ff', '#0f0', '#ff0', '#f00']] The color gradient
   * of the heatmap, specified as an array of CSS color strings.
   * @property {import("../style/flat.js").NumberExpression} [radius=8] Radius size in pixels. Note that for LineStrings,
   * the width of the line will be double the radius.
   * @property {import("../style/flat.js").NumberExpression} [blur=15] Blur size in pixels. This is added to the `radius`
   * parameter above to create the final size of the blur effect.
   * @property {WeightExpression} [weight='weight'] The feature
   * attribute to use for the weight. This also supports expressions returning a number or a function that returns a weight from a feature. Weight values
   * should range from 0 to 1 (and values outside will be clamped to that range).
   * @property {import("../style/flat.js").BooleanExpression} [filter] Optional filter expression.
   * @property {Object<string, number|Array<number>|string|boolean>} [variables] Variables used in expressions (optional)
   * @property {VectorSourceType} [source] Point source.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @enum {string}
   * @private
   */
  const Property = {
    BLUR: 'blur',
    GRADIENT: 'gradient',
    RADIUS: 'radius',
  };

  /**
   * @const
   * @type {Array<string>}
   */
  const DEFAULT_GRADIENT = ['#00f', '#0ff', '#0f0', '#ff0', '#f00'];

  /**
   * @classdesc
   * Layer for rendering vector data as a heatmap.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @fires import("../render/Event.js").RenderEvent#prerender
   * @fires import("../render/Event.js").RenderEvent#postrender
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<FeatureType>]
   * @extends {BaseVector<FeatureType, VectorSourceType, WebGLVectorLayerRenderer>}
   * @api
   */
  class Heatmap extends BaseVectorLayer {
    /**
     * @param {Options<FeatureType, VectorSourceType>} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign({}, options);

      delete baseOptions.gradient;
      delete baseOptions.radius;
      delete baseOptions.blur;
      delete baseOptions.weight;
      super(baseOptions);

      this.filter_ = options.filter ?? true;

      /**
       * @type {import('../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = options.variables || {};

      /**
       * @private
       * @type {HTMLCanvasElement}
       */
      this.gradient_ = null;

      this.addChangeListener(Property.GRADIENT, this.handleGradientChanged_);

      this.setGradient(options.gradient ? options.gradient : DEFAULT_GRADIENT);

      this.setBlur(options.blur !== undefined ? options.blur : 15);

      this.setRadius(options.radius !== undefined ? options.radius : 8);

      const weight = options.weight ? options.weight : 'weight';

      /**
       * @private
       */
      this.weight_ = weight;

      // For performance reasons, don't sort the features before rendering.
      // The render order is not relevant for a heatmap representation.
      this.setRenderOrder(null);
    }

    /**
     * Return the blur size in pixels.
     * @return {import("../style/flat.js").NumberExpression} Blur size in pixels.
     * @api
     * @observable
     */
    getBlur() {
      return /** @type {import("../style/flat.js").NumberExpression} */ (
        this.get(Property.BLUR)
      );
    }

    /**
     * Return the gradient colors as array of strings.
     * @return {Array<string>} Colors.
     * @api
     * @observable
     */
    getGradient() {
      return /** @type {Array<string>} */ (this.get(Property.GRADIENT));
    }

    /**
     * Return the size of the radius in pixels.
     * @return {import("../style/flat.js").NumberExpression} Radius size in pixel.
     * @api
     * @observable
     */
    getRadius() {
      return /** @type {import("../style/flat.js").NumberExpression} */ (
        this.get(Property.RADIUS)
      );
    }

    /**
     * @private
     */
    handleGradientChanged_() {
      this.gradient_ = createGradient(this.getGradient());
    }

    /**
     * Set the blur size in pixels.
     * @param {import("../style/flat.js").NumberExpression} blur Blur size in pixels (supports expressions).
     * @api
     * @observable
     */
    setBlur(blur) {
      const previousValue = this.get(Property.BLUR);
      this.set(Property.BLUR, blur);
      // if the value stays numerical, simply refresh the layer
      if (typeof blur === 'number' && typeof previousValue === 'number') {
        this.changed();
        return;
      }
      this.clearRenderer();
    }

    /**
     * Set the gradient colors as array of strings.
     * @param {Array<string>} colors Gradient.
     * @api
     * @observable
     */
    setGradient(colors) {
      this.set(Property.GRADIENT, colors);
    }

    /**
     * Set the size of the radius in pixels.
     * @param {import("../style/flat.js").NumberExpression} radius Radius size in pixel (supports expressions).
     * @api
     * @observable
     */
    setRadius(radius) {
      const previousValue = this.get(Property.RADIUS);
      this.set(Property.RADIUS, radius);
      // if the value stays numerical, simply refresh the layer
      if (typeof radius === 'number' && typeof previousValue === 'number') {
        this.changed();
        return;
      }
      this.clearRenderer();
    }

    /**
     * Set the filter expression
     * @param {import("../style/flat.js").BooleanExpression} filter Filter expression
     * @api
     */
    setFilter(filter) {
      this.filter_ = filter;
      this.changed();
      this.clearRenderer();
    }

    /**
     * Set the weight expression
     * @param {WeightExpression} weight Weight expression
     * @api
     */
    setWeight(weight) {
      this.weight_ = weight;
      this.changed();
      this.clearRenderer();
    }

    /**
     * @override
     */
    createRenderer() {
      const builder = new ShaderBuilder();

      const context = newCompilationContext();
      const filterCompiled = expressionToGlsl(context, this.filter_, BooleanType$1);
      let radiusCompiled = expressionToGlsl(
        context,
        this.getRadius(),
        NumberType$1,
      );
      let blurCompiled = expressionToGlsl(context, this.getBlur(), NumberType$1);

      /** @type {import('../render/webgl/VectorStyleRenderer.js').UniformDefinitions} */
      const blurRadiusUniforms = {};
      if (typeof this.getBlur() === 'number') {
        blurCompiled = 'a_blur';
        blurRadiusUniforms['a_blur'] = () => this.getBlur();
        builder.addUniform('a_blur', 'float');
      }
      if (typeof this.getRadius() === 'number') {
        radiusCompiled = 'a_radius';
        blurRadiusUniforms['a_radius'] = () => this.getRadius();
        builder.addUniform('a_radius', 'float');
      }

      /** @type {import('../render/webgl/VectorStyleRenderer.js').AttributeDefinitions} */
      const weightAttribute = {};
      let weightExpression = null;
      if (
        typeof this.weight_ === 'string' ||
        typeof this.weight_ === 'function'
      ) {
        const weightFunction =
          typeof this.weight_ === 'string'
            ? (feature) => feature.get(this.weight_)
            : this.weight_;
        weightAttribute['prop_weight'] = {
          size: 1,
          callback: (feature) => {
            const weightValue = weightFunction(feature);
            return weightValue !== undefined ? clamp$1(weightValue, 0, 1) : 1;
          },
        };
        weightExpression = 'a_prop_weight';
        builder.addAttribute('a_prop_weight', 'float');
      } else {
        const clampedWeight = ['clamp', this.weight_, 0, 1];
        weightExpression = expressionToGlsl(context, clampedWeight, NumberType$1);
      }

      builder
        .addFragmentShaderFunction(
          `float getBlurSlope() {
  float blur = max(1., ${blurCompiled});
  float radius = ${radiusCompiled};
  return radius / blur;
}`,
        )
        .setSymbolSizeExpression(`vec2(${radiusCompiled} + ${blurCompiled}) * 2.`)
        .setSymbolColorExpression(
          `vec4(smoothstep(0., 1., (1. - length(coordsPx * 2. / v_quadSizePx)) * getBlurSlope()) * ${weightExpression})`,
        )
        .setStrokeColorExpression(
          `vec4(smoothstep(0., 1., (1. - length(currentRadiusPx * 2. / v_width)) * getBlurSlope()) * ${weightExpression})`,
        )
        .setStrokeWidthExpression(`(${radiusCompiled} + ${blurCompiled}) * 2.`)
        .setFillColorExpression(`vec4(${weightExpression})`)
        .setFragmentDiscardExpression(`!${filterCompiled}`);

      applyContextToBuilder(builder, context);
      const attributes = generateAttributesFromContext(context);
      const uniforms = generateUniformsFromContext(context, this.styleVariables_);

      return new WebGLVectorLayerRenderer(this, {
        className: this.getClassName(),
        variables: this.styleVariables_,
        style: {
          builder,
          attributes: {
            ...attributes,
            ...weightAttribute,
          },
          uniforms: {
            ...uniforms,
            ...blurRadiusUniforms,
          },
        },
        disableHitDetection: false,
        postProcesses: [
          {
            fragmentShader: `
            precision mediump float;

            uniform sampler2D u_image;
            uniform sampler2D u_gradientTexture;
            uniform float u_opacity;

            varying vec2 v_texCoord;

            void main() {
              vec4 color = texture2D(u_image, v_texCoord);
              gl_FragColor.a = color.a * u_opacity;
              gl_FragColor.rgb = texture2D(u_gradientTexture, vec2(0.5, color.a)).rgb;
              gl_FragColor.rgb *= gl_FragColor.a;
            }`,
            uniforms: {
              u_gradientTexture: () => this.gradient_,
              u_opacity: () => this.getOpacity(),
            },
          },
        ],
      });
    }

    /**
     * Update any variables used by the layer style and trigger a re-render.
     * @param {import('../style/flat.js').StyleVariables} variables Variables to update.
     */
    updateStyleVariables(variables) {
      Object.assign(this.styleVariables_, variables);
      this.changed();
    }

    /**
     * @override
     */
    renderDeclutter() {}
  }

  /**
   * @param {Array<string>} colors A list of colored.
   * @return {HTMLCanvasElement} canvas with gradient texture.
   */
  function createGradient(colors) {
    const width = 1;
    const height = 256;
    const context = createCanvasContext2D(width, height);

    const gradient = context.createLinearGradient(0, 0, width, height);
    const step = 1 / (colors.length - 1);
    for (let i = 0, ii = colors.length; i < ii; ++i) {
      gradient.addColorStop(i * step, colors[i]);
    }

    context.fillStyle = gradient;
    context.fillRect(0, 0, width, height);

    return context.canvas;
  }

  /**
   * @module ol/renderer/canvas/VectorImageLayer
   */

  /**
   * @classdesc
   * Canvas renderer for image layers.
   * @api
   */
  class CanvasVectorImageLayerRenderer extends CanvasImageLayerRenderer {
    /**
     * @param {import("../../layer/VectorImage.js").default} layer Vector image layer.
     */
    constructor(layer) {
      super(layer);

      /**
       * @private
       * @type {import("./VectorLayer.js").default}
       */
      this.vectorRenderer_ = new CanvasVectorLayerRenderer(layer);

      /**
       * @private
       * @type {number}
       */
      this.layerImageRatio_ = layer.getImageRatio();

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.coordinateToVectorPixelTransform_ = create$3();

      /**
       * @private
       * @type {import("../../transform.js").Transform}
       */
      this.renderedPixelToCoordinateTransform_ = null;
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.vectorRenderer_.dispose();
      super.disposeInternal();
    }

    /**
     * Asynchronous layer level hit detection.
     * @param {import("../../pixel.js").Pixel} pixel Pixel.
     * @return {Promise<Array<import("../../Feature").default>>} Promise that resolves with an array of features.
     * @override
     */
    getFeatures(pixel) {
      if (!this.vectorRenderer_) {
        return Promise.resolve([]);
      }
      const vectorPixel = apply(
        this.coordinateToVectorPixelTransform_,
        apply(this.renderedPixelToCoordinateTransform_, pixel.slice()),
      );
      return this.vectorRenderer_.getFeatures(vectorPixel);
    }

    /**
     * Perform action necessary to get the layer rendered after new fonts have loaded
     * @override
     */
    handleFontsChanged() {
      this.vectorRenderer_.handleFontsChanged();
    }

    /**
     * Determine whether render should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrame(frameState) {
      const pixelRatio = frameState.pixelRatio;
      const viewState = frameState.viewState;
      const viewResolution = viewState.resolution;

      const hints = frameState.viewHints;
      const vectorRenderer = this.vectorRenderer_;
      let renderedExtent = frameState.extent;
      if (this.layerImageRatio_ !== 1) {
        renderedExtent = renderedExtent.slice(0);
        scaleFromCenter(renderedExtent, this.layerImageRatio_);
      }
      const width = getWidth(renderedExtent) / viewResolution;
      const height = getHeight(renderedExtent) / viewResolution;

      if (
        !hints[ViewHint.ANIMATING] &&
        !hints[ViewHint.INTERACTING] &&
        !isEmpty(renderedExtent)
      ) {
        vectorRenderer.useContainer(null, null);
        const context = vectorRenderer.context;
        const layerState = frameState.layerStatesArray[frameState.layerIndex];
        const imageLayerState = Object.assign({}, layerState, {opacity: 1});
        const imageFrameState = /** @type {import("../../Map.js").FrameState} */ (
          Object.assign({}, frameState, {
            extent: renderedExtent,
            size: [width, height],
            viewState: /** @type {import("../../View.js").State} */ (
              Object.assign({}, frameState.viewState, {
                rotation: 0,
              })
            ),
            layerStatesArray: [imageLayerState],
            layerIndex: 0,
            declutter: null,
          })
        );
        const declutter = this.getLayer().getDeclutter();
        if (declutter) {
          imageFrameState.declutter = {
            [declutter]: new RBush$1(9),
          };
        }
        const image = new ImageCanvas(
          renderedExtent,
          viewResolution,
          pixelRatio,
          context.canvas,
          function (callback) {
            if (
              vectorRenderer.prepareFrame(imageFrameState) &&
              vectorRenderer.replayGroupChanged
            ) {
              vectorRenderer.clipping = false;
              vectorRenderer.renderFrame(imageFrameState, null);
              vectorRenderer.renderDeclutter(imageFrameState);
              vectorRenderer.renderDeferred(imageFrameState);
              callback();
            }
          },
        );

        image.addEventListener(EventType.CHANGE, () => {
          if (image.getState() !== ImageState.LOADED) {
            return;
          }
          this.image = image;
          const imagePixelRatio = image.getPixelRatio();
          const renderedResolution =
            (fromResolutionLike(image.getResolution()) * pixelRatio) /
            imagePixelRatio;
          this.renderedResolution = renderedResolution;
          this.coordinateToVectorPixelTransform_ = compose(
            this.coordinateToVectorPixelTransform_,
            width / 2,
            height / 2,
            1 / renderedResolution,
            -1 / renderedResolution,
            0,
            -viewState.center[0],
            -viewState.center[1],
          );
        });
        image.load();
      }

      if (this.image) {
        this.renderedPixelToCoordinateTransform_ =
          frameState.pixelToCoordinateTransform.slice();
      }

      return !this.getLayer().getSource()?.loading && !!this.image;
    }

    /**
     * @override
     */
    preRender() {}

    /**
     * @override
     */
    postRender() {}

    /**
     */
    renderDeclutter() {}

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("../vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("../Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     * @override
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      if (this.vectorRenderer_) {
        return this.vectorRenderer_.forEachFeatureAtCoordinate(
          coordinate,
          frameState,
          hitTolerance,
          callback,
          matches,
        );
      }
      return super.forEachFeatureAtCoordinate(
        coordinate,
        frameState,
        hitTolerance,
        callback,
        matches,
      );
    }
  }

  /**
   * @module ol/layer/VectorImage
   */

  /**
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("./BaseVector.js").ExtractedFeatureType<VectorSourceType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
   * features before rendering. By default features are drawn in the order that they are created. Use
   * `null` to avoid the sort, but get an undefined draw order.
   * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the
   * renderer when getting features from the vector source for the rendering or hit-detection.
   * Recommended value: the size of the largest symbol, line width or label.
   * @property {VectorSourceType} [source] Source.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use [map.addLayer()]{@link import("../Map.js").default#addLayer}.
   * @property {boolean|string|number} [declutter=false] Declutter images and text on this layer. Any truthy value will enable
   * decluttering. The priority is defined by the `zIndex` of the style and the render order of features. Higher z-index means higher
   * priority. Within the same z-index, a feature rendered before another has higher priority. Items will
   * not be decluttered against or together with items on other layers with the same `declutter` value. If
   * that is needed, use {@link import("../layer/Vector.js").default} instead.
   * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. When set to `null`, only
   * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style
   * which will be used if this is not set.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * @property {number} [imageRatio=1] Ratio by which the rendered extent should be larger than the
   * viewport extent. A larger ratio avoids cut images during panning, but will cause a decrease in performance.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Vector data is rendered client-side, to an image. This layer type provides great performance
   * during panning and zooming, but point symbols and texts are always rotated with the view and
   * pixels are scaled during zoom animations. For more accurate rendering of vector data, use
   * {@link module:ol/layer/Vector~VectorLayer} instead.
   *
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import("./BaseVector.js").ExtractedFeatureType<VectorSourceType>]
   * @extends {BaseVectorLayer<FeatureType, VectorSourceType, CanvasVectorImageLayerRenderer>}
   * @api
   */
  class VectorImageLayer extends BaseVectorLayer {
    /**
     * @param {Options<VectorSourceType, FeatureType>} [options] Options.
     */
    constructor(options) {
      options = options ? options : {};

      const baseOptions = Object.assign({}, options);
      delete baseOptions.imageRatio;
      super(baseOptions);

      /**
       * @type {number}
       * @private
       */
      this.imageRatio_ =
        options.imageRatio !== undefined ? options.imageRatio : 1;
    }

    /**
     * @return {number} Ratio between rendered extent size and viewport extent size.
     */
    getImageRatio() {
      return this.imageRatio_;
    }

    /**
     * @override
     */
    createRenderer() {
      return new CanvasVectorImageLayerRenderer(this);
    }
  }

  /**
   * @module ol/renderer/webgl/PointsLayer
   */

  /** @typedef {import("../../geom/Point.js").default} Point */
  /** @typedef {import("../../Feature").default<Point>} PointFeature */

  /**
   * @typedef {Object} CustomAttribute A description of a custom attribute to be passed on to the GPU, with a value different
   * for each feature.
   * @property {string} name Attribute name.
   * @property {function(PointFeature, Object<string, *>):number} callback This callback computes the numerical value of the
   * attribute for a given feature (properties are available as 2nd arg for quicker access).
   */

  /**
   * @typedef {Object} FeatureCacheItem Object that holds a reference to a feature, its geometry and properties. Used to optimize
   * rebuildBuffers by accessing these objects quicker.
   * @property {PointFeature} feature Feature
   * @property {Object<string, *>} properties Feature properties
   * @property {import("../../coordinate.js").Coordinate} flatCoordinates Point coordinates
   */

  /**
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the canvas element.
   * @property {Array<CustomAttribute>} [attributes] These attributes will be read from the features in the source and then
   * passed to the GPU. The `name` property of each attribute will serve as its identifier:
   *  In the vertex shader as an `attribute` by prefixing it with `a_`
   *  In the fragment shader as a `varying` by prefixing it with `v_`
   * Please note that these can only be numerical values.
   * @property {string} vertexShader Vertex shader source, mandatory.
   * @property {string} fragmentShader Fragment shader source, mandatory.
   * @property {boolean} [hitDetectionEnabled] Whether shader is hit detection aware.
   * @property {Object<string,import("../../webgl/Helper").UniformValue>} [uniforms] Uniform definitions for the post process steps
   * Please note that `u_texture` is reserved for the main texture slot and `u_opacity` is reserved for the layer opacity.
   * @property {Array<import("./Layer").PostProcessesOptions>} [postProcesses] Post-processes definitions
   */

  /**
   * @classdesc
   * WebGL vector renderer optimized for points.
   * All features will be rendered as quads (two triangles forming a square). New data will be flushed to the GPU
   * every time the vector source changes.
   *
   * You need to provide vertex and fragment shaders for rendering. This can be done using
   * {@link module:ol/webgl/ShaderBuilder~ShaderBuilder} utilities. These shaders shall expect a `a_position` attribute
   * containing the screen-space projected center of the quad, as well as a `a_index` attribute
   * whose value (0, 1, 2 or 3) indicates which quad vertex is currently getting processed (see structure below).
   *
   * To include variable attributes in the shaders, you need to declare them using the `attributes` property of
   * the options object like so:
   * ```js
   * new WebGLPointsLayerRenderer(layer, {
   *   attributes: [
   *     {
   *       name: 'size',
   *       callback: function(feature) {
   *         // compute something with the feature
   *       }
   *     },
   *     {
   *       name: 'weight',
   *       callback: function(feature) {
   *         // compute something with the feature
   *       }
   *     },
   *   ],
   *   vertexShader:
   *     // shader using attribute a_weight and a_size
   *   fragmentShader:
   *     // shader using varying v_weight and v_size
   * ```
   *
   * To enable hit detection, you must as well provide dedicated shaders using the `hitVertexShader`
   * and `hitFragmentShader` properties. These shall expect the `a_hitColor` attribute to contain
   * the final color that will have to be output for hit detection to work.
   *
   * The following uniform is used for the main texture: `u_texture`.
   * The following uniform is used for the layer opacity: `u_opacity`.
   *
   * Please note that the main shader output should have premultiplied alpha, otherwise visual anomalies may occur.
   *
   * Points are rendered as quads with the following structure:
   *
   * ```
   *   (u0, v1)      (u1, v1)
   *  [3]----------[2]
   *   |`           |
   *   |  `         |
   *   |    `       |
   *   |      `     |
   *   |        `   |
   *   |          ` |
   *  [0]----------[1]
   *   (u0, v0)      (u1, v0)
   *  ```
   *
   * This uses {@link module:ol/webgl/Helper~WebGLHelper} internally.
   *
   * @api
   */
  class WebGLPointsLayerRenderer extends WebGLLayerRenderer {
    /**
     * @param {import("../../layer/Layer.js").default} layer Layer.
     * @param {Options} options Options.
     */
    constructor(layer, options) {
      const uniforms = options.uniforms || {};
      const projectionMatrixTransform = create$3();
      uniforms[DefaultUniform.PROJECTION_MATRIX] = projectionMatrixTransform;

      super(layer, {
        uniforms: uniforms,
        postProcesses: options.postProcesses,
      });

      /**
       * @private
       */
      this.sourceRevision_ = -1;

      /**
       * @private
       */
      this.verticesBuffer_ = new WebGLArrayBuffer(ARRAY_BUFFER, DYNAMIC_DRAW);
      /**
       * @private
       */
      this.indicesBuffer_ = new WebGLArrayBuffer(
        ELEMENT_ARRAY_BUFFER,
        DYNAMIC_DRAW,
      );

      /**
       * @private
       */
      this.vertexShader_ = options.vertexShader;

      /**
       * @private
       */
      this.fragmentShader_ = options.fragmentShader;

      /**
       * @type {WebGLProgram}
       * @private
       */
      this.program_;

      /**
       * @type {boolean}
       * @private
       */
      this.hitDetectionEnabled_ = options.hitDetectionEnabled ?? true;

      const customAttributes = options.attributes
        ? options.attributes.map(function (attribute) {
            return {
              name: 'a_' + attribute.name,
              size: 1,
              type: AttributeType.FLOAT,
            };
          })
        : [];

      /**
       * A list of attributes used by the renderer. By default only the position and
       * index of the vertex (0 to 3) are required.
       * @type {Array<import('../../webgl/Helper.js').AttributeDescription>}
       */
      this.attributes = [
        {
          name: 'a_position',
          size: 2,
          type: AttributeType.FLOAT,
        },
        {
          name: 'a_index',
          size: 1,
          type: AttributeType.FLOAT,
        },
      ];

      if (this.hitDetectionEnabled_) {
        this.attributes.push({
          name: 'a_hitColor',
          size: 4,
          type: AttributeType.FLOAT,
        });
        this.attributes.push({
          name: 'a_featureUid',
          size: 1,
          type: AttributeType.FLOAT,
        });
      }
      this.attributes.push(...customAttributes);

      this.customAttributes = options.attributes ? options.attributes : [];

      /**
       * @private
       */
      this.previousExtent_ = createEmpty();

      /**
       * This transform is updated on every frame and is the composition of:
       * - invert of the world->screen transform that was used when rebuilding buffers (see `this.renderTransform_`)
       * - current world->screen transform
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.currentTransform_ = projectionMatrixTransform;

      /**
       * This transform is updated when buffers are rebuilt and converts world space coordinates to screen space
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.renderTransform_ = create$3();

      /**
       * @type {import("../../transform.js").Transform}
       * @private
       */
      this.invertRenderTransform_ = create$3();

      /**
       * @type {Float32Array}
       * @private
       */
      this.renderInstructions_ = new Float32Array(0);

      /**
       * @type {WebGLRenderTarget}
       * @private
       */
      this.hitRenderTarget_;

      /**
       * Keep track of latest message sent to worker
       * @type {number}
       * @private
       */
      this.lastSentId = 0;

      /**
       * @private
       */
      this.worker_ = create$1();

      this.worker_.addEventListener(
        'message',
        /**
         * @param {*} event Event.
         */
        (event) => {
          const received = event.data;
          if (received.type === WebGLWorkerMessageType.GENERATE_POINT_BUFFERS) {
            const projectionTransform = received.projectionTransform;
            this.verticesBuffer_.fromArrayBuffer(received.vertexBuffer);
            this.helper.flushBufferData(this.verticesBuffer_);
            this.indicesBuffer_.fromArrayBuffer(received.indexBuffer);
            this.helper.flushBufferData(this.indicesBuffer_);

            this.renderTransform_ = projectionTransform;
            makeInverse(
              this.invertRenderTransform_,
              this.renderTransform_,
            );
            this.renderInstructions_ = new Float32Array(
              event.data.renderInstructions,
            );
            if (received.id === this.lastSentId) {
              this.ready = true;
            }
            this.getLayer().changed();
          }
        },
      );

      /**
       * This object will be updated when the source changes. Key is uid.
       * @type {Object<string, FeatureCacheItem>}
       * @private
       */
      this.featureCache_ = {};

      /**
       * Amount of features in the cache.
       * @type {number}
       * @private
       */
      this.featureCount_ = 0;

      const source = /** @type {import("../../source/Vector.js").default} */ (
        this.getLayer().getSource()
      );
      /**
       * @private
       */
      this.sourceListenKeys_ = [
        listen(
          source,
          VectorEventType.ADDFEATURE,
          this.handleSourceFeatureAdded_,
          this,
        ),
        listen(
          source,
          VectorEventType.CHANGEFEATURE,
          this.handleSourceFeatureChanged_,
          this,
        ),
        listen(
          source,
          VectorEventType.REMOVEFEATURE,
          this.handleSourceFeatureDelete_,
          this,
        ),
        listen(
          source,
          VectorEventType.CLEAR,
          this.handleSourceFeatureClear_,
          this,
        ),
      ];
      source.forEachFeature((feature) => {
        const geometry = feature.getGeometry();
        if (geometry && geometry.getType() === 'Point') {
          this.featureCache_[getUid(feature)] = {
            feature: /** @type {PointFeature} */ (feature),
            properties: feature.getProperties(),
            flatCoordinates: /** @type {Point} */ (geometry).getFlatCoordinates(),
          };
          this.featureCount_++;
        }
      });
    }

    /**
     * @override
     */
    afterHelperCreated() {
      this.program_ = this.helper.getProgram(
        this.fragmentShader_,
        this.vertexShader_,
      );

      if (this.hitDetectionEnabled_) {
        this.hitRenderTarget_ = new WebGLRenderTarget(this.helper);
      }

      // upload buffers again if any
      if (this.verticesBuffer_.getArray()) {
        this.helper.flushBufferData(this.verticesBuffer_);
      }
      if (this.indicesBuffer_.getArray()) {
        this.helper.flushBufferData(this.indicesBuffer_);
      }
    }

    /**
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureAdded_(event) {
      const feature = event.feature;
      const geometry = feature.getGeometry();
      if (geometry && geometry.getType() === 'Point') {
        this.featureCache_[getUid(feature)] = {
          feature: /** @type {PointFeature} */ (feature),
          properties: feature.getProperties(),
          flatCoordinates: /** @type {Point} */ (geometry).getFlatCoordinates(),
        };
        this.featureCount_++;
      }
    }

    /**
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureChanged_(event) {
      const feature = event.feature;
      const featureUid = getUid(feature);
      const item = this.featureCache_[featureUid];
      const geometry = feature.getGeometry();
      if (item) {
        if (geometry && geometry.getType() === 'Point') {
          item.properties = feature.getProperties();
          item.flatCoordinates = /** @type {Point} */ (
            geometry
          ).getFlatCoordinates();
        } else {
          delete this.featureCache_[featureUid];
          this.featureCount_--;
        }
      } else {
        if (geometry && geometry.getType() === 'Point') {
          this.featureCache_[featureUid] = {
            feature: /** @type {PointFeature} */ (feature),
            properties: feature.getProperties(),
            flatCoordinates: /** @type {Point} */ (geometry).getFlatCoordinates(),
          };
          this.featureCount_++;
        }
      }
    }

    /**
     * @param {import("../../source/Vector.js").VectorSourceEvent} event Event.
     * @private
     */
    handleSourceFeatureDelete_(event) {
      const feature = event.feature;
      const featureUid = getUid(feature);
      if (featureUid in this.featureCache_) {
        delete this.featureCache_[featureUid];
        this.featureCount_--;
      }
    }

    /**
     * @private
     */
    handleSourceFeatureClear_() {
      this.featureCache_ = {};
      this.featureCount_ = 0;
    }

    /**
     * Render the layer.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    renderFrame(frameState) {
      const gl = this.helper.getGL();
      this.preRender(gl, frameState);
      const [startWorld, endWorld, worldWidth] = getWorldParameters(
        frameState,
        this.getLayer(),
      );

      // draw the normal canvas
      this.renderWorlds(frameState, false, startWorld, endWorld, worldWidth);
      this.helper.finalizeDraw(
        frameState,
        this.dispatchPreComposeEvent,
        this.dispatchPostComposeEvent,
      );

      if (this.hitDetectionEnabled_) {
        // draw the hit buffer
        this.renderWorlds(frameState, true, startWorld, endWorld, worldWidth);
        this.hitRenderTarget_.clearCachedData();
      }

      this.postRender(gl, frameState);

      const canvas = this.helper.getCanvas();
      return canvas;
    }

    /**
     * Determine whether renderFrame should be called.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @return {boolean} Layer is ready to be rendered.
     * @override
     */
    prepareFrameInternal(frameState) {
      const layer = this.getLayer();
      const vectorSource = layer.getSource();
      const viewState = frameState.viewState;
      const viewNotMoving =
        !frameState.viewHints[ViewHint.ANIMATING] &&
        !frameState.viewHints[ViewHint.INTERACTING];
      const extentChanged = !equals$1(this.previousExtent_, frameState.extent);
      const sourceChanged = this.sourceRevision_ < vectorSource.getRevision();

      if (sourceChanged) {
        this.sourceRevision_ = vectorSource.getRevision();
      }

      if (viewNotMoving && (extentChanged || sourceChanged)) {
        const projection = viewState.projection;
        const resolution = viewState.resolution;

        const renderBuffer =
          layer instanceof BaseVectorLayer ? layer.getRenderBuffer() : 0;
        const extent = buffer$1(frameState.extent, renderBuffer * resolution);
        vectorSource.loadFeatures(extent, resolution, projection);

        this.rebuildBuffers_(frameState);
        this.previousExtent_ = frameState.extent.slice();
      }

      this.helper.useProgram(this.program_, frameState);
      this.helper.prepareDraw(frameState);

      // write new data
      this.helper.bindBuffer(this.verticesBuffer_);
      this.helper.bindBuffer(this.indicesBuffer_);
      this.helper.enableAttributes(this.attributes);

      return true;
    }

    /**
     * Rebuild internal webgl buffers based on current view extent; costly, should not be called too much
     * @param {import("../../Map").FrameState} frameState Frame state.
     * @private
     */
    rebuildBuffers_(frameState) {
      // saves the projection transform for the current frame state
      const projectionTransform = create$3();
      this.helper.makeProjectionTransform(frameState, projectionTransform);

      const userProjection = getUserProjection();

      const baseInstructionLength = this.hitDetectionEnabled_ ? 7 : 2; // see below
      const singleInstructionLength =
        baseInstructionLength + this.customAttributes.length;
      const totalSize = singleInstructionLength * this.featureCount_;
      const renderInstructions =
        this.renderInstructions_ && this.renderInstructions_.length === totalSize
          ? this.renderInstructions_
          : new Float32Array(totalSize);
      this.renderInstructions_ = null;

      // loop over features to fill the buffer
      /** @type {import('../../coordinate.js').Coordinate} */
      let tmpCoords = [];
      /** @type {Array<number>} */
      const tmpColor = [];
      let idx = -1;
      const projection = frameState.viewState.projection;
      for (const featureUid in this.featureCache_) {
        const featureCache = this.featureCache_[featureUid];
        if (userProjection) {
          tmpCoords = fromUserCoordinate(
            featureCache.flatCoordinates,
            projection,
          );
        } else {
          tmpCoords[0] = featureCache.flatCoordinates[0];
          tmpCoords[1] = featureCache.flatCoordinates[1];
        }
        apply(projectionTransform, tmpCoords);

        renderInstructions[++idx] = tmpCoords[0];
        renderInstructions[++idx] = tmpCoords[1];

        // for hit detection, the feature uid is saved in the opacity value
        // and the index of the opacity value is encoded in the color values
        if (this.hitDetectionEnabled_) {
          const hitColor = colorEncodeId(idx + 5, tmpColor);
          renderInstructions[++idx] = hitColor[0];
          renderInstructions[++idx] = hitColor[1];
          renderInstructions[++idx] = hitColor[2];
          renderInstructions[++idx] = hitColor[3];
          renderInstructions[++idx] = Number(featureUid);
        }

        // pushing custom attributes
        for (let j = 0; j < this.customAttributes.length; j++) {
          const value = this.customAttributes[j].callback(
            featureCache.feature,
            featureCache.properties,
          );
          renderInstructions[++idx] = value;
        }
      }

      /** @type {import('../../render/webgl/constants.js').WebGLWorkerGenerateBuffersMessage} */
      const message = {
        id: ++this.lastSentId,
        type: WebGLWorkerMessageType.GENERATE_POINT_BUFFERS,
        renderInstructions: renderInstructions.buffer,
        customAttributesSize: singleInstructionLength - 2,
      };
      // additional properties will be sent back as-is by the worker
      message['projectionTransform'] = projectionTransform;
      this.ready = false;
      this.worker_.postMessage(message, [renderInstructions.buffer]);
    }

    /**
     * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {import("../../Map.js").FrameState} frameState Frame state.
     * @param {number} hitTolerance Hit tolerance in pixels.
     * @param {import("../vector.js").FeatureCallback<T>} callback Feature callback.
     * @param {Array<import("../Map.js").HitMatch<T>>} matches The hit detected matches with tolerance.
     * @return {T|undefined} Callback result.
     * @template T
     * @override
     */
    forEachFeatureAtCoordinate(
      coordinate,
      frameState,
      hitTolerance,
      callback,
      matches,
    ) {
      assert(
        this.hitDetectionEnabled_,
        '`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has been disabled using the `disableHitDetection: true` option.',
      );
      if (!this.renderInstructions_ || !this.hitDetectionEnabled_) {
        return undefined;
      }

      const pixel = apply(
        frameState.coordinateToPixelTransform,
        coordinate.slice(),
      );

      const data = this.hitRenderTarget_.readPixel(pixel[0] / 2, pixel[1] / 2);
      const color = [data[0] / 255, data[1] / 255, data[2] / 255, data[3] / 255];
      const index = colorDecodeId(color);
      const opacity = this.renderInstructions_[index];
      const uid = Math.floor(opacity).toString();

      const source = this.getLayer().getSource();
      const feature = source.getFeatureByUid(uid);
      if (feature) {
        return callback(feature, this.getLayer(), null);
      }
      return undefined;
    }

    /**
     * Render the world, either to the main framebuffer or to the hit framebuffer
     * @param {import("../../Map.js").FrameState} frameState current frame state
     * @param {boolean} forHitDetection whether the rendering is for hit detection
     * @param {number} startWorld the world to render in the first iteration
     * @param {number} endWorld the last world to render
     * @param {number} worldWidth the width of the worlds being rendered
     */
    renderWorlds(frameState, forHitDetection, startWorld, endWorld, worldWidth) {
      let world = startWorld;

      this.helper.useProgram(this.program_, frameState);

      if (forHitDetection) {
        this.hitRenderTarget_.setSize([
          Math.floor(frameState.size[0] / 2),
          Math.floor(frameState.size[1] / 2),
        ]);
        this.helper.prepareDrawToRenderTarget(
          frameState,
          this.hitRenderTarget_,
          true,
        );
      }

      this.helper.bindBuffer(this.verticesBuffer_);
      this.helper.bindBuffer(this.indicesBuffer_);
      this.helper.enableAttributes(this.attributes);

      do {
        this.helper.makeProjectionTransform(frameState, this.currentTransform_);
        translate$2(this.currentTransform_, world * worldWidth, 0);
        multiply(this.currentTransform_, this.invertRenderTransform_);
        this.helper.applyUniforms(frameState);
        this.helper.applyHitDetectionUniform(forHitDetection);
        const renderCount = this.indicesBuffer_.getSize();
        this.helper.drawElements(0, renderCount);
      } while (++world < endWorld);
    }

    /**
     * Clean up.
     * @override
     */
    disposeInternal() {
      this.worker_.terminate();
      this.sourceListenKeys_.forEach(function (key) {
        unlistenByKey(key);
      });
      this.sourceListenKeys_ = null;
      super.disposeInternal();
    }

    renderDeclutter() {}
  }

  /**
   * @module ol/layer/WebGLPoints
   */

  /**
   * @template {import("../source/Vector.js").default<import('../Feature').FeatureLike>} VectorSourceType
   * @typedef {Object} Options
   * @property {import('../style/flat.js').FlatStyle} style Literal style to apply to the layer features.
   * @property {import("../expr/expression.js").EncodedExpression} [filter] The filter used
   * to determine if a style applies. If no filter is included, the rule always applies.
   * @property {import('../style/flat.js').StyleVariables} [variables] Style variables. Each variable must hold a literal value (not
   * an expression). These variables can be used as {@link import("../expr/expression.js").ExpressionValue expressions} in the styles properties
   * using the `['var', 'varName']` operator.
   * To update style variables, use the {@link import("./WebGLPoints.js").default#updateStyleVariables} method.
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {VectorSourceType} [source] Point source.
   * @property {boolean} [disableHitDetection=false] Setting this to true will provide a slight performance boost, but will
   * prevent all hit detection on the layer.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Layer optimized for rendering large point datasets. Takes a `style` property which
   * is a serializable JSON object describing how the layer should be rendered.
   *
   * Here are a few samples of literal style objects:
   * ```js
   * const style = {
   *   'circle-radius': 8,
   *   'circle-fill-color': '#33AAFF',
   *   'circle-opacity': 0.9
   * }
   * ```
   *
   * ```js
   * const style = {
   *   'icon-src': '../static/exclamation-mark.png',
   *   'icon-offset': [0, 12],
   *   'icon-width': 4,
   *   'icon-height': 8
   * }
   * ```
   *
   * **Important: a `WebGLPoints` layer must be manually disposed when removed, otherwise the underlying WebGL context
   * will not be garbage collected.**
   *
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Vector.js").default<import('../Feature').FeatureLike>} VectorSourceType
   * @extends {Layer<VectorSourceType, WebGLPointsLayerRenderer>}
   * @fires import("../render/Event.js").RenderEvent#prerender
   * @fires import("../render/Event.js").RenderEvent#postrender
   * @deprecated Use ol/layer/WebGLVector instead
   */
  class WebGLPointsLayer extends Layer {
    /**
     * @param {Options<VectorSourceType>} options Options.
     */
    constructor(options) {
      const baseOptions = Object.assign({}, options);

      super(baseOptions);

      /**
       * @type {import('../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = options.variables || {};

      /**
       * @private
       * @type {import('../render/webgl/style.js').StyleParseResult}
       */
      this.parseResult_ = parseLiteralStyle(
        options.style,
        this.styleVariables_,
        options.filter,
      );

      /**
       * @private
       * @type {boolean}
       */
      this.hitDetectionDisabled_ = !!options.disableHitDetection;
    }

    /**
     * @override
     */
    createRenderer() {
      const attributes = Object.keys(this.parseResult_.attributes).map(
        (name) => ({
          name,
          ...this.parseResult_.attributes[name],
        }),
      );
      return new WebGLPointsLayerRenderer(this, {
        vertexShader: this.parseResult_.builder.getSymbolVertexShader(),
        fragmentShader: this.parseResult_.builder.getSymbolFragmentShader(),
        hitDetectionEnabled: !this.hitDetectionDisabled_,
        uniforms: this.parseResult_.uniforms,
        attributes:
          /** @type {Array<import('../renderer/webgl/PointsLayer.js').CustomAttribute>} */ (
            attributes
          ),
      });
    }

    /**
     * Update any variables used by the layer style and trigger a re-render.
     * @param {Object<string, number>} variables Variables to update.
     */
    updateStyleVariables(variables) {
      Object.assign(this.styleVariables_, variables);
      this.changed();
    }
  }

  /**
   * @module ol/layer/WebGLTile
   */

  /**
   * @typedef {import("../source/DataTile.js").default<import("../DataTile.js").default|import("../ImageTile.js").default>} SourceType
   */

  /**
   * @typedef {Object} Style
   * Translates tile data to rendered pixels.
   *
   * @property {Object<string, (string|number)>} [variables] Style variables.  Each variable must hold a number or string.  These
   * variables can be used in the `color`, `brightness`, `contrast`, `exposure`, `saturation` and `gamma`
   * {@link import("../expr/expression.js").ExpressionValue expressions}, using the `['var', 'varName']` operator.
   * To update style variables, use the {@link import("./WebGLTile.js").default#updateStyleVariables} method.
   * @property {import("../expr/expression.js").ExpressionValue} [color] An expression applied to color values.
   * @property {import("../expr/expression.js").ExpressionValue} [brightness=0] Value used to decrease or increase
   * the layer brightness.  Values range from -1 to 1.
   * @property {import("../expr/expression.js").ExpressionValue} [contrast=0] Value used to decrease or increase
   * the layer contrast.  Values range from -1 to 1.
   * @property {import("../expr/expression.js").ExpressionValue} [exposure=0] Value used to decrease or increase
   * the layer exposure.  Values range from -1 to 1.
   * @property {import("../expr/expression.js").ExpressionValue} [saturation=0] Value used to decrease or increase
   * the layer saturation.  Values range from -1 to 1.
   * @property {import("../expr/expression.js").ExpressionValue} [gamma=1] Apply a gamma correction to the layer.
   * Values range from 0 to infinity.
   */

  /**
   * @typedef {Object} Options
   * @property {Style} [style] Style to apply to the layer.
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
   * means no preloading.
   * @property {SourceType} [source] Source for this layer.
   * @property {Array<SourceType>|function(import("../extent.js").Extent, number):Array<SourceType>} [sources] Array
   * of sources for this layer. Takes precedence over `source`. Can either be an array of sources, or a function that
   * expects an extent and a resolution (in view projection units per pixel) and returns an array of sources. See
   * {@link module:ol/source.sourcesFromTileGrid} for a helper function to generate sources that are organized in a
   * pyramid following the same pattern as a tile grid. **Note:** All sources must have the same band count and content.
   * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage
   * this layer in its layers collection, and the layer will be rendered on top. This is useful for
   * temporary layers. The standard way to add a layer to a map and have it managed by the map is to
   * use {@link module:ol/Map~Map#addLayer}.
   * @property {boolean} [useInterimTilesOnError=true] Deprecated.  Use interim tiles on error.
   * @property {number} [cacheSize=512] The internal texture cache size.  This needs to be large enough to render
   * two zoom levels worth of tiles.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @typedef {Object} ParsedStyle
   * @property {string} vertexShader The vertex shader.
   * @property {string} fragmentShader The fragment shader.
   * @property {Object<string,import("../webgl/Helper.js").UniformValue>} uniforms Uniform definitions.
   * @property {Array<import("../webgl/PaletteTexture.js").default>} paletteTextures Palette textures.
   */

  /**
   * @param {Style} style The layer style.
   * @param {number} [bandCount] The number of bands.
   * @return {ParsedStyle} Shaders and uniforms generated from the style.
   */
  function parseStyle(style, bandCount) {
    const vertexShader = `
    attribute vec2 ${Attributes$2.TEXTURE_COORD};
    uniform mat4 ${Uniforms$2.TILE_TRANSFORM};
    uniform float ${Uniforms$2.TEXTURE_PIXEL_WIDTH};
    uniform float ${Uniforms$2.TEXTURE_PIXEL_HEIGHT};
    uniform float ${Uniforms$2.TEXTURE_RESOLUTION};
    uniform float ${Uniforms$2.TEXTURE_ORIGIN_X};
    uniform float ${Uniforms$2.TEXTURE_ORIGIN_Y};
    uniform float ${Uniforms$2.DEPTH};

    varying vec2 v_textureCoord;
    varying vec2 v_mapCoord;

    void main() {
      v_textureCoord = ${Attributes$2.TEXTURE_COORD};
      v_mapCoord = vec2(
        ${Uniforms$2.TEXTURE_ORIGIN_X} + ${Uniforms$2.TEXTURE_RESOLUTION} * ${Uniforms$2.TEXTURE_PIXEL_WIDTH} * v_textureCoord[0],
        ${Uniforms$2.TEXTURE_ORIGIN_Y} - ${Uniforms$2.TEXTURE_RESOLUTION} * ${Uniforms$2.TEXTURE_PIXEL_HEIGHT} * v_textureCoord[1]
      );
      gl_Position = ${Uniforms$2.TILE_TRANSFORM} * vec4(${Attributes$2.TEXTURE_COORD}, ${Uniforms$2.DEPTH}, 1.0);
    }
  `;

    /**
     * @type {import("../expr/gpu.js").CompilationContext}
     */
    const context = {
      ...newCompilationContext(),
      bandCount: bandCount,
    };

    const pipeline = [];

    if (style.color !== undefined) {
      const color = expressionToGlsl(context, style.color, ColorType$1);
      pipeline.push(`color = ${color};`);
    }

    if (style.contrast !== undefined) {
      const contrast = expressionToGlsl(context, style.contrast, NumberType$1);
      pipeline.push(
        `color.rgb = clamp((${contrast} + 1.0) * color.rgb - (${contrast} / 2.0), vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`,
      );
    }

    if (style.exposure !== undefined) {
      const exposure = expressionToGlsl(context, style.exposure, NumberType$1);
      pipeline.push(
        `color.rgb = clamp((${exposure} + 1.0) * color.rgb, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`,
      );
    }

    if (style.saturation !== undefined) {
      const saturation = expressionToGlsl(context, style.saturation, NumberType$1);
      pipeline.push(`
      float saturation = ${saturation} + 1.0;
      float sr = (1.0 - saturation) * 0.2126;
      float sg = (1.0 - saturation) * 0.7152;
      float sb = (1.0 - saturation) * 0.0722;
      mat3 saturationMatrix = mat3(
        sr + saturation, sr, sr,
        sg, sg + saturation, sg,
        sb, sb, sb + saturation
      );
      color.rgb = clamp(saturationMatrix * color.rgb, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));
    `);
    }

    if (style.gamma !== undefined) {
      const gamma = expressionToGlsl(context, style.gamma, NumberType$1);
      pipeline.push(`color.rgb = pow(color.rgb, vec3(1.0 / ${gamma}));`);
    }

    if (style.brightness !== undefined) {
      const brightness = expressionToGlsl(context, style.brightness, NumberType$1);
      pipeline.push(
        `color.rgb = clamp(color.rgb + ${brightness}, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`,
      );
    }

    /** @type {Object<string,import("../webgl/Helper").UniformValue>} */
    const uniforms = {};

    const numVariables = Object.keys(context.variables).length;
    if (numVariables > 1 && !style.variables) {
      throw new Error(
        `Missing variables in style (expected ${context.variables})`,
      );
    }

    for (let i = 0; i < numVariables; ++i) {
      const variable = context.variables[Object.keys(context.variables)[i]];
      if (!(variable.name in style.variables)) {
        throw new Error(`Missing '${variable.name}' in style variables`);
      }
      const uniformName = uniformNameForVariable(variable.name);
      uniforms[uniformName] = function () {
        let value = style.variables[variable.name];
        if (typeof value === 'string') {
          value = getStringNumberEquivalent(value);
        }
        return value !== undefined ? value : -9999999; // to avoid matching with the first string literal
      };
    }

    const uniformDeclarations = Object.keys(uniforms).map(function (name) {
      return `uniform float ${name};`;
    });

    const textureCount = Math.ceil(bandCount / 4);
    uniformDeclarations.push(
      `uniform sampler2D ${Uniforms$2.TILE_TEXTURE_ARRAY}[${textureCount}];`,
    );

    if (context.paletteTextures) {
      uniformDeclarations.push(
        `uniform sampler2D ${PALETTE_TEXTURE_ARRAY}[${context.paletteTextures.length}];`,
      );
    }

    const functionDefintions = Object.keys(context.functions).map(
      function (name) {
        return context.functions[name];
      },
    );

    const fragmentShader = `
    #ifdef GL_FRAGMENT_PRECISION_HIGH
    precision highp float;
    #else
    precision mediump float;
    #endif

    varying vec2 v_textureCoord;
    varying vec2 v_mapCoord;
    uniform vec4 ${Uniforms$2.RENDER_EXTENT};
    uniform float ${Uniforms$2.TRANSITION_ALPHA};
    uniform float ${Uniforms$2.TEXTURE_PIXEL_WIDTH};
    uniform float ${Uniforms$2.TEXTURE_PIXEL_HEIGHT};
    uniform float ${Uniforms$2.RESOLUTION};
    uniform float ${Uniforms$2.ZOOM};

    ${uniformDeclarations.join('\n')}

    ${functionDefintions.join('\n')}

    void main() {
      if (
        v_mapCoord[0] < ${Uniforms$2.RENDER_EXTENT}[0] ||
        v_mapCoord[1] < ${Uniforms$2.RENDER_EXTENT}[1] ||
        v_mapCoord[0] > ${Uniforms$2.RENDER_EXTENT}[2] ||
        v_mapCoord[1] > ${Uniforms$2.RENDER_EXTENT}[3]
      ) {
        discard;
      }

      vec4 color = texture2D(${
        Uniforms$2.TILE_TEXTURE_ARRAY
      }[0],  v_textureCoord);

      ${pipeline.join('\n')}

      gl_FragColor = color;
      gl_FragColor.rgb *= gl_FragColor.a;
      gl_FragColor *= ${Uniforms$2.TRANSITION_ALPHA};
    }`;

    return {
      vertexShader: vertexShader,
      fragmentShader: fragmentShader,
      uniforms: uniforms,
      paletteTextures: context.paletteTextures,
    };
  }

  /**
   * @classdesc
   * For layer sources that provide pre-rendered, tiled images in grids that are
   * organized by zoom levels for specific resolutions.
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @extends BaseTileLayer<SourceType, WebGLTileLayerRenderer>
   * @fires import("../render/Event.js").RenderEvent#prerender
   * @fires import("../render/Event.js").RenderEvent#postrender
   * @api
   */
  class WebGLTileLayer extends BaseTileLayer {
    /**
     * @param {Options} [options] Tile layer options.
     */
    constructor(options) {
      options = options ? Object.assign({}, options) : {};

      const style = options.style || {};
      delete options.style;

      super(options);

      /**
       * @type {Array<SourceType>|function(import("../extent.js").Extent, number):Array<SourceType>}
       * @private
       */
      this.sources_ = options.sources;

      /**
       * @type {SourceType|null}
       * @private
       */
      this.renderedSource_ = null;

      /**
       * @type {number}
       * @private
       */
      this.renderedResolution_ = NaN;

      /**
       * @type {Style}
       * @private
       */
      this.style_ = style;

      /**
       * @type {Object<string, (string|number)>}
       * @private
       */
      this.styleVariables_ = this.style_.variables || {};

      this.handleSourceUpdate_();
      this.addChangeListener(LayerProperty.SOURCE, this.handleSourceUpdate_);
    }

    /**
     * Gets the sources for this layer, for a given extent and resolution.
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @return {Array<SourceType>} Sources.
     */
    getSources(extent, resolution) {
      const source = this.getSource();
      return this.sources_
        ? typeof this.sources_ === 'function'
          ? this.sources_(extent, resolution)
          : this.sources_
        : source
          ? [source]
          : [];
    }

    /**
     * @return {SourceType} The source being rendered.
     * @override
     */
    getRenderSource() {
      return this.renderedSource_ || this.getSource();
    }

    /**
     * @return {import("../source/Source.js").State} Source state.
     * @override
     */
    getSourceState() {
      const source = this.getRenderSource();
      return source ? source.getState() : 'undefined';
    }

    /**
     * @private
     */
    handleSourceUpdate_() {
      if (this.hasRenderer()) {
        this.getRenderer().clearCache();
      }
      const source = this.getSource();
      if (source) {
        if (source.getState() === 'loading') {
          const onChange = () => {
            if (source.getState() === 'ready') {
              source.removeEventListener('change', onChange);
              this.setStyle(this.style_);
            }
          };
          source.addEventListener('change', onChange);
        } else {
          this.setStyle(this.style_);
        }
      }
    }

    /**
     * @private
     * @return {number} The number of source bands.
     */
    getSourceBandCount_() {
      const max = Number.MAX_SAFE_INTEGER;
      const sources = this.getSources([-max, -max, max, max], max);
      return sources && sources.length && 'bandCount' in sources[0]
        ? sources[0].bandCount
        : 4;
    }

    /**
     * @override
     */
    createRenderer() {
      const parsedStyle = parseStyle(this.style_, this.getSourceBandCount_());

      return new WebGLTileLayerRenderer(this, {
        vertexShader: parsedStyle.vertexShader,
        fragmentShader: parsedStyle.fragmentShader,
        uniforms: parsedStyle.uniforms,
        cacheSize: this.getCacheSize(),
        paletteTextures: parsedStyle.paletteTextures,
      });
    }

    /**
     * @param {import("../Map").FrameState} frameState Frame state.
     * @param {Array<SourceType>} sources Sources.
     * @return {HTMLElement} Canvas.
     */
    renderSources(frameState, sources) {
      const layerRenderer = this.getRenderer();
      let canvas;
      for (let i = 0, ii = sources.length; i < ii; ++i) {
        this.renderedSource_ = sources[i];
        if (layerRenderer.prepareFrame(frameState)) {
          canvas = layerRenderer.renderFrame(frameState);
        }
      }
      return canvas;
    }

    /**
     * @param {?import("../Map.js").FrameState} frameState Frame state.
     * @param {HTMLElement} target Target which the renderer may (but need not) use
     * for rendering its content.
     * @return {HTMLElement} The rendered element.
     * @override
     */
    render(frameState, target) {
      this.rendered = true;
      const viewState = frameState.viewState;
      const sources = this.getSources(frameState.extent, viewState.resolution);
      let ready = true;
      for (let i = 0, ii = sources.length; i < ii; ++i) {
        const source = sources[i];
        const sourceState = source.getState();
        if (sourceState == 'loading') {
          const onChange = () => {
            if (source.getState() == 'ready') {
              source.removeEventListener('change', onChange);
              this.changed();
            }
          };
          source.addEventListener('change', onChange);
        }
        ready = ready && sourceState == 'ready';
      }
      const canvas = this.renderSources(frameState, sources);
      if (this.getRenderer().renderComplete && ready) {
        // Fully rendered, done.
        this.renderedResolution_ = viewState.resolution;
        return canvas;
      }
      // Render sources from previously fully rendered frames
      if (this.renderedResolution_ > 0.5 * viewState.resolution) {
        const altSources = this.getSources(
          frameState.extent,
          this.renderedResolution_,
        ).filter((source) => !sources.includes(source));
        if (altSources.length > 0) {
          return this.renderSources(frameState, altSources);
        }
      }
      return canvas;
    }

    /**
     * Update the layer style.  The `updateStyleVariables` function is a more efficient
     * way to update layer rendering.  In cases where the whole style needs to be updated,
     * this method may be called instead.  Note that calling this method will also replace
     * any previously set variables, so the new style also needs to include new variables,
     * if needed.
     * @param {Style} style The new style.
     */
    setStyle(style) {
      this.styleVariables_ = style.variables || {};
      this.style_ = style;
      if (this.hasRenderer()) {
        const parsedStyle = parseStyle(this.style_, this.getSourceBandCount_());
        const renderer = this.getRenderer();
        renderer.reset({
          vertexShader: parsedStyle.vertexShader,
          fragmentShader: parsedStyle.fragmentShader,
          uniforms: parsedStyle.uniforms,
          paletteTextures: parsedStyle.paletteTextures,
        });
        this.changed();
      }
    }

    /**
     * Update any variables used by the layer style and trigger a re-render.
     * @param {Object<string, number>} variables Variables to update.
     * @api
     */
    updateStyleVariables(variables) {
      Object.assign(this.styleVariables_, variables);
      this.changed();
    }
  }

  /**
   * Clean up underlying WebGL resources.
   * @function
   * @api
   */
  WebGLTileLayer.prototype.dispose;

  /**
   * @module ol/layer/WebGLVector
   */

  /***
   * @template T
   * @typedef {T extends import("../source/Vector.js").default<infer U extends import("../Feature.js").FeatureLike> ? U : never} ExtractedFeatureType
   */

  /**
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=ExtractedFeatureType<VectorSourceType>]
   * @typedef {Object} Options
   * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
   * @property {number} [opacity=1] Opacity (0, 1).
   * @property {boolean} [visible=true] Visibility.
   * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering.  The layer will not be
   * rendered outside of this extent.
   * FIXME: not supported yet
   * @property {number} [zIndex] The z-index for layer rendering.  At rendering time, the layers
   * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
   * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
   * method was used.
   * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
   * visible.
   * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
   * be visible.
   * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
   * visible.
   * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
   * be visible.
   * @property {VectorSourceType} [source] Source.
   * @property {import('../style/flat.js').FlatStyleLike} style Layer style.
   * @property {import('../style/flat.js').StyleVariables} [variables] Style variables. Each variable must hold a literal value (not
   * an expression). These variables can be used as {@link import("../expr/expression.js").ExpressionValue expressions} in the styles properties
   * using the `['var', 'varName']` operator.
   * To update style variables, use the {@link import("./WebGLVector.js").default#updateStyleVariables} method.
   * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background
   * will be rendered.
   * FIXME: not supported yet
   * @property {boolean} [disableHitDetection=false] Setting this to true will provide a slight performance boost, but will
   * prevent all hit detection on the layer.
   * @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
   */

  /**
   * @classdesc
   * Layer optimized for rendering large vector datasets.
   *
   * **Important: a `WebGLVector` layer must be manually disposed when removed, otherwise the underlying WebGL context
   * will not be garbage collected.**
   *
   * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}
   * property on the layer object; for example, setting `title: 'My Title'` in the
   * options means that `title` is observable, and has get/set accessors.
   *
   * @template {import("../source/Vector.js").default<FeatureType>} [VectorSourceType=import("../source/Vector.js").default<*>]
   * @template {import('../Feature.js').FeatureLike} [FeatureType=ExtractedFeatureType<VectorSourceType>]
   * @extends {Layer<VectorSourceType, WebGLVectorLayerRenderer>}
   */
  class WebGLVectorLayer extends Layer {
    /**
     * @param {Options<VectorSourceType, FeatureType>} [options] Options.
     */
    constructor(options) {
      const baseOptions = Object.assign({}, options);

      super(baseOptions);

      /**
       * @type {import('../style/flat.js').StyleVariables}
       * @private
       */
      this.styleVariables_ = options.variables || {};

      /**
       * @private
       */
      this.style_ = options.style;

      /**
       * @private
       */
      this.hitDetectionDisabled_ = !!options.disableHitDetection;
    }

    /**
     * @override
     */
    createRenderer() {
      return new WebGLVectorLayerRenderer(this, {
        style: this.style_,
        variables: this.styleVariables_,
        disableHitDetection: this.hitDetectionDisabled_,
      });
    }

    /**
     * Update any variables used by the layer style and trigger a re-render.
     * @param {import('../style/flat.js').StyleVariables} variables Variables to update.
     */
    updateStyleVariables(variables) {
      Object.assign(this.styleVariables_, variables);
      this.changed();
    }

    /**
     * Set the layer style.
     * @param {import('../style/flat.js').FlatStyleLike} style Layer style.
     */
    setStyle(style) {
      this.style_ = style;
      this.clearRenderer();
      this.changed();
    }
  }

  /**
   * @module ol/layer
   */

  var nsLayer = {
    __proto__: null,
    Graticule: Graticule,
    Group: LayerGroup,
    Heatmap: Heatmap,
    Image: ImageLayer,
    Layer: Layer,
    Tile: TileLayer,
    Vector: VectorLayer,
    VectorImage: VectorImageLayer,
    VectorTile: VectorTileLayer,
    WebGLPoints: WebGLPointsLayer,
    WebGLTile: WebGLTileLayer,
    WebGLVector: WebGLVectorLayer
  };

  /**
   * @module ol/proj/proj4
   */

  /**
   * @type {import("proj4")|null}
   */
  let registered = null;

  /**
   * @return {boolean} Proj4 has been registered.
   */
  function isRegistered() {
    return !!registered;
  }

  /**
   * Unsets the shared proj4 previously set with register.
   */
  function unregister() {
    registered = null;
  }

  /**
   * Make projections defined in proj4 (with `proj4.defs()`) available in
   * OpenLayers. Requires proj4 >= 2.8.0.
   *
   * This function should be called whenever changes are made to the proj4
   * registry, e.g. after calling `proj4.defs()`. Existing transforms will not be
   * modified by this function.
   *
   * @param {import("proj4")} proj4 Proj4.
   * @api
   */
  function register(proj4) {
    registered = proj4;

    const projCodes = Object.keys(proj4.defs);
    const len = projCodes.length;
    let i, j;
    for (i = 0; i < len; ++i) {
      const code = projCodes[i];
      if (!get$4(code)) {
        const def = proj4.defs(code);
        let units = /** @type {import("./Units.js").Units} */ (def.units);
        if (!units && def.projName === 'longlat') {
          units = 'degrees';
        }
        addProjection(
          new Projection({
            code: code,
            axisOrientation: def.axis,
            metersPerUnit: def.to_meter,
            units,
          }),
        );
      }
    }
    for (i = 0; i < len; ++i) {
      const code1 = projCodes[i];
      const proj1 = get$4(code1);
      for (j = 0; j < len; ++j) {
        const code2 = projCodes[j];
        const proj2 = get$4(code2);
        if (!get$3(code1, code2)) {
          if (proj4.defs[code1] === proj4.defs[code2]) {
            addEquivalentProjections([proj1, proj2]);
          } else {
            const transform = proj4(code1, code2);
            addCoordinateTransforms(
              proj1,
              proj2,
              createSafeCoordinateTransform(proj1, proj2, transform.forward),
              createSafeCoordinateTransform(proj2, proj1, transform.inverse),
            );
          }
        }
      }
    }
  }

  /**
   * @param {number} code The EPSG code.
   * @return {Promise<string>} The proj4 definition.
   */
  let epsgLookup = async function (code) {
    const response = await fetch(`https://epsg.io/${code}.proj4`);
    if (!response.ok) {
      throw new Error(`Unexpected response from epsg.io: ${response.status}`);
    }
    return response.text();
  };

  /**
   * Set the lookup function for getting proj4 definitions given an EPSG code.
   * By default, the {@link module:ol/proj/proj4.fromEPSGCode} function uses the
   * epsg.io website for proj4 definitions.  This can be changed by providing a
   * different lookup function.
   *
   * @param {function(number):Promise<string>} func The lookup function.
   * @api
   */
  function setEPSGLookup(func) {
    epsgLookup = func;
  }

  /**
   * Get the current EPSG lookup function.
   *
   * @return {function(number):Promise<string>} The EPSG lookup function.
   */
  function getEPSGLookup() {
    return epsgLookup;
  }

  /**
   * Get a projection from an EPSG code.  This function fetches the projection
   * definition from the epsg.io website, registers this definition for use with
   * proj4, and returns a configured projection.  You must call import proj4 and
   * call {@link module:ol/proj/proj4.register} before using this function.
   *
   * If the projection definition is already registered with proj4, it will not
   * be fetched again (so it is ok to call this function multiple times with the
   * same code).
   *
   * @param {number|string} code The EPSG code (e.g. 4326 or 'EPSG:4326').
   * @return {Promise<Projection>} The projection.
   * @api
   */
  async function fromEPSGCode(code) {
    if (typeof code === 'string') {
      code = parseInt(code.split(':').pop(), 10);
    }

    const proj4 = registered;
    if (!proj4) {
      throw new Error('Proj4 must be registered first with register(proj4)');
    }

    const epsgCode = 'EPSG:' + code;
    if (proj4.defs(epsgCode)) {
      return get$4(epsgCode);
    }

    proj4.defs(epsgCode, await epsgLookup(code));
    register(proj4);

    return get$4(epsgCode);
  }

  /**
   * Generate an EPSG lookup function which uses the MapTiler Coordinates API to find projection
   * definitions which do not require proj4 to be configured to handle `+nadgrids` parameters.
   * Call {@link module:ol/proj/proj4.setEPSGLookup} use the function for lookups
   * `setEPSGLookup(epsgLookupMapTiler('{YOUR_MAPTILER_API_KEY_HERE}'))`.
   *
   * @param {string} key MapTiler API key.  Get your own API key at https://www.maptiler.com/cloud/.
   * @return {function(number):Promise<string>} The EPSG lookup function.
   * @api
   */
  function epsgLookupMapTiler(key) {
    return async function (code) {
      const response = await fetch(
        `https://api.maptiler.com/coordinates/search/code:${code}.json?transformations=true&exports=true&key=${key}`,
      );
      if (!response.ok) {
        throw new Error(
          `Unexpected response from maptiler.com: ${response.status}`,
        );
      }
      return response.json().then((json) => {
        const results = json['results'];
        if (results?.length > 0) {
          const result = results.filter(
            (r) =>
              r['id']?.['authority'] === 'EPSG' && r['id']?.['code'] === code,
          )[0];
          if (result) {
            const transforms = result['transformations'];
            if (transforms?.length > 0) {
              // use default transform if it does not require grids
              const defaultTransform = result['default_transformation'];
              if (
                transforms.filter(
                  (t) =>
                    t['id']?.['authority'] === defaultTransform?.['authority'] &&
                    t['id']?.['code'] === defaultTransform?.['code'] &&
                    t['grids']?.length === 0,
                ).length > 0
              ) {
                return result['exports']?.['proj4'];
              }
              // otherwise use most accurate alternative without grids
              const transform = transforms
                .filter(
                  (t) =>
                    t['grids']?.length === 0 &&
                    t['target_crs']?.['authority'] === 'EPSG' &&
                    t['target_crs']?.['code'] === 4326 &&
                    t['deprecated'] === false &&
                    t['usable'] === true,
                )
                .sort((t1, t2) => t1['accuracy'] - t2['accuracy'])[0]?.[
                'exports'
              ]?.['proj4'];
              if (transform) {
                return transform;
              }
            }
            // fallback to default
            return result['exports']?.['proj4'];
          }
        }
      });
    };
  }

  var proj_proj4 = {
    __proto__: null,
    epsgLookupMapTiler: epsgLookupMapTiler,
    fromEPSGCode: fromEPSGCode,
    getEPSGLookup: getEPSGLookup,
    isRegistered: isRegistered,
    register: register,
    setEPSGLookup: setEPSGLookup,
    unregister: unregister
  };

  /**
   * @module ol/source/BingMaps
   */


  /**
   * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coord.
   * @return {string} Quad key.
   */
  function quadKey(tileCoord) {
    const z = tileCoord[0];
    const digits = new Array(z);
    let mask = 1 << (z - 1);
    let i, charCode;
    for (i = 0; i < z; ++i) {
      // 48 is charCode for 0 - '0'.charCodeAt(0)
      charCode = 48;
      if (tileCoord[1] & mask) {
        charCode += 1;
      }
      if (tileCoord[2] & mask) {
        charCode += 2;
      }
      digits[i] = String.fromCharCode(charCode);
      mask >>= 1;
    }
    return digits.join('');
  }

  /**
   * The attribution containing a link to the Microsoft® Bing™ Maps Platform APIs’
   * Terms Of Use.
   * @const
   * @type {string}
   */
  const TOS_ATTRIBUTION =
    '<a class="ol-attribution-bing-tos" ' +
    'href="https://www.microsoft.com/maps/product/terms.html" target="_blank">' +
    'Terms of Use</a>';

  /**
   * @typedef {Object} Options
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {boolean} [hidpi=false] If `true` hidpi tiles will be requested.
   * @property {string} [culture='en-us'] Culture code.
   * @property {string} key Bing Maps API key. Get yours at https://www.bingmapsportal.com/.
   * @property {string} imagerySet Type of imagery.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {number} [maxZoom=21] Max zoom. Default is what's advertized by the BingMaps service.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   * @property {boolean} [placeholderTiles] Whether to show BingMaps placeholder tiles when zoomed past the maximum level provided in an area. When `false`, requests beyond
   * the maximum zoom level will return no tile. When `true`, the placeholder tile will be returned. When not set, the default behaviour of the imagery set takes place,
   * which is unique for each imagery set in BingMaps.
   */

  /**
   * @typedef {Object} BingMapsImageryMetadataResponse
   * @property {number} statusCode The response status code
   * @property {string} statusDescription The response status description
   * @property {string} authenticationResultCode The authentication result code
   * @property {Array<ResourceSet>} resourceSets The array of resource sets
   */

  /**
   * @typedef {Object} ResourceSet
   * @property {Array<Resource>} resources Resources.
   */

  /**
   * @typedef {Object} Resource
   * @property {number} imageHeight The image height
   * @property {number} imageWidth The image width
   * @property {number} zoomMin The minimum zoom level
   * @property {number} zoomMax The maximum zoom level
   * @property {string} imageUrl The image URL
   * @property {Array<string>} imageUrlSubdomains The image URL subdomains for rotation
   * @property {Array<ImageryProvider>} [imageryProviders] The array of ImageryProviders
   */

  /**
   * @typedef {Object} ImageryProvider
   * @property {Array<CoverageArea>} coverageAreas The coverage areas
   * @property {string} [attribution] The attribution
   */

  /**
   * @typedef {Object} CoverageArea
   * @property {number} zoomMin The minimum zoom
   * @property {number} zoomMax The maximum zoom
   * @property {Array<number>} bbox The coverage bounding box
   */

  /**
   * @classdesc
   * Layer source for Bing Maps tile data.
   * @api
   */
  class BingMaps extends TileImage {
    /**
     * @param {Options} options Bing Maps options.
     */
    constructor(options) {
      const hidpi = options.hidpi !== undefined ? options.hidpi : false;

      super({
        cacheSize: options.cacheSize,
        crossOrigin: 'anonymous',
        interpolate: options.interpolate,
        projection: get$2('EPSG:3857'),
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        state: 'loading',
        tileLoadFunction: options.tileLoadFunction,
        tilePixelRatio: hidpi ? 2 : 1,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = hidpi;

      /**
       * @private
       * @type {string}
       */
      this.culture_ = options.culture !== undefined ? options.culture : 'en-us';

      /**
       * @private
       * @type {number}
       */
      this.maxZoom_ = options.maxZoom !== undefined ? options.maxZoom : -1;

      /**
       * @private
       * @type {string}
       */
      this.apiKey_ = options.key;

      /**
       * @private
       * @type {string}
       */
      this.imagerySet_ = options.imagerySet;

      /**
       * @private
       * @type {boolean|undefined}
       */
      this.placeholderTiles_ = options.placeholderTiles;

      const url =
        'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' +
        this.imagerySet_ +
        '?uriScheme=https&include=ImageryProviders&key=' +
        this.apiKey_ +
        '&c=' +
        this.culture_;

      fetch(url)
        .then((response) => response.json())
        .then((json) => this.handleImageryMetadataResponse(json));
    }

    /**
     * Get the api key used for this source.
     *
     * @return {string} The api key.
     * @api
     */
    getApiKey() {
      return this.apiKey_;
    }

    /**
     * Get the imagery set associated with this source.
     *
     * @return {string} The imagery set.
     * @api
     */
    getImagerySet() {
      return this.imagerySet_;
    }

    /**
     * @param {BingMapsImageryMetadataResponse} response Response.
     */
    handleImageryMetadataResponse(response) {
      if (
        response.statusCode != 200 ||
        response.statusDescription != 'OK' ||
        response.authenticationResultCode != 'ValidCredentials' ||
        response.resourceSets.length != 1 ||
        response.resourceSets[0].resources.length != 1
      ) {
        this.setState('error');
        return;
      }

      const resource = response.resourceSets[0].resources[0];
      const maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_;

      const sourceProjection = this.getProjection();
      const extent = extentFromProjection(sourceProjection);
      const scale = this.hidpi_ ? 2 : 1;
      const tileSize =
        resource.imageWidth == resource.imageHeight
          ? resource.imageWidth / scale
          : [resource.imageWidth / scale, resource.imageHeight / scale];

      const tileGrid = createXYZ({
        extent: extent,
        minZoom: resource.zoomMin,
        maxZoom: maxZoom,
        tileSize: tileSize,
      });
      this.tileGrid = tileGrid;

      const culture = this.culture_;
      const hidpi = this.hidpi_;
      const placeholderTiles = this.placeholderTiles_;
      this.tileUrlFunction = createFromTileUrlFunctions(
        resource.imageUrlSubdomains.map(function (subdomain) {
          /** @type {import('../tilecoord.js').TileCoord} */
          const quadKeyTileCoord = [0, 0, 0];
          const imageUrl = resource.imageUrl
            .replace('{subdomain}', subdomain)
            .replace('{culture}', culture);
          return (
            /**
             * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
             * @param {number} pixelRatio Pixel ratio.
             * @param {import("../proj/Projection.js").default} projection Projection.
             * @return {string|undefined} Tile URL.
             */
            function (tileCoord, pixelRatio, projection) {
              if (!tileCoord) {
                return undefined;
              }
              createOrUpdate(
                tileCoord[0],
                tileCoord[1],
                tileCoord[2],
                quadKeyTileCoord,
              );
              const url = new URL(
                imageUrl.replace('{quadkey}', quadKey(quadKeyTileCoord)),
              );
              const params = url.searchParams;
              if (hidpi) {
                params.set('dpi', 'd1');
                params.set('device', 'mobile');
              }
              if (placeholderTiles === true) {
                params.delete('n');
              } else if (placeholderTiles === false) {
                params.set('n', 'z');
              }
              return url.toString();
            }
          );
        }),
      );

      if (resource.imageryProviders) {
        const transform = getTransformFromProjections(
          get$2('EPSG:4326'),
          this.getProjection(),
        );

        this.setAttributions((frameState) => {
          const attributions = [];
          const viewState = frameState.viewState;
          const tileGrid = this.getTileGrid();
          const z = tileGrid.getZForResolution(
            viewState.resolution,
            this.zDirection,
          );
          const tileCoord = tileGrid.getTileCoordForCoordAndZ(
            viewState.center,
            z,
          );
          const zoom = tileCoord[0];
          resource.imageryProviders.map(function (imageryProvider) {
            let intersecting = false;
            const coverageAreas = imageryProvider.coverageAreas;
            for (let i = 0, ii = coverageAreas.length; i < ii; ++i) {
              const coverageArea = coverageAreas[i];
              if (zoom >= coverageArea.zoomMin && zoom <= coverageArea.zoomMax) {
                const bbox = coverageArea.bbox;
                const epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]];
                const extent = applyTransform(epsg4326Extent, transform);
                if (intersects$2(extent, frameState.extent)) {
                  intersecting = true;
                  break;
                }
              }
            }
            if (intersecting) {
              attributions.push(imageryProvider.attribution);
            }
          });

          attributions.push(TOS_ATTRIBUTION);
          return attributions;
        });
      }

      this.setState('ready');
    }
  }

  /**
   * @module ol/source/XYZ
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Projection.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.
   * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.
   * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Deprecated.  Use an ImageTile source with a loader
   * instead.  Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.
   * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px
   * by 512px images (for retina/hidpi devices) then `tilePixelRatio`
   * should be set to `2`.
   * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The tile size used by the tile service.
   * Not used if `tileGrid` is provided.
   * @property {number} [gutter=0] The size in pixels of the gutter around image tiles to ignore.
   * This allows artifacts of rendering at tile edges to be ignored.
   * Supported images should be wider and taller than the tile size by a value of `2 x gutter`.
   * @property {import("../Tile.js").UrlFunction} [tileUrlFunction] Deprecated.  Use an ImageTile source and provide a function
   * for the url option instead.
   * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`,
   * and `{z}` placeholders. A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`,
   * may be used instead of defining each one separately in the `urls` option.
   * @property {Array<string>} [urls] Deprecated.  Use an ImageTile source and provide an array of URLs for the
   * url option instead.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number} [transition=250] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data with URLs in a set XYZ format that are
   * defined in a URL template. By default, this follows the widely-used
   * Google grid where `x` 0 and `y` 0 are in the top left. Grids like
   * TMS where `x` 0 and `y` 0 are in the bottom left can be used by
   * using the `{-y}` placeholder in the URL template, so long as the
   * source does not have a custom tile grid. In this case
   * a `tileUrlFunction` can be used, such as:
   * ```js
   *  tileUrlFunction: function(coordinate) {
   *    return 'http://mapserver.com/' + coordinate[0] + '/' +
   *      coordinate[1] + '/' + (-coordinate[2] - 1) + '.png';
   *  }
   * ```
   * @api
   */
  class XYZ extends TileImage {
    /**
     * @param {Options} [options] XYZ options.
     */
    constructor(options) {
      options = options || {};

      const projection =
        options.projection !== undefined ? options.projection : 'EPSG:3857';

      const tileGrid =
        options.tileGrid !== undefined
          ? options.tileGrid
          : createXYZ({
              extent: extentFromProjection(projection),
              maxResolution: options.maxResolution,
              maxZoom: options.maxZoom,
              minZoom: options.minZoom,
              tileSize: options.tileSize,
            });

      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: projection,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileGrid: tileGrid,
        tileLoadFunction: options.tileLoadFunction,
        tilePixelRatio: options.tilePixelRatio,
        tileUrlFunction: options.tileUrlFunction,
        url: options.url,
        urls: options.urls,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        attributionsCollapsible: options.attributionsCollapsible,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {number}
       */
      this.gutter_ = options.gutter !== undefined ? options.gutter : 0;
    }

    /**
     * @return {number} Gutter.
     * @override
     */
    getGutter() {
      return this.gutter_;
    }
  }

  /**
   * @module ol/source/CartoDB
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Projection.
   * @property {number} [maxZoom=18] Max zoom.
   * @property {number} [minZoom] Minimum zoom.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {Object} [config] If using anonymous maps, the CartoDB config to use. See
   * https://carto.com/developers/maps-api/guides/anonymous-maps/
   * for more detail.
   * If using named maps, a key-value lookup with the template parameters.
   * See https://carto.com/developers/maps-api/guides/named-maps/
   * for more detail.
   * @property {string} [map] If using named maps, this will be the name of the template to load.
   * See https://carto.com/developers/maps-api/guides/named-maps/
   * for more detail.
   * @property {string} [account] Username as used to access public Carto dashboard at https://{username}.carto.com/.
   * @property {number} [transition=250] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @typedef {Object} CartoDBLayerInfo
   * @property {string} layergroupid The layer group ID
   * @property {{https: string}} cdn_url The CDN URL
   */

  /**
   * @classdesc
   * Layer source for the CartoDB Maps API.
   * @api
   */
  class CartoDB extends XYZ {
    /**
     * @param {Options} options CartoDB options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        maxZoom: options.maxZoom !== undefined ? options.maxZoom : 18,
        minZoom: options.minZoom,
        projection: options.projection,
        transition: options.transition,
        wrapX: options.wrapX,
        zDirection: options.zDirection,
      });

      /**
       * @type {string}
       * @private
       */
      this.account_ = options.account;

      /**
       * @type {string}
       * @private
       */
      this.mapId_ = options.map || '';

      /**
       * @type {!Object}
       * @private
       */
      this.config_ = options.config || {};

      /**
       * @type {!Object<string, CartoDBLayerInfo>}
       * @private
       */
      this.templateCache_ = {};

      this.initializeMap_();
    }

    /**
     * Returns the current config.
     * @return {!Object} The current configuration.
     * @api
     */
    getConfig() {
      return this.config_;
    }

    /**
     * Updates the carto db config.
     * @param {Object} config a key-value lookup. Values will replace current values
     *     in the config.
     * @api
     */
    updateConfig(config) {
      Object.assign(this.config_, config);
      this.initializeMap_();
    }

    /**
     * Sets the CartoDB config
     * @param {Object} config In the case of anonymous maps, a CartoDB configuration
     *     object.
     * If using named maps, a key-value lookup with the template parameters.
     * @api
     */
    setConfig(config) {
      this.config_ = config || {};
      this.initializeMap_();
    }

    /**
     * Issue a request to initialize the CartoDB map.
     * @private
     */
    initializeMap_() {
      const paramHash = JSON.stringify(this.config_);
      if (this.templateCache_[paramHash]) {
        this.applyTemplate_(this.templateCache_[paramHash]);
        return;
      }
      let mapUrl = 'https://' + this.account_ + '.carto.com/api/v1/map';

      if (this.mapId_) {
        mapUrl += '/named/' + this.mapId_;
      }

      const client = new XMLHttpRequest();
      client.addEventListener(
        'load',
        this.handleInitResponse_.bind(this, paramHash),
      );
      client.addEventListener('error', this.handleInitError_.bind(this));
      client.open('POST', mapUrl);
      client.setRequestHeader('Content-type', 'application/json');
      client.send(JSON.stringify(this.config_));
    }

    /**
     * Handle map initialization response.
     * @param {string} paramHash a hash representing the parameter set that was used
     *     for the request
     * @param {Event} event Event.
     * @private
     */
    handleInitResponse_(paramHash, event) {
      const client = /** @type {XMLHttpRequest} */ (event.target);
      // status will be 0 for file:// urls
      if (!client.status || (client.status >= 200 && client.status < 300)) {
        let response;
        try {
          response = /** @type {CartoDBLayerInfo} */ (
            JSON.parse(client.responseText)
          );
        } catch {
          this.setState('error');
          return;
        }
        this.applyTemplate_(response);
        this.templateCache_[paramHash] = response;
        this.setState('ready');
      } else {
        this.setState('error');
      }
    }

    /**
     * @private
     * @param {Event} event Event.
     */
    handleInitError_(event) {
      this.setState('error');
    }

    /**
     * Apply the new tile urls returned by carto db
     * @param {CartoDBLayerInfo} data Result of carto db call.
     * @private
     */
    applyTemplate_(data) {
      const tilesUrl =
        'https://' +
        data.cdn_url.https +
        '/' +
        this.account_ +
        '/api/v1/map/' +
        data.layergroupid +
        '/{z}/{x}/{y}.png';
      this.setUrl(tilesUrl);
    }
  }

  /**
   * @module ol/source/Cluster
   */


  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").FeatureLike]
   * @typedef {(feature: FeatureType) => (Point|null)} GeometryFunction
   */

  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../Feature.js").default]
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [distance=20] Distance in pixels within which features will
   * be clustered together.
   * @property {number} [minDistance=0] Minimum distance in pixels between clusters.
   * Will be capped at the configured distance.
   * By default no minimum distance is guaranteed. This config can be used to avoid
   * overlapping icons. As a tradoff, the cluster feature's position will no longer be
   * the center of all its features.
   * @property {GeometryFunction<FeatureType>} [geometryFunction]
   * Function that takes a {@link module:ol/Feature~Feature} as argument and returns a
   * {@link module:ol/geom/Point~Point} as cluster calculation point for the feature. When a
   * feature should not be considered for clustering, the function should return
   * `null`. The default, which works when the underlying source contains point
   * features only, is
   * ```js
   * function(feature) {
   *   return feature.getGeometry();
   * }
   * ```
   * See {@link module:ol/geom/Polygon~Polygon#getInteriorPoint} for a way to get a cluster
   * calculation point for polygons.
   * @property {function(Point, Array<FeatureType>):Feature} [createCluster]
   * Function that takes the cluster's center {@link module:ol/geom/Point~Point} and an array
   * of {@link module:ol/Feature~Feature} included in this cluster. Must return a
   * {@link module:ol/Feature~Feature} that will be used to render. Default implementation is:
   * ```js
   * function(point, features) {
   *   return new Feature({
   *     geometry: point,
   *     features: features
   *   });
   * }
   * ```
   * @property {VectorSource<FeatureType>} [source=null] Source.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   */

  /**
   * @classdesc
   * Layer source to cluster vector data. Works out of the box with point
   * geometries. For other geometry types, or if not all geometries should be
   * considered for clustering, a custom `geometryFunction` can be defined.
   *
   * If the instance is disposed without also disposing the underlying
   * source `setSource(null)` has to be called to remove the listener reference
   * from the wrapped source.
   * @api
   * @template {import('../Feature.js').FeatureLike} [FeatureType=import('../Feature.js').default]
   * @extends {VectorSource<Feature<import("../geom/Geometry.js").default>>}
   */
  class Cluster extends VectorSource {
    /**
     * @param {Options<FeatureType>} [options] Cluster options.
     */
    constructor(options) {
      options = options || {};
      super({
        attributions: options.attributions,
        wrapX: options.wrapX,
      });

      /**
       * @type {number|undefined}
       * @protected
       */
      this.resolution = undefined;

      /**
       * @type {number}
       * @protected
       */
      this.distance = options.distance !== undefined ? options.distance : 20;

      /**
       * @type {number}
       * @protected
       */
      this.minDistance = options.minDistance || 0;

      /**
       * @type {number}
       * @protected
       */
      this.interpolationRatio = 0;

      /**
       * @type {Array<Feature>}
       * @protected
       */
      this.features = [];

      /**
       * @type {GeometryFunction<import("../Feature.js").FeatureLike>}
       * @protected
       */
      this.geometryFunction =
        options.geometryFunction ||
        function (feature) {
          const geometry = /** @type {Point} */ (feature.getGeometry());
          assert(
            !geometry || geometry.getType() === 'Point',
            'The default `geometryFunction` can only handle `Point` or null geometries',
          );
          return geometry;
        };

      /**
       * @type {function(Point, Array<FeatureType>):Feature}
       * @private
       */
      this.createCustomCluster_ = options.createCluster;

      /**
       * @type {VectorSource<FeatureType>|null}
       * @protected
       */
      this.source = null;

      /**
       * @private
       */
      this.boundRefresh_ = this.refresh.bind(this);

      this.updateDistance(this.distance, this.minDistance);
      this.setSource(options.source || null);
    }

    /**
     * Remove all features from the source.
     * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/VectorEventType~VectorEventType#removefeature} events.
     * @api
     * @override
     */
    clear(fast) {
      this.features.length = 0;
      super.clear(fast);
    }

    /**
     * Get the distance in pixels between clusters.
     * @return {number} Distance.
     * @api
     */
    getDistance() {
      return this.distance;
    }

    /**
     * Get a reference to the wrapped source.
     * @return {VectorSource<FeatureType>|null} Source.
     * @api
     */
    getSource() {
      return this.source;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @override
     */
    loadFeatures(extent, resolution, projection) {
      this.source?.loadFeatures(extent, resolution, projection);
      if (resolution !== this.resolution) {
        this.resolution = resolution;
        this.refresh();
      }
    }

    /**
     * Set the distance within which features will be clusterd together.
     * @param {number} distance The distance in pixels.
     * @api
     */
    setDistance(distance) {
      this.updateDistance(distance, this.minDistance);
    }

    /**
     * Set the minimum distance between clusters. Will be capped at the
     * configured distance.
     * @param {number} minDistance The minimum distance in pixels.
     * @api
     */
    setMinDistance(minDistance) {
      this.updateDistance(this.distance, minDistance);
    }

    /**
     * The configured minimum distance between clusters.
     * @return {number} The minimum distance in pixels.
     * @api
     */
    getMinDistance() {
      return this.minDistance;
    }

    /**
     * Replace the wrapped source.
     * @param {VectorSource<FeatureType>|null} source The new source for this instance.
     * @api
     */
    setSource(source) {
      if (this.source) {
        this.source.removeEventListener(EventType.CHANGE, this.boundRefresh_);
      }
      this.source = source;
      if (source) {
        source.addEventListener(EventType.CHANGE, this.boundRefresh_);
      }
      this.refresh();
    }

    /**
     * Handle the source changing.
     * @override
     */
    refresh() {
      this.clear();
      this.cluster();
      this.addFeatures(this.features);
    }

    /**
     * Update the distances and refresh the source if necessary.
     * @param {number} distance The new distance.
     * @param {number} minDistance The new minimum distance.
     */
    updateDistance(distance, minDistance) {
      const ratio =
        distance === 0 ? 0 : Math.min(minDistance, distance) / distance;
      const changed =
        distance !== this.distance || this.interpolationRatio !== ratio;
      this.distance = distance;
      this.minDistance = minDistance;
      this.interpolationRatio = ratio;
      if (changed) {
        this.refresh();
      }
    }

    /**
     * @protected
     */
    cluster() {
      if (this.resolution === undefined || !this.source) {
        return;
      }
      const extent = createEmpty();
      const mapDistance = this.distance * this.resolution;
      const features = this.source.getFeatures();

      /** @type {Object<string, true>} */
      const clustered = {};

      for (let i = 0, ii = features.length; i < ii; i++) {
        const feature = features[i];
        if (!(getUid(feature) in clustered)) {
          const geometry = this.geometryFunction(feature);
          if (geometry) {
            const coordinates = geometry.getCoordinates();
            createOrUpdateFromCoordinate(coordinates, extent);
            buffer$1(extent, mapDistance, extent);

            const neighbors = this.source
              .getFeaturesInExtent(extent)
              .filter(function (neighbor) {
                const uid = getUid(neighbor);
                if (uid in clustered) {
                  return false;
                }
                clustered[uid] = true;
                return true;
              });
            this.features.push(this.createCluster(neighbors, extent));
          }
        }
      }
    }

    /**
     * @param {Array<FeatureType>} features Features
     * @param {import("../extent.js").Extent} extent The searched extent for these features.
     * @return {Feature} The cluster feature.
     * @protected
     */
    createCluster(features, extent) {
      const centroid = [0, 0];
      for (let i = features.length - 1; i >= 0; --i) {
        const geometry = this.geometryFunction(features[i]);
        if (geometry) {
          add$2(centroid, geometry.getCoordinates());
        } else {
          features.splice(i, 1);
        }
      }
      scale$4(centroid, 1 / features.length);
      const searchCenter = getCenter(extent);
      const ratio = this.interpolationRatio;
      const geometry = new Point([
        centroid[0] * (1 - ratio) + searchCenter[0] * ratio,
        centroid[1] * (1 - ratio) + searchCenter[1] * ratio,
      ]);
      if (this.createCustomCluster_) {
        return this.createCustomCluster_(geometry, features);
      }
      return new Feature({
        geometry,
        features,
      });
    }
  }

  /**
   * @module ol/webgl/Canvas
   */

  const VERTEX_SHADER = `
  attribute vec4 a_position;
  attribute vec4 a_texcoord;

  uniform mat4 u_matrix;
  uniform mat4 u_textureMatrix;

  varying vec2 v_texcoord;

  void main() {
    gl_Position = u_matrix * a_position;
    vec2 texcoord = (u_textureMatrix * a_texcoord).xy;
    v_texcoord = texcoord;
  }
`;

  const FRAGMENT_SHADER = `
  precision mediump float;

  varying vec2 v_texcoord;

  uniform sampler2D u_texture;

  void main() {
    if (
      v_texcoord.x < 0.0 ||
      v_texcoord.y < 0.0 ||
      v_texcoord.x > 1.0 ||
      v_texcoord.y > 1.0
    ) {
      discard;
    }
    gl_FragColor = texture2D(u_texture, v_texcoord);
  }
`;

  /** @typedef {import("../transform.js").Transform} Matrix */

  /**
   * Canvas-like operations implemented in webgl.
   */
  class Canvas {
    /**
     * @param {WebGLRenderingContext} gl Context to render in.
     */
    constructor(gl) {
      /**
       * @private
       * @type {WebGLRenderingContext}
       */
      this.gl_ = gl;

      /**
       * @private
       * @type {WebGLProgram}
       */
      this.program_ = createProgram(gl, FRAGMENT_SHADER, VERTEX_SHADER);

      this.positionLocation = gl.getAttribLocation(this.program_, 'a_position');
      this.texcoordLocation = gl.getAttribLocation(this.program_, 'a_texcoord');

      this.matrixLocation = gl.getUniformLocation(this.program_, 'u_matrix');
      this.textureMatrixLocation = gl.getUniformLocation(
        this.program_,
        'u_textureMatrix',
      );
      this.textureLocation = gl.getUniformLocation(this.program_, 'u_texture');

      this.positionBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);

      this.positions = [0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1];
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(this.positions),
        gl.STATIC_DRAW,
      );

      this.texcoordBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer);

      this.texcoords = [0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1];
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(this.texcoords),
        gl.STATIC_DRAW,
      );
    }

    /**
     * 2dContext drawImage call implemented in webgl.
     * Unlike images, textures do not have a width and height associated
     * with them so we'll pass in the width and height of the texture.
     *
     * @param {WebGLTexture} tex Image to draw.
     * @param {number} texWidth Image width.
     * @param {number} texHeight Image height.
     * @param {number} srcX Top-left x-point to read src image.
     * @param {number} srcY Top-left y-point to read src image.
     * @param {number} [srcWidth] Width of source to read.
     * @param {number} [srcHeight] Height of source to read.
     * @param {number} [dstX] Top-left x-point of destination.
     * @param {number} [dstY] Top-left y-point of destination.
     * @param {number} [dstWidth] Width of written image in destination.
     * @param {number} [dstHeight] Height of written image in destination.
     * @param {number} [width] Width of canvas.
     * @param {number} [height] Height of canvas.
     */
    drawImage(
      tex,
      texWidth,
      texHeight,
      srcX,
      srcY,
      srcWidth,
      srcHeight,
      dstX,
      dstY,
      dstWidth,
      dstHeight,
      width,
      height,
    ) {
      const gl = this.gl_;

      if (dstX === undefined) {
        dstX = srcX;
      }
      if (dstY === undefined) {
        dstY = srcY;
      }
      if (srcWidth === undefined) {
        srcWidth = texWidth;
      }
      if (srcHeight === undefined) {
        srcHeight = texHeight;
      }
      if (dstWidth === undefined) {
        dstWidth = srcWidth;
      }
      if (dstHeight === undefined) {
        dstHeight = srcHeight;
      }
      if (width === undefined) {
        width = gl.canvas.width;
      }
      if (height === undefined) {
        height = gl.canvas.height;
      }

      gl.bindTexture(gl.TEXTURE_2D, tex);

      gl.useProgram(this.program_);

      gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
      gl.enableVertexAttribArray(this.positionLocation);
      gl.vertexAttribPointer(this.positionLocation, 2, gl.FLOAT, false, 0, 0);
      gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer);
      gl.enableVertexAttribArray(this.texcoordLocation);
      gl.vertexAttribPointer(this.texcoordLocation, 2, gl.FLOAT, false, 0, 0);

      // matrix for converting pixels to clip space
      let matrix = orthographic(0, width, 0, height, -1, 1);
      matrix = translate(matrix, dstX, dstY, 0);
      matrix = scale(matrix, dstWidth, dstHeight, 1);
      gl.uniformMatrix4fv(this.matrixLocation, false, matrix);

      let texMatrix = translation(srcX / texWidth, srcY / texHeight, 0);
      texMatrix = scale(
        texMatrix,
        srcWidth / texWidth,
        srcHeight / texHeight,
        1,
      );

      gl.uniformMatrix4fv(this.textureMatrixLocation, false, texMatrix);
      gl.uniform1i(this.textureLocation, 0);
      gl.drawArrays(gl.TRIANGLES, 0, this.positions.length / 2);
    }
  }

  /**
   * @param {WebGLRenderingContext} gl Rendering Context.
   * @param {GLenum} type Type of shader.
   * @param {string} source source of shader.
   * @return {WebGLShader} [progam] The program.
   */
  function createShader(gl, type, source) {
    const shader = gl.createShader(type);

    if (shader === null) {
      throw new Error('Shader compilation failed');
    }

    gl.shaderSource(shader, source);

    gl.compileShader(shader);
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      const log = gl.getShaderInfoLog(shader);
      if (log === null) {
        throw new Error('Shader info log creation failed');
      }
      throw new Error(log);
    }

    return shader;
  }

  /**
   * @param {WebGLRenderingContext} gl Rendering Context.
   * @param {string} fragmentSource Fragment shader source.
   * @param {string} vertexSource Vertex shader source.
   * @return {WebGLProgram} [progam] The program.
   */
  function createProgram(gl, fragmentSource, vertexSource) {
    const program = gl.createProgram();

    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource);
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
    if (program === null) {
      throw new Error('Program creation failed');
    }

    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);

    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      const log = gl.getProgramInfoLog(program);
      if (log === null) {
        throw new Error('Program info log creation failed');
      }
      throw new Error();
    }
    return program;
  }

  /**
   * @module ol/reproj/glreproj
   */

  const EDGE_VERTEX_SHADER = `
  attribute vec4 a_position;

  uniform mat4 u_matrix;

  void main() {
     gl_Position = u_matrix * a_position;
  }
`;
  const EDGE_FRAGMENT_SHADER = `
  precision mediump float;

  uniform vec4 u_val;
  void main() {
     gl_FragColor = u_val;
  }
`;

  const TRIANGLE_VERTEX_SHADER = `
  attribute vec4 a_position;
  attribute vec2 a_texcoord;

  varying vec2 v_texcoord;

  uniform mat4 u_matrix;

  void main() {
     gl_Position = u_matrix * a_position;
     v_texcoord = a_texcoord;
  }
`;
  const TRIANGLE_FRAGMENT_SHADER = `
  precision mediump float;

  varying vec2 v_texcoord;

  uniform sampler2D u_texture;

  void main() {
    if (v_texcoord.x < 0.0 || v_texcoord.x > 1.0 || v_texcoord.y < 0.0 || v_texcoord.y > 1.0) {
      discard;
    }
    gl_FragColor = texture2D(u_texture, v_texcoord);
  }
`;

  /**
   * Create an html canvas element and returns its webgl context.
   * @param {number} [width] Canvas width.
   * @param {number} [height] Canvas height.
   * @param {Array<HTMLCanvasElement | OffscreenCanvas>} [canvasPool] Canvas pool to take existing canvas from.
   * @param {WebGLContextAttributes} [settings] CanvasRenderingContext2DSettings
   * @return {WebGLRenderingContext} The context.
   */
  function createCanvasContextWebGL(width, height, canvasPool, settings) {
    /** @type {HTMLCanvasElement|OffscreenCanvas} */
    let canvas;
    if (canvasPool && canvasPool.length) {
      canvas = /** @type {HTMLCanvasElement} */ (canvasPool.shift());
    } else if (WORKER_OFFSCREEN_CANVAS) {
      canvas = new OffscreenCanvas(width || 300, height || 300);
    } else {
      canvas = document.createElement('canvas');
    }
    if (width) {
      canvas.width = width;
    }
    if (height) {
      canvas.height = height;
    }
    //FIXME Allow OffscreenCanvasRenderingContext2D as return type
    return /** @type {WebGLRenderingContext} */ (
      canvas.getContext('webgl', settings)
    );
  }

  /**
   * Releases canvas memory to avoid exceeding memory limits in Safari.
   * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/
   * @param {WebGLRenderingContext} gl Context.
   */
  function releaseGLCanvas(gl) {
    const canvas = gl.canvas;
    canvas.width = 1;
    canvas.height = 1;
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
  }

  /**
   * @type {Array<HTMLCanvasElement | OffscreenCanvas>}
   */
  const canvasGLPool = [];

  /**
   * @typedef {Object} ImageExtent
   * @property {import("../extent.js").Extent} extent Extent.
   * @property {import("../extent.js").Extent} [clipExtent] Clip extent.
   * @property {WebGLTexture} texture Texture.
   * @property {number} width Width of texture.
   * @property {number} height Height of texture.
   */

  /**
   * Renders the source data into new canvas based on the triangulation.
   *
   * @param {WebGLRenderingContext} gl the context to render in.
   * @param {number} width_ Width of the canvas.
   * @param {number} height_ Height of the canvas.
   * @param {number} pixelRatio Pixel ratio.
   * @param {number} sourceResolution Source resolution.
   * @param {number} targetResolution Target resolution.
   * @param {import("../extent.js").Extent} targetExtent Target extent (tile).
   * @param {import("../reproj/Triangulation.js").default} triangulation Calculated triangulation.
   * @param {Array<ImageExtent>} sources Array of sources.
   * @param {number} gutter Gutter of the sources.
   * @param {number} dataType What kind of data is the textures, must be gl.FLOAT or gl.UNSIGNED_BYTE
   * TODO: Allow setting renderEdges value in the data as this is done in "data-space".
   * @param {boolean | Array<number>} [renderEdges] Render reprojection edges.
   * @param {boolean} [interpolate] Use linear interpolation when resampling.
   * @param {boolean} [drawSingle] Draw single source images directly without stitchTexture.
   * @return {{framebuffer: WebGLFramebuffer, width: number, height: number, texture: WebGLTexture}} Canvas with reprojected data.
   */
  function render(
    gl,
    width_,
    height_,
    pixelRatio,
    sourceResolution,
    targetResolution,
    targetExtent,
    triangulation,
    sources,
    gutter,
    dataType,
    renderEdges,
    interpolate,
    drawSingle,
  ) {
    const width = Math.round(pixelRatio * width_);
    const height = Math.round(pixelRatio * height_);
    gl.canvas.width = width;
    gl.canvas.height = height;

    /** @type {WebGLFramebuffer | null} */
    let resultFrameBuffer;
    /** @type {WebGLTexture | null} */
    let resultTexture;
    {
      resultTexture = gl.createTexture();
      gl.bindTexture(gl.TEXTURE_2D, resultTexture);

      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      if (interpolate) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      } else {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
      }
      gl.texImage2D(
        gl.TEXTURE_2D,
        0,
        gl.RGBA,
        width,
        height,
        0,
        gl.RGBA,
        dataType,
        null,
      );

      resultFrameBuffer = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, resultFrameBuffer);
      gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.COLOR_ATTACHMENT0,
        gl.TEXTURE_2D,
        resultTexture,
        0,
      );
    }

    if (resultFrameBuffer === null) {
      throw new Error('Could not create framebuffer');
    }
    if (resultTexture === null) {
      throw new Error('Could not create texture');
    }

    if (sources.length === 0) {
      return {
        width,
        height,
        framebuffer: resultFrameBuffer,
        texture: resultTexture,
      };
    }

    const sourceDataExtent = createEmpty();
    sources.forEach(function (src, i, arr) {
      extend$1(sourceDataExtent, src.extent);
    });

    /** @type {WebGLTexture | null} */
    let stitchTexture;
    /** @type {number} */
    let stitchWidth;
    /** @type {number} */
    let stitchHeight;
    const stitchScale = 1 / sourceResolution;

    {
      stitchTexture = gl.createTexture();
      if (resultTexture === null) {
        throw new Error('Could not create texture');
      }
      stitchWidth = Math.round(getWidth(sourceDataExtent) * stitchScale);
      stitchHeight = Math.round(getHeight(sourceDataExtent) * stitchScale);

      // Make sure we do not exceed the max texture size by lowering the resolution for this image.
      // https://github.com/openlayers/openlayers/pull/15860#issuecomment-2254123580
      const maxTexSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
      const largeSide = Math.max(stitchWidth, stitchHeight);
      const scaleFactor = largeSide > maxTexSize ? maxTexSize / largeSide : 1;
      const stitchWidthFixed = Math.round(stitchWidth * scaleFactor);
      const stitchHeightFixed = Math.round(stitchHeight * scaleFactor);

      gl.bindTexture(gl.TEXTURE_2D, stitchTexture);

      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      if (interpolate) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      } else {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
      }
      gl.texImage2D(
        gl.TEXTURE_2D,
        0,
        gl.RGBA,
        stitchWidthFixed,
        stitchHeightFixed,
        0,
        gl.RGBA,
        dataType,
        null,
      );

      const fb = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
      gl.framebufferTexture2D(
        gl.FRAMEBUFFER,
        gl.COLOR_ATTACHMENT0,
        gl.TEXTURE_2D,
        stitchTexture,
        0,
      );
      const webGLCanvas = new Canvas(gl);

      sources.forEach(function (src, i, arr) {
        const xPos =
          (src.extent[0] - sourceDataExtent[0]) * stitchScale * scaleFactor;
        const yPos =
          -(src.extent[3] - sourceDataExtent[3]) * stitchScale * scaleFactor;
        const srcWidth = getWidth(src.extent) * stitchScale * scaleFactor;
        const srcHeight = getHeight(src.extent) * stitchScale * scaleFactor;
        gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
        gl.viewport(0, 0, stitchWidthFixed, stitchHeightFixed);

        if (src.clipExtent) {
          const xPos =
            (src.clipExtent[0] - sourceDataExtent[0]) * stitchScale * scaleFactor;
          const yPos =
            -(src.clipExtent[3] - sourceDataExtent[3]) *
            stitchScale *
            scaleFactor;
          const width = getWidth(src.clipExtent) * stitchScale * scaleFactor;
          const height = getHeight(src.clipExtent) * stitchScale * scaleFactor;
          gl.enable(gl.SCISSOR_TEST);
          gl.scissor(
            interpolate ? xPos : Math.round(xPos),
            interpolate ? yPos : Math.round(yPos),
            interpolate ? width : Math.round(xPos + width) - Math.round(xPos),
            interpolate ? height : Math.round(yPos + height) - Math.round(yPos),
          );
        }

        webGLCanvas.drawImage(
          src.texture,
          src.width,
          src.height,
          gutter,
          gutter,
          src.width - 2 * gutter,
          src.height - 2 * gutter,
          interpolate ? xPos : Math.round(xPos),
          interpolate ? yPos : Math.round(yPos),
          interpolate ? srcWidth : Math.round(xPos + srcWidth) - Math.round(xPos),
          interpolate
            ? srcHeight
            : Math.round(yPos + srcHeight) - Math.round(yPos),
          stitchWidthFixed,
          stitchHeightFixed,
        );

        gl.disable(gl.SCISSOR_TEST);
      });
      gl.deleteFramebuffer(fb);
    }

    const targetTopLeft = getTopLeft(targetExtent);
    const sourceTopLeft = getTopLeft(sourceDataExtent);

    const getUVs = (
      /** @type {Array<import("../coordinate.js").Coordinate>} */ target,
    ) => {
      const u0 =
        ((target[0][0] - targetTopLeft[0]) / targetResolution) * pixelRatio;
      const v0 =
        (-(target[0][1] - targetTopLeft[1]) / targetResolution) * pixelRatio;
      const u1 =
        ((target[1][0] - targetTopLeft[0]) / targetResolution) * pixelRatio;
      const v1 =
        (-(target[1][1] - targetTopLeft[1]) / targetResolution) * pixelRatio;
      const u2 =
        ((target[2][0] - targetTopLeft[0]) / targetResolution) * pixelRatio;
      const v2 =
        (-(target[2][1] - targetTopLeft[1]) / targetResolution) * pixelRatio;
      return {u1, v1, u0, v0, u2, v2};
    };

    gl.bindFramebuffer(gl.FRAMEBUFFER, resultFrameBuffer);
    gl.viewport(0, 0, width, height);

    // Draw source to reprojtile
    {
      /** @type {Array<number>} */
      const vertices = [];
      /** @type {Array<number>} */
      const texcoords = [];

      const triProgram = createProgram(
        gl,
        TRIANGLE_FRAGMENT_SHADER,
        TRIANGLE_VERTEX_SHADER,
      );
      gl.useProgram(triProgram);

      // Bind image
      const textureLocation = gl.getUniformLocation(triProgram, 'u_texture');
      gl.bindTexture(gl.TEXTURE_2D, stitchTexture);

      // Tell the shader to get the texture from texture unit 0
      gl.uniform1i(textureLocation, 0);

      // Calculate vert and tex coordinates.
      triangulation.getTriangles().forEach(function (triangle, i, arr) {
        const source = triangle.source;
        const target = triangle.target;
        // Make sure that everything is on pixel boundaries
        const {u1, v1, u0, v0, u2, v2} = getUVs(target);

        const su0 =
          (source[0][0] - sourceTopLeft[0]) / sourceResolution / stitchWidth;
        const sv0 =
          -(source[0][1] - sourceTopLeft[1]) / sourceResolution / stitchHeight;
        const su1 =
          (source[1][0] - sourceTopLeft[0]) / sourceResolution / stitchWidth;
        const sv1 =
          -(source[1][1] - sourceTopLeft[1]) / sourceResolution / stitchHeight;
        const su2 =
          (source[2][0] - sourceTopLeft[0]) / sourceResolution / stitchWidth;
        const sv2 =
          -(source[2][1] - sourceTopLeft[1]) / sourceResolution / stitchHeight;

        vertices.push(u1, v1, u0, v0, u2, v2);
        texcoords.push(su1, sv1, su0, sv0, su2, sv2);
      });

      // Convert pixel space to clip space.
      const matrix = orthographic(0, width, height, 0, -1, 1);
      const matrixLocation = gl.getUniformLocation(triProgram, 'u_matrix');
      gl.uniformMatrix4fv(matrixLocation, false, matrix);

      const positionLocation = gl.getAttribLocation(triProgram, 'a_position');
      const positionBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
      gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(positionLocation);

      const texcoordLocation = gl.getAttribLocation(triProgram, 'a_texcoord');
      const texcoordBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW);
      gl.vertexAttribPointer(texcoordLocation, 2, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(texcoordLocation);

      gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2);
    }

    if (renderEdges) {
      const edgeProgram = createProgram(
        gl,
        EDGE_FRAGMENT_SHADER,
        EDGE_VERTEX_SHADER,
      );
      gl.useProgram(edgeProgram);
      const matrix = orthographic(0, width, height, 0, -1, 1);
      const matrixLocation = gl.getUniformLocation(edgeProgram, 'u_matrix');
      gl.uniformMatrix4fv(matrixLocation, false, matrix);

      const burnval = Array.isArray(renderEdges) ? renderEdges : [0, 0, 0, 255];
      const burnvalLocation = gl.getUniformLocation(edgeProgram, 'u_val');
      {
        gl.uniform4fv(burnvalLocation, burnval);
      }

      const positionLocation = gl.getAttribLocation(edgeProgram, 'a_position');
      const positionBuffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
      gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
      gl.enableVertexAttribArray(positionLocation);

      /** @type {Array<number>} */
      const lines = triangulation.getTriangles().reduce(function (
        /** @type {Array<number>} */ lines,
        triangle,
      ) {
        const target = triangle.target;
        const {u1, v1, u0, v0, u2, v2} = getUVs(target);

        return lines.concat([u1, v1, u0, v0, u0, v0, u2, v2, u2, v2, u1, v1]);
      }, []);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(lines), gl.STATIC_DRAW);
      gl.drawArrays(gl.LINES, 0, lines.length / 2);
    }

    return {
      width,
      height,
      framebuffer: resultFrameBuffer,
      texture: resultTexture,
    };
  }

  /**
   * @module ol/reproj/DataTile
   */


  /**
   * @typedef {function(number, number, number, number) : import("../DataTile.js").default} TileGetter
   */

  /**
   * @typedef {Object} TileOffset
   * @property {DataTile} tile Tile.
   * @property {number} offset Offset.
   */

  /**
   * @typedef {Object} Options
   * @property {import("../proj/Projection.js").default} sourceProj Source projection.
   * @property {import("../tilegrid/TileGrid.js").default} sourceTileGrid Source tile grid.
   * @property {import("../proj/Projection.js").default} targetProj Target projection.
   * @property {import("../tilegrid/TileGrid.js").default} targetTileGrid Target tile grid.
   * @property {import("../tilecoord.js").TileCoord} tileCoord Coordinate of the tile.
   * @property {import("../tilecoord.js").TileCoord} [wrappedTileCoord] Coordinate of the tile wrapped in X.
   * @property {number} pixelRatio Pixel ratio.
   * @property {number} gutter Gutter of the source tiles.
   * @property {TileGetter} getTileFunction Function returning source tiles (z, x, y, pixelRatio).
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   * @property {number} [errorThreshold] Acceptable reprojection error (in px).
   * @property {number} [transition=250] A duration for tile opacity
   * transitions in milliseconds. A duration of 0 disables the opacity transition.
   * @property {import("../transform.js").Transform} [transformMatrix] Source transform matrix.
   * @property {boolean} [renderEdges] Render reprojection edges.
   */

  /**
   * @classdesc
   * Class encapsulating single reprojected data tile.
   * See {@link module:ol/source/DataTile~DataTileSource}.
   *
   */
  class ReprojDataTile extends DataTile {
    /**
     * @param {Options} options Tile options.
     */
    constructor(options) {
      super({
        tileCoord: options.tileCoord,
        loader: () => Promise.resolve(new Uint8ClampedArray(4)),
        interpolate: options.interpolate,
        transition: options.transition,
      });

      /**
       * @private
       * @type {boolean | Array<number>}
       */
      this.renderEdges_ =
        options.renderEdges !== undefined ? options.renderEdges : false;

      /**
       * @private
       * @type {number}
       */
      this.pixelRatio_ = options.pixelRatio;

      /**
       * @private
       * @type {number}
       */
      this.gutter_ = options.gutter;

      /**
       * @type {import("../DataTile.js").Data}
       * @private
       */
      this.reprojData_ = null;

      /**
       * @type {Error}
       * @private
       */
      this.reprojError_ = null;

      /**
       * @type {import('../size.js').Size}
       * @private
       */
      this.reprojSize_ = undefined;

      /**
       * @private
       * @type {import("../tilegrid/TileGrid.js").default}
       */
      this.sourceTileGrid_ = options.sourceTileGrid;

      /**
       * @private
       * @type {import("../tilegrid/TileGrid.js").default}
       */
      this.targetTileGrid_ = options.targetTileGrid;

      /**
       * @private
       * @type {import("../tilecoord.js").TileCoord}
       */
      this.wrappedTileCoord_ = options.wrappedTileCoord || options.tileCoord;

      /**
       * @private
       * @type {!Array<TileOffset>}
       */
      this.sourceTiles_ = [];

      /**
       * @private
       * @type {?Array<import("../events.js").EventsKey>}
       */
      this.sourcesListenerKeys_ = null;

      /**
       * @private
       * @type {number}
       */
      this.sourceZ_ = 0;

      const sourceProj = options.sourceProj;
      const sourceProjExtent = sourceProj.getExtent();
      const sourceTileGridExtent = options.sourceTileGrid.getExtent();

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.clipExtent_ = sourceProj.canWrapX()
        ? sourceTileGridExtent
          ? getIntersection(sourceProjExtent, sourceTileGridExtent)
          : sourceProjExtent
        : sourceTileGridExtent;

      const targetExtent = this.targetTileGrid_.getTileCoordExtent(
        this.wrappedTileCoord_,
      );
      const maxTargetExtent = this.targetTileGrid_.getExtent();
      let maxSourceExtent = this.sourceTileGrid_.getExtent();

      const limitedTargetExtent = maxTargetExtent
        ? getIntersection(targetExtent, maxTargetExtent)
        : targetExtent;

      if (getArea$1(limitedTargetExtent) === 0) {
        // Tile is completely outside range -> EMPTY
        // TODO: is it actually correct that the source even creates the tile ?
        this.state = TileState.EMPTY;
        return;
      }

      if (sourceProjExtent) {
        if (!maxSourceExtent) {
          maxSourceExtent = sourceProjExtent;
        } else {
          maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent);
        }
      }

      const targetResolution = this.targetTileGrid_.getResolution(
        this.wrappedTileCoord_[0],
      );

      const targetProj = options.targetProj;
      const sourceResolution = calculateSourceExtentResolution(
        sourceProj,
        targetProj,
        limitedTargetExtent,
        targetResolution,
      );

      if (!isFinite(sourceResolution) || sourceResolution <= 0) {
        // invalid sourceResolution -> EMPTY
        // probably edges of the projections when no extent is defined
        this.state = TileState.EMPTY;
        return;
      }

      const errorThresholdInPixels =
        options.errorThreshold !== undefined
          ? options.errorThreshold
          : ERROR_THRESHOLD;

      /**
       * @private
       * @type {!import("./Triangulation.js").default}
       */
      this.triangulation_ = new Triangulation(
        sourceProj,
        targetProj,
        limitedTargetExtent,
        maxSourceExtent,
        sourceResolution * errorThresholdInPixels,
        targetResolution,
        options.transformMatrix,
      );

      if (this.triangulation_.getTriangles().length === 0) {
        // no valid triangles -> EMPTY
        this.state = TileState.EMPTY;
        return;
      }

      this.sourceZ_ = this.sourceTileGrid_.getZForResolution(sourceResolution);
      let sourceExtent = this.triangulation_.calculateSourceExtent();

      if (maxSourceExtent) {
        if (sourceProj.canWrapX()) {
          sourceExtent[1] = clamp$1(
            sourceExtent[1],
            maxSourceExtent[1],
            maxSourceExtent[3],
          );
          sourceExtent[3] = clamp$1(
            sourceExtent[3],
            maxSourceExtent[1],
            maxSourceExtent[3],
          );
        } else {
          sourceExtent = getIntersection(sourceExtent, maxSourceExtent);
        }
      }

      if (!getArea$1(sourceExtent)) {
        this.state = TileState.EMPTY;
      } else {
        let worldWidth = 0;
        let worldsAway = 0;
        if (sourceProj.canWrapX()) {
          worldWidth = getWidth(sourceProjExtent);
          worldsAway = Math.floor(
            (sourceExtent[0] - sourceProjExtent[0]) / worldWidth,
          );
        }

        const sourceExtents = wrapAndSliceX(
          sourceExtent.slice(),
          sourceProj,
          true,
        );
        sourceExtents.forEach((extent) => {
          const sourceRange = this.sourceTileGrid_.getTileRangeForExtentAndZ(
            extent,
            this.sourceZ_,
          );
          const getTile = options.getTileFunction;
          for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) {
            for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) {
              const tile = getTile(this.sourceZ_, srcX, srcY, this.pixelRatio_);
              if (tile) {
                const offset = worldsAway * worldWidth;
                this.sourceTiles_.push({tile, offset});
              }
            }
          }
          ++worldsAway;
        });

        if (this.sourceTiles_.length === 0) {
          this.state = TileState.EMPTY;
        }
      }
    }

    /**
     * Get the tile size.
     * @return {import('../size.js').Size} Tile size.
     * @override
     */
    getSize() {
      return this.reprojSize_;
    }

    /**
     * Get the data for the tile.
     * @return {import("../DataTile.js").Data} Tile data.
     * @override
     */
    getData() {
      return this.reprojData_;
    }

    /**
     * Get any loading error.
     * @return {Error} Loading error.
     * @override
     */
    getError() {
      return this.reprojError_;
    }

    /**
     * @private
     */
    reproject_() {
      const dataSources = [];
      let imageLike = false;
      this.sourceTiles_.forEach((source) => {
        const tile = source.tile;
        if (!tile || tile.getState() !== TileState.LOADED) {
          return;
        }
        const size = tile.getSize();
        const gutter = this.gutter_;
        /**
         * @type {import("../DataTile.js").ArrayLike}
         */
        let tileData;
        const arrayData = asArrayLike(tile.getData());
        if (arrayData) {
          tileData = arrayData;
        } else {
          imageLike = true;
          tileData = toArray(asImageLike(tile.getData()));
        }
        const pixelSize = [size[0] + 2 * gutter, size[1] + 2 * gutter];
        const isFloat = tileData instanceof Float32Array;
        const pixelCount = pixelSize[0] * pixelSize[1];
        const DataType = isFloat ? Float32Array : Uint8ClampedArray;
        const tileDataR = new DataType(tileData.buffer);
        const bytesPerElement = DataType.BYTES_PER_ELEMENT;
        const bytesPerPixel = (bytesPerElement * tileDataR.length) / pixelCount;
        const bytesPerRow = tileDataR.byteLength / pixelSize[1];
        const bandCount = Math.floor(
          bytesPerRow / bytesPerElement / pixelSize[0],
        );
        const extent = this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord);
        extent[0] += source.offset;
        extent[2] += source.offset;
        const clipExtent = this.clipExtent_?.slice();
        if (clipExtent) {
          clipExtent[0] += source.offset;
          clipExtent[2] += source.offset;
        }
        dataSources.push({
          extent: extent,
          clipExtent: clipExtent,
          data: tileDataR,
          dataType: DataType,
          bytesPerPixel: bytesPerPixel,
          pixelSize: pixelSize,
          bandCount: bandCount,
        });
      });
      this.sourceTiles_.length = 0;

      if (dataSources.length === 0) {
        this.state = TileState.ERROR;
        this.changed();
        return;
      }

      const z = this.wrappedTileCoord_[0];
      const size = this.targetTileGrid_.getTileSize(z);
      const targetWidth = typeof size === 'number' ? size : size[0];
      const targetHeight = typeof size === 'number' ? size : size[1];
      const outWidth = targetWidth * this.pixelRatio_;
      const outHeight = targetHeight * this.pixelRatio_;
      const targetResolution = this.targetTileGrid_.getResolution(z);
      const sourceResolution = this.sourceTileGrid_.getResolution(this.sourceZ_);

      const targetExtent = this.targetTileGrid_.getTileCoordExtent(
        this.wrappedTileCoord_,
      );

      const bandCount = dataSources[0].bandCount;
      const dataR = new dataSources[0].dataType(bandCount * outWidth * outHeight);

      const gl = createCanvasContextWebGL(outWidth, outHeight, canvasGLPool, {
        premultipliedAlpha: false,
        antialias: false,
      });

      let willInterpolate;
      const format = gl.RGBA;
      let textureType;
      if (dataSources[0].dataType == Float32Array) {
        textureType = gl.FLOAT;
        gl.getExtension('WEBGL_color_buffer_float');
        gl.getExtension('OES_texture_float');
        gl.getExtension('EXT_float_blend');
        const extension = gl.getExtension('OES_texture_float_linear');
        const canInterpolate = extension !== null;
        willInterpolate = canInterpolate && this.interpolate;
      } else {
        textureType = gl.UNSIGNED_BYTE;
        willInterpolate = this.interpolate;
      }

      const BANDS_PR_REPROJ = 4;
      const reprojs = Math.ceil(bandCount / BANDS_PR_REPROJ);
      for (let reproj = reprojs - 1; reproj >= 0; --reproj) {
        const sources = [];
        for (let i = 0, len = dataSources.length; i < len; ++i) {
          const dataSource = dataSources[i];

          const pixelSize = dataSource.pixelSize;
          const width = pixelSize[0];
          const height = pixelSize[1];

          const data = new dataSource.dataType(BANDS_PR_REPROJ * width * height);
          const dataS = dataSource.data;
          let offset = reproj * BANDS_PR_REPROJ;
          for (let j = 0, len = data.length; j < len; j += BANDS_PR_REPROJ) {
            data[j] = dataS[offset];
            data[j + 1] = dataS[offset + 1];
            data[j + 2] = dataS[offset + 2];
            data[j + 3] = dataS[offset + 3];
            offset += bandCount;
          }

          const texture = gl.createTexture();
          gl.bindTexture(gl.TEXTURE_2D, texture);

          if (willInterpolate) {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
          } else {
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
          }
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
          gl.texImage2D(
            gl.TEXTURE_2D,
            0,
            format,
            width,
            height,
            0,
            format,
            textureType,
            data,
          );

          sources.push({
            extent: dataSource.extent,
            clipExtent: dataSource.clipExtent,
            texture: texture,
            width: width,
            height: height,
          });
        }

        const {framebuffer, width, height} = render(
          gl,
          targetWidth,
          targetHeight,
          this.pixelRatio_,
          sourceResolution,
          targetResolution,
          targetExtent,
          this.triangulation_,
          sources,
          this.gutter_,
          textureType,
          this.renderEdges_,
          willInterpolate,
        );

        // The texture is always RGBA.
        const rows = width;
        const cols = height * BANDS_PR_REPROJ;
        const data = new dataSources[0].dataType(rows * cols);
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        gl.readPixels(0, 0, width, height, gl.RGBA, textureType, data);

        let offset = reproj * BANDS_PR_REPROJ;
        for (let i = 0, len = data.length; i < len; i += BANDS_PR_REPROJ) {
          // The data read by `readPixels` is flipped in the y-axis so flip it again.
          const flipY = (rows - 1 - ((i / cols) | 0)) * cols + (i % cols);
          dataR[offset] = data[flipY];
          dataR[offset + 1] = data[flipY + 1];
          dataR[offset + 2] = data[flipY + 2];
          dataR[offset + 3] = data[flipY + 3];
          offset += bandCount;
        }
      }

      releaseGLCanvas(gl);
      canvasGLPool.push(gl.canvas);

      if (imageLike) {
        const context = createCanvasContext2D(targetWidth, targetHeight);
        const imageData = new ImageData(dataR, targetWidth);
        context.putImageData(imageData, 0, 0);
        this.reprojData_ = context.canvas;
      } else {
        this.reprojData_ = dataR;
      }
      this.reprojSize_ = [Math.round(outWidth), Math.round(outHeight)];
      this.state = TileState.LOADED;
      this.changed();
    }

    /**
     * Load not yet loaded URI.
     * @override
     */
    load() {
      if (this.state !== TileState.IDLE && this.state !== TileState.ERROR) {
        return;
      }
      this.state = TileState.LOADING;
      this.changed();

      let leftToLoad = 0;

      this.sourcesListenerKeys_ = [];
      this.sourceTiles_.forEach(({tile}) => {
        const state = tile.getState();
        if (state !== TileState.IDLE && state !== TileState.LOADING) {
          return;
        }
        leftToLoad++;

        const sourceListenKey = listen(tile, EventType.CHANGE, () => {
          const state = tile.getState();
          if (
            state == TileState.LOADED ||
            state == TileState.ERROR ||
            state == TileState.EMPTY
          ) {
            unlistenByKey(sourceListenKey);
            leftToLoad--;
            if (leftToLoad === 0) {
              this.unlistenSources_();
              this.reproject_();
            }
          }
        });
        this.sourcesListenerKeys_.push(sourceListenKey);
      });

      if (leftToLoad === 0) {
        setTimeout(this.reproject_.bind(this), 0);
      } else {
        this.sourceTiles_.forEach(function ({tile}) {
          const state = tile.getState();
          if (state == TileState.IDLE) {
            tile.load();
          }
        });
      }
    }

    /**
     * @private
     */
    unlistenSources_() {
      this.sourcesListenerKeys_.forEach(unlistenByKey);
      this.sourcesListenerKeys_ = null;
    }
  }

  /**
   * @module ol/source/DataTile
   */

  /**
   * @typedef {'anonymous'|'use-credentials'} CrossOriginAttribute
   */

  /**
   * @typedef {Object} LoaderOptions
   * @property {AbortSignal} signal An abort controller signal.
   * @property {CrossOriginAttribute} [crossOrigin] The cross-origin attribute for images.
   * @property {number} [maxY] The maximum y coordinate at the given z level.  Will be undefined if the
   * underlying tile grid does not have a known extent.
   */

  /**
   * Data tile loading function.  The function is called with z, x, and y tile coordinates and
   * returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
   * @typedef {function(number, number, number, LoaderOptions) : (import("../DataTile.js").Data|Promise<import("../DataTile.js").Data>)} Loader
   */

  /**
   * @typedef {Object} Options
   * @property {Loader} [loader] Data loader.  Called with z, x, and y tile coordinates.
   * Returns {@link import("../DataTile.js").Data data} for a tile or a promise for the same.
   * For loaders that generate images, the promise should not resolve until the image is loaded.
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.
   * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.
   * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The pixel width and height of the source tiles.
   * This may be different than the rendered pixel size if a `tileGrid` is provided.
   * @property {number} [gutter=0] The size in pixels of the gutter around data tiles to ignore.
   * This allows artifacts of rendering at tile edges to be ignored.
   * Supported data should be wider and taller than the tile size by a value of `2 x gutter`.
   * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Tile projection.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {import("./Source.js").State} [state] The source state.
   * @property {boolean} [wrapX=false] Render tiles beyond the antimeridian.
   * @property {number} [transition] Transition time when fading in new tiles (in milliseconds).
   * @property {number} [bandCount=4] Number of bands represented in the data.
   * @property {boolean} [interpolate=false] Use interpolated values when resampling.  By default,
   * the nearest neighbor is used when resampling.
   * @property {CrossOriginAttribute} [crossOrigin='anonymous'] The crossOrigin property to pass to loaders for image data.
   * @property {string} [key] Key for use in caching tiles.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * A source for typed array data tiles.
   *
   * @fires import("./Tile.js").TileSourceEvent
   * @template {import("../Tile.js").default} [TileType=DataTile]
   * @extends TileSource<TileType>
   * @api
   */
  class DataTileSource extends TileSource {
    /**
     * @param {Options} options DataTile source options.
     */
    constructor(options) {
      const projection =
        options.projection === undefined ? 'EPSG:3857' : options.projection;

      let tileGrid = options.tileGrid;
      if (tileGrid === undefined && projection) {
        tileGrid = createXYZ({
          extent: extentFromProjection(projection),
          maxResolution: options.maxResolution,
          maxZoom: options.maxZoom,
          minZoom: options.minZoom,
          tileSize: options.tileSize,
        });
      }

      super({
        cacheSize: 0.1, // don't cache on the source
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        projection: projection,
        tileGrid: tileGrid,
        state: options.state,
        wrapX: options.wrapX,
        transition: options.transition,
        interpolate: options.interpolate,
        key: options.key,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {number}
       */
      this.gutter_ = options.gutter !== undefined ? options.gutter : 0;

      /**
       * @private
       * @type {import('../size.js').Size|null}
       */
      this.tileSize_ = options.tileSize ? toSize(options.tileSize) : null;

      /**
       * @private
       * @type {Array<import('../size.js').Size>|null}
       */
      this.tileSizes_ = null;

      /**
       * @private
       * @type {!Object<string, boolean>}
       */
      this.tileLoadingKeys_ = {};

      /**
       * @private
       */
      this.loader_ = options.loader;

      /**
       * @private
       */
      this.handleTileChange_ = this.handleTileChange_.bind(this);

      /**
       * @type {number}
       */
      this.bandCount = options.bandCount === undefined ? 4 : options.bandCount; // assume RGBA if undefined

      /**
       * @private
       * @type {!Object<string, import("../tilegrid/TileGrid.js").default>}
       */
      this.tileGridForProjection_ = {};

      /**
       * @private
       * @type {CrossOriginAttribute}
       */
      this.crossOrigin_ = options.crossOrigin || 'anonymous';

      /**
       * @type {import("../transform.js").Transform|null}
       */
      this.transformMatrix = null;
    }

    /**
     * Set the source tile sizes.  The length of the array is expected to match the number of
     * levels in the tile grid.
     * @protected
     * @param {Array<import('../size.js').Size>} tileSizes An array of tile sizes.
     */
    setTileSizes(tileSizes) {
      this.tileSizes_ = tileSizes;
    }

    /**
     * Get the source tile size at the given zoom level.  This may be different than the rendered tile
     * size.
     * @protected
     * @param {number} z Tile zoom level.
     * @return {import('../size.js').Size} The source tile size.
     */
    getTileSize(z) {
      if (this.tileSizes_) {
        return this.tileSizes_[z];
      }
      if (this.tileSize_) {
        return this.tileSize_;
      }
      const tileGrid = this.getTileGrid();
      return tileGrid ? toSize(tileGrid.getTileSize(z)) : [256, 256];
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {number} Gutter.
     * @override
     */
    getGutterForProjection(projection) {
      const thisProj = this.getProjection();
      if (
        (!thisProj || equivalent$1(thisProj, projection)) &&
        !this.transformMatrix
      ) {
        return this.gutter_;
      }

      return 0;
    }

    /**
     * @param {Loader} loader The data loader.
     * @protected
     */
    setLoader(loader) {
      this.loader_ = loader;
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {import("../proj/Projection.js").default} targetProj The output projection.
     * @param {import("../proj/Projection.js").default} sourceProj The input projection.
     * @return {!TileType} Tile.
     */
    getReprojTile_(z, x, y, targetProj, sourceProj) {
      const sourceTileGrid =
        this.tileGrid || this.getTileGridForProjection(sourceProj || targetProj);
      const reprojTilePixelRatio = Math.max.apply(
        null,
        sourceTileGrid.getResolutions().map((r, z) => {
          const tileSize = toSize(sourceTileGrid.getTileSize(z));
          const textureSize = this.getTileSize(z);
          return Math.max(
            textureSize[0] / tileSize[0],
            textureSize[1] / tileSize[1],
          );
        }),
      );

      const targetTileGrid = this.getTileGridForProjection(targetProj);
      const tileCoord = [z, x, y];
      const wrappedTileCoord = this.getTileCoordForTileUrlFunction(
        tileCoord,
        targetProj,
      );

      const options = Object.assign(
        {
          sourceProj: sourceProj || targetProj,
          sourceTileGrid,
          targetProj,
          targetTileGrid,
          tileCoord,
          wrappedTileCoord,
          pixelRatio: reprojTilePixelRatio,
          gutter: this.gutter_,
          getTileFunction: (z, x, y, pixelRatio) =>
            this.getTile(z, x, y, pixelRatio),
          transformMatrix: this.transformMatrix,
        },
        /** @type {import("../reproj/DataTile.js").Options} */ (this.tileOptions),
      );
      const tile = /** @type {TileType} */ (
        /** @type {*} */ (new ReprojDataTile(options))
      );
      tile.key = this.getKey();
      return tile;
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} [projection] Projection.
     * @return {TileType|null} Tile (or null if outside source extent).
     * @override
     */
    getTile(z, x, y, pixelRatio, projection) {
      const sourceProjection = this.getProjection();
      if (
        projection &&
        ((sourceProjection && !equivalent$1(sourceProjection, projection)) ||
          this.transformMatrix)
      ) {
        return this.getReprojTile_(z, x, y, projection, sourceProjection);
      }

      const size = this.getTileSize(z);

      const sourceLoader = this.loader_;

      const controller = new AbortController();

      /**
       * @type {LoaderOptions}
       */
      const loaderOptions = {
        signal: controller.signal,
        crossOrigin: this.crossOrigin_,
      };

      const tileCoord = this.getTileCoordForTileUrlFunction([z, x, y]);
      if (!tileCoord) {
        return null;
      }

      const requestZ = tileCoord[0];
      const requestX = tileCoord[1];
      const requestY = tileCoord[2];
      const range = this.getTileGrid()?.getFullTileRange(requestZ);
      if (range) {
        loaderOptions.maxY = range.getHeight() - 1;
      }
      function loader() {
        return toPromise(function () {
          return sourceLoader(requestZ, requestX, requestY, loaderOptions);
        });
      }

      /**
       * @type {import("../DataTile.js").Options}
       */
      const options = Object.assign(
        {
          tileCoord: [z, x, y],
          loader: loader,
          size: size,
          controller: controller,
        },
        this.tileOptions,
      );

      const tile = /** @type {TileType} */ (
        /** @type {*} */ (new DataTile(options))
      );
      tile.key = this.getKey();
      tile.addEventListener(EventType.CHANGE, this.handleTileChange_);

      return tile;
    }

    /**
     * Handle tile change events.
     * @param {import("../events/Event.js").default} event Event.
     */
    handleTileChange_(event) {
      const tile = /** @type {import("../Tile.js").default} */ (event.target);
      const uid = getUid(tile);
      const tileState = tile.getState();
      let type;
      if (tileState == TileState.LOADING) {
        this.tileLoadingKeys_[uid] = true;
        type = TileEventType.TILELOADSTART;
      } else if (uid in this.tileLoadingKeys_) {
        delete this.tileLoadingKeys_[uid];
        type =
          tileState == TileState.ERROR
            ? TileEventType.TILELOADERROR
            : tileState == TileState.LOADED
              ? TileEventType.TILELOADEND
              : undefined;
      }
      if (type) {
        this.dispatchEvent(new TileSourceEvent(type, tile));
      }
    }

    /**
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!import("../tilegrid/TileGrid.js").default} Tile grid.
     * @override
     */
    getTileGridForProjection(projection) {
      const thisProj = this.getProjection();
      if (
        this.tileGrid &&
        (!thisProj || equivalent$1(thisProj, projection)) &&
        !this.transformMatrix
      ) {
        return this.tileGrid;
      }

      const projKey = getUid(projection);
      if (!(projKey in this.tileGridForProjection_)) {
        this.tileGridForProjection_[projKey] =
          getForProjection(projection);
      }
      return this.tileGridForProjection_[projKey];
    }

    /**
     * Sets the tile grid to use when reprojecting the tiles to the given
     * projection instead of the default tile grid for the projection.
     *
     * This can be useful when the default tile grid cannot be created
     * (e.g. projection has no extent defined) or
     * for optimization reasons (custom tile size, resolutions, ...).
     *
     * @param {import("../proj.js").ProjectionLike} projection Projection.
     * @param {import("../tilegrid/TileGrid.js").default} tilegrid Tile grid to use for the projection.
     * @api
     */
    setTileGridForProjection(projection, tilegrid) {
      const proj = get$2(projection);
      if (proj) {
        const projKey = getUid(proj);
        if (!(projKey in this.tileGridForProjection_)) {
          this.tileGridForProjection_[projKey] = tilegrid;
        }
      }
    }
  }

  /* eslint-disable no-restricted-globals, no-restricted-syntax */
  /* global SharedArrayBuffer */


  /** @type {<T extends (...args: any) => any>(target: T) => (thisArg: ThisType<T>, ...args: any[]) => any} */
  function uncurryThis(target) {
    return (thisArg, ...args) => {
      return ReflectApply(target, thisArg, args);
    };
  }

  /** @type {(target: any, key: string | symbol) => (thisArg: any, ...args: any[]) => any} */
  function uncurryThisGetter(target, key) {
    return uncurryThis(
      ReflectGetOwnPropertyDescriptor(
        target,
        key
      ).get
    );
  }

  // Reflect
  const {
    apply: ReflectApply,
    getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
    getPrototypeOf: ReflectGetPrototypeOf,
    ownKeys: ReflectOwnKeys} = Reflect;

  // Symbol
  const {
    iterator: SymbolIterator,
    toStringTag: SymbolToStringTag} = Symbol;

  // Object
  const NativeObject = Object;
  const {
    create: ObjectCreate,
    defineProperty: ObjectDefineProperty} = NativeObject;

  // Array
  const NativeArray = Array;
  const ArrayPrototype = NativeArray.prototype;
  const NativeArrayPrototypeSymbolIterator = ArrayPrototype[SymbolIterator];
  /** @type {<T>(array: T[]) => IterableIterator<T>} */
  const ArrayPrototypeSymbolIterator = uncurryThis(NativeArrayPrototypeSymbolIterator);

  // ArrayBuffer
  const NativeArrayBuffer = ArrayBuffer;
  const ArrayBufferPrototype = NativeArrayBuffer.prototype;
  /** @type {(buffer: ArrayBuffer) => ArrayBuffer} */
  uncurryThisGetter(ArrayBufferPrototype, "byteLength");

  // SharedArrayBuffer
  const NativeSharedArrayBuffer = typeof SharedArrayBuffer !== "undefined" ? SharedArrayBuffer : null;
  /** @type {(buffer: SharedArrayBuffer) => SharedArrayBuffer} */
  NativeSharedArrayBuffer
    && uncurryThisGetter(NativeSharedArrayBuffer.prototype, "byteLength");

  // TypedArray
  /** @typedef {Uint8Array|Uint8ClampedArray|Uint16Array|Uint32Array|Int8Array|Int16Array|Int32Array|Float32Array|Float64Array|BigUint64Array|BigInt64Array} TypedArray */
  /** @type {any} */
  const TypedArray = ReflectGetPrototypeOf(Uint8Array);
  TypedArray.from;
  const TypedArrayPrototype = TypedArray.prototype;
  TypedArrayPrototype[SymbolIterator];
  /** @type {(typedArray: TypedArray) => IterableIterator<number>} */
  uncurryThis(TypedArrayPrototype.keys);
  /** @type {(typedArray: TypedArray) => IterableIterator<number>} */
  uncurryThis(
    TypedArrayPrototype.values
  );
  /** @type {(typedArray: TypedArray) => IterableIterator<[number, number]>} */
  uncurryThis(
    TypedArrayPrototype.entries
  );
  /** @type {(typedArray: TypedArray, array: ArrayLike<number>, offset?: number) => void} */
  uncurryThis(TypedArrayPrototype.set);
  /** @type {<T extends TypedArray>(typedArray: T) => T} */
  uncurryThis(
    TypedArrayPrototype.reverse
  );
  /** @type {<T extends TypedArray>(typedArray: T, value: number, start?: number, end?: number) => T} */
  uncurryThis(TypedArrayPrototype.fill);
  /** @type {<T extends TypedArray>(typedArray: T, target: number, start: number, end?: number) => T} */
  uncurryThis(
    TypedArrayPrototype.copyWithin
  );
  /** @type {<T extends TypedArray>(typedArray: T, compareFn?: (a: number, b: number) => number) => T} */
  uncurryThis(TypedArrayPrototype.sort);
  /** @type {<T extends TypedArray>(typedArray: T, start?: number, end?: number) => T} */
  uncurryThis(TypedArrayPrototype.slice);
  /** @type {<T extends TypedArray>(typedArray: T, start?: number, end?: number) => T} */
  uncurryThis(
    TypedArrayPrototype.subarray
  );
  /** @type {((typedArray: TypedArray) => ArrayBuffer)} */
  uncurryThisGetter(
    TypedArrayPrototype,
    "buffer"
  );
  /** @type {((typedArray: TypedArray) => number)} */
  uncurryThisGetter(
    TypedArrayPrototype,
    "byteOffset"
  );
  /** @type {((typedArray: TypedArray) => number)} */
  uncurryThisGetter(
    TypedArrayPrototype,
    "length"
  );
  /** @type {(target: unknown) => string} */
  uncurryThisGetter(
    TypedArrayPrototype,
    SymbolToStringTag
  );

  // Uint8Array
  const NativeUint8Array = Uint8Array;

  // Uint16Array
  const NativeUint16Array = Uint16Array;

  // Uint32Array
  const NativeUint32Array = Uint32Array;

  // Float32Array
  const NativeFloat32Array = Float32Array;

  // ArrayIterator
  /** @type {any} */
  const ArrayIteratorPrototype = ReflectGetPrototypeOf([][SymbolIterator]());
  /** @type {<T>(arrayIterator: IterableIterator<T>) => IteratorResult<T>} */
  const ArrayIteratorPrototypeNext = uncurryThis(ArrayIteratorPrototype.next);

  // Generator
  /** @type {<T = unknown, TReturn = any, TNext = unknown>(generator: Generator<T, TReturn, TNext>, value?: TNext) => T} */
  const GeneratorPrototypeNext = uncurryThis((function* () {})().next);

  // Iterator
  const IteratorPrototype = ReflectGetPrototypeOf(ArrayIteratorPrototype);

  // DataView
  const DataViewPrototype = DataView.prototype;
  /** @type {(dataView: DataView, byteOffset: number, littleEndian?: boolean) => number} */
  const DataViewPrototypeGetUint16 = uncurryThis(
    DataViewPrototype.getUint16
  );

  // WeakMap
  /**
   * Do not construct with arguments to avoid calling the "set" method
   * @type {{new <K extends {}, V>(): WeakMap<K, V>}}
   */
  const NativeWeakMap = WeakMap;
  const WeakMapPrototype = NativeWeakMap.prototype;
  /** @type {<K extends {}, V>(weakMap: WeakMap<K, V>, key: K) => V} */
  const WeakMapPrototypeGet = uncurryThis(WeakMapPrototype.get);
  /** @type {<K extends {}, V>(weakMap: WeakMap<K, V>, key: K, value: V) => WeakMap} */
  const WeakMapPrototypeSet = uncurryThis(WeakMapPrototype.set);

  /** @type {WeakMap<{}, IterableIterator<any>>} */
  const arrayIterators = new NativeWeakMap();

  const SafeIteratorPrototype = ObjectCreate(null, {
    next: {
      value: function next() {
        const arrayIterator = WeakMapPrototypeGet(arrayIterators, this);
        return ArrayIteratorPrototypeNext(arrayIterator);
      },
    },

    [SymbolIterator]: {
      value: function values() {
        return this;
      },
    },
  });

  /**
   * Wrap the Array around the SafeIterator If Array.prototype [@@iterator] has been modified
   * @type {<T>(array: T[]) => Iterable<T>}
   */
  function safeIfNeeded(array) {
    if (
      array[SymbolIterator] === NativeArrayPrototypeSymbolIterator &&
      ArrayIteratorPrototype.next === ArrayIteratorPrototypeNext
    ) {
      return array;
    }

    const safe = ObjectCreate(SafeIteratorPrototype);
    WeakMapPrototypeSet(arrayIterators, safe, ArrayPrototypeSymbolIterator(array));
    return safe;
  }

  /** @type {WeakMap<{}, Generator<any>>} */
  const generators = new NativeWeakMap();

  /** @see https://tc39.es/ecma262/#sec-%arrayiteratorprototype%-object */
  const DummyArrayIteratorPrototype = ObjectCreate(IteratorPrototype, {
    next: {
      value: function next() {
        const generator = WeakMapPrototypeGet(generators, this);
        return GeneratorPrototypeNext(generator);
      },
      writable: true,
      configurable: true,
    },
  });

  for (const key of ReflectOwnKeys(ArrayIteratorPrototype)) {
    // next method has already defined
    if (key === "next") {
      continue;
    }

    // Copy ArrayIteratorPrototype descriptors to DummyArrayIteratorPrototype
    ObjectDefineProperty(DummyArrayIteratorPrototype, key, ReflectGetOwnPropertyDescriptor(ArrayIteratorPrototype, key));
  }

  // base algorithm: http://fox-toolkit.org/ftp/fasthalffloatconversion.pdf

  const buffer = new NativeArrayBuffer(4);
  const floatView = new NativeFloat32Array(buffer);
  const uint32View = new NativeUint32Array(buffer);

  const baseTable = new NativeUint16Array(512);
  const shiftTable = new NativeUint8Array(512);

  for (let i = 0; i < 256; ++i) {
    const e = i - 127;

    // very small number (0, -0)
    if (e < -24) {
      baseTable[i]         = 0x0000;
      baseTable[i | 0x100] = 0x8000;
      shiftTable[i]         = 24;
      shiftTable[i | 0x100] = 24;

    // small number (denorm)
    } else if (e < -14) {
      baseTable[i]         =  0x0400 >> (-e - 14);
      baseTable[i | 0x100] = (0x0400 >> (-e - 14)) | 0x8000;
      shiftTable[i]         = -e - 1;
      shiftTable[i | 0x100] = -e - 1;

    // normal number
    } else if (e <= 15) {
      baseTable[i]         =  (e + 15) << 10;
      baseTable[i | 0x100] = ((e + 15) << 10) | 0x8000;
      shiftTable[i]         = 13;
      shiftTable[i | 0x100] = 13;

    // large number (Infinity, -Infinity)
    } else if (e < 128) {
      baseTable[i]         = 0x7c00;
      baseTable[i | 0x100] = 0xfc00;
      shiftTable[i]         = 24;
      shiftTable[i | 0x100] = 24;

    // stay (NaN, Infinity, -Infinity)
    } else {
      baseTable[i]         = 0x7c00;
      baseTable[i | 0x100] = 0xfc00;
      shiftTable[i]         = 13;
      shiftTable[i | 0x100] = 13;
    }
  }

  const mantissaTable = new NativeUint32Array(2048);
  for (let i = 1; i < 1024; ++i) {
    let m = i << 13; // zero pad mantissa bits
    let e = 0; // zero exponent

    // normalized
    while ((m & 0x00800000) === 0) {
      m <<= 1;
      e -= 0x00800000; // decrement exponent
    }

    m &= -8388609; // clear leading 1 bit
    e += 0x38800000; // adjust bias

    mantissaTable[i] = m | e;
  }
  for (let i = 1024; i < 2048; ++i) {
    mantissaTable[i] = 0x38000000 + ((i - 1024) << 13);
  }

  const exponentTable = new NativeUint32Array(64);
  for (let i = 1; i < 31; ++i) {
    exponentTable[i] = i << 23;
  }
  exponentTable[31] = 0x47800000;
  exponentTable[32] = 0x80000000;
  for (let i = 33; i < 63; ++i) {
    exponentTable[i] = 0x80000000 + ((i - 32) << 23);
  }
  exponentTable[63] = 0xc7800000;

  const offsetTable = new NativeUint16Array(64);
  for (let i = 1; i < 64; ++i) {
    if (i !== 32) {
      offsetTable[i] = 1024;
    }
  }

  /**
   * convert a half float number bits to a number
   * @param {number} float16bits - half float number bits
   * @returns {number} double float
   */
  function convertToNumber(float16bits) {
    const i = float16bits >> 10;
    uint32View[0] = mantissaTable[offsetTable[i] + (float16bits & 0x3ff)] + exponentTable[i];
    return floatView[0];
  }

  /**
   * returns an unsigned 16-bit float at the specified byte offset from the start of the DataView
   * @param {DataView} dataView
   * @param {number} byteOffset
   * @param {[boolean]} opts
   * @returns {number}
   */
  function getFloat16(dataView, byteOffset, ...opts) {
    return convertToNumber(
      DataViewPrototypeGetUint16(dataView, byteOffset, ...safeIfNeeded(opts))
    );
  }

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

  var getAttribute$1 = {exports: {}};

  var hasRequiredGetAttribute;

  function requireGetAttribute () {
  	if (hasRequiredGetAttribute) return getAttribute$1.exports;
  	hasRequiredGetAttribute = 1;
  	function getAttribute(tag, attributeName, options) {
  	  const debug = (options && options.debug) || false;
  	  if (debug) console.log("[xml-utils] getting " + attributeName + " in " + tag);

  	  const xml = typeof tag === "object" ? tag.outer : tag;

  	  // only search for attributes in the opening tag
  	  const opening = xml.slice(0, xml.indexOf(">") + 1);

  	  const quotechars = ['"', "'"];
  	  for (let i = 0; i < quotechars.length; i++) {
  	    const char = quotechars[i];
  	    const pattern = attributeName + "\\=" + char + "([^" + char + "]*)" + char;
  	    if (debug) console.log("[xml-utils] pattern:", pattern);

  	    const re = new RegExp(pattern);
  	    const match = re.exec(opening);
  	    if (debug) console.log("[xml-utils] match:", match);
  	    if (match) return match[1];
  	  }
  	}

  	getAttribute$1.exports = getAttribute;
  	getAttribute$1.exports.default = getAttribute;
  	return getAttribute$1.exports;
  }

  var getAttributeExports = requireGetAttribute();
  var getAttribute = /*@__PURE__*/getDefaultExportFromCjs(getAttributeExports);

  var findTagsByName$1 = {exports: {}};

  var findTagByName = {exports: {}};

  var indexOfMatch = {exports: {}};

  var hasRequiredIndexOfMatch;

  function requireIndexOfMatch () {
  	if (hasRequiredIndexOfMatch) return indexOfMatch.exports;
  	hasRequiredIndexOfMatch = 1;
  	function indexOfMatch$1(xml, pattern, startIndex) {
  	  const re = new RegExp(pattern);
  	  const match = re.exec(xml.slice(startIndex));
  	  if (match) return startIndex + match.index;
  	  else return -1;
  	}

  	indexOfMatch.exports = indexOfMatch$1;
  	indexOfMatch.exports.default = indexOfMatch$1;
  	return indexOfMatch.exports;
  }

  var indexOfMatchEnd = {exports: {}};

  var hasRequiredIndexOfMatchEnd;

  function requireIndexOfMatchEnd () {
  	if (hasRequiredIndexOfMatchEnd) return indexOfMatchEnd.exports;
  	hasRequiredIndexOfMatchEnd = 1;
  	function indexOfMatchEnd$1(xml, pattern, startIndex) {
  	  const re = new RegExp(pattern);
  	  const match = re.exec(xml.slice(startIndex));
  	  if (match) return startIndex + match.index + match[0].length - 1;
  	  else return -1;
  	}

  	indexOfMatchEnd.exports = indexOfMatchEnd$1;
  	indexOfMatchEnd.exports.default = indexOfMatchEnd$1;
  	return indexOfMatchEnd.exports;
  }

  var countSubstring = {exports: {}};

  var hasRequiredCountSubstring;

  function requireCountSubstring () {
  	if (hasRequiredCountSubstring) return countSubstring.exports;
  	hasRequiredCountSubstring = 1;
  	function countSubstring$1(string, substring) {
  	  const pattern = new RegExp(substring, "g");
  	  const match = string.match(pattern);
  	  return match ? match.length : 0;
  	}

  	countSubstring.exports = countSubstring$1;
  	countSubstring.exports.default = countSubstring$1;
  	return countSubstring.exports;
  }

  var hasRequiredFindTagByName;

  function requireFindTagByName () {
  	if (hasRequiredFindTagByName) return findTagByName.exports;
  	hasRequiredFindTagByName = 1;
  	const indexOfMatch = requireIndexOfMatch();
  	const indexOfMatchEnd = requireIndexOfMatchEnd();
  	const countSubstring = requireCountSubstring();

  	function findTagByName$1(xml, tagName, options) {
  	  const debug = (options && options.debug) || false;
  	  const nested = !(options && typeof options.nested === false);

  	  const startIndex = (options && options.startIndex) || 0;

  	  if (debug) console.log("[xml-utils] starting findTagByName with", tagName, " and ", options);

  	  const start = indexOfMatch(xml, `\<${tagName}[ \n\>\/]`, startIndex);
  	  if (debug) console.log("[xml-utils] start:", start);
  	  if (start === -1) return undefined;

  	  const afterStart = xml.slice(start + tagName.length);

  	  let relativeEnd = indexOfMatchEnd(afterStart, "^[^<]*[ /]>", 0);

  	  const selfClosing = relativeEnd !== -1 && afterStart[relativeEnd - 1] === "/";
  	  if (debug) console.log("[xml-utils] selfClosing:", selfClosing);

  	  if (selfClosing === false) {
  	    // check if tag has subtags with the same name
  	    if (nested) {
  	      let startIndex = 0;
  	      let openings = 1;
  	      let closings = 0;
  	      while ((relativeEnd = indexOfMatchEnd(afterStart, "[ /]" + tagName + ">", startIndex)) !== -1) {
  	        const clip = afterStart.substring(startIndex, relativeEnd + 1);
  	        openings += countSubstring(clip, "<" + tagName + "[ \n\t>]");
  	        closings += countSubstring(clip, "</" + tagName + ">");
  	        // we can't have more openings than closings
  	        if (closings >= openings) break;
  	        startIndex = relativeEnd;
  	      }
  	    } else {
  	      relativeEnd = indexOfMatchEnd(afterStart, "[ /]" + tagName + ">", 0);
  	    }
  	  }

  	  const end = start + tagName.length + relativeEnd + 1;
  	  if (debug) console.log("[xml-utils] end:", end);
  	  if (end === -1) return undefined;

  	  const outer = xml.slice(start, end);
  	  // tag is like <gml:identifier codeSpace="OGP">urn:ogc:def:crs:EPSG::32617</gml:identifier>

  	  let inner;
  	  if (selfClosing) {
  	    inner = null;
  	  } else {
  	    inner = outer.slice(outer.indexOf(">") + 1, outer.lastIndexOf("<"));
  	  }

  	  return { inner, outer, start, end };
  	}

  	findTagByName.exports = findTagByName$1;
  	findTagByName.exports.default = findTagByName$1;
  	return findTagByName.exports;
  }

  var hasRequiredFindTagsByName;

  function requireFindTagsByName () {
  	if (hasRequiredFindTagsByName) return findTagsByName$1.exports;
  	hasRequiredFindTagsByName = 1;
  	const findTagByName = requireFindTagByName();

  	function findTagsByName(xml, tagName, options) {
  	  const tags = [];
  	  const debug = (options && options.debug) || false;
  	  const nested = options && typeof options.nested === "boolean" ? options.nested : true;
  	  let startIndex = (options && options.startIndex) || 0;
  	  let tag;
  	  while ((tag = findTagByName(xml, tagName, { debug, startIndex }))) {
  	    if (nested) {
  	      startIndex = tag.start + 1 + tagName.length;
  	    } else {
  	      startIndex = tag.end;
  	    }
  	    tags.push(tag);
  	  }
  	  if (debug) console.log("findTagsByName found", tags.length, "tags");
  	  return tags;
  	}

  	findTagsByName$1.exports = findTagsByName;
  	findTagsByName$1.exports.default = findTagsByName;
  	return findTagsByName$1.exports;
  }

  var findTagsByNameExports = requireFindTagsByName();
  var findTagsByName = /*@__PURE__*/getDefaultExportFromCjs(findTagsByNameExports);

  const fieldTagNames = {
    // TIFF Baseline
    0x013B: 'Artist',
    0x0102: 'BitsPerSample',
    0x0109: 'CellLength',
    0x0108: 'CellWidth',
    0x0140: 'ColorMap',
    0x0103: 'Compression',
    0x8298: 'Copyright',
    0x0132: 'DateTime',
    0x0152: 'ExtraSamples',
    0x010A: 'FillOrder',
    0x0121: 'FreeByteCounts',
    0x0120: 'FreeOffsets',
    0x0123: 'GrayResponseCurve',
    0x0122: 'GrayResponseUnit',
    0x013C: 'HostComputer',
    0x010E: 'ImageDescription',
    0x0101: 'ImageLength',
    0x0100: 'ImageWidth',
    0x010F: 'Make',
    0x0119: 'MaxSampleValue',
    0x0118: 'MinSampleValue',
    0x0110: 'Model',
    0x00FE: 'NewSubfileType',
    0x0112: 'Orientation',
    0x0106: 'PhotometricInterpretation',
    0x011C: 'PlanarConfiguration',
    0x0128: 'ResolutionUnit',
    0x0116: 'RowsPerStrip',
    0x0115: 'SamplesPerPixel',
    0x0131: 'Software',
    0x0117: 'StripByteCounts',
    0x0111: 'StripOffsets',
    0x00FF: 'SubfileType',
    0x0107: 'Threshholding',
    0x011A: 'XResolution',
    0x011B: 'YResolution',

    // TIFF Extended
    0x0146: 'BadFaxLines',
    0x0147: 'CleanFaxData',
    0x0157: 'ClipPath',
    0x0148: 'ConsecutiveBadFaxLines',
    0x01B1: 'Decode',
    0x01B2: 'DefaultImageColor',
    0x010D: 'DocumentName',
    0x0150: 'DotRange',
    0x0141: 'HalftoneHints',
    0x015A: 'Indexed',
    0x015B: 'JPEGTables',
    0x011D: 'PageName',
    0x0129: 'PageNumber',
    0x013D: 'Predictor',
    0x013F: 'PrimaryChromaticities',
    0x0214: 'ReferenceBlackWhite',
    0x0153: 'SampleFormat',
    0x0154: 'SMinSampleValue',
    0x0155: 'SMaxSampleValue',
    0x022F: 'StripRowCounts',
    0x014A: 'SubIFDs',
    0x0124: 'T4Options',
    0x0125: 'T6Options',
    0x0145: 'TileByteCounts',
    0x0143: 'TileLength',
    0x0144: 'TileOffsets',
    0x0142: 'TileWidth',
    0x012D: 'TransferFunction',
    0x013E: 'WhitePoint',
    0x0158: 'XClipPathUnits',
    0x011E: 'XPosition',
    0x0211: 'YCbCrCoefficients',
    0x0213: 'YCbCrPositioning',
    0x0212: 'YCbCrSubSampling',
    0x0159: 'YClipPathUnits',
    0x011F: 'YPosition',

    // EXIF
    0x9202: 'ApertureValue',
    0xA001: 'ColorSpace',
    0x9004: 'DateTimeDigitized',
    0x9003: 'DateTimeOriginal',
    0x8769: 'Exif IFD',
    0x9000: 'ExifVersion',
    0x829A: 'ExposureTime',
    0xA300: 'FileSource',
    0x9209: 'Flash',
    0xA000: 'FlashpixVersion',
    0x829D: 'FNumber',
    0xA420: 'ImageUniqueID',
    0x9208: 'LightSource',
    0x927C: 'MakerNote',
    0x9201: 'ShutterSpeedValue',
    0x9286: 'UserComment',

    // IPTC
    0x83BB: 'IPTC',

    // ICC
    0x8773: 'ICC Profile',

    // XMP
    0x02BC: 'XMP',

    // GDAL
    0xA480: 'GDAL_METADATA',
    0xA481: 'GDAL_NODATA',

    // Photoshop
    0x8649: 'Photoshop',

    // GeoTiff
    0x830E: 'ModelPixelScale',
    0x8482: 'ModelTiepoint',
    0x85D8: 'ModelTransformation',
    0x87AF: 'GeoKeyDirectory',
    0x87B0: 'GeoDoubleParams',
    0x87B1: 'GeoAsciiParams',

    // LERC
    0xC5F2: 'LercParameters',
  };

  const fieldTags = {};
  for (const key in fieldTagNames) {
    if (fieldTagNames.hasOwnProperty(key)) {
      fieldTags[fieldTagNames[key]] = parseInt(key, 10);
    }
  }

  const arrayFields = [
    fieldTags.BitsPerSample,
    fieldTags.ExtraSamples,
    fieldTags.SampleFormat,
    fieldTags.StripByteCounts,
    fieldTags.StripOffsets,
    fieldTags.StripRowCounts,
    fieldTags.TileByteCounts,
    fieldTags.TileOffsets,
    fieldTags.SubIFDs,
  ];

  const fieldTypeNames = {
    0x0001: 'BYTE',
    0x0002: 'ASCII',
    0x0003: 'SHORT',
    0x0004: 'LONG',
    0x0005: 'RATIONAL',
    0x0006: 'SBYTE',
    0x0007: 'UNDEFINED',
    0x0008: 'SSHORT',
    0x0009: 'SLONG',
    0x000A: 'SRATIONAL',
    0x000B: 'FLOAT',
    0x000C: 'DOUBLE',
    // IFD offset, suggested by https://owl.phy.queensu.ca/~phil/exiftool/standards.html
    0x000D: 'IFD',
    // introduced by BigTIFF
    0x0010: 'LONG8',
    0x0011: 'SLONG8',
    0x0012: 'IFD8',
  };

  const fieldTypes = {};
  for (const key in fieldTypeNames) {
    if (fieldTypeNames.hasOwnProperty(key)) {
      fieldTypes[fieldTypeNames[key]] = parseInt(key, 10);
    }
  }

  const photometricInterpretations = {
    WhiteIsZero: 0,
    BlackIsZero: 1,
    RGB: 2,
    Palette: 3,
    CMYK: 5,
    YCbCr: 6,

    CIELab: 8,
    ICCLab: 9,
  };

  const ExtraSamplesValues = {
    Unspecified: 0};

  const LercParameters = {
    AddCompression: 1,
  };

  const LercAddCompression = {
    None: 0,
    Deflate: 1,
    Zstandard: 2,
  };

  const geoKeyNames = {
    1024: 'GTModelTypeGeoKey',
    1025: 'GTRasterTypeGeoKey',
    1026: 'GTCitationGeoKey',
    2048: 'GeographicTypeGeoKey',
    2049: 'GeogCitationGeoKey',
    2050: 'GeogGeodeticDatumGeoKey',
    2051: 'GeogPrimeMeridianGeoKey',
    2052: 'GeogLinearUnitsGeoKey',
    2053: 'GeogLinearUnitSizeGeoKey',
    2054: 'GeogAngularUnitsGeoKey',
    2055: 'GeogAngularUnitSizeGeoKey',
    2056: 'GeogEllipsoidGeoKey',
    2057: 'GeogSemiMajorAxisGeoKey',
    2058: 'GeogSemiMinorAxisGeoKey',
    2059: 'GeogInvFlatteningGeoKey',
    2060: 'GeogAzimuthUnitsGeoKey',
    2061: 'GeogPrimeMeridianLongGeoKey',
    2062: 'GeogTOWGS84GeoKey',
    3072: 'ProjectedCSTypeGeoKey',
    3073: 'PCSCitationGeoKey',
    3074: 'ProjectionGeoKey',
    3075: 'ProjCoordTransGeoKey',
    3076: 'ProjLinearUnitsGeoKey',
    3077: 'ProjLinearUnitSizeGeoKey',
    3078: 'ProjStdParallel1GeoKey',
    3079: 'ProjStdParallel2GeoKey',
    3080: 'ProjNatOriginLongGeoKey',
    3081: 'ProjNatOriginLatGeoKey',
    3082: 'ProjFalseEastingGeoKey',
    3083: 'ProjFalseNorthingGeoKey',
    3084: 'ProjFalseOriginLongGeoKey',
    3085: 'ProjFalseOriginLatGeoKey',
    3086: 'ProjFalseOriginEastingGeoKey',
    3087: 'ProjFalseOriginNorthingGeoKey',
    3088: 'ProjCenterLongGeoKey',
    3089: 'ProjCenterLatGeoKey',
    3090: 'ProjCenterEastingGeoKey',
    3091: 'ProjCenterNorthingGeoKey',
    3092: 'ProjScaleAtNatOriginGeoKey',
    3093: 'ProjScaleAtCenterGeoKey',
    3094: 'ProjAzimuthAngleGeoKey',
    3095: 'ProjStraightVertPoleLongGeoKey',
    3096: 'ProjRectifiedGridAngleGeoKey',
    4096: 'VerticalCSTypeGeoKey',
    4097: 'VerticalCitationGeoKey',
    4098: 'VerticalDatumGeoKey',
    4099: 'VerticalUnitsGeoKey',
  };

  function fromWhiteIsZero(raster, max) {
    const { width, height } = raster;
    const rgbRaster = new Uint8Array(width * height * 3);
    let value;
    for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {
      value = 256 - (raster[i] / max * 256);
      rgbRaster[j] = value;
      rgbRaster[j + 1] = value;
      rgbRaster[j + 2] = value;
    }
    return rgbRaster;
  }

  function fromBlackIsZero(raster, max) {
    const { width, height } = raster;
    const rgbRaster = new Uint8Array(width * height * 3);
    let value;
    for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {
      value = raster[i] / max * 256;
      rgbRaster[j] = value;
      rgbRaster[j + 1] = value;
      rgbRaster[j + 2] = value;
    }
    return rgbRaster;
  }

  function fromPalette(raster, colorMap) {
    const { width, height } = raster;
    const rgbRaster = new Uint8Array(width * height * 3);
    const greenOffset = colorMap.length / 3;
    const blueOffset = colorMap.length / 3 * 2;
    for (let i = 0, j = 0; i < raster.length; ++i, j += 3) {
      const mapIndex = raster[i];
      rgbRaster[j] = colorMap[mapIndex] / 65536 * 256;
      rgbRaster[j + 1] = colorMap[mapIndex + greenOffset] / 65536 * 256;
      rgbRaster[j + 2] = colorMap[mapIndex + blueOffset] / 65536 * 256;
    }
    return rgbRaster;
  }

  function fromCMYK(cmykRaster) {
    const { width, height } = cmykRaster;
    const rgbRaster = new Uint8Array(width * height * 3);
    for (let i = 0, j = 0; i < cmykRaster.length; i += 4, j += 3) {
      const c = cmykRaster[i];
      const m = cmykRaster[i + 1];
      const y = cmykRaster[i + 2];
      const k = cmykRaster[i + 3];

      rgbRaster[j] = 255 * ((255 - c) / 256) * ((255 - k) / 256);
      rgbRaster[j + 1] = 255 * ((255 - m) / 256) * ((255 - k) / 256);
      rgbRaster[j + 2] = 255 * ((255 - y) / 256) * ((255 - k) / 256);
    }
    return rgbRaster;
  }

  function fromYCbCr(yCbCrRaster) {
    const { width, height } = yCbCrRaster;
    const rgbRaster = new Uint8ClampedArray(width * height * 3);
    for (let i = 0, j = 0; i < yCbCrRaster.length; i += 3, j += 3) {
      const y = yCbCrRaster[i];
      const cb = yCbCrRaster[i + 1];
      const cr = yCbCrRaster[i + 2];

      rgbRaster[j] = (y + (1.40200 * (cr - 0x80)));
      rgbRaster[j + 1] = (y - (0.34414 * (cb - 0x80)) - (0.71414 * (cr - 0x80)));
      rgbRaster[j + 2] = (y + (1.77200 * (cb - 0x80)));
    }
    return rgbRaster;
  }

  const Xn = 0.95047;
  const Yn = 1.00000;
  const Zn = 1.08883;

  // from https://github.com/antimatter15/rgb-lab/blob/master/color.js

  function fromCIELab(cieLabRaster) {
    const { width, height } = cieLabRaster;
    const rgbRaster = new Uint8Array(width * height * 3);

    for (let i = 0, j = 0; i < cieLabRaster.length; i += 3, j += 3) {
      const L = cieLabRaster[i + 0];
      const a_ = cieLabRaster[i + 1] << 24 >> 24; // conversion from uint8 to int8
      const b_ = cieLabRaster[i + 2] << 24 >> 24; // same

      let y = (L + 16) / 116;
      let x = (a_ / 500) + y;
      let z = y - (b_ / 200);
      let r;
      let g;
      let b;

      x = Xn * ((x * x * x > 0.008856) ? x * x * x : (x - (16 / 116)) / 7.787);
      y = Yn * ((y * y * y > 0.008856) ? y * y * y : (y - (16 / 116)) / 7.787);
      z = Zn * ((z * z * z > 0.008856) ? z * z * z : (z - (16 / 116)) / 7.787);

      r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
      g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
      b = (x * 0.0557) + (y * -0.204) + (z * 1.0570);

      r = (r > 0.0031308) ? ((1.055 * (r ** (1 / 2.4))) - 0.055) : 12.92 * r;
      g = (g > 0.0031308) ? ((1.055 * (g ** (1 / 2.4))) - 0.055) : 12.92 * g;
      b = (b > 0.0031308) ? ((1.055 * (b ** (1 / 2.4))) - 0.055) : 12.92 * b;

      rgbRaster[j] = Math.max(0, Math.min(1, r)) * 255;
      rgbRaster[j + 1] = Math.max(0, Math.min(1, g)) * 255;
      rgbRaster[j + 2] = Math.max(0, Math.min(1, b)) * 255;
    }
    return rgbRaster;
  }

  const registry = new Map();

  function addDecoder(cases, importFn) {
    if (!Array.isArray(cases)) {
      cases = [cases]; // eslint-disable-line no-param-reassign
    }
    cases.forEach((c) => registry.set(c, importFn));
  }

  async function getDecoder(fileDirectory) {
    const importFn = registry.get(fileDirectory.Compression);
    if (!importFn) {
      throw new Error(`Unknown compression method identifier: ${fileDirectory.Compression}`);
    }
    const Decoder = await importFn();
    return new Decoder(fileDirectory);
  }

  // Add default decoders to registry (end-user may override with other implementations)
  addDecoder([undefined, 1], () => Promise.resolve().then(function () { return raw; }).then((m) => m.default));
  addDecoder(5, () => Promise.resolve().then(function () { return lzw; }).then((m) => m.default));
  addDecoder(6, () => {
    throw new Error('old style JPEG compression is not supported.');
  });
  addDecoder(7, () => Promise.resolve().then(function () { return jpeg; }).then((m) => m.default));
  addDecoder([8, 32946], () => Promise.resolve().then(function () { return deflate; }).then((m) => m.default));
  addDecoder(32773, () => Promise.resolve().then(function () { return packbits; }).then((m) => m.default));
  addDecoder(34887, () => Promise.resolve().then(function () { return lerc; })
    .then(async (m) => {
      await m.zstd.init();
      return m;
    })
    .then((m) => m.default),
  );
  addDecoder(50001, () => Promise.resolve().then(function () { return webimage; }).then((m) => m.default));

  /**
   * @module resample
   */

  function copyNewSize(array, width, height, samplesPerPixel = 1) {
    return new (Object.getPrototypeOf(array).constructor)(width * height * samplesPerPixel);
  }

  /**
   * Resample the input arrays using nearest neighbor value selection.
   * @param {TypedArray[]} valueArrays The input arrays to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @returns {TypedArray[]} The resampled rasters
   */
  function resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight) {
    const relX = inWidth / outWidth;
    const relY = inHeight / outHeight;
    return valueArrays.map((array) => {
      const newArray = copyNewSize(array, outWidth, outHeight);
      for (let y = 0; y < outHeight; ++y) {
        const cy = Math.min(Math.round(relY * y), inHeight - 1);
        for (let x = 0; x < outWidth; ++x) {
          const cx = Math.min(Math.round(relX * x), inWidth - 1);
          const value = array[(cy * inWidth) + cx];
          newArray[(y * outWidth) + x] = value;
        }
      }
      return newArray;
    });
  }

  // simple linear interpolation, code from:
  // https://en.wikipedia.org/wiki/Linear_interpolation#Programming_language_support
  function lerp(v0, v1, t) {
    return ((1 - t) * v0) + (t * v1);
  }

  /**
   * Resample the input arrays using bilinear interpolation.
   * @param {TypedArray[]} valueArrays The input arrays to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @returns {TypedArray[]} The resampled rasters
   */
  function resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight) {
    const relX = inWidth / outWidth;
    const relY = inHeight / outHeight;

    return valueArrays.map((array) => {
      const newArray = copyNewSize(array, outWidth, outHeight);
      for (let y = 0; y < outHeight; ++y) {
        const rawY = relY * y;

        const yl = Math.floor(rawY);
        const yh = Math.min(Math.ceil(rawY), (inHeight - 1));

        for (let x = 0; x < outWidth; ++x) {
          const rawX = relX * x;
          const tx = rawX % 1;

          const xl = Math.floor(rawX);
          const xh = Math.min(Math.ceil(rawX), (inWidth - 1));

          const ll = array[(yl * inWidth) + xl];
          const hl = array[(yl * inWidth) + xh];
          const lh = array[(yh * inWidth) + xl];
          const hh = array[(yh * inWidth) + xh];

          const value = lerp(
            lerp(ll, hl, tx),
            lerp(lh, hh, tx),
            rawY % 1,
          );
          newArray[(y * outWidth) + x] = value;
        }
      }
      return newArray;
    });
  }

  /**
   * Resample the input arrays using the selected resampling method.
   * @param {TypedArray[]} valueArrays The input arrays to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @param {string} [method = 'nearest'] The desired resampling method
   * @returns {TypedArray[]} The resampled rasters
   */
  function resample(valueArrays, inWidth, inHeight, outWidth, outHeight, method = 'nearest') {
    switch (method.toLowerCase()) {
      case 'nearest':
        return resampleNearest(valueArrays, inWidth, inHeight, outWidth, outHeight);
      case 'bilinear':
      case 'linear':
        return resampleBilinear(valueArrays, inWidth, inHeight, outWidth, outHeight);
      default:
        throw new Error(`Unsupported resampling method: '${method}'`);
    }
  }

  /**
   * Resample the pixel interleaved input array using nearest neighbor value selection.
   * @param {TypedArray} valueArrays The input arrays to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @param {number} samples The number of samples per pixel for pixel
   *                         interleaved data
   * @returns {TypedArray} The resampled raster
   */
  function resampleNearestInterleaved(
    valueArray, inWidth, inHeight, outWidth, outHeight, samples) {
    const relX = inWidth / outWidth;
    const relY = inHeight / outHeight;

    const newArray = copyNewSize(valueArray, outWidth, outHeight, samples);
    for (let y = 0; y < outHeight; ++y) {
      const cy = Math.min(Math.round(relY * y), inHeight - 1);
      for (let x = 0; x < outWidth; ++x) {
        const cx = Math.min(Math.round(relX * x), inWidth - 1);
        for (let i = 0; i < samples; ++i) {
          const value = valueArray[(cy * inWidth * samples) + (cx * samples) + i];
          newArray[(y * outWidth * samples) + (x * samples) + i] = value;
        }
      }
    }
    return newArray;
  }

  /**
   * Resample the pixel interleaved input array using bilinear interpolation.
   * @param {TypedArray} valueArrays The input arrays to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @param {number} samples The number of samples per pixel for pixel
   *                         interleaved data
   * @returns {TypedArray} The resampled raster
   */
  function resampleBilinearInterleaved(
    valueArray, inWidth, inHeight, outWidth, outHeight, samples) {
    const relX = inWidth / outWidth;
    const relY = inHeight / outHeight;
    const newArray = copyNewSize(valueArray, outWidth, outHeight, samples);
    for (let y = 0; y < outHeight; ++y) {
      const rawY = relY * y;

      const yl = Math.floor(rawY);
      const yh = Math.min(Math.ceil(rawY), (inHeight - 1));

      for (let x = 0; x < outWidth; ++x) {
        const rawX = relX * x;
        const tx = rawX % 1;

        const xl = Math.floor(rawX);
        const xh = Math.min(Math.ceil(rawX), (inWidth - 1));

        for (let i = 0; i < samples; ++i) {
          const ll = valueArray[(yl * inWidth * samples) + (xl * samples) + i];
          const hl = valueArray[(yl * inWidth * samples) + (xh * samples) + i];
          const lh = valueArray[(yh * inWidth * samples) + (xl * samples) + i];
          const hh = valueArray[(yh * inWidth * samples) + (xh * samples) + i];

          const value = lerp(
            lerp(ll, hl, tx),
            lerp(lh, hh, tx),
            rawY % 1,
          );
          newArray[(y * outWidth * samples) + (x * samples) + i] = value;
        }
      }
    }
    return newArray;
  }

  /**
   * Resample the pixel interleaved input array using the selected resampling method.
   * @param {TypedArray} valueArray The input array to resample
   * @param {number} inWidth The width of the input rasters
   * @param {number} inHeight The height of the input rasters
   * @param {number} outWidth The desired width of the output rasters
   * @param {number} outHeight The desired height of the output rasters
   * @param {number} samples The number of samples per pixel for pixel
   *                                 interleaved data
   * @param {string} [method = 'nearest'] The desired resampling method
   * @returns {TypedArray} The resampled rasters
   */
  function resampleInterleaved(valueArray, inWidth, inHeight, outWidth, outHeight, samples, method = 'nearest') {
    switch (method.toLowerCase()) {
      case 'nearest':
        return resampleNearestInterleaved(
          valueArray, inWidth, inHeight, outWidth, outHeight, samples,
        );
      case 'bilinear':
      case 'linear':
        return resampleBilinearInterleaved(
          valueArray, inWidth, inHeight, outWidth, outHeight, samples,
        );
      default:
        throw new Error(`Unsupported resampling method: '${method}'`);
    }
  }

  /** @module geotiffimage */

  /**
   * @typedef {Object} ReadRasterOptions
   * @property {Array<number>} [window=whole window] the subset to read data from in pixels.
   * @property {Array<number>} [bbox=whole image] the subset to read data from in
   *                                           geographical coordinates.
   * @property {Array<number>} [samples=all samples] the selection of samples to read from. Default is all samples.
   * @property {boolean} [interleave=false] whether the data shall be read
   *                                             in one single array or separate
   *                                             arrays.
   * @property {Pool} [pool=null] The optional decoder pool to use.
   * @property {number} [width] The desired width of the output. When the width is not the
   *                                 same as the images, resampling will be performed.
   * @property {number} [height] The desired height of the output. When the width is not the
   *                                  same as the images, resampling will be performed.
   * @property {string} [resampleMethod='nearest'] The desired resampling method.
   * @property {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
   *                                       to be aborted
   * @property {number|number[]} [fillValue] The value to use for parts of the image
   *                                              outside of the images extent. When multiple
   *                                              samples are requested, an array of fill values
   *                                              can be passed.
   */

  /** @typedef {import("./geotiff.js").TypedArray} TypedArray */
  /** @typedef {import("./geotiff.js").ReadRasterResult} ReadRasterResult */

  function sum(array, start, end) {
    let s = 0;
    for (let i = start; i < end; ++i) {
      s += array[i];
    }
    return s;
  }

  function arrayForType(format, bitsPerSample, size) {
    switch (format) {
      case 1: // unsigned integer data
        if (bitsPerSample <= 8) {
          return new Uint8Array(size);
        } else if (bitsPerSample <= 16) {
          return new Uint16Array(size);
        } else if (bitsPerSample <= 32) {
          return new Uint32Array(size);
        }
        break;
      case 2: // twos complement signed integer data
        if (bitsPerSample === 8) {
          return new Int8Array(size);
        } else if (bitsPerSample === 16) {
          return new Int16Array(size);
        } else if (bitsPerSample === 32) {
          return new Int32Array(size);
        }
        break;
      case 3: // floating point data
        switch (bitsPerSample) {
          case 16:
          case 32:
            return new Float32Array(size);
          case 64:
            return new Float64Array(size);
        }
        break;
    }
    throw Error('Unsupported data format/bitsPerSample');
  }

  function needsNormalization(format, bitsPerSample) {
    if ((format === 1 || format === 2) && bitsPerSample <= 32 && bitsPerSample % 8 === 0) {
      return false;
    } else if (format === 3 && (bitsPerSample === 16 || bitsPerSample === 32 || bitsPerSample === 64)) {
      return false;
    }
    return true;
  }

  function normalizeArray(inBuffer, format, planarConfiguration, samplesPerPixel, bitsPerSample, tileWidth, tileHeight) {
    // const inByteArray = new Uint8Array(inBuffer);
    const view = new DataView(inBuffer);
    const outSize = planarConfiguration === 2
      ? tileHeight * tileWidth
      : tileHeight * tileWidth * samplesPerPixel;
    const samplesToTransfer = planarConfiguration === 2
      ? 1 : samplesPerPixel;
    const outArray = arrayForType(format, bitsPerSample, outSize);
    // let pixel = 0;

    const bitMask = parseInt('1'.repeat(bitsPerSample), 2);

    if (format === 1) { // unsigned integer
      // translation of https://github.com/OSGeo/gdal/blob/master/gdal/frmts/gtiff/geotiff.cpp#L7337
      let pixelBitSkip;
      // let sampleBitOffset = 0;
      if (planarConfiguration === 1) {
        pixelBitSkip = samplesPerPixel * bitsPerSample;
        // sampleBitOffset = (samplesPerPixel - 1) * bitsPerSample;
      } else {
        pixelBitSkip = bitsPerSample;
      }

      // Bits per line rounds up to next byte boundary.
      let bitsPerLine = tileWidth * pixelBitSkip;
      if ((bitsPerLine & 7) !== 0) {
        bitsPerLine = (bitsPerLine + 7) & (-8);
      }

      for (let y = 0; y < tileHeight; ++y) {
        const lineBitOffset = y * bitsPerLine;
        for (let x = 0; x < tileWidth; ++x) {
          const pixelBitOffset = lineBitOffset + (x * samplesToTransfer * bitsPerSample);
          for (let i = 0; i < samplesToTransfer; ++i) {
            const bitOffset = pixelBitOffset + (i * bitsPerSample);
            const outIndex = (((y * tileWidth) + x) * samplesToTransfer) + i;

            const byteOffset = Math.floor(bitOffset / 8);
            const innerBitOffset = bitOffset % 8;
            if (innerBitOffset + bitsPerSample <= 8) {
              outArray[outIndex] = (view.getUint8(byteOffset) >> (8 - bitsPerSample) - innerBitOffset) & bitMask;
            } else if (innerBitOffset + bitsPerSample <= 16) {
              outArray[outIndex] = (view.getUint16(byteOffset) >> (16 - bitsPerSample) - innerBitOffset) & bitMask;
            } else if (innerBitOffset + bitsPerSample <= 24) {
              const raw = (view.getUint16(byteOffset) << 8) | (view.getUint8(byteOffset + 2));
              outArray[outIndex] = (raw >> (24 - bitsPerSample) - innerBitOffset) & bitMask;
            } else {
              outArray[outIndex] = (view.getUint32(byteOffset) >> (32 - bitsPerSample) - innerBitOffset) & bitMask;
            }

            // let outWord = 0;
            // for (let bit = 0; bit < bitsPerSample; ++bit) {
            //   if (inByteArray[bitOffset >> 3]
            //     & (0x80 >> (bitOffset & 7))) {
            //     outWord |= (1 << (bitsPerSample - 1 - bit));
            //   }
            //   ++bitOffset;
            // }

            // outArray[outIndex] = outWord;
            // outArray[pixel] = outWord;
            // pixel += 1;
          }
          // bitOffset = bitOffset + pixelBitSkip - bitsPerSample;
        }
      }
    }

    return outArray.buffer;
  }

  /**
   * GeoTIFF sub-file image.
   */
  class GeoTIFFImage {
    /**
     * @constructor
     * @param {Object} fileDirectory The parsed file directory
     * @param {Object} geoKeys The parsed geo-keys
     * @param {DataView} dataView The DataView for the underlying file.
     * @param {Boolean} littleEndian Whether the file is encoded in little or big endian
     * @param {Boolean} cache Whether or not decoded tiles shall be cached
     * @param {import('./source/basesource').BaseSource} source The datasource to read from
     */
    constructor(fileDirectory, geoKeys, dataView, littleEndian, cache, source) {
      this.fileDirectory = fileDirectory;
      this.geoKeys = geoKeys;
      this.dataView = dataView;
      this.littleEndian = littleEndian;
      this.tiles = cache ? {} : null;
      this.isTiled = !fileDirectory.StripOffsets;
      const planarConfiguration = fileDirectory.PlanarConfiguration;
      this.planarConfiguration = (typeof planarConfiguration === 'undefined') ? 1 : planarConfiguration;
      if (this.planarConfiguration !== 1 && this.planarConfiguration !== 2) {
        throw new Error('Invalid planar configuration.');
      }

      this.source = source;
    }

    /**
     * Returns the associated parsed file directory.
     * @returns {Object} the parsed file directory
     */
    getFileDirectory() {
      return this.fileDirectory;
    }

    /**
     * Returns the associated parsed geo keys.
     * @returns {Object} the parsed geo keys
     */
    getGeoKeys() {
      return this.geoKeys;
    }

    /**
     * Returns the width of the image.
     * @returns {Number} the width of the image
     */
    getWidth() {
      return this.fileDirectory.ImageWidth;
    }

    /**
     * Returns the height of the image.
     * @returns {Number} the height of the image
     */
    getHeight() {
      return this.fileDirectory.ImageLength;
    }

    /**
     * Returns the number of samples per pixel.
     * @returns {Number} the number of samples per pixel
     */
    getSamplesPerPixel() {
      return typeof this.fileDirectory.SamplesPerPixel !== 'undefined'
        ? this.fileDirectory.SamplesPerPixel : 1;
    }

    /**
     * Returns the width of each tile.
     * @returns {Number} the width of each tile
     */
    getTileWidth() {
      return this.isTiled ? this.fileDirectory.TileWidth : this.getWidth();
    }

    /**
     * Returns the height of each tile.
     * @returns {Number} the height of each tile
     */
    getTileHeight() {
      if (this.isTiled) {
        return this.fileDirectory.TileLength;
      }
      if (typeof this.fileDirectory.RowsPerStrip !== 'undefined') {
        return Math.min(this.fileDirectory.RowsPerStrip, this.getHeight());
      }
      return this.getHeight();
    }

    getBlockWidth() {
      return this.getTileWidth();
    }

    getBlockHeight(y) {
      if (this.isTiled || (y + 1) * this.getTileHeight() <= this.getHeight()) {
        return this.getTileHeight();
      } else {
        return this.getHeight() - (y * this.getTileHeight());
      }
    }

    /**
     * Calculates the number of bytes for each pixel across all samples. Only full
     * bytes are supported, an exception is thrown when this is not the case.
     * @returns {Number} the bytes per pixel
     */
    getBytesPerPixel() {
      let bytes = 0;
      for (let i = 0; i < this.fileDirectory.BitsPerSample.length; ++i) {
        bytes += this.getSampleByteSize(i);
      }
      return bytes;
    }

    getSampleByteSize(i) {
      if (i >= this.fileDirectory.BitsPerSample.length) {
        throw new RangeError(`Sample index ${i} is out of range.`);
      }
      return Math.ceil(this.fileDirectory.BitsPerSample[i] / 8);
    }

    getReaderForSample(sampleIndex) {
      const format = this.fileDirectory.SampleFormat
        ? this.fileDirectory.SampleFormat[sampleIndex] : 1;
      const bitsPerSample = this.fileDirectory.BitsPerSample[sampleIndex];
      switch (format) {
        case 1: // unsigned integer data
          if (bitsPerSample <= 8) {
            return DataView.prototype.getUint8;
          } else if (bitsPerSample <= 16) {
            return DataView.prototype.getUint16;
          } else if (bitsPerSample <= 32) {
            return DataView.prototype.getUint32;
          }
          break;
        case 2: // twos complement signed integer data
          if (bitsPerSample <= 8) {
            return DataView.prototype.getInt8;
          } else if (bitsPerSample <= 16) {
            return DataView.prototype.getInt16;
          } else if (bitsPerSample <= 32) {
            return DataView.prototype.getInt32;
          }
          break;
        case 3:
          switch (bitsPerSample) {
            case 16:
              return function (offset, littleEndian) {
                return getFloat16(this, offset, littleEndian);
              };
            case 32:
              return DataView.prototype.getFloat32;
            case 64:
              return DataView.prototype.getFloat64;
          }
          break;
      }
      throw Error('Unsupported data format/bitsPerSample');
    }

    getSampleFormat(sampleIndex = 0) {
      return this.fileDirectory.SampleFormat
        ? this.fileDirectory.SampleFormat[sampleIndex] : 1;
    }

    getBitsPerSample(sampleIndex = 0) {
      return this.fileDirectory.BitsPerSample[sampleIndex];
    }

    getArrayForSample(sampleIndex, size) {
      const format = this.getSampleFormat(sampleIndex);
      const bitsPerSample = this.getBitsPerSample(sampleIndex);
      return arrayForType(format, bitsPerSample, size);
    }

    /**
     * Returns the decoded strip or tile.
     * @param {Number} x the strip or tile x-offset
     * @param {Number} y the tile y-offset (0 for stripped images)
     * @param {Number} sample the sample to get for separated samples
     * @param {import("./geotiff").Pool|import("./geotiff").BaseDecoder} poolOrDecoder the decoder or decoder pool
     * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
     *                               to be aborted
     * @returns {Promise.<ArrayBuffer>}
     */
    async getTileOrStrip(x, y, sample, poolOrDecoder, signal) {
      const numTilesPerRow = Math.ceil(this.getWidth() / this.getTileWidth());
      const numTilesPerCol = Math.ceil(this.getHeight() / this.getTileHeight());
      let index;
      const { tiles } = this;
      if (this.planarConfiguration === 1) {
        index = (y * numTilesPerRow) + x;
      } else if (this.planarConfiguration === 2) {
        index = (sample * numTilesPerRow * numTilesPerCol) + (y * numTilesPerRow) + x;
      }

      let offset;
      let byteCount;
      if (this.isTiled) {
        offset = this.fileDirectory.TileOffsets[index];
        byteCount = this.fileDirectory.TileByteCounts[index];
      } else {
        offset = this.fileDirectory.StripOffsets[index];
        byteCount = this.fileDirectory.StripByteCounts[index];
      }
      const slice = (await this.source.fetch([{ offset, length: byteCount }], signal))[0];

      let request;
      if (tiles === null || !tiles[index]) {
      // resolve each request by potentially applying array normalization
        request = (async () => {
          let data = await poolOrDecoder.decode(this.fileDirectory, slice);
          const sampleFormat = this.getSampleFormat();
          const bitsPerSample = this.getBitsPerSample();
          if (needsNormalization(sampleFormat, bitsPerSample)) {
            data = normalizeArray(
              data,
              sampleFormat,
              this.planarConfiguration,
              this.getSamplesPerPixel(),
              bitsPerSample,
              this.getTileWidth(),
              this.getBlockHeight(y),
            );
          }
          return data;
        })();

        // set the cache
        if (tiles !== null) {
          tiles[index] = request;
        }
      } else {
        // get from the cache
        request = tiles[index];
      }

      // cache the tile request
      return { x, y, sample, data: await request };
    }

    /**
     * Internal read function.
     * @private
     * @param {Array} imageWindow The image window in pixel coordinates
     * @param {Array} samples The selected samples (0-based indices)
     * @param {TypedArray|TypedArray[]} valueArrays The array(s) to write into
     * @param {Boolean} interleave Whether or not to write in an interleaved manner
     * @param {import("./geotiff").Pool|AbstractDecoder} poolOrDecoder the decoder or decoder pool
     * @param {number} width the width of window to be read into
     * @param {number} height the height of window to be read into
     * @param {number} resampleMethod the resampling method to be used when interpolating
     * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
     *                               to be aborted
     * @returns {Promise<ReadRasterResult>}
     */
    async _readRaster(imageWindow, samples, valueArrays, interleave, poolOrDecoder, width,
      height, resampleMethod, signal) {
      const tileWidth = this.getTileWidth();
      const tileHeight = this.getTileHeight();
      const imageWidth = this.getWidth();
      const imageHeight = this.getHeight();

      const minXTile = Math.max(Math.floor(imageWindow[0] / tileWidth), 0);
      const maxXTile = Math.min(
        Math.ceil(imageWindow[2] / tileWidth),
        Math.ceil(imageWidth / tileWidth),
      );
      const minYTile = Math.max(Math.floor(imageWindow[1] / tileHeight), 0);
      const maxYTile = Math.min(
        Math.ceil(imageWindow[3] / tileHeight),
        Math.ceil(imageHeight / tileHeight),
      );
      const windowWidth = imageWindow[2] - imageWindow[0];

      let bytesPerPixel = this.getBytesPerPixel();

      const srcSampleOffsets = [];
      const sampleReaders = [];
      for (let i = 0; i < samples.length; ++i) {
        if (this.planarConfiguration === 1) {
          srcSampleOffsets.push(sum(this.fileDirectory.BitsPerSample, 0, samples[i]) / 8);
        } else {
          srcSampleOffsets.push(0);
        }
        sampleReaders.push(this.getReaderForSample(samples[i]));
      }

      const promises = [];
      const { littleEndian } = this;

      for (let yTile = minYTile; yTile < maxYTile; ++yTile) {
        for (let xTile = minXTile; xTile < maxXTile; ++xTile) {
          let getPromise;
          if (this.planarConfiguration === 1) {
            getPromise = this.getTileOrStrip(xTile, yTile, 0, poolOrDecoder, signal);
          }
          for (let sampleIndex = 0; sampleIndex < samples.length; ++sampleIndex) {
            const si = sampleIndex;
            const sample = samples[sampleIndex];
            if (this.planarConfiguration === 2) {
              bytesPerPixel = this.getSampleByteSize(sample);
              getPromise = this.getTileOrStrip(xTile, yTile, sample, poolOrDecoder, signal);
            }
            const promise = getPromise.then((tile) => {
              const buffer = tile.data;
              const dataView = new DataView(buffer);
              const blockHeight = this.getBlockHeight(tile.y);
              const firstLine = tile.y * tileHeight;
              const firstCol = tile.x * tileWidth;
              const lastLine = firstLine + blockHeight;
              const lastCol = (tile.x + 1) * tileWidth;
              const reader = sampleReaders[si];

              const ymax = Math.min(blockHeight, blockHeight - (lastLine - imageWindow[3]), imageHeight - firstLine);
              const xmax = Math.min(tileWidth, tileWidth - (lastCol - imageWindow[2]), imageWidth - firstCol);

              for (let y = Math.max(0, imageWindow[1] - firstLine); y < ymax; ++y) {
                for (let x = Math.max(0, imageWindow[0] - firstCol); x < xmax; ++x) {
                  const pixelOffset = ((y * tileWidth) + x) * bytesPerPixel;
                  const value = reader.call(
                    dataView, pixelOffset + srcSampleOffsets[si], littleEndian,
                  );
                  let windowCoordinate;
                  if (interleave) {
                    windowCoordinate = ((y + firstLine - imageWindow[1]) * windowWidth * samples.length)
                      + ((x + firstCol - imageWindow[0]) * samples.length)
                      + si;
                    valueArrays[windowCoordinate] = value;
                  } else {
                    windowCoordinate = (
                      (y + firstLine - imageWindow[1]) * windowWidth
                    ) + x + firstCol - imageWindow[0];
                    valueArrays[si][windowCoordinate] = value;
                  }
                }
              }
            });
            promises.push(promise);
          }
        }
      }
      await Promise.all(promises);

      if ((width && (imageWindow[2] - imageWindow[0]) !== width)
          || (height && (imageWindow[3] - imageWindow[1]) !== height)) {
        let resampled;
        if (interleave) {
          resampled = resampleInterleaved(
            valueArrays,
            imageWindow[2] - imageWindow[0],
            imageWindow[3] - imageWindow[1],
            width, height,
            samples.length,
            resampleMethod,
          );
        } else {
          resampled = resample(
            valueArrays,
            imageWindow[2] - imageWindow[0],
            imageWindow[3] - imageWindow[1],
            width, height,
            resampleMethod,
          );
        }
        resampled.width = width;
        resampled.height = height;
        return resampled;
      }

      valueArrays.width = width || imageWindow[2] - imageWindow[0];
      valueArrays.height = height || imageWindow[3] - imageWindow[1];

      return valueArrays;
    }

    /**
     * Reads raster data from the image. This function reads all selected samples
     * into separate arrays of the correct type for that sample or into a single
     * combined array when `interleave` is set. When provided, only a subset
     * of the raster is read for each sample.
     *
     * @param {ReadRasterOptions} [options={}] optional parameters
     * @returns {Promise<ReadRasterResult>} the decoded arrays as a promise
     */
    async readRasters({
      window: wnd, samples = [], interleave, pool = null,
      width, height, resampleMethod, fillValue, signal,
    } = {}) {
      const imageWindow = wnd || [0, 0, this.getWidth(), this.getHeight()];

      // check parameters
      if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) {
        throw new Error('Invalid subsets');
      }

      const imageWindowWidth = imageWindow[2] - imageWindow[0];
      const imageWindowHeight = imageWindow[3] - imageWindow[1];
      const numPixels = imageWindowWidth * imageWindowHeight;
      const samplesPerPixel = this.getSamplesPerPixel();

      if (!samples || !samples.length) {
        for (let i = 0; i < samplesPerPixel; ++i) {
          samples.push(i);
        }
      } else {
        for (let i = 0; i < samples.length; ++i) {
          if (samples[i] >= samplesPerPixel) {
            return Promise.reject(new RangeError(`Invalid sample index '${samples[i]}'.`));
          }
        }
      }
      let valueArrays;
      if (interleave) {
        const format = this.fileDirectory.SampleFormat
          ? Math.max.apply(null, this.fileDirectory.SampleFormat) : 1;
        const bitsPerSample = Math.max.apply(null, this.fileDirectory.BitsPerSample);
        valueArrays = arrayForType(format, bitsPerSample, numPixels * samples.length);
        if (fillValue) {
          valueArrays.fill(fillValue);
        }
      } else {
        valueArrays = [];
        for (let i = 0; i < samples.length; ++i) {
          const valueArray = this.getArrayForSample(samples[i], numPixels);
          if (Array.isArray(fillValue) && i < fillValue.length) {
            valueArray.fill(fillValue[i]);
          } else if (fillValue && !Array.isArray(fillValue)) {
            valueArray.fill(fillValue);
          }
          valueArrays.push(valueArray);
        }
      }

      const poolOrDecoder = pool || await getDecoder(this.fileDirectory);

      const result = await this._readRaster(
        imageWindow, samples, valueArrays, interleave, poolOrDecoder, width, height, resampleMethod, signal,
      );
      return result;
    }

    /**
     * Reads raster data from the image as RGB. The result is always an
     * interleaved typed array.
     * Colorspaces other than RGB will be transformed to RGB, color maps expanded.
     * When no other method is applicable, the first sample is used to produce a
     * grayscale image.
     * When provided, only a subset of the raster is read for each sample.
     *
     * @param {Object} [options] optional parameters
     * @param {Array<number>} [options.window] the subset to read data from in pixels.
     * @param {boolean} [options.interleave=true] whether the data shall be read
     *                                             in one single array or separate
     *                                             arrays.
     * @param {import("./geotiff").Pool} [options.pool=null] The optional decoder pool to use.
     * @param {number} [options.width] The desired width of the output. When the width is no the
     *                                 same as the images, resampling will be performed.
     * @param {number} [options.height] The desired height of the output. When the width is no the
     *                                  same as the images, resampling will be performed.
     * @param {string} [options.resampleMethod='nearest'] The desired resampling method.
     * @param {boolean} [options.enableAlpha=false] Enable reading alpha channel if present.
     * @param {AbortSignal} [options.signal] An AbortSignal that may be signalled if the request is
     *                                       to be aborted
     * @returns {Promise<ReadRasterResult>} the RGB array as a Promise
     */
    async readRGB({ window, interleave = true, pool = null, width, height,
      resampleMethod, enableAlpha = false, signal } = {}) {
      const imageWindow = window || [0, 0, this.getWidth(), this.getHeight()];

      // check parameters
      if (imageWindow[0] > imageWindow[2] || imageWindow[1] > imageWindow[3]) {
        throw new Error('Invalid subsets');
      }

      const pi = this.fileDirectory.PhotometricInterpretation;

      if (pi === photometricInterpretations.RGB) {
        let s = [0, 1, 2];
        if ((!(this.fileDirectory.ExtraSamples === ExtraSamplesValues.Unspecified)) && enableAlpha) {
          s = [];
          for (let i = 0; i < this.fileDirectory.BitsPerSample.length; i += 1) {
            s.push(i);
          }
        }
        return this.readRasters({
          window,
          interleave,
          samples: s,
          pool,
          width,
          height,
          resampleMethod,
          signal,
        });
      }

      let samples;
      switch (pi) {
        case photometricInterpretations.WhiteIsZero:
        case photometricInterpretations.BlackIsZero:
        case photometricInterpretations.Palette:
          samples = [0];
          break;
        case photometricInterpretations.CMYK:
          samples = [0, 1, 2, 3];
          break;
        case photometricInterpretations.YCbCr:
        case photometricInterpretations.CIELab:
          samples = [0, 1, 2];
          break;
        default:
          throw new Error('Invalid or unsupported photometric interpretation.');
      }

      const subOptions = {
        window: imageWindow,
        interleave: true,
        samples,
        pool,
        width,
        height,
        resampleMethod,
        signal,
      };
      const { fileDirectory } = this;
      const raster = await this.readRasters(subOptions);

      const max = 2 ** this.fileDirectory.BitsPerSample[0];
      let data;
      switch (pi) {
        case photometricInterpretations.WhiteIsZero:
          data = fromWhiteIsZero(raster, max);
          break;
        case photometricInterpretations.BlackIsZero:
          data = fromBlackIsZero(raster, max);
          break;
        case photometricInterpretations.Palette:
          data = fromPalette(raster, fileDirectory.ColorMap);
          break;
        case photometricInterpretations.CMYK:
          data = fromCMYK(raster);
          break;
        case photometricInterpretations.YCbCr:
          data = fromYCbCr(raster);
          break;
        case photometricInterpretations.CIELab:
          data = fromCIELab(raster);
          break;
        default:
          throw new Error('Unsupported photometric interpretation.');
      }

      // if non-interleaved data is requested, we must split the channels
      // into their respective arrays
      if (!interleave) {
        const red = new Uint8Array(data.length / 3);
        const green = new Uint8Array(data.length / 3);
        const blue = new Uint8Array(data.length / 3);
        for (let i = 0, j = 0; i < data.length; i += 3, ++j) {
          red[j] = data[i];
          green[j] = data[i + 1];
          blue[j] = data[i + 2];
        }
        data = [red, green, blue];
      }

      data.width = raster.width;
      data.height = raster.height;
      return data;
    }

    /**
     * Returns an array of tiepoints.
     * @returns {Object[]}
     */
    getTiePoints() {
      if (!this.fileDirectory.ModelTiepoint) {
        return [];
      }

      const tiePoints = [];
      for (let i = 0; i < this.fileDirectory.ModelTiepoint.length; i += 6) {
        tiePoints.push({
          i: this.fileDirectory.ModelTiepoint[i],
          j: this.fileDirectory.ModelTiepoint[i + 1],
          k: this.fileDirectory.ModelTiepoint[i + 2],
          x: this.fileDirectory.ModelTiepoint[i + 3],
          y: this.fileDirectory.ModelTiepoint[i + 4],
          z: this.fileDirectory.ModelTiepoint[i + 5],
        });
      }
      return tiePoints;
    }

    /**
     * Returns the parsed GDAL metadata items.
     *
     * If sample is passed to null, dataset-level metadata will be returned.
     * Otherwise only metadata specific to the provided sample will be returned.
     *
     * @param {number} [sample=null] The sample index.
     * @returns {Object}
     */
    getGDALMetadata(sample = null) {
      const metadata = {};
      if (!this.fileDirectory.GDAL_METADATA) {
        return null;
      }
      const string = this.fileDirectory.GDAL_METADATA;

      let items = findTagsByName(string, 'Item');

      if (sample === null) {
        items = items.filter((item) => getAttribute(item, 'sample') === undefined);
      } else {
        items = items.filter((item) => Number(getAttribute(item, 'sample')) === sample);
      }

      for (let i = 0; i < items.length; ++i) {
        const item = items[i];
        metadata[getAttribute(item, 'name')] = item.inner;
      }
      return metadata;
    }

    /**
     * Returns the GDAL nodata value
     * @returns {number|null}
     */
    getGDALNoData() {
      if (!this.fileDirectory.GDAL_NODATA) {
        return null;
      }
      const string = this.fileDirectory.GDAL_NODATA;
      return Number(string.substring(0, string.length - 1));
    }

    /**
     * Returns the image origin as a XYZ-vector. When the image has no affine
     * transformation, then an exception is thrown.
     * @returns {Array<number>} The origin as a vector
     */
    getOrigin() {
      const tiePoints = this.fileDirectory.ModelTiepoint;
      const modelTransformation = this.fileDirectory.ModelTransformation;
      if (tiePoints && tiePoints.length === 6) {
        return [
          tiePoints[3],
          tiePoints[4],
          tiePoints[5],
        ];
      }
      if (modelTransformation) {
        return [
          modelTransformation[3],
          modelTransformation[7],
          modelTransformation[11],
        ];
      }
      throw new Error('The image does not have an affine transformation.');
    }

    /**
     * Returns the image resolution as a XYZ-vector. When the image has no affine
     * transformation, then an exception is thrown.
     * @param {GeoTIFFImage} [referenceImage=null] A reference image to calculate the resolution from
     *                                             in cases when the current image does not have the
     *                                             required tags on its own.
     * @returns {Array<number>} The resolution as a vector
     */
    getResolution(referenceImage = null) {
      const modelPixelScale = this.fileDirectory.ModelPixelScale;
      const modelTransformation = this.fileDirectory.ModelTransformation;

      if (modelPixelScale) {
        return [
          modelPixelScale[0],
          -modelPixelScale[1],
          modelPixelScale[2],
        ];
      }
      if (modelTransformation) {
        if (modelTransformation[1] === 0 && modelTransformation[4] === 0) {
          return [
            modelTransformation[0],
            -modelTransformation[5],
            modelTransformation[10],
          ];
        }
        return [
          Math.sqrt((modelTransformation[0] * modelTransformation[0])
            + (modelTransformation[4] * modelTransformation[4])),
          -Math.sqrt((modelTransformation[1] * modelTransformation[1])
            + (modelTransformation[5] * modelTransformation[5])),
          modelTransformation[10]];
      }

      if (referenceImage) {
        const [refResX, refResY, refResZ] = referenceImage.getResolution();
        return [
          refResX * referenceImage.getWidth() / this.getWidth(),
          refResY * referenceImage.getHeight() / this.getHeight(),
          refResZ * referenceImage.getWidth() / this.getWidth(),
        ];
      }

      throw new Error('The image does not have an affine transformation.');
    }

    /**
     * Returns whether or not the pixels of the image depict an area (or point).
     * @returns {Boolean} Whether the pixels are a point
     */
    pixelIsArea() {
      return this.geoKeys.GTRasterTypeGeoKey === 1;
    }

    /**
     * Returns the image bounding box as an array of 4 values: min-x, min-y,
     * max-x and max-y. When the image has no affine transformation, then an
     * exception is thrown.
     * @param {boolean} [tilegrid=false] If true return extent for a tilegrid
     *                                   without adjustment for ModelTransformation.
     * @returns {Array<number>} The bounding box
     */
    getBoundingBox(tilegrid = false) {
      const height = this.getHeight();
      const width = this.getWidth();

      if (this.fileDirectory.ModelTransformation && !tilegrid) {
        // eslint-disable-next-line no-unused-vars
        const [a, b, c, d, e, f, g, h] = this.fileDirectory.ModelTransformation;

        const corners = [
          [0, 0],
          [0, height],
          [width, 0],
          [width, height],
        ];

        const projected = corners.map(([I, J]) => [
          d + (a * I) + (b * J),
          h + (e * I) + (f * J),
        ]);

        const xs = projected.map((pt) => pt[0]);
        const ys = projected.map((pt) => pt[1]);

        return [
          Math.min(...xs),
          Math.min(...ys),
          Math.max(...xs),
          Math.max(...ys),
        ];
      } else {
        const origin = this.getOrigin();
        const resolution = this.getResolution();

        const x1 = origin[0];
        const y1 = origin[1];

        const x2 = x1 + (resolution[0] * width);
        const y2 = y1 + (resolution[1] * height);

        return [
          Math.min(x1, x2),
          Math.min(y1, y2),
          Math.max(x1, x2),
          Math.max(y1, y2),
        ];
      }
    }
  }

  class DataView64 {
    constructor(arrayBuffer) {
      this._dataView = new DataView(arrayBuffer);
    }

    get buffer() {
      return this._dataView.buffer;
    }

    getUint64(offset, littleEndian) {
      const left = this.getUint32(offset, littleEndian);
      const right = this.getUint32(offset + 4, littleEndian);
      let combined;
      if (littleEndian) {
        combined = left + ((2 ** 32) * right);
        if (!Number.isSafeInteger(combined)) {
          throw new Error(
            `${combined} exceeds MAX_SAFE_INTEGER. `
            + 'Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues',
          );
        }
        return combined;
      }
      combined = ((2 ** 32) * left) + right;
      if (!Number.isSafeInteger(combined)) {
        throw new Error(
          `${combined} exceeds MAX_SAFE_INTEGER. `
          + 'Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues',
        );
      }

      return combined;
    }

    // adapted from https://stackoverflow.com/a/55338384/8060591
    getInt64(offset, littleEndian) {
      let value = 0;
      const isNegative = (this._dataView.getUint8(offset + (littleEndian ? 7 : 0)) & 0x80) > 0;
      let carrying = true;
      for (let i = 0; i < 8; i++) {
        let byte = this._dataView.getUint8(offset + (littleEndian ? i : 7 - i));
        if (isNegative) {
          if (carrying) {
            if (byte !== 0x00) {
              byte = ~(byte - 1) & 0xff;
              carrying = false;
            }
          } else {
            byte = ~byte & 0xff;
          }
        }
        value += byte * (256 ** i);
      }
      if (isNegative) {
        value = -value;
      }
      return value;
    }

    getUint8(offset, littleEndian) {
      return this._dataView.getUint8(offset, littleEndian);
    }

    getInt8(offset, littleEndian) {
      return this._dataView.getInt8(offset, littleEndian);
    }

    getUint16(offset, littleEndian) {
      return this._dataView.getUint16(offset, littleEndian);
    }

    getInt16(offset, littleEndian) {
      return this._dataView.getInt16(offset, littleEndian);
    }

    getUint32(offset, littleEndian) {
      return this._dataView.getUint32(offset, littleEndian);
    }

    getInt32(offset, littleEndian) {
      return this._dataView.getInt32(offset, littleEndian);
    }

    getFloat16(offset, littleEndian) {
      return getFloat16(this._dataView, offset, littleEndian);
    }

    getFloat32(offset, littleEndian) {
      return this._dataView.getFloat32(offset, littleEndian);
    }

    getFloat64(offset, littleEndian) {
      return this._dataView.getFloat64(offset, littleEndian);
    }
  }

  class DataSlice {
    constructor(arrayBuffer, sliceOffset, littleEndian, bigTiff) {
      this._dataView = new DataView(arrayBuffer);
      this._sliceOffset = sliceOffset;
      this._littleEndian = littleEndian;
      this._bigTiff = bigTiff;
    }

    get sliceOffset() {
      return this._sliceOffset;
    }

    get sliceTop() {
      return this._sliceOffset + this.buffer.byteLength;
    }

    get littleEndian() {
      return this._littleEndian;
    }

    get bigTiff() {
      return this._bigTiff;
    }

    get buffer() {
      return this._dataView.buffer;
    }

    covers(offset, length) {
      return this.sliceOffset <= offset && this.sliceTop >= offset + length;
    }

    readUint8(offset) {
      return this._dataView.getUint8(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readInt8(offset) {
      return this._dataView.getInt8(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readUint16(offset) {
      return this._dataView.getUint16(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readInt16(offset) {
      return this._dataView.getInt16(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readUint32(offset) {
      return this._dataView.getUint32(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readInt32(offset) {
      return this._dataView.getInt32(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readFloat32(offset) {
      return this._dataView.getFloat32(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readFloat64(offset) {
      return this._dataView.getFloat64(
        offset - this._sliceOffset, this._littleEndian,
      );
    }

    readUint64(offset) {
      const left = this.readUint32(offset);
      const right = this.readUint32(offset + 4);
      let combined;
      if (this._littleEndian) {
        combined = left + ((2 ** 32) * right);
        if (!Number.isSafeInteger(combined)) {
          throw new Error(
            `${combined} exceeds MAX_SAFE_INTEGER. `
            + 'Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues',
          );
        }
        return combined;
      }
      combined = ((2 ** 32) * left) + right;
      if (!Number.isSafeInteger(combined)) {
        throw new Error(
          `${combined} exceeds MAX_SAFE_INTEGER. `
          + 'Precision may be lost. Please report if you get this message to https://github.com/geotiffjs/geotiff.js/issues',
        );
      }

      return combined;
    }

    // adapted from https://stackoverflow.com/a/55338384/8060591
    readInt64(offset) {
      let value = 0;
      const isNegative = (this._dataView.getUint8(offset + (this._littleEndian ? 7 : 0)) & 0x80)
        > 0;
      let carrying = true;
      for (let i = 0; i < 8; i++) {
        let byte = this._dataView.getUint8(
          offset + (this._littleEndian ? i : 7 - i),
        );
        if (isNegative) {
          if (carrying) {
            if (byte !== 0x00) {
              byte = ~(byte - 1) & 0xff;
              carrying = false;
            }
          } else {
            byte = ~byte & 0xff;
          }
        }
        value += byte * (256 ** i);
      }
      if (isNegative) {
        value = -value;
      }
      return value;
    }

    readOffset(offset) {
      if (this._bigTiff) {
        return this.readUint64(offset);
      }
      return this.readUint32(offset);
    }
  }

  const defaultPoolSize = typeof navigator !== 'undefined' ? (navigator.hardwareConcurrency || 2) : 2;

  /**
   * @module pool
   */

  /**
   * Pool for workers to decode chunks of the images.
   */
  class Pool {
    /**
     * @constructor
     * @param {Number} [size] The size of the pool. Defaults to the number of CPUs
     *                      available. When this parameter is `null` or 0, then the
     *                      decoding will be done in the main thread.
     * @param {function(): Worker} [createWorker] A function that creates the decoder worker.
     * Defaults to a worker with all decoders that ship with geotiff.js. The `createWorker()`
     * function is expected to return a `Worker` compatible with Web Workers. For code that
     * runs in Node, [web-worker](https://www.npmjs.com/package/web-worker) is a good choice.
     *
     * A worker that uses a custom lzw decoder would look like this `my-custom-worker.js` file:
     * ```js
     * import { addDecoder, getDecoder } from 'geotiff';
     * addDecoder(5, () => import ('./my-custom-lzw').then((m) => m.default));
     * self.addEventListener('message', async (e) => {
     *   const { id, fileDirectory, buffer } = e.data;
     *   const decoder = await getDecoder(fileDirectory);
     *   const decoded = await decoder.decode(fileDirectory, buffer);
     *   self.postMessage({ decoded, id }, [decoded]);
     * });
     * ```
     * The way the above code is built into a worker by the `createWorker()` function
     * depends on the used bundler. For most bundlers, something like this will work:
     * ```js
     * function createWorker() {
     *   return new Worker(new URL('./my-custom-worker.js', import.meta.url));
     * }
     * ```
     */
    constructor(size = defaultPoolSize, createWorker) {
      this.workers = null;
      this._awaitingDecoder = null;
      this.size = size;
      this.messageId = 0;
      if (size) {
        this._awaitingDecoder = createWorker ? Promise.resolve(createWorker) : new Promise((resolve) => {
          Promise.resolve().then(function () { return decoder; }).then((module) => {
            resolve(module.create);
          });
        });
        this._awaitingDecoder.then((create) => {
          this._awaitingDecoder = null;
          this.workers = [];
          for (let i = 0; i < size; i++) {
            this.workers.push({ worker: create(), idle: true });
          }
        });
      }
    }

    /**
     * Decode the given block of bytes with the set compression method.
     * @param {ArrayBuffer} buffer the array buffer of bytes to decode.
     * @returns {Promise<ArrayBuffer>} the decoded result as a `Promise`
     */
    async decode(fileDirectory, buffer) {
      if (this._awaitingDecoder) {
        await this._awaitingDecoder;
      }
      return this.size === 0
        ? getDecoder(fileDirectory).then((decoder) => decoder.decode(fileDirectory, buffer))
        : new Promise((resolve) => {
          const worker = this.workers.find((candidate) => candidate.idle)
            || this.workers[Math.floor(Math.random() * this.size)];
          worker.idle = false;
          const id = this.messageId++;
          const onMessage = (e) => {
            if (e.data.id === id) {
              worker.idle = true;
              resolve(e.data.decoded);
              worker.worker.removeEventListener('message', onMessage);
            }
          };
          worker.worker.addEventListener('message', onMessage);
          worker.worker.postMessage({ fileDirectory, buffer, id }, [buffer]);
        });
    }

    destroy() {
      if (this.workers) {
        this.workers.forEach((worker) => {
          worker.worker.terminate();
        });
        this.workers = null;
      }
    }
  }

  const CRLFCRLF = '\r\n\r\n';

  /*
   * Shim for 'Object.fromEntries'
   */
  function itemsToObject(items) {
    if (typeof Object.fromEntries !== 'undefined') {
      return Object.fromEntries(items);
    }
    const obj = {};
    for (const [key, value] of items) {
      obj[key.toLowerCase()] = value;
    }
    return obj;
  }

  /**
   * Parse HTTP headers from a given string.
   * @param {String} text the text to parse the headers from
   * @returns {Object} the parsed headers with lowercase keys
   */
  function parseHeaders(text) {
    const items = text
      .split('\r\n')
      .map((line) => {
        const kv = line.split(':').map((str) => str.trim());
        kv[0] = kv[0].toLowerCase();
        return kv;
      });

    return itemsToObject(items);
  }

  /**
   * Parse a 'Content-Type' header value to the content-type and parameters
   * @param {String} rawContentType the raw string to parse from
   * @returns {Object} the parsed content type with the fields: type and params
   */
  function parseContentType(rawContentType) {
    const [type, ...rawParams] = rawContentType.split(';').map((s) => s.trim());
    const paramsItems = rawParams.map((param) => param.split('='));
    return { type, params: itemsToObject(paramsItems) };
  }

  /**
   * Parse a 'Content-Range' header value to its start, end, and total parts
   * @param {String} rawContentRange the raw string to parse from
   * @returns {Object} the parsed parts
   */
  function parseContentRange(rawContentRange) {
    let start;
    let end;
    let total;

    if (rawContentRange) {
      [, start, end, total] = rawContentRange.match(/bytes (\d+)-(\d+)\/(\d+)/);
      start = parseInt(start, 10);
      end = parseInt(end, 10);
      total = parseInt(total, 10);
    }

    return { start, end, total };
  }

  /**
   * Parses a list of byteranges from the given 'multipart/byteranges' HTTP response.
   * Each item in the list has the following properties:
   * - headers: the HTTP headers
   * - data: the sliced ArrayBuffer for that specific part
   * - offset: the offset of the byterange within its originating file
   * - length: the length of the byterange
   * @param {ArrayBuffer} responseArrayBuffer the response to be parsed and split
   * @param {String} boundary the boundary string used to split the sections
   * @returns {Object[]} the parsed byteranges
   */
  function parseByteRanges(responseArrayBuffer, boundary) {
    let offset = null;
    const decoder = new TextDecoder('ascii');
    const out = [];

    const startBoundary = `--${boundary}`;
    const endBoundary = `${startBoundary}--`;

    // search for the initial boundary, may be offset by some bytes
    // TODO: more efficient to check for `--` in bytes directly
    for (let i = 0; i < 10; ++i) {
      const text = decoder.decode(
        new Uint8Array(responseArrayBuffer, i, startBoundary.length),
      );
      if (text === startBoundary) {
        offset = i;
      }
    }

    if (offset === null) {
      throw new Error('Could not find initial boundary');
    }

    while (offset < responseArrayBuffer.byteLength) {
      const text = decoder.decode(
        new Uint8Array(responseArrayBuffer, offset,
          Math.min(startBoundary.length + 1024, responseArrayBuffer.byteLength - offset),
        ),
      );

      // break if we arrived at the end
      if (text.length === 0 || text.startsWith(endBoundary)) {
        break;
      }

      // assert that we are actually dealing with a byterange and are at the correct offset
      if (!text.startsWith(startBoundary)) {
        throw new Error('Part does not start with boundary');
      }

      // get a substring from where we read the headers
      const innerText = text.substr(startBoundary.length + 2);

      if (innerText.length === 0) {
        break;
      }

      // find the double linebreak that denotes the end of the headers
      const endOfHeaders = innerText.indexOf(CRLFCRLF);

      // parse the headers to get the content range size
      const headers = parseHeaders(innerText.substr(0, endOfHeaders));
      const { start, end, total } = parseContentRange(headers['content-range']);

      // calculate the length of the slice and the next offset
      const startOfData = offset + startBoundary.length + endOfHeaders + CRLFCRLF.length;
      const length = parseInt(end, 10) + 1 - parseInt(start, 10);
      out.push({
        headers,
        data: responseArrayBuffer.slice(startOfData, startOfData + length),
        offset: start,
        length,
        fileSize: total,
      });

      offset = startOfData + length + 4;
    }

    return out;
  }

  /**
   * @typedef Slice
   * @property {number} offset
   * @property {number} length
   */

  class BaseSource {
    /**
     *
     * @param {Slice[]} slices
     * @returns {ArrayBuffer[]}
     */
    async fetch(slices, signal = undefined) {
      return Promise.all(
        slices.map((slice) => this.fetchSlice(slice, signal)),
      );
    }

    /**
     *
     * @param {Slice} slice
     * @returns {ArrayBuffer}
     */
    async fetchSlice(slice) {
      throw new Error(`fetching of slice ${slice} not possible, not implemented`);
    }

    /**
     * Returns the filesize if already determined and null otherwise
     */
    get fileSize() {
      return null;
    }

    async close() {
      // no-op by default
    }
  }

  class QuickLRU extends Map {
  	constructor(options = {}) {
  		super();

  		if (!(options.maxSize && options.maxSize > 0)) {
  			throw new TypeError('`maxSize` must be a number greater than 0');
  		}

  		if (typeof options.maxAge === 'number' && options.maxAge === 0) {
  			throw new TypeError('`maxAge` must be a number greater than 0');
  		}

  		// TODO: Use private class fields when ESLint supports them.
  		this.maxSize = options.maxSize;
  		this.maxAge = options.maxAge || Number.POSITIVE_INFINITY;
  		this.onEviction = options.onEviction;
  		this.cache = new Map();
  		this.oldCache = new Map();
  		this._size = 0;
  	}

  	// TODO: Use private class methods when targeting Node.js 16.
  	_emitEvictions(cache) {
  		if (typeof this.onEviction !== 'function') {
  			return;
  		}

  		for (const [key, item] of cache) {
  			this.onEviction(key, item.value);
  		}
  	}

  	_deleteIfExpired(key, item) {
  		if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {
  			if (typeof this.onEviction === 'function') {
  				this.onEviction(key, item.value);
  			}

  			return this.delete(key);
  		}

  		return false;
  	}

  	_getOrDeleteIfExpired(key, item) {
  		const deleted = this._deleteIfExpired(key, item);
  		if (deleted === false) {
  			return item.value;
  		}
  	}

  	_getItemValue(key, item) {
  		return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
  	}

  	_peek(key, cache) {
  		const item = cache.get(key);

  		return this._getItemValue(key, item);
  	}

  	_set(key, value) {
  		this.cache.set(key, value);
  		this._size++;

  		if (this._size >= this.maxSize) {
  			this._size = 0;
  			this._emitEvictions(this.oldCache);
  			this.oldCache = this.cache;
  			this.cache = new Map();
  		}
  	}

  	_moveToRecent(key, item) {
  		this.oldCache.delete(key);
  		this._set(key, item);
  	}

  	* _entriesAscending() {
  		for (const item of this.oldCache) {
  			const [key, value] = item;
  			if (!this.cache.has(key)) {
  				const deleted = this._deleteIfExpired(key, value);
  				if (deleted === false) {
  					yield item;
  				}
  			}
  		}

  		for (const item of this.cache) {
  			const [key, value] = item;
  			const deleted = this._deleteIfExpired(key, value);
  			if (deleted === false) {
  				yield item;
  			}
  		}
  	}

  	get(key) {
  		if (this.cache.has(key)) {
  			const item = this.cache.get(key);

  			return this._getItemValue(key, item);
  		}

  		if (this.oldCache.has(key)) {
  			const item = this.oldCache.get(key);
  			if (this._deleteIfExpired(key, item) === false) {
  				this._moveToRecent(key, item);
  				return item.value;
  			}
  		}
  	}

  	set(key, value, {maxAge = this.maxAge} = {}) {
  		const expiry =
  			typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY ?
  				Date.now() + maxAge :
  				undefined;
  		if (this.cache.has(key)) {
  			this.cache.set(key, {
  				value,
  				expiry
  			});
  		} else {
  			this._set(key, {value, expiry});
  		}

  		return this;
  	}

  	has(key) {
  		if (this.cache.has(key)) {
  			return !this._deleteIfExpired(key, this.cache.get(key));
  		}

  		if (this.oldCache.has(key)) {
  			return !this._deleteIfExpired(key, this.oldCache.get(key));
  		}

  		return false;
  	}

  	peek(key) {
  		if (this.cache.has(key)) {
  			return this._peek(key, this.cache);
  		}

  		if (this.oldCache.has(key)) {
  			return this._peek(key, this.oldCache);
  		}
  	}

  	delete(key) {
  		const deleted = this.cache.delete(key);
  		if (deleted) {
  			this._size--;
  		}

  		return this.oldCache.delete(key) || deleted;
  	}

  	clear() {
  		this.cache.clear();
  		this.oldCache.clear();
  		this._size = 0;
  	}

  	resize(newSize) {
  		if (!(newSize && newSize > 0)) {
  			throw new TypeError('`maxSize` must be a number greater than 0');
  		}

  		const items = [...this._entriesAscending()];
  		const removeCount = items.length - newSize;
  		if (removeCount < 0) {
  			this.cache = new Map(items);
  			this.oldCache = new Map();
  			this._size = items.length;
  		} else {
  			if (removeCount > 0) {
  				this._emitEvictions(items.slice(0, removeCount));
  			}

  			this.oldCache = new Map(items.slice(removeCount));
  			this.cache = new Map();
  			this._size = 0;
  		}

  		this.maxSize = newSize;
  	}

  	* keys() {
  		for (const [key] of this) {
  			yield key;
  		}
  	}

  	* values() {
  		for (const [, value] of this) {
  			yield value;
  		}
  	}

  	* [Symbol.iterator]() {
  		for (const item of this.cache) {
  			const [key, value] = item;
  			const deleted = this._deleteIfExpired(key, value);
  			if (deleted === false) {
  				yield [key, value.value];
  			}
  		}

  		for (const item of this.oldCache) {
  			const [key, value] = item;
  			if (!this.cache.has(key)) {
  				const deleted = this._deleteIfExpired(key, value);
  				if (deleted === false) {
  					yield [key, value.value];
  				}
  			}
  		}
  	}

  	* entriesDescending() {
  		let items = [...this.cache];
  		for (let i = items.length - 1; i >= 0; --i) {
  			const item = items[i];
  			const [key, value] = item;
  			const deleted = this._deleteIfExpired(key, value);
  			if (deleted === false) {
  				yield [key, value.value];
  			}
  		}

  		items = [...this.oldCache];
  		for (let i = items.length - 1; i >= 0; --i) {
  			const item = items[i];
  			const [key, value] = item;
  			if (!this.cache.has(key)) {
  				const deleted = this._deleteIfExpired(key, value);
  				if (deleted === false) {
  					yield [key, value.value];
  				}
  			}
  		}
  	}

  	* entriesAscending() {
  		for (const [key, value] of this._entriesAscending()) {
  			yield [key, value.value];
  		}
  	}

  	get size() {
  		if (!this._size) {
  			return this.oldCache.size;
  		}

  		let oldCacheSize = 0;
  		for (const key of this.oldCache.keys()) {
  			if (!this.cache.has(key)) {
  				oldCacheSize++;
  			}
  		}

  		return Math.min(this._size + oldCacheSize, this.maxSize);
  	}

  	entries() {
  		return this.entriesAscending();
  	}

  	forEach(callbackFunction, thisArgument = this) {
  		for (const [key, value] of this.entriesAscending()) {
  			callbackFunction.call(thisArgument, value, key, this);
  		}
  	}

  	get [Symbol.toStringTag]() {
  		return JSON.stringify([...this.entriesAscending()]);
  	}
  }

  /*
   * Promisified wrapper around 'setTimeout' to allow 'await'
   */
  async function wait(milliseconds) {
    return new Promise((resolve) => setTimeout(resolve, milliseconds));
  }

  function zip(a, b) {
    const A = Array.isArray(a) ? a : Array.from(a);
    const B = Array.isArray(b) ? b : Array.from(b);
    return A.map((k, i) => [k, B[i]]);
  }

  // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
  class AbortError extends Error {
    constructor(params) {
      // Pass remaining arguments (including vendor specific ones) to parent constructor
      super(params);

      // Maintains proper stack trace for where our error was thrown (only available on V8)
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, AbortError);
      }

      this.name = 'AbortError';
    }
  }

  class CustomAggregateError extends Error {
    constructor(errors, message) {
      super(message);
      this.errors = errors;
      this.message = message;
      this.name = 'AggregateError';
    }
  }

  const AggregateError = CustomAggregateError;

  class Block {
    /**
     *
     * @param {number} offset
     * @param {number} length
     * @param {ArrayBuffer} [data]
     */
    constructor(offset, length, data = null) {
      this.offset = offset;
      this.length = length;
      this.data = data;
    }

    /**
     * @returns {number} the top byte border
     */
    get top() {
      return this.offset + this.length;
    }
  }

  class BlockGroup {
    /**
     *
     * @param {number} offset
     * @param {number} length
     * @param {number[]} blockIds
     */
    constructor(offset, length, blockIds) {
      this.offset = offset;
      this.length = length;
      this.blockIds = blockIds;
    }
  }

  class BlockedSource extends BaseSource {
    /**
     *
     * @param {BaseSource} source The underlying source that shall be blocked and cached
     * @param {object} options
     * @param {number} [options.blockSize]
     * @param {number} [options.cacheSize]
     */
    constructor(source, { blockSize = 65536, cacheSize = 100 } = {}) {
      super();
      this.source = source;
      this.blockSize = blockSize;

      this.blockCache = new QuickLRU({
        maxSize: cacheSize,
        onEviction: (blockId, block) => {
          this.evictedBlocks.set(blockId, block);
        },
      });

      /** @type {Map<number, Block>} */
      this.evictedBlocks = new Map();

      // mapping blockId -> Block instance
      this.blockRequests = new Map();

      // set of blockIds missing for the current requests
      this.blockIdsToFetch = new Set();

      this.abortedBlockIds = new Set();
    }

    get fileSize() {
      return this.source.fileSize;
    }

    /**
     *
     * @param {import("./basesource").Slice[]} slices
     */
    async fetch(slices, signal) {
      const blockRequests = [];
      const missingBlockIds = [];
      const allBlockIds = [];
      this.evictedBlocks.clear();

      for (const { offset, length } of slices) {
        let top = offset + length;

        const { fileSize } = this;
        if (fileSize !== null) {
          top = Math.min(top, fileSize);
        }

        const firstBlockOffset = Math.floor(offset / this.blockSize) * this.blockSize;

        for (let current = firstBlockOffset; current < top; current += this.blockSize) {
          const blockId = Math.floor(current / this.blockSize);
          if (!this.blockCache.has(blockId) && !this.blockRequests.has(blockId)) {
            this.blockIdsToFetch.add(blockId);
            missingBlockIds.push(blockId);
          }
          if (this.blockRequests.has(blockId)) {
            blockRequests.push(this.blockRequests.get(blockId));
          }
          allBlockIds.push(blockId);
        }
      }

      // allow additional block requests to accumulate
      await wait();
      this.fetchBlocks(signal);

      // Gather all of the new requests that this fetch call is contributing to `fetch`.
      const missingRequests = [];
      for (const blockId of missingBlockIds) {
        // The requested missing block could already be in the cache
        // instead of having its request still be outstanding.
        if (this.blockRequests.has(blockId)) {
          missingRequests.push(this.blockRequests.get(blockId));
        }
      }

      // Actually await all pending requests that are needed for this `fetch`.
      await Promise.allSettled(blockRequests);
      await Promise.allSettled(missingRequests);

      // Perform retries if a block was interrupted by a previous signal
      const abortedBlockRequests = [];
      const abortedBlockIds = allBlockIds
        .filter((id) => this.abortedBlockIds.has(id) || !this.blockCache.has(id));
      abortedBlockIds.forEach((id) => this.blockIdsToFetch.add(id));
      // start the retry of some blocks if required
      if (abortedBlockIds.length > 0 && signal && !signal.aborted) {
        this.fetchBlocks(null);
        for (const blockId of abortedBlockIds) {
          const block = this.blockRequests.get(blockId);
          if (!block) {
            throw new Error(`Block ${blockId} is not in the block requests`);
          }
          abortedBlockRequests.push(block);
        }
        await Promise.allSettled(abortedBlockRequests);
      }

      // throw an  abort error
      if (signal && signal.aborted) {
        throw new AbortError('Request was aborted');
      }

      const blocks = allBlockIds.map((id) => this.blockCache.get(id) || this.evictedBlocks.get(id));
      const failedBlocks = blocks.filter((i) => !i);
      if (failedBlocks.length) {
        throw new AggregateError(failedBlocks, 'Request failed');
      }

      // create a final Map, with all required blocks for this request to satisfy
      const requiredBlocks = new Map(zip(allBlockIds, blocks));

      // TODO: satisfy each slice
      return this.readSliceData(slices, requiredBlocks);
    }

    /**
     *
     * @param {AbortSignal} signal
     */
    fetchBlocks(signal) {
      // check if we still need to
      if (this.blockIdsToFetch.size > 0) {
        const groups = this.groupBlocks(this.blockIdsToFetch);

        // start requesting slices of data
        const groupRequests = this.source.fetch(groups, signal);

        for (let groupIndex = 0; groupIndex < groups.length; ++groupIndex) {
          const group = groups[groupIndex];

          for (const blockId of group.blockIds) {
            // make an async IIFE for each block
            this.blockRequests.set(blockId, (async () => {
              try {
                const response = (await groupRequests)[groupIndex];
                const blockOffset = blockId * this.blockSize;
                const o = blockOffset - response.offset;
                const t = Math.min(o + this.blockSize, response.data.byteLength);
                const data = response.data.slice(o, t);
                const block = new Block(
                  blockOffset,
                  data.byteLength,
                  data,
                  blockId,
                );
                this.blockCache.set(blockId, block);
                this.abortedBlockIds.delete(blockId);
              } catch (err) {
                if (err.name === 'AbortError') {
                  // store the signal here, we need it to determine later if an
                  // error was caused by this signal
                  err.signal = signal;
                  this.blockCache.delete(blockId);
                  this.abortedBlockIds.add(blockId);
                } else {
                  throw err;
                }
              } finally {
                this.blockRequests.delete(blockId);
              }
            })());
          }
        }
        this.blockIdsToFetch.clear();
      }
    }

    /**
     *
     * @param {Set} blockIds
     * @returns {BlockGroup[]}
     */
    groupBlocks(blockIds) {
      const sortedBlockIds = Array.from(blockIds).sort((a, b) => a - b);
      if (sortedBlockIds.length === 0) {
        return [];
      }
      let current = [];
      let lastBlockId = null;
      const groups = [];

      for (const blockId of sortedBlockIds) {
        if (lastBlockId === null || lastBlockId + 1 === blockId) {
          current.push(blockId);
          lastBlockId = blockId;
        } else {
          groups.push(new BlockGroup(
            current[0] * this.blockSize,
            current.length * this.blockSize,
            current,
          ));
          current = [blockId];
          lastBlockId = blockId;
        }
      }

      groups.push(new BlockGroup(
        current[0] * this.blockSize,
        current.length * this.blockSize,
        current,
      ));

      return groups;
    }

    /**
     *
     * @param {import("./basesource").Slice[]} slices
     * @param {Map} blocks
     */
    readSliceData(slices, blocks) {
      return slices.map((slice) => {
        let top = slice.offset + slice.length;
        if (this.fileSize !== null) {
          top = Math.min(this.fileSize, top);
        }
        const blockIdLow = Math.floor(slice.offset / this.blockSize);
        const blockIdHigh = Math.floor(top / this.blockSize);
        const sliceData = new ArrayBuffer(slice.length);
        const sliceView = new Uint8Array(sliceData);

        for (let blockId = blockIdLow; blockId <= blockIdHigh; ++blockId) {
          const block = blocks.get(blockId);
          const delta = block.offset - slice.offset;
          const topDelta = block.top - top;
          let blockInnerOffset = 0;
          let rangeInnerOffset = 0;
          let usedBlockLength;

          if (delta < 0) {
            blockInnerOffset = -delta;
          } else if (delta > 0) {
            rangeInnerOffset = delta;
          }

          if (topDelta < 0) {
            usedBlockLength = block.length - blockInnerOffset;
          } else {
            usedBlockLength = top - block.offset - blockInnerOffset;
          }

          const blockView = new Uint8Array(block.data, blockInnerOffset, usedBlockLength);
          sliceView.set(blockView, rangeInnerOffset);
        }

        return sliceData;
      });
    }
  }

  class BaseResponse {
    /**
     * Returns whether the response has an ok'ish status code
     */
    get ok() {
      return this.status >= 200 && this.status <= 299;
    }

    /**
     * Returns the status code of the response
     */
    get status() {
      throw new Error('not implemented');
    }

    /**
     * Returns the value of the specified header
     * @param {string} headerName the header name
     * @returns {string} the header value
     */
    getHeader(headerName) { // eslint-disable-line no-unused-vars
      throw new Error('not implemented');
    }

    /**
     * @returns {ArrayBuffer} the response data of the request
     */
    async getData() {
      throw new Error('not implemented');
    }
  }

  class BaseClient {
    constructor(url) {
      this.url = url;
    }

    /**
     * Send a request with the options
     * @param {{headers: HeadersInit, signal: AbortSignal}} [options={}]
     * @returns {Promise<BaseResponse>}
     */
    async request({ headers, signal } = {}) { // eslint-disable-line no-unused-vars
      throw new Error('request is not implemented');
    }
  }

  class FetchResponse extends BaseResponse {
    /**
     * BaseResponse facade for fetch API Response
     * @param {Response} response
     */
    constructor(response) {
      super();
      this.response = response;
    }

    get status() {
      return this.response.status;
    }

    getHeader(name) {
      return this.response.headers.get(name);
    }

    async getData() {
      const data = this.response.arrayBuffer
        ? await this.response.arrayBuffer()
        : (await this.response.buffer()).buffer;
      return data;
    }
  }

  class FetchClient extends BaseClient {
    constructor(url, credentials) {
      super(url);
      this.credentials = credentials;
    }

    /**
     * @param {{headers: HeadersInit, signal: AbortSignal}} [options={}]
     * @returns {Promise<FetchResponse>}
     */
    async request({ headers, signal } = {}) {
      const response = await fetch(this.url, {
        headers, credentials: this.credentials, signal,
      });
      return new FetchResponse(response);
    }
  }

  class XHRResponse extends BaseResponse {
    /**
     * BaseResponse facade for XMLHttpRequest
     * @param {XMLHttpRequest} xhr
     * @param {ArrayBuffer} data
     */
    constructor(xhr, data) {
      super();
      this.xhr = xhr;
      this.data = data;
    }

    get status() {
      return this.xhr.status;
    }

    getHeader(name) {
      return this.xhr.getResponseHeader(name);
    }

    async getData() {
      return this.data;
    }
  }

  class XHRClient extends BaseClient {
    constructRequest(headers, signal) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', this.url);
        xhr.responseType = 'arraybuffer';
        for (const [key, value] of Object.entries(headers)) {
          xhr.setRequestHeader(key, value);
        }

        // hook signals
        xhr.onload = () => {
          const data = xhr.response;
          resolve(new XHRResponse(xhr, data));
        };
        xhr.onerror = reject;
        xhr.onabort = () => reject(new AbortError('Request aborted'));
        xhr.send();

        if (signal) {
          if (signal.aborted) {
            xhr.abort();
          }
          signal.addEventListener('abort', () => xhr.abort());
        }
      });
    }

    async request({ headers, signal } = {}) {
      const response = await this.constructRequest(headers, signal);
      return response;
    }
  }

  var fs = {};

  class HttpResponse extends BaseResponse {
    /**
     * BaseResponse facade for node HTTP/HTTPS API Response
     * @param {http.ServerResponse} response
     */
    constructor(response, dataPromise) {
      super();
      this.response = response;
      this.dataPromise = dataPromise;
    }

    get status() {
      return this.response.statusCode;
    }

    getHeader(name) {
      return this.response.headers[name];
    }

    async getData() {
      const data = await this.dataPromise;
      return data;
    }
  }

  class HttpClient extends BaseClient {
    constructor(url) {
      super(url);
      this.parsedUrl = fs.parse(this.url);
      this.httpApi = (this.parsedUrl.protocol === 'http:' ? fs : fs);
    }

    constructRequest(headers, signal) {
      return new Promise((resolve, reject) => {
        const request = this.httpApi.get(
          {
            ...this.parsedUrl,
            headers,
          },
          (response) => {
            const dataPromise = new Promise((resolveData) => {
              const chunks = [];

              // collect chunks
              response.on('data', (chunk) => {
                chunks.push(chunk);
              });

              // concatenate all chunks and resolve the promise with the resulting buffer
              response.on('end', () => {
                const data = Buffer.concat(chunks).buffer;
                resolveData(data);
              });
              response.on('error', reject);
            });
            resolve(new HttpResponse(response, dataPromise));
          },
        );
        request.on('error', reject);

        if (signal) {
          if (signal.aborted) {
            request.destroy(new AbortError('Request aborted'));
          }
          signal.addEventListener('abort', () => request.destroy(new AbortError('Request aborted')));
        }
      });
    }

    async request({ headers, signal } = {}) {
      const response = await this.constructRequest(headers, signal);
      return response;
    }
  }

  class RemoteSource extends BaseSource {
    /**
     *
     * @param {BaseClient} client
     * @param {object} headers
     * @param {numbers} maxRanges
     * @param {boolean} allowFullFile
     */
    constructor(client, headers, maxRanges, allowFullFile) {
      super();
      this.client = client;
      this.headers = headers;
      this.maxRanges = maxRanges;
      this.allowFullFile = allowFullFile;
      this._fileSize = null;
    }

    /**
     *
     * @param {Slice[]} slices
     */
    async fetch(slices, signal) {
      // if we allow multi-ranges, split the incoming request into that many sub-requests
      // and join them afterwards
      if (this.maxRanges >= slices.length) {
        return this.fetchSlices(slices, signal);
      } else if (this.maxRanges > 0 && slices.length > 1) ;

      // otherwise make a single request for each slice
      return Promise.all(
        slices.map((slice) => this.fetchSlice(slice, signal)),
      );
    }

    async fetchSlices(slices, signal) {
      const response = await this.client.request({
        headers: {
          ...this.headers,
          Range: `bytes=${slices
          .map(({ offset, length }) => `${offset}-${offset + length}`)
          .join(',')
        }`,
        },
        signal,
      });

      if (!response.ok) {
        throw new Error('Error fetching data.');
      } else if (response.status === 206) {
        const { type, params } = parseContentType(response.getHeader('content-type'));
        if (type === 'multipart/byteranges') {
          const byteRanges = parseByteRanges(await response.getData(), params.boundary);
          this._fileSize = byteRanges[0].fileSize || null;
          return byteRanges;
        }

        const data = await response.getData();

        const { start, end, total } = parseContentRange(response.getHeader('content-range'));
        this._fileSize = total || null;
        const first = [{
          data,
          offset: start,
          length: end - start,
        }];

        if (slices.length > 1) {
          // we requested more than one slice, but got only the first
          // unfortunately, some HTTP Servers don't support multi-ranges
          // and return only the first

          // get the rest of the slices and fetch them iteratively
          const others = await Promise.all(slices.slice(1).map((slice) => this.fetchSlice(slice, signal)));
          return first.concat(others);
        }
        return first;
      } else {
        if (!this.allowFullFile) {
          throw new Error('Server responded with full file');
        }
        const data = await response.getData();
        this._fileSize = data.byteLength;
        return [{
          data,
          offset: 0,
          length: data.byteLength,
        }];
      }
    }

    async fetchSlice(slice, signal) {
      const { offset, length } = slice;
      const response = await this.client.request({
        headers: {
          ...this.headers,
          Range: `bytes=${offset}-${offset + length}`,
        },
        signal,
      });

      // check the response was okay and if the server actually understands range requests
      if (!response.ok) {
        throw new Error('Error fetching data.');
      } else if (response.status === 206) {
        const data = await response.getData();

        const { total } = parseContentRange(response.getHeader('content-range'));
        this._fileSize = total || null;
        return {
          data,
          offset,
          length,
        };
      } else {
        if (!this.allowFullFile) {
          throw new Error('Server responded with full file');
        }

        const data = await response.getData();

        this._fileSize = data.byteLength;
        return {
          data,
          offset: 0,
          length: data.byteLength,
        };
      }
    }

    get fileSize() {
      return this._fileSize;
    }
  }

  function maybeWrapInBlockedSource(source, { blockSize, cacheSize }) {
    if (blockSize === null) {
      return source;
    }
    return new BlockedSource(source, { blockSize, cacheSize });
  }

  function makeFetchSource(url, { headers = {}, credentials, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {
    const client = new FetchClient(url, credentials);
    const source = new RemoteSource(client, headers, maxRanges, allowFullFile);
    return maybeWrapInBlockedSource(source, blockOptions);
  }

  function makeXHRSource(url, { headers = {}, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {
    const client = new XHRClient(url);
    const source = new RemoteSource(client, headers, maxRanges, allowFullFile);
    return maybeWrapInBlockedSource(source, blockOptions);
  }

  function makeHttpSource(url, { headers = {}, maxRanges = 0, allowFullFile = false, ...blockOptions } = {}) {
    const client = new HttpClient(url);
    const source = new RemoteSource(client, headers, maxRanges, allowFullFile);
    return maybeWrapInBlockedSource(source, blockOptions);
  }

  /**
   *
   * @param {string} url
   * @param {object} options
   */
  function makeRemoteSource(url, { forceXHR = false, ...clientOptions } = {}) {
    if (typeof fetch === 'function' && !forceXHR) {
      return makeFetchSource(url, clientOptions);
    }
    if (typeof XMLHttpRequest !== 'undefined') {
      return makeXHRSource(url, clientOptions);
    }
    return makeHttpSource(url, clientOptions);
  }

  class FileReaderSource extends BaseSource {
    constructor(file) {
      super();
      this.file = file;
    }

    async fetchSlice(slice, signal) {
      return new Promise((resolve, reject) => {
        const blob = this.file.slice(slice.offset, slice.offset + slice.length);
        const reader = new FileReader();
        reader.onload = (event) => resolve(event.target.result);
        reader.onerror = reject;
        reader.onabort = reject;
        reader.readAsArrayBuffer(blob);

        if (signal) {
          signal.addEventListener('abort', () => reader.abort());
        }
      });
    }
  }

  /**
   * Create a new source from a given file/blob.
   * @param {Blob} file The file or blob to read from.
   * @returns The constructed source
   */
  function makeFileReaderSource(file) {
    return new FileReaderSource(file);
  }

  function decodeRowAcc(row, stride) {
    let length = row.length - stride;
    let offset = 0;
    do {
      for (let i = stride; i > 0; i--) {
        row[offset + stride] += row[offset];
        offset++;
      }

      length -= stride;
    } while (length > 0);
  }

  function decodeRowFloatingPoint(row, stride, bytesPerSample) {
    let index = 0;
    let count = row.length;
    const wc = count / bytesPerSample;

    while (count > stride) {
      for (let i = stride; i > 0; --i) {
        row[index + stride] += row[index];
        ++index;
      }
      count -= stride;
    }

    const copy = row.slice();
    for (let i = 0; i < wc; ++i) {
      for (let b = 0; b < bytesPerSample; ++b) {
        row[(bytesPerSample * i) + b] = copy[((bytesPerSample - b - 1) * wc) + i];
      }
    }
  }

  function applyPredictor(block, predictor, width, height, bitsPerSample,
    planarConfiguration) {
    if (predictor === 1) {
      return block;
    }

    for (let i = 0; i < bitsPerSample.length; ++i) {
      if (bitsPerSample[i] % 8 !== 0) {
        throw new Error('When decoding with predictor, only multiple of 8 bits are supported.');
      }
      if (bitsPerSample[i] !== bitsPerSample[0]) {
        throw new Error('When decoding with predictor, all samples must have the same size.');
      }
    }

    const bytesPerSample = bitsPerSample[0] / 8;
    const stride = planarConfiguration === 2 ? 1 : bitsPerSample.length;

    for (let i = 0; i < height; ++i) {
      // Last strip will be truncated if height % stripHeight != 0
      if (i * stride * width * bytesPerSample >= block.byteLength) {
        break;
      }
      let row;
      if (predictor === 2) { // horizontal prediction
        switch (bitsPerSample[0]) {
          case 8:
            row = new Uint8Array(
              block, i * stride * width * bytesPerSample, stride * width * bytesPerSample,
            );
            break;
          case 16:
            row = new Uint16Array(
              block, i * stride * width * bytesPerSample, stride * width * bytesPerSample / 2,
            );
            break;
          case 32:
            row = new Uint32Array(
              block, i * stride * width * bytesPerSample, stride * width * bytesPerSample / 4,
            );
            break;
          default:
            throw new Error(`Predictor 2 not allowed with ${bitsPerSample[0]} bits per sample.`);
        }
        decodeRowAcc(row, stride);
      } else if (predictor === 3) { // horizontal floating point
        row = new Uint8Array(
          block, i * stride * width * bytesPerSample, stride * width * bytesPerSample,
        );
        decodeRowFloatingPoint(row, stride, bytesPerSample);
      }
    }
    return block;
  }

  class BaseDecoder {
    async decode(fileDirectory, buffer) {
      const decoded = await this.decodeBlock(buffer);
      const predictor = fileDirectory.Predictor || 1;
      if (predictor !== 1) {
        const isTiled = !fileDirectory.StripOffsets;
        const tileWidth = isTiled ? fileDirectory.TileWidth : fileDirectory.ImageWidth;
        const tileHeight = isTiled ? fileDirectory.TileLength : (
          fileDirectory.RowsPerStrip || fileDirectory.ImageLength
        );
        return applyPredictor(
          decoded, predictor, tileWidth, tileHeight, fileDirectory.BitsPerSample,
          fileDirectory.PlanarConfiguration,
        );
      }
      return decoded;
    }
  }

  /** @module geotiff */

  /**
   * @typedef {Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array}
   * TypedArray
   */

  /**
   * @typedef {{ height:number, width: number }} Dimensions
   */

  /**
   * The autogenerated docs are a little confusing here. The effective type is:
   *
   * `TypedArray & { height: number; width: number}`
   * @typedef {TypedArray & Dimensions} TypedArrayWithDimensions
   */

  /**
   * The autogenerated docs are a little confusing here. The effective type is:
   *
   * `TypedArray[] & { height: number; width: number}`
   * @typedef {TypedArray[] & Dimensions} TypedArrayArrayWithDimensions
   */

  /**
   *  The autogenerated docs are a little confusing here. The effective type is:
   *
   * `(TypedArray | TypedArray[]) & { height: number; width: number}`
   * @typedef {TypedArrayWithDimensions | TypedArrayArrayWithDimensions} ReadRasterResult
   */

  function getFieldTypeLength(fieldType) {
    switch (fieldType) {
      case fieldTypes.BYTE: case fieldTypes.ASCII: case fieldTypes.SBYTE: case fieldTypes.UNDEFINED:
        return 1;
      case fieldTypes.SHORT: case fieldTypes.SSHORT:
        return 2;
      case fieldTypes.LONG: case fieldTypes.SLONG: case fieldTypes.FLOAT: case fieldTypes.IFD:
        return 4;
      case fieldTypes.RATIONAL: case fieldTypes.SRATIONAL: case fieldTypes.DOUBLE:
      case fieldTypes.LONG8: case fieldTypes.SLONG8: case fieldTypes.IFD8:
        return 8;
      default:
        throw new RangeError(`Invalid field type: ${fieldType}`);
    }
  }

  function parseGeoKeyDirectory(fileDirectory) {
    const rawGeoKeyDirectory = fileDirectory.GeoKeyDirectory;
    if (!rawGeoKeyDirectory) {
      return null;
    }

    const geoKeyDirectory = {};
    for (let i = 4; i <= rawGeoKeyDirectory[3] * 4; i += 4) {
      const key = geoKeyNames[rawGeoKeyDirectory[i]];
      const location = (rawGeoKeyDirectory[i + 1])
        ? (fieldTagNames[rawGeoKeyDirectory[i + 1]]) : null;
      const count = rawGeoKeyDirectory[i + 2];
      const offset = rawGeoKeyDirectory[i + 3];

      let value = null;
      if (!location) {
        value = offset;
      } else {
        value = fileDirectory[location];
        if (typeof value === 'undefined' || value === null) {
          throw new Error(`Could not get value of geoKey '${key}'.`);
        } else if (typeof value === 'string') {
          value = value.substring(offset, offset + count - 1);
        } else if (value.subarray) {
          value = value.subarray(offset, offset + count);
          if (count === 1) {
            value = value[0];
          }
        }
      }
      geoKeyDirectory[key] = value;
    }
    return geoKeyDirectory;
  }

  function getValues(dataSlice, fieldType, count, offset) {
    let values = null;
    let readMethod = null;
    const fieldTypeLength = getFieldTypeLength(fieldType);

    switch (fieldType) {
      case fieldTypes.BYTE: case fieldTypes.ASCII: case fieldTypes.UNDEFINED:
        values = new Uint8Array(count); readMethod = dataSlice.readUint8;
        break;
      case fieldTypes.SBYTE:
        values = new Int8Array(count); readMethod = dataSlice.readInt8;
        break;
      case fieldTypes.SHORT:
        values = new Uint16Array(count); readMethod = dataSlice.readUint16;
        break;
      case fieldTypes.SSHORT:
        values = new Int16Array(count); readMethod = dataSlice.readInt16;
        break;
      case fieldTypes.LONG: case fieldTypes.IFD:
        values = new Uint32Array(count); readMethod = dataSlice.readUint32;
        break;
      case fieldTypes.SLONG:
        values = new Int32Array(count); readMethod = dataSlice.readInt32;
        break;
      case fieldTypes.LONG8: case fieldTypes.IFD8:
        values = new Array(count); readMethod = dataSlice.readUint64;
        break;
      case fieldTypes.SLONG8:
        values = new Array(count); readMethod = dataSlice.readInt64;
        break;
      case fieldTypes.RATIONAL:
        values = new Uint32Array(count * 2); readMethod = dataSlice.readUint32;
        break;
      case fieldTypes.SRATIONAL:
        values = new Int32Array(count * 2); readMethod = dataSlice.readInt32;
        break;
      case fieldTypes.FLOAT:
        values = new Float32Array(count); readMethod = dataSlice.readFloat32;
        break;
      case fieldTypes.DOUBLE:
        values = new Float64Array(count); readMethod = dataSlice.readFloat64;
        break;
      default:
        throw new RangeError(`Invalid field type: ${fieldType}`);
    }

    // normal fields
    if (!(fieldType === fieldTypes.RATIONAL || fieldType === fieldTypes.SRATIONAL)) {
      for (let i = 0; i < count; ++i) {
        values[i] = readMethod.call(
          dataSlice, offset + (i * fieldTypeLength),
        );
      }
    } else { // RATIONAL or SRATIONAL
      for (let i = 0; i < count; i += 2) {
        values[i] = readMethod.call(
          dataSlice, offset + (i * fieldTypeLength),
        );
        values[i + 1] = readMethod.call(
          dataSlice, offset + ((i * fieldTypeLength) + 4),
        );
      }
    }

    if (fieldType === fieldTypes.ASCII) {
      return new TextDecoder('utf-8').decode(values);
    }
    return values;
  }

  /**
   * Data class to store the parsed file directory, geo key directory and
   * offset to the next IFD
   */
  class ImageFileDirectory {
    constructor(fileDirectory, geoKeyDirectory, nextIFDByteOffset) {
      this.fileDirectory = fileDirectory;
      this.geoKeyDirectory = geoKeyDirectory;
      this.nextIFDByteOffset = nextIFDByteOffset;
    }
  }

  /**
   * Error class for cases when an IFD index was requested, that does not exist
   * in the file.
   */
  class GeoTIFFImageIndexError extends Error {
    constructor(index) {
      super(`No image at index ${index}`);
      this.index = index;
    }
  }

  class GeoTIFFBase {
    /**
     * (experimental) Reads raster data from the best fitting image. This function uses
     * the image with the lowest resolution that is still a higher resolution than the
     * requested resolution.
     * When specified, the `bbox` option is translated to the `window` option and the
     * `resX` and `resY` to `width` and `height` respectively.
     * Then, the [readRasters]{@link GeoTIFFImage#readRasters} method of the selected
     * image is called and the result returned.
     * @see GeoTIFFImage.readRasters
     * @param {import('./geotiffimage').ReadRasterOptions} [options={}] optional parameters
     * @returns {Promise<ReadRasterResult>} the decoded array(s), with `height` and `width`, as a promise
     */
    async readRasters(options = {}) {
      const { window: imageWindow, width, height } = options;
      let { resX, resY, bbox } = options;

      const firstImage = await this.getImage();
      let usedImage = firstImage;
      const imageCount = await this.getImageCount();
      const imgBBox = firstImage.getBoundingBox();

      if (imageWindow && bbox) {
        throw new Error('Both "bbox" and "window" passed.');
      }

      // if width/height is passed, transform it to resolution
      if (width || height) {
        // if we have an image window (pixel coordinates), transform it to a BBox
        // using the origin/resolution of the first image.
        if (imageWindow) {
          const [oX, oY] = firstImage.getOrigin();
          const [rX, rY] = firstImage.getResolution();

          bbox = [
            oX + (imageWindow[0] * rX),
            oY + (imageWindow[1] * rY),
            oX + (imageWindow[2] * rX),
            oY + (imageWindow[3] * rY),
          ];
        }

        // if we have a bbox (or calculated one)

        const usedBBox = bbox || imgBBox;

        if (width) {
          if (resX) {
            throw new Error('Both width and resX passed');
          }
          resX = (usedBBox[2] - usedBBox[0]) / width;
        }
        if (height) {
          if (resY) {
            throw new Error('Both width and resY passed');
          }
          resY = (usedBBox[3] - usedBBox[1]) / height;
        }
      }

      // if resolution is set or calculated, try to get the image with the worst acceptable resolution
      if (resX || resY) {
        const allImages = [];
        for (let i = 0; i < imageCount; ++i) {
          const image = await this.getImage(i);
          const { SubfileType: subfileType, NewSubfileType: newSubfileType } = image.fileDirectory;
          if (i === 0 || subfileType === 2 || newSubfileType & 1) {
            allImages.push(image);
          }
        }

        allImages.sort((a, b) => a.getWidth() - b.getWidth());
        for (let i = 0; i < allImages.length; ++i) {
          const image = allImages[i];
          const imgResX = (imgBBox[2] - imgBBox[0]) / image.getWidth();
          const imgResY = (imgBBox[3] - imgBBox[1]) / image.getHeight();

          usedImage = image;
          if ((resX && resX > imgResX) || (resY && resY > imgResY)) {
            break;
          }
        }
      }

      let wnd = imageWindow;
      if (bbox) {
        const [oX, oY] = firstImage.getOrigin();
        const [imageResX, imageResY] = usedImage.getResolution(firstImage);

        wnd = [
          Math.round((bbox[0] - oX) / imageResX),
          Math.round((bbox[1] - oY) / imageResY),
          Math.round((bbox[2] - oX) / imageResX),
          Math.round((bbox[3] - oY) / imageResY),
        ];
        wnd = [
          Math.min(wnd[0], wnd[2]),
          Math.min(wnd[1], wnd[3]),
          Math.max(wnd[0], wnd[2]),
          Math.max(wnd[1], wnd[3]),
        ];
      }

      return usedImage.readRasters({ ...options, window: wnd });
    }
  }

  /**
   * @typedef {Object} GeoTIFFOptions
   * @property {boolean} [cache=false] whether or not decoded tiles shall be cached.
   */

  /**
   * The abstraction for a whole GeoTIFF file.
   * @augments GeoTIFFBase
   */
  class GeoTIFF extends GeoTIFFBase {
    /**
     * @constructor
     * @param {*} source The datasource to read from.
     * @param {boolean} littleEndian Whether the image uses little endian.
     * @param {boolean} bigTiff Whether the image uses bigTIFF conventions.
     * @param {number} firstIFDOffset The numeric byte-offset from the start of the image
     *                                to the first IFD.
     * @param {GeoTIFFOptions} [options] further options.
     */
    constructor(source, littleEndian, bigTiff, firstIFDOffset, options = {}) {
      super();
      this.source = source;
      this.littleEndian = littleEndian;
      this.bigTiff = bigTiff;
      this.firstIFDOffset = firstIFDOffset;
      this.cache = options.cache || false;
      this.ifdRequests = [];
      this.ghostValues = null;
    }

    async getSlice(offset, size) {
      const fallbackSize = this.bigTiff ? 4048 : 1024;
      return new DataSlice(
        (await this.source.fetch([{
          offset,
          length: typeof size !== 'undefined' ? size : fallbackSize,
        }]))[0],
        offset,
        this.littleEndian,
        this.bigTiff,
      );
    }

    /**
     * Instructs to parse an image file directory at the given file offset.
     * As there is no way to ensure that a location is indeed the start of an IFD,
     * this function must be called with caution (e.g only using the IFD offsets from
     * the headers or other IFDs).
     * @param {number} offset the offset to parse the IFD at
     * @returns {Promise<ImageFileDirectory>} the parsed IFD
     */
    async parseFileDirectoryAt(offset) {
      const entrySize = this.bigTiff ? 20 : 12;
      const offsetSize = this.bigTiff ? 8 : 2;

      let dataSlice = await this.getSlice(offset);
      const numDirEntries = this.bigTiff
        ? dataSlice.readUint64(offset)
        : dataSlice.readUint16(offset);

      // if the slice does not cover the whole IFD, request a bigger slice, where the
      // whole IFD fits: num of entries + n x tag length + offset to next IFD
      const byteSize = (numDirEntries * entrySize) + (this.bigTiff ? 16 : 6);
      if (!dataSlice.covers(offset, byteSize)) {
        dataSlice = await this.getSlice(offset, byteSize);
      }

      const fileDirectory = {};

      // loop over the IFD and create a file directory object
      let i = offset + (this.bigTiff ? 8 : 2);
      for (let entryCount = 0; entryCount < numDirEntries; i += entrySize, ++entryCount) {
        const fieldTag = dataSlice.readUint16(i);
        const fieldType = dataSlice.readUint16(i + 2);
        const typeCount = this.bigTiff
          ? dataSlice.readUint64(i + 4)
          : dataSlice.readUint32(i + 4);

        let fieldValues;
        let value;
        const fieldTypeLength = getFieldTypeLength(fieldType);
        const valueOffset = i + (this.bigTiff ? 12 : 8);

        // check whether the value is directly encoded in the tag or refers to a
        // different external byte range
        if (fieldTypeLength * typeCount <= (this.bigTiff ? 8 : 4)) {
          fieldValues = getValues(dataSlice, fieldType, typeCount, valueOffset);
        } else {
          // resolve the reference to the actual byte range
          const actualOffset = dataSlice.readOffset(valueOffset);
          const length = getFieldTypeLength(fieldType) * typeCount;

          // check, whether we actually cover the referenced byte range; if not,
          // request a new slice of bytes to read from it
          if (dataSlice.covers(actualOffset, length)) {
            fieldValues = getValues(dataSlice, fieldType, typeCount, actualOffset);
          } else {
            const fieldDataSlice = await this.getSlice(actualOffset, length);
            fieldValues = getValues(fieldDataSlice, fieldType, typeCount, actualOffset);
          }
        }

        // unpack single values from the array
        if (typeCount === 1 && arrayFields.indexOf(fieldTag) === -1
          && !(fieldType === fieldTypes.RATIONAL || fieldType === fieldTypes.SRATIONAL)) {
          value = fieldValues[0];
        } else {
          value = fieldValues;
        }

        // write the tags value to the file directly
        fileDirectory[fieldTagNames[fieldTag]] = value;
      }
      const geoKeyDirectory = parseGeoKeyDirectory(fileDirectory);
      const nextIFDByteOffset = dataSlice.readOffset(
        offset + offsetSize + (entrySize * numDirEntries),
      );

      return new ImageFileDirectory(
        fileDirectory,
        geoKeyDirectory,
        nextIFDByteOffset,
      );
    }

    async requestIFD(index) {
      // see if we already have that IFD index requested.
      if (this.ifdRequests[index]) {
        // attach to an already requested IFD
        return this.ifdRequests[index];
      } else if (index === 0) {
        // special case for index 0
        this.ifdRequests[index] = this.parseFileDirectoryAt(this.firstIFDOffset);
        return this.ifdRequests[index];
      } else if (!this.ifdRequests[index - 1]) {
        // if the previous IFD was not yet loaded, load that one first
        // this is the recursive call.
        try {
          this.ifdRequests[index - 1] = this.requestIFD(index - 1);
        } catch (e) {
          // if the previous one already was an index error, rethrow
          // with the current index
          if (e instanceof GeoTIFFImageIndexError) {
            throw new GeoTIFFImageIndexError(index);
          }
          // rethrow anything else
          throw e;
        }
      }
      // if the previous IFD was loaded, we can finally fetch the one we are interested in.
      // we need to wrap this in an IIFE, otherwise this.ifdRequests[index] would be delayed
      this.ifdRequests[index] = (async () => {
        const previousIfd = await this.ifdRequests[index - 1];
        if (previousIfd.nextIFDByteOffset === 0) {
          throw new GeoTIFFImageIndexError(index);
        }
        return this.parseFileDirectoryAt(previousIfd.nextIFDByteOffset);
      })();
      return this.ifdRequests[index];
    }

    /**
     * Get the n-th internal subfile of an image. By default, the first is returned.
     *
     * @param {number} [index=0] the index of the image to return.
     * @returns {Promise<GeoTIFFImage>} the image at the given index
     */
    async getImage(index = 0) {
      const ifd = await this.requestIFD(index);
      return new GeoTIFFImage(
        ifd.fileDirectory, ifd.geoKeyDirectory,
        this.dataView, this.littleEndian, this.cache, this.source,
      );
    }

    /**
     * Returns the count of the internal subfiles.
     *
     * @returns {Promise<number>} the number of internal subfile images
     */
    async getImageCount() {
      let index = 0;
      // loop until we run out of IFDs
      let hasNext = true;
      while (hasNext) {
        try {
          await this.requestIFD(index);
          ++index;
        } catch (e) {
          if (e instanceof GeoTIFFImageIndexError) {
            hasNext = false;
          } else {
            throw e;
          }
        }
      }
      return index;
    }

    /**
     * Get the values of the COG ghost area as a parsed map.
     * See https://gdal.org/drivers/raster/cog.html#header-ghost-area for reference
     * @returns {Promise<Object>} the parsed ghost area or null, if no such area was found
     */
    async getGhostValues() {
      const offset = this.bigTiff ? 16 : 8;
      if (this.ghostValues) {
        return this.ghostValues;
      }
      const detectionString = 'GDAL_STRUCTURAL_METADATA_SIZE=';
      const heuristicAreaSize = detectionString.length + 100;
      let slice = await this.getSlice(offset, heuristicAreaSize);
      if (detectionString === getValues(slice, fieldTypes.ASCII, detectionString.length, offset)) {
        const valuesString = getValues(slice, fieldTypes.ASCII, heuristicAreaSize, offset);
        const firstLine = valuesString.split('\n')[0];
        const metadataSize = Number(firstLine.split('=')[1].split(' ')[0]) + firstLine.length;
        if (metadataSize > heuristicAreaSize) {
          slice = await this.getSlice(offset, metadataSize);
        }
        const fullString = getValues(slice, fieldTypes.ASCII, metadataSize, offset);
        this.ghostValues = {};
        fullString
          .split('\n')
          .filter((line) => line.length > 0)
          .map((line) => line.split('='))
          .forEach(([key, value]) => {
            this.ghostValues[key] = value;
          });
      }
      return this.ghostValues;
    }

    /**
     * Parse a (Geo)TIFF file from the given source.
     *
     * @param {*} source The source of data to parse from.
     * @param {GeoTIFFOptions} [options] Additional options.
     * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
     *                               to be aborted
     */
    static async fromSource(source, options, signal) {
      const headerData = (await source.fetch([{ offset: 0, length: 1024 }], signal))[0];
      const dataView = new DataView64(headerData);

      const BOM = dataView.getUint16(0, 0);
      let littleEndian;
      if (BOM === 0x4949) {
        littleEndian = true;
      } else if (BOM === 0x4D4D) {
        littleEndian = false;
      } else {
        throw new TypeError('Invalid byte order value.');
      }

      const magicNumber = dataView.getUint16(2, littleEndian);
      let bigTiff;
      if (magicNumber === 42) {
        bigTiff = false;
      } else if (magicNumber === 43) {
        bigTiff = true;
        const offsetByteSize = dataView.getUint16(4, littleEndian);
        if (offsetByteSize !== 8) {
          throw new Error('Unsupported offset byte-size.');
        }
      } else {
        throw new TypeError('Invalid magic number.');
      }

      const firstIFDOffset = bigTiff
        ? dataView.getUint64(8, littleEndian)
        : dataView.getUint32(4, littleEndian);
      return new GeoTIFF(source, littleEndian, bigTiff, firstIFDOffset, options);
    }

    /**
     * Closes the underlying file buffer
     * N.B. After the GeoTIFF has been completely processed it needs
     * to be closed but only if it has been constructed from a file.
     */
    close() {
      if (typeof this.source.close === 'function') {
        return this.source.close();
      }
      return false;
    }
  }

  /**
   * Wrapper for GeoTIFF files that have external overviews.
   * @augments GeoTIFFBase
   */
  class MultiGeoTIFF extends GeoTIFFBase {
    /**
     * Construct a new MultiGeoTIFF from a main and several overview files.
     * @param {GeoTIFF} mainFile The main GeoTIFF file.
     * @param {GeoTIFF[]} overviewFiles An array of overview files.
     */
    constructor(mainFile, overviewFiles) {
      super();
      this.mainFile = mainFile;
      this.overviewFiles = overviewFiles;
      this.imageFiles = [mainFile].concat(overviewFiles);

      this.fileDirectoriesPerFile = null;
      this.fileDirectoriesPerFileParsing = null;
      this.imageCount = null;
    }

    async parseFileDirectoriesPerFile() {
      const requests = [this.mainFile.parseFileDirectoryAt(this.mainFile.firstIFDOffset)]
        .concat(this.overviewFiles.map((file) => file.parseFileDirectoryAt(file.firstIFDOffset)));

      this.fileDirectoriesPerFile = await Promise.all(requests);
      return this.fileDirectoriesPerFile;
    }

    /**
     * Get the n-th internal subfile of an image. By default, the first is returned.
     *
     * @param {number} [index=0] the index of the image to return.
     * @returns {Promise<GeoTIFFImage>} the image at the given index
     */
    async getImage(index = 0) {
      await this.getImageCount();
      await this.parseFileDirectoriesPerFile();
      let visited = 0;
      let relativeIndex = 0;
      for (let i = 0; i < this.imageFiles.length; i++) {
        const imageFile = this.imageFiles[i];
        for (let ii = 0; ii < this.imageCounts[i]; ii++) {
          if (index === visited) {
            const ifd = await imageFile.requestIFD(relativeIndex);
            return new GeoTIFFImage(
              ifd.fileDirectory, ifd.geoKeyDirectory,
              imageFile.dataView, imageFile.littleEndian, imageFile.cache, imageFile.source,
            );
          }
          visited++;
          relativeIndex++;
        }
        relativeIndex = 0;
      }

      throw new RangeError('Invalid image index');
    }

    /**
     * Returns the count of the internal subfiles.
     *
     * @returns {Promise<number>} the number of internal subfile images
     */
    async getImageCount() {
      if (this.imageCount !== null) {
        return this.imageCount;
      }
      const requests = [this.mainFile.getImageCount()]
        .concat(this.overviewFiles.map((file) => file.getImageCount()));
      this.imageCounts = await Promise.all(requests);
      this.imageCount = this.imageCounts.reduce((count, ifds) => count + ifds, 0);
      return this.imageCount;
    }
  }

  /**
   * Creates a new GeoTIFF from a remote URL.
   * @param {string} url The URL to access the image from
   * @param {object} [options] Additional options to pass to the source.
   *                           See {@link makeRemoteSource} for details.
   * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
   *                               to be aborted
   * @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
   */
  async function fromUrl(url, options = {}, signal) {
    return GeoTIFF.fromSource(makeRemoteSource(url, options), signal);
  }

  /**
   * Construct a GeoTIFF from an HTML
   * [Blob]{@link https://developer.mozilla.org/en-US/docs/Web/API/Blob} or
   * [File]{@link https://developer.mozilla.org/en-US/docs/Web/API/File}
   * object.
   * @param {Blob|File} blob The Blob or File object to read from.
   * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
   *                               to be aborted
   * @returns {Promise<GeoTIFF>} The resulting GeoTIFF file.
   */
  async function fromBlob(blob, signal) {
    return GeoTIFF.fromSource(makeFileReaderSource(blob), signal);
  }

  /**
   * Construct a MultiGeoTIFF from the given URLs.
   * @param {string} mainUrl The URL for the main file.
   * @param {string[]} overviewUrls An array of URLs for the overview images.
   * @param {Object} [options] Additional options to pass to the source.
   *                           See [makeRemoteSource]{@link module:source.makeRemoteSource}
   *                           for details.
   * @param {AbortSignal} [signal] An AbortSignal that may be signalled if the request is
   *                               to be aborted
   * @returns {Promise<MultiGeoTIFF>} The resulting MultiGeoTIFF file.
   */
  async function fromUrls(mainUrl, overviewUrls = [], options = {}, signal) {
    const mainFile = await GeoTIFF.fromSource(makeRemoteSource(mainUrl, options), signal);
    const overviewFiles = await Promise.all(
      overviewUrls.map((url) => GeoTIFF.fromSource(makeRemoteSource(url, options))),
    );

    return new MultiGeoTIFF(mainFile, overviewFiles);
  }

  /**
   * @module ol/source/GeoTIFF
   */

  /**
   * Determine if an image type is a mask.
   * See https://www.awaresystems.be/imaging/tiff/tifftags/newsubfiletype.html
   * @param {GeoTIFFImage} image The image.
   * @return {boolean} The image is a mask.
   */
  function isMask(image) {
    const fileDirectory = image.fileDirectory;
    const type = fileDirectory.NewSubfileType || 0;
    return (type & 4) === 4;
  }

  /**
   * @param {true|false|'auto'} preference The convertToRGB option.
   * @param {GeoTIFFImage} image The image.
   * @return {boolean} Use the `image.readRGB()` method.
   */
  function readRGB(preference, image) {
    if (!preference) {
      return false;
    }
    if (preference === true) {
      return true;
    }
    if (image.getSamplesPerPixel() !== 3) {
      return false;
    }
    const interpretation = image.fileDirectory.PhotometricInterpretation;
    const interpretations = photometricInterpretations;
    return (
      interpretation === interpretations.CMYK ||
      interpretation === interpretations.YCbCr ||
      interpretation === interpretations.CIELab ||
      interpretation === interpretations.ICCLab
    );
  }

  /**
   * @typedef {Object} SourceInfo
   * @property {string} [url] URL for the source GeoTIFF.
   * @property {Array<string>} [overviews] List of any overview URLs, only applies if the url parameter is given.
   * @property {Blob} [blob] Blob containing the source GeoTIFF. `blob` and `url` are mutually exclusive.
   * @property {number} [min=0] The minimum source data value.  Rendered values are scaled from 0 to 1 based on
   * the configured min and max.  If not provided and raster statistics are available, those will be used instead.
   * If neither are available, the minimum for the data type will be used.  To disable this behavior, set
   * the `normalize` option to `false` in the constructor.
   * @property {number} [max] The maximum source data value.  Rendered values are scaled from 0 to 1 based on
   * the configured min and max.  If not provided and raster statistics are available, those will be used instead.
   * If neither are available, the maximum for the data type will be used.  To disable this behavior, set
   * the `normalize` option to `false` in the constructor.
   * @property {number} [nodata] Values to discard (overriding any nodata values in the metadata).
   * When provided, an additional alpha band will be added to the data.  Often the GeoTIFF metadata
   * will include information about nodata values, so you should only need to set this property if
   * you find that it is not already extracted from the metadata.
   * @property {Array<number>} [bands] Band numbers to be read from (where the first band is `1`). If not provided, all bands will
   * be read. For example, if a GeoTIFF has blue (1), green (2), red (3), and near-infrared (4) bands, and you only need the
   * near-infrared band, configure `bands: [4]`.
   */

  /**
   * @typedef {Object} GeoKeys
   * @property {number} GTModelTypeGeoKey Model type.
   * @property {number} GTRasterTypeGeoKey Raster type.
   * @property {number} GeogAngularUnitsGeoKey Angular units.
   * @property {number} GeogInvFlatteningGeoKey Inverse flattening.
   * @property {number} GeogSemiMajorAxisGeoKey Semi-major axis.
   * @property {number} GeographicTypeGeoKey Geographic coordinate system code.
   * @property {number} ProjLinearUnitsGeoKey Projected linear unit code.
   * @property {number} ProjectedCSTypeGeoKey Projected coordinate system code.
   */

  /**
   * @typedef {import("geotiff").GeoTIFF} GeoTIFF
   */

  /**
   * @typedef {import("geotiff").MultiGeoTIFF} MultiGeoTIFF
   */

  /**
   * @typedef {Object} GDALMetadata
   * @property {string} STATISTICS_MINIMUM The minimum value (as a string).
   * @property {string} STATISTICS_MAXIMUM The maximum value (as a string).
   */

  const STATISTICS_MAXIMUM = 'STATISTICS_MAXIMUM';
  const STATISTICS_MINIMUM = 'STATISTICS_MINIMUM';

  const defaultTileSize = 256;

  /**
   * @typedef {import("geotiff").GeoTIFFImage} GeoTIFFImage
   */

  let workerPool;
  function getWorkerPool() {
    if (!workerPool) {
      workerPool = new Pool();
    }
    return workerPool;
  }

  /**
   * Get the bounding box of an image.  If the image does not have an affine transform,
   * the pixel bounds are returned.
   * @param {GeoTIFFImage} image The image.
   * @return {Array<number>} The image bounding box.
   */
  function getBoundingBox(image) {
    try {
      return image.getBoundingBox(true);
    } catch {
      return [0, 0, image.getWidth(), image.getHeight()];
    }
  }

  /**
   * Get the origin of an image.  If the image does not have an affine transform,
   * the top-left corner of the pixel bounds is returned.
   * @param {GeoTIFFImage} image The image.
   * @return {Array<number>} The image origin.
   */
  function getOrigin(image) {
    try {
      return image.getOrigin().slice(0, 2);
    } catch {
      return [0, image.getHeight()];
    }
  }

  /**
   * Get the resolution of an image.  If the image does not have an affine transform,
   * the width of the image is compared with the reference image.
   * @param {GeoTIFFImage} image The image.
   * @param {GeoTIFFImage} referenceImage The reference image.
   * @return {Array<number>} The map x and y units per pixel.
   */
  function getResolutions(image, referenceImage) {
    try {
      return image.getResolution(referenceImage);
    } catch {
      return [
        referenceImage.getWidth() / image.getWidth(),
        referenceImage.getHeight() / image.getHeight(),
      ];
    }
  }

  /**
   * @param {GeoTIFFImage} image A GeoTIFF.
   * @return {import("../proj/Projection.js").default} The image projection.
   */
  function getProjection(image) {
    const geoKeys = image.geoKeys;
    if (!geoKeys) {
      return null;
    }

    if (
      geoKeys.ProjectedCSTypeGeoKey &&
      geoKeys.ProjectedCSTypeGeoKey !== 32767
    ) {
      const code = 'EPSG:' + geoKeys.ProjectedCSTypeGeoKey;
      let projection = get$2(code);
      if (!projection) {
        const units = fromCode(geoKeys.ProjLinearUnitsGeoKey);
        if (units) {
          projection = new Projection({
            code: code,
            units: units,
          });
        }
      }
      return projection;
    }

    if (geoKeys.GeographicTypeGeoKey && geoKeys.GeographicTypeGeoKey !== 32767) {
      const code = 'EPSG:' + geoKeys.GeographicTypeGeoKey;
      let projection = get$2(code);
      if (!projection) {
        const units = fromCode(geoKeys.GeogAngularUnitsGeoKey);
        if (units) {
          projection = new Projection({
            code: code,
            units: units,
          });
        }
      }
      return projection;
    }

    return null;
  }

  /**
   * @param {GeoTIFF|MultiGeoTIFF} tiff A GeoTIFF.
   * @return {Promise<Array<GeoTIFFImage>>} Resolves to a list of images.
   */
  function getImagesForTIFF(tiff) {
    return tiff.getImageCount().then(function (count) {
      const requests = new Array(count);
      for (let i = 0; i < count; ++i) {
        requests[i] = tiff.getImage(i);
      }
      return Promise.all(requests);
    });
  }

  /**
   * @param {SourceInfo} source The GeoTIFF source.
   * @param {Object} options Options for the GeoTIFF source.
   * @return {Promise<Array<GeoTIFFImage>>} Resolves to a list of images.
   */
  function getImagesForSource(source, options) {
    let request;
    if (source.blob) {
      request = fromBlob(source.blob);
    } else if (source.overviews) {
      request = fromUrls(source.url, source.overviews, options);
    } else {
      request = fromUrl(source.url, options);
    }
    return request.then(getImagesForTIFF);
  }

  /**
   * @param {number|Array<number>|Array<Array<number>>} expected Expected value.
   * @param {number|Array<number>|Array<Array<number>>} got Actual value.
   * @param {number} tolerance Accepted tolerance in fraction of expected between expected and got.
   * @param {string} message The error message.
   * @param {function(Error):void} rejector A function to be called with any error.
   */
  function assertEqual(expected, got, tolerance, message, rejector) {
    if (Array.isArray(expected)) {
      const length = expected.length;
      if (!Array.isArray(got) || length != got.length) {
        const error = new Error(message);
        rejector(error);
        throw error;
      }
      for (let i = 0; i < length; ++i) {
        assertEqual(expected[i], got[i], tolerance, message, rejector);
      }
      return;
    }

    got = /** @type {number} */ (got);
    if (Math.abs(expected - got) > tolerance * expected) {
      throw new Error(message);
    }
  }

  /**
   * @param {Array} array The data array.
   * @return {number} The minimum value.
   */
  function getMinForDataType(array) {
    if (array instanceof Int8Array) {
      return -128;
    }
    if (array instanceof Int16Array) {
      return -32768;
    }
    if (array instanceof Int32Array) {
      return -2147483648;
    }
    if (array instanceof Float32Array) {
      return 1.2e-38;
    }
    return 0;
  }

  /**
   * @param {Array} array The data array.
   * @return {number} The maximum value.
   */
  function getMaxForDataType(array) {
    if (array instanceof Int8Array) {
      return 127;
    }
    if (array instanceof Uint8Array) {
      return 255;
    }
    if (array instanceof Uint8ClampedArray) {
      return 255;
    }
    if (array instanceof Int16Array) {
      return 32767;
    }
    if (array instanceof Uint16Array) {
      return 65535;
    }
    if (array instanceof Int32Array) {
      return 2147483647;
    }
    if (array instanceof Uint32Array) {
      return 4294967295;
    }
    if (array instanceof Float32Array) {
      return 3.4e38;
    }
    return 255;
  }

  /**
   * @typedef {Object} GeoTIFFSourceOptions
   * @property {boolean} [forceXHR=false] Whether to force the usage of the browsers XMLHttpRequest API.
   * @property {Object<string, string>} [headers] additional key-value pairs of headers to be passed with each request. Key is the header name, value the header value.
   * @property {string} [credentials] How credentials shall be handled. See
   * https://developer.mozilla.org/en-US/docs/Web/API/fetch for reference and possible values
   * @property {number} [maxRanges] The maximum amount of ranges to request in a single multi-range request.
   * By default only a single range is used.
   * @property {boolean} [allowFullFile=false] Whether or not a full file is accepted when only a portion is
   * requested. Only use this when you know the source image to be small enough to fit in memory.
   * @property {number} [blockSize=65536] The block size to use.
   * @property {number} [cacheSize=100] The number of blocks that shall be held in a LRU cache.
   */

  /**
   * @typedef {Object} Options
   * @property {Array<SourceInfo>} sources List of information about GeoTIFF sources.
   * Multiple sources can be combined when their resolution sets are equal after applying a scale.
   * The list of sources defines a mapping between input bands as they are read from each GeoTIFF and
   * the output bands that are provided by data tiles. To control which bands to read from each GeoTIFF,
   * use the {@link import("./GeoTIFF.js").SourceInfo bands} property. If, for example, you specify two
   * sources, one with 3 bands and {@link import("./GeoTIFF.js").SourceInfo nodata} configured, and
   * another with 1 band, the resulting data tiles will have 5 bands: 3 from the first source, 1 alpha
   * band from the first source, and 1 band from the second source.
   * @property {GeoTIFFSourceOptions} [sourceOptions] Additional options to be passed to [geotiff.js](https://geotiffjs.github.io/geotiff.js/module-geotiff.html)'s `fromUrl` or `fromUrls` methods.
   * @property {true|false|'auto'} [convertToRGB=false] By default, bands from the sources are read as-is. When
   * reading GeoTIFFs with the purpose of displaying them as RGB images, setting this to `true` will
   * convert other color spaces (YCbCr, CMYK) to RGB.  Setting the option to `'auto'` will make it so CMYK, YCbCr,
   * CIELab, and ICCLab images will automatically be converted to RGB.
   * @property {boolean} [normalize=true] By default, the source data is normalized to values between
   * 0 and 1 with scaling factors based on the raster statistics or `min` and `max` properties of each source.
   * If instead you want to work with the raw values in a style expression, set this to `false`.  Setting this option
   * to `false` will make it so any `min` and `max` properties on sources are ignored.
   * @property {import("../proj.js").ProjectionLike} [projection] Source projection.  If not provided, the GeoTIFF metadata
   * will be read for projection information.
   * @property {number} [transition=250] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {boolean} [wrapX=false] Render tiles beyond the tile grid extent.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * the linear interpolation is used to resample the data.  If false, nearest neighbor is used.
   */

  /**
   * @classdesc
   * A source for working with GeoTIFF data.
   * **Note for users of the full build**: The `GeoTIFF` source requires the
   * [geotiff.js](https://github.com/geotiffjs/geotiff.js) library to be loaded as well.
   *
   * @api
   */
  class GeoTIFFSource extends DataTileSource {
    /**
     * @param {Options} options Data tile options.
     */
    constructor(options) {
      super({
        state: 'loading',
        tileGrid: null,
        projection: options.projection || null,
        transition: options.transition,
        interpolate: options.interpolate !== false,
        wrapX: options.wrapX,
      });

      /**
       * @type {Array<SourceInfo>}
       * @private
       */
      this.sourceInfo_ = options.sources;

      const numSources = this.sourceInfo_.length;

      /**
       * @type {Object}
       * @private
       */
      this.sourceOptions_ = options.sourceOptions;

      /**
       * @type {Array<Array<GeoTIFFImage>>}
       * @private
       */
      this.sourceImagery_ = new Array(numSources);

      /**
       * @type {Array<Array<GeoTIFFImage>>}
       * @private
       */
      this.sourceMasks_ = new Array(numSources);

      /**
       * @type {Array<number>}
       * @private
       */
      this.resolutionFactors_ = new Array(numSources);

      /**
       * @type {Array<number>}
       * @private
       */
      this.samplesPerPixel_;

      /**
       * @type {Array<Array<number>>}
       * @private
       */
      this.nodataValues_;

      /**
       * @type {Array<Array<GDALMetadata>>}
       * @private
       */
      this.metadata_;

      /**
       * @type {boolean}
       * @private
       */
      this.normalize_ = options.normalize !== false;

      /**
       * @type {boolean}
       * @private
       */
      this.addAlpha_ = false;

      /**
       * @type {Error}
       * @private
       */
      this.error_ = null;

      /**
       * @type {true|false|'auto'}
       * @private
       */
      this.convertToRGB_ = options.convertToRGB || false;

      this.setKey(this.sourceInfo_.map((source) => source.url).join(','));

      const self = this;
      const requests = new Array(numSources);
      for (let i = 0; i < numSources; ++i) {
        requests[i] = getImagesForSource(
          this.sourceInfo_[i],
          this.sourceOptions_,
        );
      }
      Promise.all(requests)
        .then(function (sources) {
          self.configure_(sources);
        })
        .catch(function (error) {
          error$1(error);
          self.error_ = error;
          self.setState('error');
        });
    }

    /**
     * @return {Error} A source loading error. When the source state is `error`, use this function
     * to get more information about the error. To debug a faulty configuration, you may want to use
     * a listener like
     * ```js
     * geotiffSource.on('change', () => {
     *   if (geotiffSource.getState() === 'error') {
     *     console.error(geotiffSource.getError());
     *   }
     * });
     * ```
     */
    getError() {
      return this.error_;
    }

    /**
     * Determine the projection of the images in this GeoTIFF.
     * The default implementation looks at the ProjectedCSTypeGeoKey and the GeographicTypeGeoKey
     * of each image in turn.
     * You can override this method in a subclass to support more projections.
     *
     * @param {Array<Array<GeoTIFFImage>>} sources Each source is a list of images
     * from a single GeoTIFF.
     */
    determineProjection(sources) {
      const firstSource = sources[0];
      for (let i = firstSource.length - 1; i >= 0; --i) {
        const image = firstSource[i];
        const projection = getProjection(image);
        if (projection) {
          this.projection = projection;
          break;
        }
      }
    }

    /**
     * Determine any transform matrix for the images in this GeoTIFF.
     *
     * @param {Array<Array<GeoTIFFImage>>} sources Each source is a list of images
     * from a single GeoTIFF.
     */
    determineTransformMatrix(sources) {
      const firstSource = sources[0];
      for (let i = firstSource.length - 1; i >= 0; --i) {
        const image = firstSource[i];
        const modelTransformation = image.fileDirectory.ModelTransformation;
        if (modelTransformation) {
          // eslint-disable-next-line no-unused-vars
          const [a, b, c, d, e, f, g, h] = modelTransformation;
          const matrix = multiply(
            multiply(
              [
                1 / Math.sqrt(a * a + e * e),
                0,
                0,
                -1 / Math.sqrt(b * b + f * f),
                d,
                h,
              ],
              [a, e, b, f, 0, 0],
            ),
            [1, 0, 0, 1, -d, -h],
          );
          this.transformMatrix = matrix;
          this.addAlpha_ = true;
          break;
        }
      }
    }

    /**
     * Configure the tile grid based on images within the source GeoTIFFs.  Each GeoTIFF
     * must have the same internal tiled structure.
     * @param {Array<Array<GeoTIFFImage>>} sources Each source is a list of images
     * from a single GeoTIFF.
     * @private
     */
    configure_(sources) {
      let extent;
      let origin;
      let commonRenderTileSizes;
      let commonSourceTileSizes;
      let resolutions;
      const samplesPerPixel = new Array(sources.length);
      const nodataValues = new Array(sources.length);
      const metadata = new Array(sources.length);
      let minZoom = 0;

      const sourceCount = sources.length;
      for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {
        const images = [];
        const masks = [];
        sources[sourceIndex].forEach((item) => {
          if (isMask(item)) {
            masks.push(item);
          } else {
            images.push(item);
          }
        });

        const imageCount = images.length;
        if (masks.length > 0 && masks.length !== imageCount) {
          throw new Error(
            `Expected one mask per image found ${masks.length} masks and ${imageCount} images`,
          );
        }

        let sourceExtent;
        let sourceOrigin;
        const sourceTileSizes = new Array(imageCount);
        const renderTileSizes = new Array(imageCount);
        const sourceResolutions = new Array(imageCount);

        nodataValues[sourceIndex] = new Array(imageCount);
        metadata[sourceIndex] = new Array(imageCount);

        for (let imageIndex = 0; imageIndex < imageCount; ++imageIndex) {
          const image = images[imageIndex];
          const nodataValue = image.getGDALNoData();
          metadata[sourceIndex][imageIndex] = image.getGDALMetadata(0);
          nodataValues[sourceIndex][imageIndex] = nodataValue;

          const wantedSamples = this.sourceInfo_[sourceIndex].bands;
          samplesPerPixel[sourceIndex] = wantedSamples
            ? wantedSamples.length
            : image.getSamplesPerPixel();
          const level = imageCount - (imageIndex + 1);

          if (!sourceExtent) {
            sourceExtent = getBoundingBox(image);
          }

          if (!sourceOrigin) {
            sourceOrigin = getOrigin(image);
          }

          const imageResolutions = getResolutions(image, images[0]);
          sourceResolutions[level] = imageResolutions[0];

          const sourceTileSize = [image.getTileWidth(), image.getTileHeight()];

          // request larger blocks for untiled layouts
          if (
            sourceTileSize[0] !== sourceTileSize[1] &&
            sourceTileSize[1] < defaultTileSize
          ) {
            sourceTileSize[0] = defaultTileSize;
            sourceTileSize[1] = defaultTileSize;
          }

          sourceTileSizes[level] = sourceTileSize;

          const aspectRatio = imageResolutions[0] / Math.abs(imageResolutions[1]);
          renderTileSizes[level] = [
            sourceTileSize[0],
            sourceTileSize[1] / aspectRatio,
          ];
        }

        if (!extent) {
          extent = sourceExtent;
        } else {
          getIntersection(extent, sourceExtent, extent);
        }

        if (!origin) {
          origin = sourceOrigin;
        } else {
          const message = `Origin mismatch for source ${sourceIndex}, got [${sourceOrigin}] but expected [${origin}]`;
          assertEqual(origin, sourceOrigin, 0, message, this.viewRejector);
        }

        if (!resolutions) {
          resolutions = sourceResolutions;
          this.resolutionFactors_[sourceIndex] = 1;
        } else {
          if (resolutions.length - minZoom > sourceResolutions.length) {
            minZoom = resolutions.length - sourceResolutions.length;
          }
          const resolutionFactor =
            resolutions[resolutions.length - 1] /
            sourceResolutions[sourceResolutions.length - 1];
          this.resolutionFactors_[sourceIndex] = resolutionFactor;
          const scaledSourceResolutions = sourceResolutions.map(
            (resolution) => (resolution *= resolutionFactor),
          );
          const message = `Resolution mismatch for source ${sourceIndex}, got [${scaledSourceResolutions}] but expected [${resolutions}]`;
          assertEqual(
            resolutions.slice(minZoom, resolutions.length),
            scaledSourceResolutions,
            0.02,
            message,
            this.viewRejector,
          );
        }

        if (!commonRenderTileSizes) {
          commonRenderTileSizes = renderTileSizes;
        } else {
          assertEqual(
            commonRenderTileSizes.slice(minZoom, commonRenderTileSizes.length),
            renderTileSizes,
            0.01,
            `Tile size mismatch for source ${sourceIndex}`,
            this.viewRejector,
          );
        }

        if (!commonSourceTileSizes) {
          commonSourceTileSizes = sourceTileSizes;
        } else {
          assertEqual(
            commonSourceTileSizes.slice(minZoom, commonSourceTileSizes.length),
            sourceTileSizes,
            0,
            `Tile size mismatch for source ${sourceIndex}`,
            this.viewRejector,
          );
        }

        this.sourceImagery_[sourceIndex] = images.reverse();
        this.sourceMasks_[sourceIndex] = masks.reverse();
      }

      for (let i = 0, ii = this.sourceImagery_.length; i < ii; ++i) {
        const sourceImagery = this.sourceImagery_[i];
        while (sourceImagery.length < resolutions.length) {
          sourceImagery.unshift(undefined);
        }
      }

      if (!this.getProjection()) {
        this.determineProjection(sources);
      }
      this.determineTransformMatrix(sources);

      this.samplesPerPixel_ = samplesPerPixel;
      this.nodataValues_ = nodataValues;
      this.metadata_ = metadata;

      // decide if we need to add an alpha band to handle nodata
      outer: for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {
        // option 1: source is configured with a nodata value
        if (this.sourceInfo_[sourceIndex].nodata !== undefined) {
          this.addAlpha_ = true;
          break;
        }
        if (this.sourceMasks_[sourceIndex].length) {
          this.addAlpha_ = true;
          break;
        }

        const values = nodataValues[sourceIndex];

        // option 2: check image metadata for limited bands
        const bands = this.sourceInfo_[sourceIndex].bands;
        if (bands) {
          for (let i = 0; i < bands.length; ++i) {
            if (values[bands[i] - 1] !== null) {
              this.addAlpha_ = true;
              break outer;
            }
          }
          continue;
        }

        // option 3: check image metadata for all bands
        for (let imageIndex = 0; imageIndex < values.length; ++imageIndex) {
          if (values[imageIndex] !== null) {
            this.addAlpha_ = true;
            break outer;
          }
        }
      }

      let bandCount = this.addAlpha_ ? 1 : 0;
      for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {
        bandCount += samplesPerPixel[sourceIndex];
      }
      this.bandCount = bandCount;

      const tileGrid = new TileGrid({
        extent: extent,
        minZoom: minZoom,
        origin: origin,
        resolutions: resolutions,
        tileSizes: commonRenderTileSizes,
      });

      this.tileGrid = tileGrid;
      this.setTileSizes(commonSourceTileSizes);

      this.setLoader(this.loadTile_.bind(this));
      this.setState('ready');

      const zoom = 1;
      if (resolutions.length === 2) {
        resolutions = [resolutions[0], resolutions[1], resolutions[1] / 2];
      } else if (resolutions.length === 1) {
        resolutions = [resolutions[0] * 2, resolutions[0], resolutions[0] / 2];
      }

      let viewExtent = extent;
      if (this.transformMatrix) {
        const matrix = makeInverse(create$3(), this.transformMatrix.slice());
        const transformFn = createTransformFromCoordinateTransform((input) =>
          apply(matrix, input),
        );
        viewExtent = applyTransform(extent, transformFn);
      }

      this.viewResolver({
        showFullExtent: true,
        projection: this.projection,
        resolutions: resolutions,
        center: toUserCoordinate(getCenter(viewExtent), this.projection),
        extent: toUserExtent(viewExtent, this.projection),
        zoom: zoom,
      });
    }

    /**
     * @param {number} z The z tile index.
     * @param {number} x The x tile index.
     * @param {number} y The y tile index.
     * @param {import('./DataTile.js').LoaderOptions} options The loader options.
     * @return {Promise} The composed tile data.
     * @private
     */
    loadTile_(z, x, y, options) {
      const sourceTileSize = this.getTileSize(z);
      const sourceCount = this.sourceImagery_.length;
      const requests = new Array(sourceCount * 2);
      const nodataValues = this.nodataValues_;
      const sourceInfo = this.sourceInfo_;
      const pool = getWorkerPool();
      for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {
        const source = sourceInfo[sourceIndex];
        const resolutionFactor = this.resolutionFactors_[sourceIndex];
        const pixelBounds = [
          Math.round(x * (sourceTileSize[0] * resolutionFactor)),
          Math.round(y * (sourceTileSize[1] * resolutionFactor)),
          Math.round((x + 1) * (sourceTileSize[0] * resolutionFactor)),
          Math.round((y + 1) * (sourceTileSize[1] * resolutionFactor)),
        ];
        const image = this.sourceImagery_[sourceIndex][z];
        let samples;
        if (source.bands) {
          samples = source.bands.map(function (bandNumber) {
            return bandNumber - 1;
          });
        }

        /** @type {number|Array<number>} */
        let fillValue;
        if ('nodata' in source && source.nodata !== null) {
          fillValue = source.nodata;
        } else {
          if (!samples) {
            fillValue = nodataValues[sourceIndex];
          } else {
            fillValue = samples.map(function (sampleIndex) {
              return nodataValues[sourceIndex][sampleIndex];
            });
          }
        }

        const readOptions = {
          window: pixelBounds,
          width: sourceTileSize[0],
          height: sourceTileSize[1],
          samples: samples,
          fillValue: fillValue,
          pool: pool,
          interleave: false,
          signal: options.signal,
        };
        if (readRGB(this.convertToRGB_, image)) {
          requests[sourceIndex] = image.readRGB(readOptions);
        } else {
          requests[sourceIndex] = image.readRasters(readOptions);
        }

        // requests after `sourceCount` are for mask data (if any)
        const maskIndex = sourceCount + sourceIndex;
        const mask = this.sourceMasks_[sourceIndex][z];
        if (!mask) {
          requests[maskIndex] = Promise.resolve(null);
          continue;
        }

        requests[maskIndex] = mask.readRasters({
          window: pixelBounds,
          width: sourceTileSize[0],
          height: sourceTileSize[1],
          samples: [0],
          pool: pool,
          interleave: false,
        });
      }

      return Promise.all(requests)
        .then(this.composeTile_.bind(this, sourceTileSize))
        .catch(function (error) {
          error$1(error);
          throw error;
        });
    }

    /**
     * @param {import("../size.js").Size} sourceTileSize The source tile size.
     * @param {Array} sourceSamples The source samples.
     * @return {import("../DataTile.js").Data} The composed tile data.
     * @private
     */
    composeTile_(sourceTileSize, sourceSamples) {
      const metadata = this.metadata_;
      const sourceInfo = this.sourceInfo_;
      const sourceCount = this.sourceImagery_.length;
      const bandCount = this.bandCount;
      const samplesPerPixel = this.samplesPerPixel_;
      const nodataValues = this.nodataValues_;
      const normalize = this.normalize_;
      const addAlpha = this.addAlpha_;

      const pixelCount = sourceTileSize[0] * sourceTileSize[1];
      const dataLength = pixelCount * bandCount;

      /** @type {Uint8Array|Float32Array} */
      let data;
      if (normalize) {
        data = new Uint8Array(dataLength);
      } else {
        data = new Float32Array(dataLength);
      }

      let dataIndex = 0;
      for (let pixelIndex = 0; pixelIndex < pixelCount; ++pixelIndex) {
        let transparent = addAlpha;
        for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {
          const source = sourceInfo[sourceIndex];

          let min = source.min;
          let max = source.max;
          let gain, bias;
          if (normalize) {
            const stats = metadata[sourceIndex][0];
            if (min === undefined) {
              if (stats && STATISTICS_MINIMUM in stats) {
                min = parseFloat(stats[STATISTICS_MINIMUM]);
              } else {
                min = getMinForDataType(sourceSamples[sourceIndex][0]);
              }
            }
            if (max === undefined) {
              if (stats && STATISTICS_MAXIMUM in stats) {
                max = parseFloat(stats[STATISTICS_MAXIMUM]);
              } else {
                max = getMaxForDataType(sourceSamples[sourceIndex][0]);
              }
            }

            gain = 255 / (max - min);
            bias = -min * gain;
          }

          for (
            let sampleIndex = 0;
            sampleIndex < samplesPerPixel[sourceIndex];
            ++sampleIndex
          ) {
            const sourceValue =
              sourceSamples[sourceIndex][sampleIndex][pixelIndex];

            let value;
            if (normalize) {
              value = clamp$1(gain * sourceValue + bias, 0, 255);
            } else {
              value = sourceValue;
            }

            if (!addAlpha) {
              data[dataIndex] = value;
            } else {
              let nodata = source.nodata;
              if (nodata === undefined) {
                let bandIndex;
                if (source.bands) {
                  bandIndex = source.bands[sampleIndex] - 1;
                } else {
                  bandIndex = sampleIndex;
                }
                nodata = nodataValues[sourceIndex][bandIndex];
              }

              const nodataIsNaN = isNaN(nodata);
              if (
                (!nodataIsNaN && sourceValue !== nodata) ||
                (nodataIsNaN && !isNaN(sourceValue))
              ) {
                transparent = false;
                data[dataIndex] = value;
              }
            }
            dataIndex++;
          }
          if (!transparent) {
            const maskIndex = sourceCount + sourceIndex;
            const mask = sourceSamples[maskIndex];
            if (mask && !mask[0][pixelIndex]) {
              transparent = true;
            }
          }
        }
        if (addAlpha) {
          if (!transparent) {
            data[dataIndex] = 255;
          }
          dataIndex++;
        }
      }

      return data;
    }
  }

  /**
   * Get a promise for view properties based on the source.  Use the result of this function
   * as the `view` option in a map constructor.
   *
   *     const source = new GeoTIFF(options);
   *
   *     const map = new Map({
   *       target: 'map',
   *       layers: [
   *         new TileLayer({
   *           source: source,
   *         }),
   *       ],
   *       view: source.getView(),
   *     });
   *
   * @function
   * @return {Promise<import("../View.js").ViewOptions>} A promise for view-related properties.
   * @api
   *
   */
  GeoTIFFSource.prototype.getView;

  /**
   * @module ol/source/Google
   */


  const createSessionUrl = 'https://tile.googleapis.com/v1/createSession';
  const tileUrl = 'https://tile.googleapis.com/v1/2dtiles';
  const attributionUrl = 'https://tile.googleapis.com/tile/v1/viewport';
  const maxZoom = 22;

  /**
   * @typedef {Object} Options
   * @property {string} key Google Map Tiles API key. Get yours at https://developers.google.com/maps/documentation/tile/get-api-key.
   * @property {string} [mapType='roadmap'] The type of [base map](https://developers.google.com/maps/documentation/tile/session_tokens#required_fields).
   * @property {string} [language='en-US'] An [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag) for information displayed on the tiles.
   * @property {string} [region='US'] A [Common Locale Data Repository](https://cldr.unicode.org/) (CLDR) region identifier that represents the user location.
   * @property {string} [imageFormat] The image format used for the map tiles (e.g. `'jpeg'`, or `'png'`).
   * @property {string} [scale] Scale for map elements (`'scaleFactor1x'`, `'scaleFactor2x'`, or `'scaleFactor4x'`).
   * @property {boolean} [highDpi=false] Use high-resolution tiles.
   * @property {Array<string>} [layerTypes] The layer types added to the map (e.g. `'layerRoadmap'`, `'layerStreetview'`, or `'layerTraffic'`).
   * @property {boolean} [overlay=false] Display only the `layerTypes` and not the underlying `mapType` (only works if `layerTypes` is provided).
   * @property {Array<Object>} [styles] [Custom styles](https://developers.google.com/maps/documentation/tile/style-reference) applied to the map.
   * @property {boolean} [attributionsCollapsible=true] Allow the attributions to be collapsed.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {Array<string>} [apiOptions] An array of values specifying additional options to apply.
   * @property {boolean} [wrapX=true] Wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @typedef {Object} SessionTokenRequest
   * @property {string} mapType The map type.
   * @property {string} language The language.
   * @property {string} region The region.
   * @property {string} [imageFormat] The image format.
   * @property {string} [scale] The scale.
   * @property {boolean} [highDpi] Use high resolution tiles.
   * @property {Array<string>} [layerTypes] The layer types.
   * @property {boolean} [overlay] The overlay.
   * @property {Array<Object>} [styles] The styles.
   * @property {Array<string>} [apiOptions] An array of values specifying additional options to apply.
   */

  /**
   * @typedef {Object} SessionTokenResponse
   * @property {string} session The session token.
   * @property {string} expiry The session token expiry (seconds since the epoch as a string).
   * @property {number} tileWidth The tile width.
   * @property {number} tileHeight The tile height.
   * @property {string} imageFormat The image format.
   */

  /**
   * @classdesc
   * A tile layer source that renders tiles from the Google [Map Tiles API](https://developers.google.com/maps/documentation/tile/overview).
   * The constructor takes options that are passed to the request to create a session token.  Refer to the
   * [documentation](https://developers.google.com/maps/documentation/tile/session_tokens#required_fields)
   * for additional details.
   * @api
   */
  class Google extends TileImage {
    /**
     * @param {Options} options Google Maps options.
     */
    constructor(options) {
      const highDpi = !!options.highDpi;

      super({
        attributionsCollapsible: options.attributionsCollapsible,
        cacheSize: options.cacheSize,
        crossOrigin: 'anonymous',
        interpolate: options.interpolate,
        projection: 'EPSG:3857',
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        state: 'loading',
        tileLoadFunction: options.tileLoadFunction,
        tilePixelRatio: highDpi ? 2 : 1,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @type {string}
       * @private
       */
      this.apiKey_ = options.key;

      /**
       * @type {Error|null}
       * @private
       */
      this.error_ = null;

      /**
       * @type {SessionTokenRequest}
       */
      const sessionTokenRequest = {
        mapType: options.mapType || 'roadmap',
        language: options.language || 'en-US',
        region: options.region || 'US',
      };
      if (options.imageFormat) {
        sessionTokenRequest.imageFormat = options.imageFormat;
      }
      if (options.scale) {
        sessionTokenRequest.scale = options.scale;
      }
      if (highDpi) {
        sessionTokenRequest.highDpi = true;
      }
      if (options.layerTypes) {
        sessionTokenRequest.layerTypes = options.layerTypes;
      }
      if (options.styles) {
        sessionTokenRequest.styles = options.styles;
      }
      if (options.overlay === true) {
        sessionTokenRequest.overlay = true;
      }
      if (options.apiOptions) {
        sessionTokenRequest.apiOptions = options.apiOptions;
      }

      /**
       * @type {SessionTokenRequest}
       * @private
       */
      this.sessionTokenRequest_ = sessionTokenRequest;

      /**
       * @type {string}
       * @private
       */
      this.sessionTokenValue_;

      /**
       * @type {ReturnType<typeof setTimeout>}
       * @private
       */
      this.sessionRefreshId_;

      /**
       * @type {string}
       * @private
       */
      this.previousViewportAttribution_;

      /**
       * @type {string}
       * @private
       */
      this.previousViewportExtent_;

      this.createSession_();
    }

    /**
     * @return {Error|null} A source loading error. When the source state is `error`, use this function
     * to get more information about the error. To debug a faulty configuration, you may want to use
     * a listener like
     * ```js
     * source.on('change', () => {
     *   if (source.getState() === 'error') {
     *     console.error(source.getError());
     *   }
     * });
     * ```
     */
    getError() {
      return this.error_;
    }

    /**
     * Exposed here so it can be overridden in the tests.
     * @param {string} url The URL.
     * @param {RequestInit} config The config.
     * @return {Promise<Response>} A promise that resolves with the response.
     */
    fetchSessionToken(url, config) {
      return fetch(url, config);
    }

    /**
     * Get or renew a session token for use with tile requests.
     * @private
     */
    async createSession_() {
      const url = createSessionUrl + '?key=' + this.apiKey_;
      const config = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.sessionTokenRequest_),
      };

      const response = await this.fetchSessionToken(url, config);
      if (!response.ok) {
        try {
          const body = await response.json();
          this.error_ = new Error(body.error.message);
        } catch {
          this.error_ = new Error('Error fetching session token');
        }
        this.setState('error');
        return;
      }

      /**
       * @type {SessionTokenResponse}
       */
      const sessionTokenResponse = await response.json();

      const tilePixelRatio = this.getTilePixelRatio(1);
      const tileSize = [
        sessionTokenResponse.tileWidth / tilePixelRatio,
        sessionTokenResponse.tileHeight / tilePixelRatio,
      ];

      this.tileGrid = createXYZ({
        extent: extentFromProjection(this.getProjection()),
        maxZoom: maxZoom,
        tileSize: tileSize,
      });

      const session = sessionTokenResponse.session;
      this.sessionTokenValue_ = session;
      const key = this.apiKey_;
      this.tileUrlFunction = function (tileCoord, pixelRatio, projection) {
        const z = tileCoord[0];
        const x = tileCoord[1];
        const y = tileCoord[2];
        const url = `${tileUrl}/${z}/${x}/${y}?session=${session}&key=${key}`;
        return url;
      };

      const expiry = parseInt(sessionTokenResponse.expiry, 10) * 1000;
      const timeout = Math.max(expiry - Date.now() - 60 * 1000, 1);
      this.sessionRefreshId_ = setTimeout(() => this.createSession_(), timeout);

      this.setAttributions(this.fetchAttributions_.bind(this));
      // even if the state is already ready, we want the change event
      this.setState('ready');
    }

    /**
     * @param {import('../Map.js').FrameState} frameState The frame state.
     * @return {Promise<string>} The attributions.
     * @private
     */
    async fetchAttributions_(frameState) {
      if (
        frameState.viewHints[ViewHint.ANIMATING] ||
        frameState.viewHints[ViewHint.INTERACTING] ||
        frameState.animate
      ) {
        return this.previousViewportAttribution_;
      }
      const [west, south] = toLonLat(
        getBottomLeft(frameState.extent),
        frameState.viewState.projection,
      );
      const [east, north] = toLonLat(
        getTopRight(frameState.extent),
        frameState.viewState.projection,
      );
      const tileGrid = this.getTileGrid();
      const zoom = tileGrid.getZForResolution(
        frameState.viewState.resolution,
        this.zDirection,
      );
      const viewportExtent = `zoom=${zoom}&north=${north}&south=${south}&east=${east}&west=${west}`;
      // check if the extent or zoom has actually changed to avoid unnecessary requests
      if (this.previousViewportExtent_ == viewportExtent) {
        return this.previousViewportAttribution_;
      }
      this.previousViewportExtent_ = viewportExtent;
      const session = this.sessionTokenValue_;
      const key = this.apiKey_;
      const url = `${attributionUrl}?session=${session}&key=${key}&${viewportExtent}`;
      this.previousViewportAttribution_ = await fetch(url)
        .then((response) => response.json())
        .then((json) => json.copyright);

      return this.previousViewportAttribution_;
    }

    /**
     * @override
     */
    disposeInternal() {
      clearTimeout(this.sessionRefreshId_);
      super.disposeInternal();
    }
  }

  /**
   * @module ol/source/Zoomify
   */


  /**
   * @typedef {'default' | 'truncated'} TierSizeCalculation
   */

  let CustomTile$1 = class CustomTile extends ImageTile {
    /**
     * @param {import("../size.js").Size} tileSize Full tile size.
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../TileState.js").default} state State.
     * @param {string} src Image source URI.
     * @param {?string} crossOrigin Cross origin.
     * @param {import("../Tile.js").LoadFunction} tileLoadFunction Tile load function.
     * @param {import("../Tile.js").Options} [options] Tile options.
     */
    constructor(
      tileSize,
      tileCoord,
      state,
      src,
      crossOrigin,
      tileLoadFunction,
      options,
    ) {
      super(tileCoord, state, src, crossOrigin, tileLoadFunction, options);

      /**
       * @private
       * @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement}
       */
      this.zoomifyImage_ = null;

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.tileSize_ = tileSize;
    }

    /**
     * Get the image element for this tile.
     * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
     * @override
     */
    getImage() {
      if (this.zoomifyImage_) {
        return this.zoomifyImage_;
      }
      const image = super.getImage();
      if (this.state == TileState.LOADED) {
        const tileSize = this.tileSize_;
        if (image.width == tileSize[0] && image.height == tileSize[1]) {
          this.zoomifyImage_ = image;
          return image;
        }
        const context = createCanvasContext2D(tileSize[0], tileSize[1]);
        context.drawImage(image, 0, 0);
        this.zoomifyImage_ = context.canvas;
        return context.canvas;
      }
      return image;
    }
  };

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value  you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection.
   * @property {number} [tilePixelRatio] The pixel ratio used by the tile service. For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px by 512px images (for retina/hidpi devices) then `tilePixelRatio` should be set to `2`
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {string} url URL template or base URL of the Zoomify service.
   * A base URL is the fixed part
   * of the URL, excluding the tile group, z, x, and y folder structure, e.g.
   * `http://my.zoomify.info/IMAGE.TIF/`. A URL template must include
   * `{TileGroup}`, `{x}`, `{y}`, and `{z}` placeholders, e.g.
   * `http://my.zoomify.info/IMAGE.TIF/{TileGroup}/{z}-{x}-{y}.jpg`.
   * Internet Imaging Protocol (IIP) with JTL extension can be also used with
   * `{tileIndex}` and `{z}` placeholders, e.g.
   * `http://my.zoomify.info?FIF=IMAGE.TIF&JTL={z},{tileIndex}`.
   * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be
   * used instead of defining each one separately in the `urls` option.
   * @property {TierSizeCalculation} [tierSizeCalculation] Tier size calculation method: `default` or `truncated`.
   * @property {import("../size.js").Size} size Size.
   * @property {import("../extent.js").Extent} [extent] Extent for the TileGrid that is created.
   * Default sets the TileGrid in the
   * fourth quadrant, meaning extent is `[0, -height, width, 0]`. To change the
   * extent to the first quadrant (the default for OpenLayers 2) set the extent
   * as `[0, 0, width, height]`.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number} [tileSize=256] Tile size. Same tile size is used for all zoom levels.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data in Zoomify format (both Zoomify and Internet
   * Imaging Protocol are supported).
   * @api
   */
  class Zoomify extends TileImage {
    /**
     * @param {Options} options Options.
     */
    constructor(options) {
      const size = options.size;
      const tierSizeCalculation =
        options.tierSizeCalculation !== undefined
          ? options.tierSizeCalculation
          : 'default';

      const tilePixelRatio = options.tilePixelRatio || 1;
      const imageWidth = size[0];
      const imageHeight = size[1];
      const tierSizeInTiles = [];
      const tileSize = options.tileSize || DEFAULT_TILE_SIZE;
      let tileSizeForTierSizeCalculation = tileSize * tilePixelRatio;

      switch (tierSizeCalculation) {
        case 'default':
          while (
            imageWidth > tileSizeForTierSizeCalculation ||
            imageHeight > tileSizeForTierSizeCalculation
          ) {
            tierSizeInTiles.push([
              Math.ceil(imageWidth / tileSizeForTierSizeCalculation),
              Math.ceil(imageHeight / tileSizeForTierSizeCalculation),
            ]);
            tileSizeForTierSizeCalculation += tileSizeForTierSizeCalculation;
          }
          break;
        case 'truncated':
          let width = imageWidth;
          let height = imageHeight;
          while (
            width > tileSizeForTierSizeCalculation ||
            height > tileSizeForTierSizeCalculation
          ) {
            tierSizeInTiles.push([
              Math.ceil(width / tileSizeForTierSizeCalculation),
              Math.ceil(height / tileSizeForTierSizeCalculation),
            ]);
            width >>= 1;
            height >>= 1;
          }
          break;
        default:
          throw new Error('Unknown `tierSizeCalculation` configured');
      }

      tierSizeInTiles.push([1, 1]);
      tierSizeInTiles.reverse();

      const resolutions = [tilePixelRatio];
      const tileCountUpToTier = [0];
      for (let i = 1, ii = tierSizeInTiles.length; i < ii; i++) {
        resolutions.push(tilePixelRatio << i);
        tileCountUpToTier.push(
          tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] +
            tileCountUpToTier[i - 1],
        );
      }
      resolutions.reverse();

      const tileGrid = new TileGrid({
        tileSize: tileSize,
        extent: options.extent || [0, -imageHeight, imageWidth, 0],
        resolutions: resolutions,
      });

      let url = options.url;
      if (url && !url.includes('{TileGroup}') && !url.includes('{tileIndex}')) {
        url += '{TileGroup}/{z}-{x}-{y}.jpg';
      }
      const urls = expandUrl(url);

      let tileWidth = tileSize * tilePixelRatio;

      /**
       * @param {string} template Template.
       * @return {import("../Tile.js").UrlFunction} Tile URL function.
       */
      function createFromTemplate(template) {
        return (
          /**
           * @param {import("../tilecoord.js").TileCoord} tileCoord Tile Coordinate.
           * @param {number} pixelRatio Pixel ratio.
           * @param {import("../proj/Projection.js").default} projection Projection.
           * @return {string|undefined} Tile URL.
           */
          function (tileCoord, pixelRatio, projection) {
            if (!tileCoord) {
              return undefined;
            }
            const tileCoordZ = tileCoord[0];
            const tileCoordX = tileCoord[1];
            const tileCoordY = tileCoord[2];
            const tileIndex =
              tileCoordX + tileCoordY * tierSizeInTiles[tileCoordZ][0];
            const tileGroup =
              ((tileIndex + tileCountUpToTier[tileCoordZ]) / tileWidth) | 0;
            const localContext = {
              'z': tileCoordZ,
              'x': tileCoordX,
              'y': tileCoordY,
              'tileIndex': tileIndex,
              'TileGroup': 'TileGroup' + tileGroup,
            };
            return template.replace(/\{(\w+?)\}/g, function (m, p) {
              return localContext[p];
            });
          }
        );
      }

      const tileUrlFunction = createFromTileUrlFunctions(
        urls.map(createFromTemplate),
      );

      const ZoomifyTileClass = CustomTile$1.bind(
        null,
        toSize(tileSize * tilePixelRatio),
      );

      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: options.projection,
        tilePixelRatio: tilePixelRatio,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileClass: ZoomifyTileClass,
        tileGrid: tileGrid,
        tileUrlFunction: tileUrlFunction,
        transition: options.transition,
      });

      /**
       * @type {number|import("../array.js").NearestDirectionFunction}
       */
      this.zDirection = options.zDirection;

      // Server retina tile detection (non-standard):
      // Try loading the center tile for the highest resolution. If it is not
      // available, we are dealing with retina tiles, and need to adjust the
      // tile url calculation.
      const tileUrl = tileGrid.getTileCoordForCoordAndResolution(
        getCenter(tileGrid.getExtent()),
        resolutions[resolutions.length - 1],
      );
      const testTileUrl = tileUrlFunction(tileUrl, 1, null);
      const image = new Image();
      image.addEventListener('error', () => {
        tileWidth = tileSize;
        this.changed();
      });
      image.src = testTileUrl;
    }
  }

  /**
   * @module ol/source/IIIF
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The value for the crossOrigin option of the request.
   * @property {import("../extent.js").Extent} [extent=[0, -height, width, 0]] The extent.
   * @property {string} [format='jpg'] Requested image format.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection.
   * @property {string} [quality] Requested IIIF image quality. Default is 'native'
   * for version 1, 'default' for versions 2 and 3.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {Array<number>} [resolutions] Supported resolutions as given in IIIF 'scaleFactors'
   * @property {import("../size.js").Size} size Size of the image [width, height].
   * @property {Array<import("../size.js").Size>} [sizes] Supported scaled image sizes.
   * Content of the IIIF info.json 'sizes' property, but as array of Size objects.
   * @property {import("./Source.js").State} [state] Source state.
   * @property {Array<string>} [supports=[]] Supported IIIF region and size calculation
   * features.
   * @property {number} [tilePixelRatio] Tile pixel ratio.
   * @property {number|import("../size.js").Size} [tileSize] Tile size.
   * Same tile size is used for all zoom levels. If tile size is a number,
   * a square tile is assumed. If the IIIF image service supports arbitrary
   * tiling (sizeByH, sizeByW, sizeByWh or sizeByPct as well as regionByPx or regionByPct
   * are supported), the default tilesize is 256.
   * @property {number} [transition] Transition.
   * @property {string} [url] Base URL of the IIIF Image service.
   * This should be the same as the IIIF Image ID.
   * @property {import("../format/IIIFInfo.js").Versions} [version=Versions.VERSION2] Service's IIIF Image API version.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  function formatPercentage(percentage) {
    return percentage.toLocaleString('en', {maximumFractionDigits: 10});
  }

  /**
   * @classdesc
   * Layer source for IIIF Image API services.
   * @api
   */
  class IIIF extends TileImage {
    /**
     * @param {Options} [options] Tile source options. Use {@link import("../format/IIIFInfo.js").IIIFInfo}
     * to parse Image API service information responses into constructor options.
     * @api
     */
    constructor(options) {
      /**
       * @type {Partial<Options>}
       */
      const partialOptions = options || {};

      let baseUrl = partialOptions.url || '';
      baseUrl =
        baseUrl +
        (baseUrl.lastIndexOf('/') === baseUrl.length - 1 || baseUrl === ''
          ? ''
          : '/');
      const version = partialOptions.version || Versions.VERSION2;
      const sizes = partialOptions.sizes || [];
      const size = partialOptions.size;
      assert(
        size != undefined &&
          Array.isArray(size) &&
          size.length == 2 &&
          !isNaN(size[0]) &&
          size[0] > 0 &&
          !isNaN(size[1]) &&
          size[1] > 0,
        'Missing or invalid `size`',
      );
      const width = size[0];
      const height = size[1];
      const tileSize = partialOptions.tileSize;
      const tilePixelRatio = partialOptions.tilePixelRatio || 1;
      const format = partialOptions.format || 'jpg';
      const quality =
        partialOptions.quality ||
        (partialOptions.version == Versions.VERSION1 ? 'native' : 'default');
      let resolutions = partialOptions.resolutions || [];
      const supports = partialOptions.supports || [];
      const extent = partialOptions.extent || [0, -height, width, 0];

      const supportsListedSizes =
        sizes != undefined && Array.isArray(sizes) && sizes.length > 0;
      const supportsListedTiles =
        tileSize !== undefined &&
        ((typeof tileSize === 'number' &&
          Number.isInteger(tileSize) &&
          tileSize > 0) ||
          (Array.isArray(tileSize) && tileSize.length > 0));
      const supportsArbitraryTiling =
        supports != undefined &&
        Array.isArray(supports) &&
        (supports.includes('regionByPx') || supports.includes('regionByPct')) &&
        (supports.includes('sizeByWh') ||
          supports.includes('sizeByH') ||
          supports.includes('sizeByW') ||
          supports.includes('sizeByPct'));

      let tileWidth, tileHeight, maxZoom;

      resolutions.sort(function (a, b) {
        return b - a;
      });

      if (supportsListedTiles || supportsArbitraryTiling) {
        if (tileSize != undefined) {
          if (
            typeof tileSize === 'number' &&
            Number.isInteger(tileSize) &&
            tileSize > 0
          ) {
            tileWidth = tileSize;
            tileHeight = tileSize;
          } else if (Array.isArray(tileSize) && tileSize.length > 0) {
            if (
              tileSize.length == 1 ||
              (tileSize[1] == undefined && Number.isInteger(tileSize[0]))
            ) {
              tileWidth = tileSize[0];
              tileHeight = tileSize[0];
            }
            if (tileSize.length == 2) {
              if (
                Number.isInteger(tileSize[0]) &&
                Number.isInteger(tileSize[1])
              ) {
                tileWidth = tileSize[0];
                tileHeight = tileSize[1];
              } else if (
                tileSize[0] == undefined &&
                Number.isInteger(tileSize[1])
              ) {
                tileWidth = tileSize[1];
                tileHeight = tileSize[1];
              }
            }
          }
        }
        if (tileWidth === undefined || tileHeight === undefined) {
          tileWidth = DEFAULT_TILE_SIZE;
          tileHeight = DEFAULT_TILE_SIZE;
        }
        if (resolutions.length == 0) {
          maxZoom = Math.max(
            Math.ceil(Math.log(width / tileWidth) / Math.LN2),
            Math.ceil(Math.log(height / tileHeight) / Math.LN2),
          );
          for (let i = maxZoom; i >= 0; i--) {
            resolutions.push(Math.pow(2, i));
          }
        } else {
          const maxScaleFactor = Math.max(...resolutions);
          // TODO maxScaleFactor might not be a power to 2
          maxZoom = Math.round(Math.log(maxScaleFactor) / Math.LN2);
        }
      } else {
        // No tile support.
        tileWidth = width;
        tileHeight = height;
        resolutions = [];
        if (supportsListedSizes) {
          /*
           * 'sizes' provided. Use full region in different resolutions. Every
           * resolution has only one tile.
           */
          sizes.sort(function (a, b) {
            return a[0] - b[0];
          });
          maxZoom = -1;
          const ignoredSizesIndex = [];
          for (let i = 0; i < sizes.length; i++) {
            const resolution = width / sizes[i][0];
            if (
              resolutions.length > 0 &&
              resolutions[resolutions.length - 1] == resolution
            ) {
              ignoredSizesIndex.push(i);
              continue;
            }
            resolutions.push(resolution);
            maxZoom++;
          }
          if (ignoredSizesIndex.length > 0) {
            for (let i = 0; i < ignoredSizesIndex.length; i++) {
              sizes.splice(ignoredSizesIndex[i] - i, 1);
            }
          }
        } else {
          // No useful image information at all. Try pseudo tile with full image.
          resolutions.push(1);
          sizes.push([width, height]);
          maxZoom = 0;
        }
      }

      const tileGrid = new TileGrid({
        tileSize: [tileWidth, tileHeight],
        extent: extent,
        origin: getTopLeft(extent),
        resolutions: resolutions,
      });

      const tileUrlFunction = function (tileCoord, pixelRatio, projection) {
        let regionParam, sizeParam;
        const zoom = tileCoord[0];
        if (zoom > maxZoom) {
          return;
        }
        const tileX = tileCoord[1],
          tileY = tileCoord[2],
          scale = resolutions[zoom];
        if (
          tileX === undefined ||
          tileY === undefined ||
          scale === undefined ||
          tileX < 0 ||
          Math.ceil(width / scale / tileWidth) <= tileX ||
          tileY < 0 ||
          Math.ceil(height / scale / tileHeight) <= tileY
        ) {
          return;
        }
        if (supportsArbitraryTiling || supportsListedTiles) {
          const regionX = tileX * tileWidth * scale,
            regionY = tileY * tileHeight * scale;
          let regionW = tileWidth * scale,
            regionH = tileHeight * scale,
            sizeW = tileWidth,
            sizeH = tileHeight;
          if (regionX + regionW > width) {
            regionW = width - regionX;
          }
          if (regionY + regionH > height) {
            regionH = height - regionY;
          }
          if (regionX + tileWidth * scale > width) {
            sizeW = Math.floor((width - regionX + scale - 1) / scale);
          }
          if (regionY + tileHeight * scale > height) {
            sizeH = Math.floor((height - regionY + scale - 1) / scale);
          }
          if (
            regionX == 0 &&
            regionW == width &&
            regionY == 0 &&
            regionH == height
          ) {
            // canonical full image region parameter is 'full', not 'x,y,w,h'
            regionParam = 'full';
          } else if (
            !supportsArbitraryTiling ||
            supports.includes('regionByPx')
          ) {
            regionParam = regionX + ',' + regionY + ',' + regionW + ',' + regionH;
          } else if (supports.includes('regionByPct')) {
            const pctX = formatPercentage((regionX / width) * 100),
              pctY = formatPercentage((regionY / height) * 100),
              pctW = formatPercentage((regionW / width) * 100),
              pctH = formatPercentage((regionH / height) * 100);
            regionParam = 'pct:' + pctX + ',' + pctY + ',' + pctW + ',' + pctH;
          }
          if (
            version == Versions.VERSION3 &&
            (!supportsArbitraryTiling || supports.includes('sizeByWh'))
          ) {
            sizeParam = sizeW + ',' + sizeH;
          } else if (!supportsArbitraryTiling || supports.includes('sizeByW')) {
            sizeParam = sizeW + ',';
          } else if (supports.includes('sizeByH')) {
            sizeParam = ',' + sizeH;
          } else if (supports.includes('sizeByWh')) {
            sizeParam = sizeW + ',' + sizeH;
          } else if (supports.includes('sizeByPct')) {
            sizeParam = 'pct:' + formatPercentage(100 / scale);
          }
        } else {
          regionParam = 'full';
          if (supportsListedSizes) {
            const regionWidth = sizes[zoom][0],
              regionHeight = sizes[zoom][1];
            if (version == Versions.VERSION3) {
              if (regionWidth == width && regionHeight == height) {
                sizeParam = 'max';
              } else {
                sizeParam = regionWidth + ',' + regionHeight;
              }
            } else {
              if (regionWidth == width) {
                sizeParam = 'full';
              } else {
                sizeParam = regionWidth + ',';
              }
            }
          } else {
            sizeParam = version == Versions.VERSION3 ? 'max' : 'full';
          }
        }
        return (
          baseUrl + regionParam + '/' + sizeParam + '/0/' + quality + '.' + format
        );
      };

      const IiifTileClass = CustomTile$1.bind(
        null,
        toSize(tileSize || 256).map(function (size) {
          return size * tilePixelRatio;
        }),
      );

      super({
        attributions: partialOptions.attributions,
        attributionsCollapsible: partialOptions.attributionsCollapsible,
        cacheSize: partialOptions.cacheSize,
        crossOrigin: partialOptions.crossOrigin,
        interpolate: partialOptions.interpolate,
        projection: partialOptions.projection,
        reprojectionErrorThreshold: partialOptions.reprojectionErrorThreshold,
        state: partialOptions.state,
        tileClass: IiifTileClass,
        tileGrid: tileGrid,
        tilePixelRatio: partialOptions.tilePixelRatio,
        tileUrlFunction: tileUrlFunction,
        transition: partialOptions.transition,
      });

      /**
       * @type {number|import("../array.js").NearestDirectionFunction}
       */
      this.zDirection = partialOptions.zDirection;
    }
  }

  /**
   * @module ol/source/arcgisRest
   */


  /**
   * @param {string} baseUrl Base URL for the ArcGIS Rest service.
   * @param {import("../extent.js").Extent} extent Extent.
   * @param {number} resolution Resolution.
   * @param {number} pixelRatio Pixel ratio.
   * @param {import("../proj/Projection.js").default} projection Projection.
   * @param {Object} params Params.
   * @return {string} Request URL.
   */
  function getRequestUrl(
    baseUrl,
    extent,
    resolution,
    pixelRatio,
    projection,
    params,
  ) {
    // ArcGIS Server only wants the numeric portion of the projection ID.
    // (if there is no numeric portion the entire projection code must
    // form a valid ArcGIS SpatialReference definition).
    const srid = projection
      .getCode()
      .split(/:(?=\d+$)/)
      .pop();

    const imageResolution = resolution / pixelRatio;

    const imageSize = [
      round(getWidth(extent) / imageResolution, DECIMALS$1),
      round(getHeight(extent) / imageResolution, DECIMALS$1),
    ];

    params['SIZE'] = imageSize[0] + ',' + imageSize[1];
    params['BBOX'] = extent.join(',');
    params['BBOXSR'] = srid;
    params['IMAGESR'] = srid;
    params['DPI'] = Math.round(
      params['DPI'] ? params['DPI'] * pixelRatio : 90 * pixelRatio,
    );

    const modifiedUrl = baseUrl
      .replace(/MapServer\/?$/, 'MapServer/export')
      .replace(/ImageServer\/?$/, 'ImageServer/exportImage');
    return appendParams(modifiedUrl, params);
  }

  /**
   * @typedef {Object} LoaderOptions
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting the image from
   * the remote server.
   * @property {Object<string,*>} [params] ArcGIS Rest parameters. This field is optional. Service
   * defaults will be used for any fields not specified. `FORMAT` is `PNG32` by default. `F` is
   * `IMAGE` by default. `TRANSPARENT` is `true` by default.  `BBOX`, `SIZE`, `BBOXSR`, and `IMAGESR`
   * will be set dynamically. Set `LAYERS` to override the default service layer visibility. See
   * https://developers.arcgis.com/rest/services-reference/export-map.htm
   * for further reference.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is 'EPSG:3857'.
   * The projection code must contain a numeric end portion separated by :
   * or the entire code must form a valid ArcGIS SpatialReference definition.
   * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport,
   * `2` means twice the size of the map viewport, and so on.
   * @property {string} url ArcGIS Rest service URL for a Map Service or Image Service. The url
   * should include /MapServer or /ImageServer.
   * @property {function(HTMLImageElement, string): Promise<import('../DataTile.js').ImageLike>} [load] Function
   * to perform loading of the image. Receives the created `HTMLImageElement` and the desired `src` as argument and
   * returns a promise resolving to the loaded or decoded image. Default is {@link module:ol/Image.decode}.
   */

  /**
   * Creates a loader for ArcGIS Rest images.
   * @param {LoaderOptions} options Image ArcGIS Rest Options.
   * @return {import('../Image.js').ImageObjectPromiseLoader} ArcGIS Rest image.
   * @api
   */
  function createLoader$2(options) {
    const load = options.load ? options.load : decode;
    const projection = get$2(options.projection || 'EPSG:3857');
    const ratio = options.ratio ?? 1.5;
    const crossOrigin = options.crossOrigin ?? null;

    return function (extent, resolution, pixelRatio) {
      pixelRatio = options.hidpi ? pixelRatio : 1;

      const params = {
        'F': 'image',
        'FORMAT': 'PNG32',
        'TRANSPARENT': true,
      };
      Object.assign(params, options.params);

      extent = getRequestExtent(extent, resolution, pixelRatio, ratio);

      const src = getRequestUrl(
        options.url,
        extent,
        resolution,
        pixelRatio,
        projection,
        params,
      );

      const image = new Image();
      image.crossOrigin = crossOrigin;

      return load(image, src).then((image) => {
        // Update resolution, because the server may return a smaller size than requested
        const resolution = (getWidth(extent) / image.width) * pixelRatio;
        return {image, extent, resolution, pixelRatio};
      });
    };
  }

  /**
   * @module ol/source/ImageArcGISRest
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting the image from
   * the remote server.
   * @property {import("../Image.js").LoadFunction} [imageLoadFunction] Optional function to load an image given
   * a URL.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {Object<string,*>} [params] ArcGIS Rest parameters. This field is optional. Service
   * defaults will be used for any fields not specified. `FORMAT` is `PNG32` by default. `F` is
   * `IMAGE` by default. `TRANSPARENT` is `true` by default.  `BBOX`, `SIZE`, `BBOXSR`, and `IMAGESR`
   * will be set dynamically. Set `LAYERS` to override the default service layer visibility. See
   * https://developers.arcgis.com/rest/services-reference/export-map.htm
   * for further reference.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * The projection code must contain a numeric end portion separated by :
   * or the entire code must form a valid ArcGIS SpatialReference definition.
   * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport,
   * `2` means twice the size of the map viewport, and so on.
   * @property {Array<number>} [resolutions] Resolutions. If specified, requests will be made for
   * these resolutions only.
   * @property {string} [url] ArcGIS Rest service URL for a Map Service or Image Service. The url
   * should include /MapServer or /ImageServer.
   */

  /**
   * @classdesc
   * Source for data from ArcGIS Rest services providing single, untiled images.
   * Useful when underlying map service has labels.
   *
   * If underlying map service is not using labels,
   * take advantage of ol image caching and use
   * {@link module:ol/source/TileArcGISRest~TileArcGISRest} data source.
   *
   * @fires module:ol/source/Image.ImageSourceEvent
   * @api
   */
  class ImageArcGISRest extends ImageSource {
    /**
     * @param {Options} [options] Image ArcGIS Rest Options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        attributions: options.attributions,
        interpolate: options.interpolate,
        projection: options.projection,
        resolutions: options.resolutions,
      });

      /**
       * @private
       * @type {?string}
       */
      this.crossOrigin_ =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;

      /**
       * @private
       * @type {string|undefined}
       */
      this.url_ = options.url;

      /**
       * @private
       * @type {import("../Image.js").LoadFunction}
       */
      this.imageLoadFunction_ =
        options.imageLoadFunction !== undefined
          ? options.imageLoadFunction
          : defaultImageLoadFunction;

      /**
       * @private
       * @type {!Object}
       */
      this.params_ = Object.assign({}, options.params);

      /**
       * @private
       * @type {import("../size.js").Size}
       */
      this.imageSize_ = [0, 0];

      /**
       * @private
       * @type {number}
       */
      this.renderedRevision_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.loaderProjection_ = null;
    }

    /**
     * Get the user-provided params, i.e. those passed to the constructor through
     * the "params" option, and possibly updated using the updateParams method.
     * @return {Object} Params.
     * @api
     */
    getParams() {
      return this.params_;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     * @override
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      if (this.url_ === undefined) {
        return null;
      }
      if (!this.loader || this.loaderProjection_ !== projection) {
        // Lazily create loader to pick up the view projection and to allow `params` updates
        this.loaderProjection_ = projection;
        this.loader = createLoader$2({
          crossOrigin: this.crossOrigin_,
          params: this.params_,
          projection: projection,
          hidpi: this.hidpi_,
          url: this.url_,
          ratio: this.ratio_,
          load: (image, src) => {
            this.image.setImage(image);
            this.imageLoadFunction_(this.image, src);
            return decode(image);
          },
        });
      }

      return super.getImageInternal(extent, resolution, pixelRatio, projection);
    }

    /**
     * Return the image load function of the source.
     * @return {import("../Image.js").LoadFunction} The image load function.
     * @api
     */
    getImageLoadFunction() {
      return this.imageLoadFunction_;
    }

    /**
     * Return the URL used for this ArcGIS source.
     * @return {string|undefined} URL.
     * @api
     */
    getUrl() {
      return this.url_;
    }

    /**
     * Set the image load function of the source.
     * @param {import("../Image.js").LoadFunction} imageLoadFunction Image load function.
     * @api
     */
    setImageLoadFunction(imageLoadFunction) {
      this.imageLoadFunction_ = imageLoadFunction;
      this.changed();
    }

    /**
     * Set the URL to use for requests.
     * @param {string|undefined} url URL.
     * @api
     */
    setUrl(url) {
      if (url != this.url_) {
        this.url_ = url;
        this.loader = null;
        this.changed();
      }
    }

    /**
     * Set the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    setParams(params) {
      this.params_ = Object.assign({}, params);
      this.changed();
    }

    /**
     * Update the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    updateParams(params) {
      Object.assign(this.params_, params);
      this.changed();
    }

    /**
     * @override
     */
    changed() {
      this.image = null;
      super.changed();
    }
  }

  /**
   * @module ol/source/ImageCanvas
   */


  /**
   * A function returning the canvas element (`{HTMLCanvasElement}`)
   * used by the source as an image. The arguments passed to the function are:
   * {@link module:ol/extent~Extent} the image extent, `{number}` the image resolution,
   * `{number}` the pixel ratio of the map, {@link module:ol/size~Size} the image size,
   * and {@link module:ol/proj/Projection~Projection} the image projection. The canvas returned by
   * this function is cached by the source. The this keyword inside the function
   * references the {@link module:ol/source/ImageCanvas~ImageCanvasSource}.
   *
   * @typedef {function(this:import("../ImageCanvas.js").default, import("../extent.js").Extent, number,
   *     number, import("../size.js").Size, import("../proj/Projection.js").default): HTMLCanvasElement} FunctionType
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {FunctionType} [canvasFunction] Canvas function.
   * The function returning the canvas element used by the source
   * as an image. The arguments passed to the function are: {@link import("../extent.js").Extent} the
   * image extent, `{number}` the image resolution, `{number}` the pixel ratio of the map,
   * {@link import("../size.js").Size} the image size, and {@link import("../proj/Projection.js").default} the image
   * projection. The canvas returned by this function is cached by the source. If
   * the value returned by the function is later changed then
   * `changed` should be called on the source for the source to
   * invalidate the current cached image. See: {@link module:ol/Observable~Observable#changed}
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [ratio=1.5] Ratio. 1 means canvases are the size of the map viewport, 2 means twice the
   * width and height of the map viewport, and so on. Must be `1` or higher.
   * @property {Array<number>} [resolutions] Resolutions.
   * If specified, new canvases will be created for these resolutions
   * @property {import("./Source.js").State} [state] Source state.
   */

  /**
   * @classdesc
   * Base class for image sources where a canvas element is the image.
   * @api
   */
  class ImageCanvasSource extends ImageSource {
    /**
     * @param {Options} [options] ImageCanvas options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        attributions: options.attributions,
        interpolate: options.interpolate,
        projection: options.projection,
        resolutions: options.resolutions,
        state: options.state,
      });

      /**
       * @private
       * @type {FunctionType}
       */
      this.canvasFunction_ = options.canvasFunction;

      /**
       * @private
       * @type {import("../ImageCanvas.js").default}
       */
      this.canvas_ = null;

      /**
       * @private
       * @type {number}
       */
      this.renderedRevision_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../ImageCanvas.js").default} Single image.
     * @override
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      resolution = this.findNearestResolution(resolution);

      let canvas = this.canvas_;
      if (
        canvas &&
        this.renderedRevision_ == this.getRevision() &&
        canvas.getResolution() == resolution &&
        canvas.getPixelRatio() == pixelRatio &&
        containsExtent(canvas.getExtent(), extent)
      ) {
        return canvas;
      }

      extent = extent.slice();
      scaleFromCenter(extent, this.ratio_);
      const width = getWidth(extent) / resolution;
      const height = getHeight(extent) / resolution;
      const size = [width * pixelRatio, height * pixelRatio];

      const canvasElement = this.canvasFunction_.call(
        this,
        extent,
        resolution,
        pixelRatio,
        size,
        projection,
      );
      if (canvasElement) {
        canvas = new ImageCanvas(extent, resolution, pixelRatio, canvasElement);
      }
      this.canvas_ = canvas;
      this.renderedRevision_ = this.getRevision();

      return canvas;
    }
  }

  /**
   * @module ol/source/mapguide
   */


  /**
   * @typedef {Object} LoaderOptions
   * @property {string} url The mapagent url.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {number} [displayDpi=96] The display resolution.
   * @property {number} [metersPerUnit=1] The meters-per-unit value.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {boolean} [useOverlay] If `true`, will use `GETDYNAMICMAPOVERLAYIMAGE`.
   * @property {number} [ratio=1] Ratio. `1` means image requests are the size of the map viewport, `2` means
   * twice the width and height of the map viewport, and so on. Must be `1` or higher.
   * @property {Object} [params] Additional query parameters.
   * @property {function(HTMLImageElement, string): Promise<import('../DataTile.js').ImageLike>} [load] Function
   * to perform loading of the image. Receives the created `HTMLImageElement` and the desired `src` as argument and
   * returns a promise resolving to the loaded or decoded image. Default is {@link module:ol/Image.decode}.
   */

  /**
   * @param {import("../extent.js").Extent} extent The map extents.
   * @param {import("../size.js").Size} size The viewport size.
   * @param {number} metersPerUnit The meters-per-unit value.
   * @param {number} dpi The display resolution.
   * @return {number} The computed map scale.
   */
  function getScale(extent, size, metersPerUnit, dpi) {
    const mcsW = getWidth(extent);
    const mcsH = getHeight(extent);
    const devW = size[0];
    const devH = size[1];
    const mpp = 0.0254 / dpi;
    if (devH * mcsW > devW * mcsH) {
      return (mcsW * metersPerUnit) / (devW * mpp); // width limited
    }
    return (mcsH * metersPerUnit) / (devH * mpp); // height limited
  }

  /**
   * @param {string} baseUrl The mapagent url.
   * @param {Object<string, string|number>} params Request parameters.
   * @param {import("../extent.js").Extent} extent Extent.
   * @param {import("../size.js").Size} size Size.
   * @param {boolean} useOverlay If `true`, will use `GETDYNAMICMAPOVERLAYIMAGE`.
   * @param {number} metersPerUnit The meters-per-unit value.
   * @param {number} displayDpi The display resolution.
   * @return {string} The mapagent map image request URL.
   */
  function getUrl(
    baseUrl,
    params,
    extent,
    size,
    useOverlay,
    metersPerUnit,
    displayDpi,
  ) {
    const scale = getScale(extent, size, metersPerUnit, displayDpi);
    const center = getCenter(extent);
    const baseParams = {
      'OPERATION': useOverlay ? 'GETDYNAMICMAPOVERLAYIMAGE' : 'GETMAPIMAGE',
      'VERSION': '2.0.0',
      'LOCALE': 'en',
      'CLIENTAGENT': 'ol/source/ImageMapGuide source',
      'CLIP': '1',
      'SETDISPLAYDPI': displayDpi,
      'SETDISPLAYWIDTH': Math.round(size[0]),
      'SETDISPLAYHEIGHT': Math.round(size[1]),
      'SETVIEWSCALE': scale,
      'SETVIEWCENTERX': center[0],
      'SETVIEWCENTERY': center[1],
    };
    Object.assign(baseParams, params);
    return appendParams(baseUrl, baseParams);
  }

  /**
   * Creates a loader for MapGuide images.
   * @param {LoaderOptions} options Image ArcGIS Rest Options.
   * @return {import('../Image.js').ImageObjectPromiseLoader} ArcGIS Rest image.
   * @api
   */
  function createLoader$1(options) {
    const load = options.load || decode;
    const useOverlay = options.useOverlay ?? false;
    const metersPerUnit = options.metersPerUnit || 1;
    const displayDpi = options.displayDpi || 96;
    const ratio = options.ratio ?? 1;
    const crossOrigin = options.crossOrigin ?? null;

    return function (extent, resolution, pixelRatio) {
      const image = new Image();
      image.crossOrigin = crossOrigin;
      extent = getRequestExtent(extent, resolution, pixelRatio, ratio);
      const width = getWidth(extent) / resolution;
      const height = getHeight(extent) / resolution;
      const size = [width * pixelRatio, height * pixelRatio];
      const src = getUrl(
        options.url,
        options.params,
        extent,
        size,
        useOverlay,
        metersPerUnit,
        displayDpi,
      );
      return load(image, src).then((image) => ({image, extent, pixelRatio}));
    };
  }

  /**
   * @module ol/source/ImageMapGuide
   */


  /**
   * @typedef {Object} Options
   * @property {string} [url] The mapagent url.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {number} [displayDpi=96] The display resolution.
   * @property {number} [metersPerUnit=1] The meters-per-unit value.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {boolean} [useOverlay] If `true`, will use `GETDYNAMICMAPOVERLAYIMAGE`.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [ratio=1] Ratio. `1` means image requests are the size of the map viewport, `2` means
   * twice the width and height of the map viewport, and so on. Must be `1` or higher.
   * @property {Array<number>} [resolutions] Resolutions.
   * If specified, requests will be made for these resolutions only.
   * @property {import("../Image.js").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {Object} [params] Additional parameters.
   */

  /**
   * @classdesc
   * Source for images from Mapguide servers
   *
   * @fires module:ol/source/Image.ImageSourceEvent
   * @api
   */
  class ImageMapGuide extends ImageSource {
    /**
     * @param {Options} options ImageMapGuide options.
     */
    constructor(options) {
      super({
        interpolate: options.interpolate,
        projection: options.projection,
        resolutions: options.resolutions,
      });

      /**
       * @private
       * @type {?string}
       */
      this.crossOrigin_ =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      /**
       * @private
       * @type {number}
       */
      this.displayDpi_ =
        options.displayDpi !== undefined ? options.displayDpi : 96;

      /**
       * @private
       * @type {!Object}
       */
      this.params_ = Object.assign({}, options.params);

      /**
       * @private
       * @type {string|undefined}
       */
      this.url_ = options.url;

      /**
       * @private
       * @type {import("../Image.js").LoadFunction}
       */
      this.imageLoadFunction_ =
        options.imageLoadFunction !== undefined
          ? options.imageLoadFunction
          : defaultImageLoadFunction;

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;

      /**
       * @private
       * @type {number}
       */
      this.metersPerUnit_ =
        options.metersPerUnit !== undefined ? options.metersPerUnit : 1;

      /**
       * @private
       * @type {number}
       */
      this.ratio_ = options.ratio !== undefined ? options.ratio : 1;

      /**
       * @private
       * @type {boolean}
       */
      this.useOverlay_ =
        options.useOverlay !== undefined ? options.useOverlay : false;

      /**
       * @private
       * @type {number}
       */
      this.renderedRevision_ = 0;

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.loaderProjection_ = null;
    }

    /**
     * Get the user-provided params, i.e. those passed to the constructor through
     * the "params" option, and possibly updated using the updateParams method.
     * @return {Object} Params.
     * @api
     */
    getParams() {
      return this.params_;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     * @override
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      if (this.url_ === undefined) {
        return null;
      }
      if (!this.loader || this.loaderProjection_ !== projection) {
        // Lazily create loader to pick up the view projection and to allow `params` updates
        this.loaderProjection_ = projection;
        this.loader = createLoader$1({
          crossOrigin: this.crossOrigin_,
          params: this.params_,
          hidpi: this.hidpi_,
          metersPerUnit: this.metersPerUnit_,
          url: this.url_,
          useOverlay: this.useOverlay_,
          ratio: this.ratio_,
          load: (image, src) => {
            this.image.setImage(image);
            this.imageLoadFunction_(this.image, src);
            return decode(image);
          },
        });
      }

      return super.getImageInternal(extent, resolution, pixelRatio, projection);
    }

    /**
     * Return the image load function of the source.
     * @return {import("../Image.js").LoadFunction} The image load function.
     * @api
     */
    getImageLoadFunction() {
      return this.imageLoadFunction_;
    }

    /**
     * Set the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    setParams(params) {
      this.params_ = Object.assign({}, params);
      this.changed();
    }

    /**
     * Update the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    updateParams(params) {
      Object.assign(this.params_, params);
      this.changed();
    }

    /**
     * Set the image load function of the MapGuide source.
     * @param {import("../Image.js").LoadFunction} imageLoadFunction Image load function.
     * @api
     */
    setImageLoadFunction(imageLoadFunction) {
      this.imageLoadFunction_ = imageLoadFunction;
      this.changed();
    }

    /**
     * @override
     */
    changed() {
      this.image = null;
      super.changed();
    }
  }

  /**
   * @module ol/source/static
   */


  /**
   * @typedef {Object} LoaderOptions
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {import("../extent.js").Extent} imageExtent Extent of the image in map coordinates.
   * This is the [left, bottom, right, top] map coordinates of your image. When using this loader with an
   * `ol/source/Image`, the same extent must be set as `extent` of the `ol/layer/Image`.
   * @property {string} url Image URL.
   * @property {function(HTMLImageElement, string): Promise<import('../DataTile.js').ImageLike>} [load] Function
   * to perform loading of the image. Receives the created `HTMLImageElement` and the desired `src` as argument and
   * returns a promise resolving to the loaded or decoded image. Default is {@link module:ol/Image.decode}.
   */

  /**
   * Creates a loader for static images.
   * @param {LoaderOptions} options Loader options.
   * @return {import("../Image.js").ImageObjectPromiseLoader} Loader.
   * @api
   */
  function createLoader(options) {
    const load = options.load || decode;
    const extent = options.imageExtent;
    const crossOrigin = options.crossOrigin ?? null;

    return () => {
      const image = new Image();
      image.crossOrigin = crossOrigin;
      return load(image, options.url).then((image) => {
        const resolutionX = getWidth(extent) / image.width;
        const resolutionY = getHeight(extent) / image.height;
        const resolution =
          resolutionX !== resolutionY ? [resolutionX, resolutionY] : resolutionY;
        return {image, extent, resolution, pixelRatio: 1};
      });
    };
  }

  /**
   * @module ol/source/ImageStatic
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {import("../extent.js").Extent} imageExtent Extent of the image in map coordinates.
   * This is the [left, bottom, right, top] map coordinates of your image.
   * @property {import("../Image.js").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {string} url Image URL.
   */

  /**
   * @classdesc
   * A layer source for displaying a single, static image.
   * @api
   */
  class Static extends ImageSource {
    /**
     * @param {Options} options ImageStatic options.
     */
    constructor(options) {
      const crossOrigin =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      const /** @type {import("../Image.js").LoadFunction} */ imageLoadFunction =
          options.imageLoadFunction !== undefined
            ? options.imageLoadFunction
            : defaultImageLoadFunction;

      super({
        attributions: options.attributions,
        interpolate: options.interpolate,
        projection: get$2(options.projection),
      });

      /**
       * @private
       * @type {string}
       */
      this.url_ = options.url;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.imageExtent_ = options.imageExtent;

      /**
       * @private
       * @type {import("../Image.js").default}
       */
      this.image = null;

      this.image = new ImageWrapper(
        this.imageExtent_,
        undefined,
        1,
        createLoader({
          url: options.url,
          imageExtent: options.imageExtent,
          crossOrigin,
          load: (image, src) => {
            this.image.setImage(image);
            imageLoadFunction(this.image, src);
            return decode(image);
          },
        }),
      );

      this.image.addEventListener(
        EventType.CHANGE,
        this.handleImageChange.bind(this),
      );
    }

    /**
     * Returns the image extent
     * @return {import("../extent.js").Extent} image extent.
     * @api
     */
    getImageExtent() {
      return this.imageExtent_;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     * @override
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      if (intersects$2(extent, this.image.getExtent())) {
        return this.image;
      }
      return null;
    }

    /**
     * Return the URL used for this image source.
     * @return {string} URL.
     * @api
     */
    getUrl() {
      return this.url_;
    }
  }

  /**
   * @module ol/source/ImageTile
   */

  /**
   * Image tile loading function.  The function is called with z, x, and y tile coordinates and
   * returns an {@link import("../DataTile.js").ImageLike image} or a promise for the same.
   *
   * @typedef {function(number, number, number, import("./DataTile.js").LoaderOptions):(import("../DataTile.js").ImageLike|Promise<import("../DataTile.js").ImageLike>)} Loader
   */

  /**
   * @typedef {function(number, number, number, import("./DataTile.js").LoaderOptions):string} UrlGetter
   */

  /**
   * @typedef {string | Array<string> | UrlGetter} UrlLike
   */

  /**
   * @typedef {Object} Options
   * @property {UrlLike} [url] The image URL template.  In addition to a single URL template, an array of URL templates or a function
   * can be provided.  If a function is provided, it will be called with z, x, y tile coordinates and loader options and should
   * return a URL.
   * @property {Loader} [loader] Data loader.  Called with z, x, and y tile coordinates.
   * Returns an {@link import("../DataTile.js").ImageLike image} for a tile or a promise for the same.
   * The promise should not resolve until the image is loaded.  If the `url` option is provided, a loader will be created.
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.
   * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.
   * @property {number|import("../size.js").Size} [tileSize=[256, 256]] The pixel width and height of the source tiles.
   * This may be different than the rendered pixel size if a `tileGrid` is provided.
   * @property {number} [gutter=0] The size in pixels of the gutter around data tiles to ignore.
   * This allows artifacts of rendering at tile edges to be ignored.
   * Supported data should be wider and taller than the tile size by a value of `2 x gutter`.
   * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Tile projection.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {import("./Source.js").State} [state] The source state.
   * @property {boolean} [wrapX=true] Render tiles beyond the antimeridian.
   * @property {number} [transition] Transition time when fading in new tiles (in miliseconds).
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.
   * @property {import('./DataTile.js').CrossOriginAttribute} [crossOrigin='anonymous'] The crossOrigin property to pass to loaders for image data.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  const loadError = new Error('Image failed to load');

  /**
   * @param {string} template The image url template.
   * @param {number} z The tile z coordinate.
   * @param {number} x The tile x coordinate.
   * @param {number} y The tile y coordinate.
   * @param {import('./DataTile.js').LoaderOptions} options The loader options.
   * @return {Promise<HTMLImageElement>} Resolves with a loaded image.
   */
  function loadImage(template, z, x, y, options) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.crossOrigin = options.crossOrigin ?? null;
      image.addEventListener('load', () => resolve(image));
      image.addEventListener('error', () => reject(loadError));
      image.src = renderXYZTemplate(template, z, x, y, options.maxY);
    });
  }

  /**
   * @param {Array<string>} templates The url templates.
   * @return {Loader} The image loader.
   */
  function makeLoaderFromTemplates(templates) {
    return function (z, x, y, options) {
      const template = pickUrl(templates, z, x, y);
      return loadImage(template, z, x, y, options);
    };
  }

  /**
   * @param {UrlGetter} getter The url getter.
   * @return {Loader} The image loader.
   */
  function makeLoaderFromGetter(getter) {
    return function (z, x, y, options) {
      const url = getter(z, x, y, options);
      return loadImage(url, z, x, y, options);
    };
  }

  /**
   * @param {UrlLike} url The URL-like option.
   * @return {Loader} The tile loader.
   */
  function makeLoaderFromUrlLike(url) {
    /**
     * @type {Loader}
     */
    let loader;

    if (Array.isArray(url)) {
      loader = makeLoaderFromTemplates(url);
    } else if (typeof url === 'string') {
      const urls = expandUrl(url);
      loader = makeLoaderFromTemplates(urls);
    } else if (typeof url === 'function') {
      loader = makeLoaderFromGetter(url);
    } else {
      throw new Error(
        'The url option must be a single template, an array of templates, or a function for getting a URL',
      );
    }
    return loader;
  }

  let keyCount = 0;

  /**
   * @param {UrlLike} url The URL-like option.
   * @return {string} A key for the URL.
   */
  function keyFromUrlLike(url) {
    if (Array.isArray(url)) {
      return url.join('\n');
    }

    if (typeof url === 'string') {
      return url;
    }

    ++keyCount;
    return 'url-function-key-' + keyCount;
  }

  /**
   * @classdesc
   * A source for typed array data tiles.
   *
   * @extends DataTileSource<import("../ImageTile.js").default>
   * @fires import("./Tile.js").TileSourceEvent
   * @api
   */
  class ImageTileSource extends DataTileSource {
    /**
     * @param {Options} [options] DataTile source options.
     */
    constructor(options) {
      options = options || {};

      /**
       * @type {Loader}
       */
      let loader = options.loader;

      /**
       * @type {string}
       */
      let key;

      if (options.url) {
        loader = makeLoaderFromUrlLike(options.url);
        key = keyFromUrlLike(options.url);
      }

      /**
       * @type {import('./Source.js').State}
       */
      const state = !loader ? 'loading' : options.state;

      const wrapX = options.wrapX === undefined ? true : options.wrapX;

      super({
        loader: loader,
        key: key,
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        maxZoom: options.maxZoom,
        minZoom: options.minZoom,
        tileSize: options.tileSize,
        gutter: options.gutter,
        maxResolution: options.maxResolution,
        projection: options.projection,
        tileGrid: options.tileGrid,
        state: state,
        wrapX: wrapX,
        transition: options.transition,
        interpolate: options.interpolate !== false,
        crossOrigin: options.crossOrigin,
        zDirection: options.zDirection,
      });
    }

    /**
     * @param {UrlLike} url The new URL.
     * @api
     */
    setUrl(url) {
      const loader = makeLoaderFromUrlLike(url);
      this.setLoader(loader);
      this.setKey(keyFromUrlLike(url));
      if (this.getState() !== 'ready') {
        this.setState('ready');
      }
    }
  }

  /**
   * @module ol/source/ImageWMS
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {import("./wms.js").ServerType} [serverType] The type of
   * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.
   * Only needed if `hidpi` is `true`.
   * @property {import("../Image.js").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {Object<string,*>} [params] WMS request parameters.
   * At least a `LAYERS` param is required. `STYLES` is
   * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT`, `BBOX`
   * and `CRS` (`SRS` for WMS version < 1.3.0) will be set dynamically.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport, `2` means
   * twice the width and height of the map viewport, and so on. Must be `1` or higher.
   * @property {Array<number>} [resolutions] Resolutions.
   * If specified, requests will be made for these resolutions only.
   * @property {string} [url] WMS service URL.
   */

  /**
   * @classdesc
   * Source for WMS servers providing single, untiled images.
   *
   * @fires module:ol/source/Image.ImageSourceEvent
   * @api
   */
  class ImageWMS extends ImageSource {
    /**
     * @param {Options} [options] ImageWMS options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        attributions: options.attributions,
        interpolate: options.interpolate,
        projection: options.projection,
        resolutions: options.resolutions,
      });

      /**
       * @private
       * @type {?string}
       */
      this.crossOrigin_ =
        options.crossOrigin !== undefined ? options.crossOrigin : null;

      /**
       * @private
       * @type {string|undefined}
       */
      this.url_ = options.url;

      /**
       * @private
       * @type {import("../Image.js").LoadFunction}
       */
      this.imageLoadFunction_ =
        options.imageLoadFunction !== undefined
          ? options.imageLoadFunction
          : defaultImageLoadFunction;

      /**
       * @private
       * @type {!Object}
       */
      this.params_ = Object.assign({}, options.params);

      /**
       * @private
       * @type {import("./wms.js").ServerType}
       */
      this.serverType_ = options.serverType;

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;

      /**
       * @private
       * @type {number}
       */
      this.renderedRevision_ = 0;

      /**
       * @private
       * @type {number}
       */
      this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;

      /**
       * @private
       * @type {import("../proj/Projection.js").default}
       */
      this.loaderProjection_ = null;
    }

    /**
     * Return the GetFeatureInfo URL for the passed coordinate, resolution, and
     * projection. Return `undefined` if the GetFeatureInfo URL cannot be
     * constructed.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} resolution Resolution.
     * @param {import("../proj.js").ProjectionLike} projection Projection.
     * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should
     *     be provided. If `QUERY_LAYERS` is not provided then the layers specified
     *     in the `LAYERS` parameter will be used. `VERSION` should not be
     *     specified here.
     * @return {string|undefined} GetFeatureInfo URL.
     * @api
     */
    getFeatureInfoUrl(coordinate, resolution, projection, params) {
      const projectionObj = get$2(projection);
      const sourceProjectionObj = this.getProjection();

      if (sourceProjectionObj && sourceProjectionObj !== projectionObj) {
        resolution = calculateSourceResolution(
          sourceProjectionObj,
          projectionObj,
          coordinate,
          resolution,
        );
        coordinate = transform(coordinate, projectionObj, sourceProjectionObj);
      }

      const options = {
        url: this.url_,
        params: {
          ...this.params_,
          ...params,
        },
        projection: sourceProjectionObj || projectionObj,
      };
      return getFeatureInfoUrl(options, coordinate, resolution);
    }

    /**
     * Return the GetLegendGraphic URL, optionally optimized for the passed
     * resolution and possibly including any passed specific parameters. Returns
     * `undefined` if the GetLegendGraphic URL cannot be constructed.
     *
     * @param {number} [resolution] Resolution. If set to undefined, `SCALE`
     *     will not be calculated and included in URL.
     * @param {Object} [params] GetLegendGraphic params. If `LAYER` is set, the
     *     request is generated for this wms layer, else it will try to use the
     *     configured wms layer. Default `FORMAT` is `image/png`.
     *     `VERSION` should not be specified here.
     * @return {string|undefined} GetLegendGraphic URL.
     * @api
     */
    getLegendUrl(resolution, params) {
      return getLegendUrl(
        {
          url: this.url_,
          params: {
            ...this.params_,
            ...params,
          },
        },
        resolution,
      );
    }

    /**
     * Get the user-provided params, i.e. those passed to the constructor through
     * the "params" option, and possibly updated using the updateParams method.
     * @return {Object} Params.
     * @api
     */
    getParams() {
      return this.params_;
    }

    /**
     * @param {import("../extent.js").Extent} extent Extent.
     * @param {number} resolution Resolution.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {import("../Image.js").default} Single image.
     * @override
     */
    getImageInternal(extent, resolution, pixelRatio, projection) {
      if (this.url_ === undefined) {
        return null;
      }
      if (!this.loader || this.loaderProjection_ !== projection) {
        // Lazily create loader to pick up the view projection and to allow `params` updates
        this.loaderProjection_ = projection;
        this.loader = createLoader$3({
          crossOrigin: this.crossOrigin_,
          params: this.params_,
          projection: projection,
          serverType: this.serverType_,
          hidpi: this.hidpi_,
          url: this.url_,
          ratio: this.ratio_,
          load: (image, src) => {
            this.image.setImage(image);
            this.imageLoadFunction_(this.image, src);
            return decode(image);
          },
        });
      }

      return super.getImageInternal(extent, resolution, pixelRatio, projection);
    }

    /**
     * Return the image load function of the source.
     * @return {import("../Image.js").LoadFunction} The image load function.
     * @api
     */
    getImageLoadFunction() {
      return this.imageLoadFunction_;
    }

    /**
     * Return the URL used for this WMS source.
     * @return {string|undefined} URL.
     * @api
     */
    getUrl() {
      return this.url_;
    }

    /**
     * Set the image load function of the source.
     * @param {import("../Image.js").LoadFunction} imageLoadFunction Image load function.
     * @api
     */
    setImageLoadFunction(imageLoadFunction) {
      this.imageLoadFunction_ = imageLoadFunction;
      this.changed();
    }

    /**
     * Set the URL to use for requests.
     * @param {string|undefined} url URL.
     * @api
     */
    setUrl(url) {
      if (url != this.url_) {
        this.url_ = url;
        this.loader = null;
        this.changed();
      }
    }

    /**
     * Set the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    setParams(params) {
      this.params_ = Object.assign({}, params);
      this.changed();
    }

    /**
     * Update the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    updateParams(params) {
      Object.assign(this.params_, params);
      this.changed();
    }

    /**
     * @override
     */
    changed() {
      this.image = null;
      super.changed();
    }
  }

  /**
   * @module ol/source/ogcTileUtil
   */


  /**
   * See https://ogcapi.ogc.org/tiles/.
   */

  /**
   * @typedef {'map' | 'vector'} TileType
   */

  /**
   * @typedef {'topLeft' | 'bottomLeft'} CornerOfOrigin
   */

  /**
   * @typedef {Object} TileSet
   * @property {TileType} dataType Type of data represented in the tileset.
   * @property {string} [tileMatrixSetDefinition] Reference to a tile matrix set definition.
   * @property {TileMatrixSet} [tileMatrixSet] Tile matrix set definition.
   * @property {Array<TileMatrixSetLimit>} [tileMatrixSetLimits] Tile matrix set limits.
   * @property {Array<Link>} links Tileset links.
   */

  /**
   * @typedef {Object} Link
   * @property {string} rel The link rel attribute.
   * @property {string} href The link URL.
   * @property {string} type The link type.
   */

  /**
   * @typedef {Object} TileMatrixSetLimit
   * @property {string} tileMatrix The tile matrix id.
   * @property {number} minTileRow The minimum tile row.
   * @property {number} maxTileRow The maximum tile row.
   * @property {number} minTileCol The minimum tile column.
   * @property {number} maxTileCol The maximum tile column.
   */

  /**
   * @typedef {Object} TileMatrixSet
   * @property {string} id The tile matrix set identifier.
   * @property {string|CrsUri|CrsWkt|CrsReferenceSystem} crs The coordinate reference system.
   * @property {Array<string>} [orderedAxes] Axis order.
   * @property {Array<TileMatrix>} tileMatrices Array of tile matrices.
   */

  /**
   * @typedef {Object} CrsUri
   * @property {string} uri Reference to one coordinate reference system (CRS).
   */

  /**
   * @typedef {Object} CrsWkt
   * @property {Object} wkt JSON encoding for WKT representation of CRS 2.0.
   */

  /**
   * @typedef {Object} CrsReferenceSystem
   * @property {Object} referenceSystem Data structure as defined in the MD_ReferenceSystem of the ISO 19115.
   */

  /**
   * @typedef {Object} TileMatrix
   * @property {string} id The tile matrix identifier.
   * @property {number} cellSize The pixel resolution (map units per pixel).
   * @property {Array<number>} pointOfOrigin The map location of the matrix origin.
   * @property {CornerOfOrigin} [cornerOfOrigin='topLeft'] The corner of the matrix that represents the origin ('topLeft' or 'bottomLeft').
   * @property {number} matrixWidth The number of columns.
   * @property {number} matrixHeight The number of rows.
   * @property {number} tileWidth The pixel width of a tile.
   * @property {number} tileHeight The pixel height of a tile.
   */

  /**
   * @type {Object<string, boolean>}
   */
  const knownMapMediaTypes = {
    'image/png': true,
    'image/jpeg': true,
    'image/gif': true,
    'image/webp': true,
  };

  /**
   * @type {Object<string, boolean>}
   */
  const knownVectorMediaTypes = {
    'application/vnd.mapbox-vector-tile': true,
    'application/geo+json': true,
  };

  /**
   * @typedef {Object} TileSetInfo
   * @property {string} urlTemplate The tile URL template.
   * @property {import("../proj/Projection.js").default} projection The source projection.
   * @property {import("../tilegrid/TileGrid.js").default} grid The tile grid.
   * @property {import("../Tile.js").UrlFunction} urlFunction The tile URL function.
   */

  /**
   * @typedef {Object} SourceInfo
   * @property {string} url The tile set URL.
   * @property {string} mediaType The preferred tile media type.
   * @property {Array<string>} [supportedMediaTypes] The supported media types.
   * @property {import("../proj/Projection.js").default} projection The source projection.
   * @property {Object} [context] Optional context for constructing the URL.
   * @property {Array<string>} [collections] Optional collections to append the URL with.
   */

  /**
   * @param {string} tileUrlTemplate Tile URL template.
   * @param {Array<string>} collections List of collections to include as query parameter.
   * @return {string} The tile URL template with appended collections query parameter.
   */
  function appendCollectionsQueryParam(tileUrlTemplate, collections) {
    if (!collections.length) {
      return tileUrlTemplate;
    }

    // making sure we can always construct a URL instance.
    const url = new URL(tileUrlTemplate, 'file:/');

    if (url.pathname.split('/').includes('collections')) {
      error$1(
        'The "collections" query parameter cannot be added to collection endpoints',
      );
      return tileUrlTemplate;
    }
    // According to conformance class
    // http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/collections-selection
    // commata in the identifiers of the `collections` query parameter
    // need to be URLEncoded, while the commata separating the identifiers
    // should not.
    const encodedCollections = collections
      .map((c) => encodeURIComponent(c))
      .join(',');

    url.searchParams.append('collections', encodedCollections);
    const baseUrl = tileUrlTemplate.split('?')[0];
    const queryParams = decodeURIComponent(url.searchParams.toString());
    return `${baseUrl}?${queryParams}`;
  }

  /**
   * @param {Array<Link>} links Tileset links.
   * @param {string} [mediaType] The preferred media type.
   * @param {Array<string>} [collections] Optional collections to append the URL with.
   * @return {string} The tile URL template.
   */
  function getMapTileUrlTemplate(links, mediaType, collections) {
    let tileUrlTemplate;
    let fallbackUrlTemplate;
    for (let i = 0; i < links.length; ++i) {
      const link = links[i];
      if (link.rel === 'item') {
        if (link.type === mediaType) {
          tileUrlTemplate = link.href;
          break;
        }
        if (knownMapMediaTypes[link.type]) {
          fallbackUrlTemplate = link.href;
        } else if (!fallbackUrlTemplate && link.type.startsWith('image/')) {
          fallbackUrlTemplate = link.href;
        }
      }
    }

    if (!tileUrlTemplate) {
      if (fallbackUrlTemplate) {
        tileUrlTemplate = fallbackUrlTemplate;
      } else {
        throw new Error('Could not find "item" link');
      }
    }

    if (collections) {
      tileUrlTemplate = appendCollectionsQueryParam(tileUrlTemplate, collections);
    }

    return tileUrlTemplate;
  }

  /**
   * @param {Array<Link>} links Tileset links.
   * @param {string} [mediaType] The preferred media type.
   * @param {Array<string>} [supportedMediaTypes] The media types supported by the parser.
   * @param {Array<string>} [collections] Optional collections to append the URL with.
   * @return {string} The tile URL template.
   */
  function getVectorTileUrlTemplate(
    links,
    mediaType,
    supportedMediaTypes,
    collections,
  ) {
    let tileUrlTemplate;
    let fallbackUrlTemplate;

    /**
     * Lookup of URL by media type.
     * @type {Object<string, string>}
     */
    const hrefLookup = {};

    for (let i = 0; i < links.length; ++i) {
      const link = links[i];
      hrefLookup[link.type] = link.href;
      if (link.rel === 'item') {
        if (link.type === mediaType) {
          tileUrlTemplate = link.href;
          break;
        }
        if (knownVectorMediaTypes[link.type]) {
          fallbackUrlTemplate = link.href;
        }
      }
    }

    if (!tileUrlTemplate && supportedMediaTypes) {
      for (let i = 0; i < supportedMediaTypes.length; ++i) {
        const supportedMediaType = supportedMediaTypes[i];
        if (hrefLookup[supportedMediaType]) {
          tileUrlTemplate = hrefLookup[supportedMediaType];
          break;
        }
      }
    }

    if (!tileUrlTemplate) {
      if (fallbackUrlTemplate) {
        tileUrlTemplate = fallbackUrlTemplate;
      } else {
        throw new Error('Could not find "item" link');
      }
    }

    if (collections) {
      tileUrlTemplate = appendCollectionsQueryParam(tileUrlTemplate, collections);
    }

    return tileUrlTemplate;
  }

  /**
   * @param {SourceInfo} sourceInfo The source info.
   * @param {TileMatrixSet} tileMatrixSet Tile matrix set.
   * @param {string} tileUrlTemplate Tile URL template.
   * @param {Array<TileMatrixSetLimit>} [tileMatrixSetLimits] Tile matrix set limits.
   * @return {TileSetInfo} Tile set info.
   */
  function parseTileMatrixSet(
    sourceInfo,
    tileMatrixSet,
    tileUrlTemplate,
    tileMatrixSetLimits,
  ) {
    let projection = sourceInfo.projection;
    if (!projection) {
      if (typeof tileMatrixSet.crs === 'string') {
        projection = get$2(tileMatrixSet.crs);
      } else if ('uri' in tileMatrixSet.crs) {
        projection = get$2(tileMatrixSet.crs.uri);
      }
      if (!projection) {
        throw new Error(`Unsupported CRS: ${JSON.stringify(tileMatrixSet.crs)}`);
      }
    }
    const orderedAxes = tileMatrixSet.orderedAxes;
    const axisOrientation = orderedAxes
      ? orderedAxes
          .slice(0, 2)
          .map((s) => s.replace(/E|X|Lon/i, 'e').replace(/N|Y|Lat/i, 'n'))
          .join('')
      : projection.getAxisOrientation();
    const backwards = !axisOrientation.startsWith('en');

    const matrices = tileMatrixSet.tileMatrices;

    /**
     * @type {Object<string, TileMatrix>}
     */
    const matrixLookup = {};
    for (let i = 0; i < matrices.length; ++i) {
      const matrix = matrices[i];
      matrixLookup[matrix.id] = matrix;
    }

    /**
     * @type {Object<string, TileMatrixSetLimit>}
     */
    const limitLookup = {};

    /**
     * @type {Array<string>}
     */
    const matrixIds = [];

    if (tileMatrixSetLimits) {
      for (let i = 0; i < tileMatrixSetLimits.length; ++i) {
        const limit = tileMatrixSetLimits[i];
        const id = limit.tileMatrix;
        matrixIds.push(id);
        limitLookup[id] = limit;
      }
    } else {
      for (let i = 0; i < matrices.length; ++i) {
        const id = matrices[i].id;
        matrixIds.push(id);
      }
    }

    const length = matrixIds.length;
    const origins = new Array(length);
    const resolutions = new Array(length);
    const sizes = new Array(length);
    const tileSizes = new Array(length);
    const extent = [-Infinity, -Infinity, Infinity, Infinity];

    for (let i = 0; i < length; ++i) {
      const id = matrixIds[i];
      const matrix = matrixLookup[id];
      const origin = matrix.pointOfOrigin;
      if (backwards) {
        origins[i] = [origin[1], origin[0]];
      } else {
        origins[i] = origin;
      }
      resolutions[i] = matrix.cellSize;
      sizes[i] = [matrix.matrixWidth, matrix.matrixHeight];
      tileSizes[i] = [matrix.tileWidth, matrix.tileHeight];
      const limit = limitLookup[id];
      if (limit) {
        const tileMapWidth = matrix.cellSize * matrix.tileWidth;
        const minX = origins[i][0] + limit.minTileCol * tileMapWidth;
        const maxX = origins[i][0] + (limit.maxTileCol + 1) * tileMapWidth;

        const tileMapHeight = matrix.cellSize * matrix.tileHeight;
        const upsideDown = matrix.cornerOfOrigin === 'bottomLeft';

        let minY;
        let maxY;
        if (upsideDown) {
          minY = origins[i][1] + limit.minTileRow * tileMapHeight;
          maxY = origins[i][1] + (limit.maxTileRow + 1) * tileMapHeight;
        } else {
          minY = origins[i][1] - (limit.maxTileRow + 1) * tileMapHeight;
          maxY = origins[i][1] - limit.minTileRow * tileMapHeight;
        }

        getIntersection(extent, [minX, minY, maxX, maxY], extent);
      }
    }

    const tileGrid = new TileGrid({
      origins: origins,
      resolutions: resolutions,
      sizes: sizes,
      tileSizes: tileSizes,
      extent: tileMatrixSetLimits ? extent : undefined,
    });

    const context = sourceInfo.context;
    const base = sourceInfo.url;

    /** @type {import('../Tile.js').UrlFunction} */
    function tileUrlFunction(tileCoord, pixelRatio, projection) {
      if (!tileCoord) {
        return undefined;
      }

      const id = matrixIds[tileCoord[0]];
      const matrix = matrixLookup[id];
      const upsideDown = matrix.cornerOfOrigin === 'bottomLeft';

      const localContext = {
        tileMatrix: id,
        tileCol: tileCoord[1],
        tileRow: upsideDown ? -tileCoord[2] - 1 : tileCoord[2],
      };

      if (tileMatrixSetLimits) {
        const limit = limitLookup[matrix.id];
        if (
          localContext.tileCol < limit.minTileCol ||
          localContext.tileCol > limit.maxTileCol ||
          localContext.tileRow < limit.minTileRow ||
          localContext.tileRow > limit.maxTileRow
        ) {
          return undefined;
        }
      }

      Object.assign(localContext, context);

      const url = tileUrlTemplate.replace(/\{(\w+?)\}/g, function (m, p) {
        return localContext[p];
      });

      return resolveUrl(base, url);
    }

    return {
      grid: tileGrid,
      projection: projection,
      urlTemplate: tileUrlTemplate,
      urlFunction: tileUrlFunction,
    };
  }

  /**
   * @param {SourceInfo} sourceInfo The source info.
   * @param {TileSet} tileSet Tile set.
   * @return {TileSetInfo|Promise<TileSetInfo>} Tile set info.
   */
  function parseTileSetMetadata(sourceInfo, tileSet) {
    const tileMatrixSetLimits = tileSet.tileMatrixSetLimits;
    /** @type {string} */
    let tileUrlTemplate;

    if (tileSet.dataType === 'map') {
      tileUrlTemplate = getMapTileUrlTemplate(
        tileSet.links,
        sourceInfo.mediaType,
        sourceInfo.collections,
      );
    } else if (tileSet.dataType === 'vector') {
      tileUrlTemplate = getVectorTileUrlTemplate(
        tileSet.links,
        sourceInfo.mediaType,
        sourceInfo.supportedMediaTypes,
        sourceInfo.collections,
      );
    } else {
      throw new Error('Expected tileset data type to be "map" or "vector"');
    }

    if (tileSet.tileMatrixSet) {
      return parseTileMatrixSet(
        sourceInfo,
        tileSet.tileMatrixSet,
        tileUrlTemplate,
        tileMatrixSetLimits,
      );
    }

    const tileMatrixSetLink = tileSet.links.find(
      (link) =>
        link.rel === 'http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme',
    );
    if (!tileMatrixSetLink) {
      throw new Error(
        'Expected http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme link or tileMatrixSet',
      );
    }
    const tileMatrixSetDefinition = tileMatrixSetLink.href;

    const url = resolveUrl(sourceInfo.url, tileMatrixSetDefinition);
    return getJSON(url).then(function (tileMatrixSet) {
      return parseTileMatrixSet(
        sourceInfo,
        tileMatrixSet,
        tileUrlTemplate,
        tileMatrixSetLimits,
      );
    });
  }

  /**
   * @param {SourceInfo} sourceInfo Source info.
   * @return {Promise<TileSetInfo>} Tile set info.
   */
  function getTileSetInfo(sourceInfo) {
    return getJSON(sourceInfo.url).then(function (tileSet) {
      return parseTileSetMetadata(sourceInfo, tileSet);
    });
  }

  /**
   * @module ol/source/OGCMapTile
   */

  /**
   * @typedef {Object} Options
   * @property {string} url URL to the OGC Map Tileset endpoint.
   * @property {Object} [context] A lookup of values to use in the tile URL template.  The `{tileMatrix}`
   * (zoom level), `{tileRow}`, and `{tileCol}` variables in the URL will always be provided by the source.
   * @property {string} [mediaType] The content type for the tiles (e.g. "image/png").  If not provided,
   * the source will try to find a link with rel="item" that uses a supported image type.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. By default, the projection
   * will be derived from the `crs` of the `tileMatrixSet`.  You can override this by supplying
   * a projection to the constructor.
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(tile, src) {
   *   tile.getImage().src = src;
   * };
   * ```
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {Array<string>} [collections] A list of geospatial data sub-resources to include. If not provided, the entire dataset will
   * be included. This option is not applicable when requesting the tileset for a single collection.
   */

  /**
   * @classdesc
   * Layer source for map tiles from an [OGC API - Tiles](https://ogcapi.ogc.org/tiles/) service that provides "map" type tiles.
   * The service must conform to at least the core (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/core)
   * and tileset (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tileset) conformance classes. For supporting the `collections`
   * option, the service must conform to the collections selection
   * (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/collections-selection) conformance class.
   * @api
   */
  class OGCMapTile extends TileImage {
    /**
     * @param {Options} options OGC map tile options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: options.projection,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        state: 'loading',
        tileLoadFunction: options.tileLoadFunction,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
      });

      const sourceInfo = {
        url: options.url,
        projection: this.getProjection(),
        mediaType: options.mediaType,
        context: options.context || null,
        collections: options.collections,
      };

      getTileSetInfo(sourceInfo)
        .then(this.handleTileSetInfo_.bind(this))
        .catch(this.handleError_.bind(this));
    }

    /**
     * @param {import("./ogcTileUtil.js").TileSetInfo} tileSetInfo Tile set info.
     * @private
     */
    handleTileSetInfo_(tileSetInfo) {
      this.tileGrid = tileSetInfo.grid;
      this.projection = tileSetInfo.projection;
      this.setTileUrlFunction(tileSetInfo.urlFunction, tileSetInfo.urlTemplate);
      this.setState('ready');
    }

    /**
     * @private
     * @param {Error} error The error.
     */
    handleError_(error) {
      error$1(error);
      this.setState('error');
    }
  }

  /**
   * @module ol/source/OGCVectorTile
   */


  /**
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   * @typedef {Object} Options
   * @property {string} url URL to the OGC Vector Tileset endpoint.
   * @property {Object} [context] A lookup of values to use in the tile URL template.  The `{tileMatrix}`
   * (zoom level), `{tileRow}`, and `{tileCol}` variables in the URL will always be provided by the source.
   * @property {import("../format/Feature.js").default<FeatureType>} [format] Feature format for tiles. Used and required by the default.
   * @property {string} [mediaType] The content type for the tiles (e.g. "application/vnd.mapbox-vector-tile").  If not provided,
   * the source will try to find a link with rel="item" that uses a vector type supported by the configured format.
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {boolean} [overlaps=true] This source may have overlapping geometries. Setting this
   * to `false` (e.g. for sources with polygons that represent administrative
   * boundaries or TopoJSON sources) allows the renderer to optimise fill and
   * stroke operations.
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Projection of the tile grid.
   * @property {typeof import("../VectorTile.js").default} [tileClass] Class used to instantiate image tiles.
   * Default is {@link module:ol/VectorTile~VectorTile}.
   * @property {number} [transition] A duration for tile opacity
   * transitions in milliseconds. A duration of 0 disables the opacity transition.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * When set to `false`, only one world
   * will be rendered. When set to `true`, tiles will be wrapped horizontally to
   * render multiple worlds.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=1]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   * @property {Array<string>} [collections] A list of geospatial data sub-resources to include. If not provided, the entire dataset will
   * be included. This option is not applicable when requesting the tileset for a single collection.
   */

  /**
   * @classdesc
   * Layer source for map tiles from an [OGC API - Tiles](https://ogcapi.ogc.org/tiles/) service that provides "vector" type tiles.
   * The service must conform to at least the core (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/core)
   * and tileset (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tileset) conformance classes. For supporting the `collections`
   * option, the service must conform to the collections selection
   * (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/collections-selection) conformance class.
   *
   * Vector tile sets may come in a variety of formats (e.g. GeoJSON, MVT).  The `format` option is used to determine
   * which of the advertised media types is used.  If you need to force the use of a particular media type, you can
   * provide the `mediaType` option.
   * @api
   * @template {import("../Feature.js").FeatureLike} [FeatureType=import("../render/Feature.js").default]
   * @extends {VectorTileSource<FeatureType>}
   */
  class OGCVectorTile extends VectorTile {
    /**
     * @param {Options<FeatureType>} options OGC vector tile options.
     */
    constructor(options) {
      super({
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        cacheSize: options.cacheSize,
        format: options.format,
        overlaps: options.overlaps,
        projection: options.projection,
        tileClass: options.tileClass,
        transition: options.transition,
        wrapX: options.wrapX,
        zDirection: options.zDirection,
        state: 'loading',
      });

      const sourceInfo = {
        url: options.url,
        projection: this.getProjection(),
        mediaType: options.mediaType,
        supportedMediaTypes: options.format.supportedMediaTypes,
        context: options.context || null,
        collections: options.collections,
      };

      getTileSetInfo(sourceInfo)
        .then(this.handleTileSetInfo_.bind(this))
        .catch(this.handleError_.bind(this));
    }

    /**
     * @param {import("./ogcTileUtil.js").TileSetInfo} tileSetInfo Tile set info.
     * @private
     */
    handleTileSetInfo_(tileSetInfo) {
      this.tileGrid = tileSetInfo.grid;
      this.projection = tileSetInfo.projection;
      this.setTileUrlFunction(tileSetInfo.urlFunction, tileSetInfo.urlTemplate);
      this.setState('ready');
    }

    /**
     * @private
     * @param {Error} error The error.
     */
    handleError_(error) {
      error$1(error);
      this.setState('error');
    }
  }

  /**
   * @module ol/source/OSM
   */


  /**
   * The attribution containing a link to the OpenStreetMap Copyright and License
   * page.
   * @const
   * @type {string}
   * @api
   */
  const ATTRIBUTION =
    '&#169; ' +
    '<a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> ' +
    'contributors.';

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin='anonymous'] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {number} [maxZoom=19] Max zoom.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {number} [transition=250] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {string} [url='https://tile.openstreetmap.org/{z}/{x}/{y}.png'] URL template.
   * Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for the OpenStreetMap tile server.
   * @api
   */
  class OSM extends XYZ {
    /**
     * @param {Options} [options] Open Street Map options.
     */
    constructor(options) {
      options = options || {};

      let attributions;
      if (options.attributions !== undefined) {
        attributions = options.attributions;
      } else {
        attributions = [ATTRIBUTION];
      }

      const crossOrigin =
        options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous';

      const url =
        options.url !== undefined
          ? options.url
          : 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';

      super({
        attributions: attributions,
        attributionsCollapsible: false,
        cacheSize: options.cacheSize,
        crossOrigin: crossOrigin,
        interpolate: options.interpolate,
        maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileLoadFunction: options.tileLoadFunction,
        transition: options.transition,
        url: url,
        wrapX: options.wrapX,
        zDirection: options.zDirection,
      });
    }
  }

  /**
   * @module ol/source/StadiaMaps
   */


  /**
   * @type {string}
   */
  const STADIA_ATTRIBUTION =
    '&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a>';

  /**
   * @type {string}
   */
  const OMT_ATTRIBUTION =
    '&copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a>';

  /**
   * @type {string}
   */
  const STAMEN_ATTRIBUTION =
    '&copy; <a href="https://stamen.com/" target="_blank">Stamen Design</a>';

  /**
   * @type {Object<string, {extension: string}>}
   */
  const LayerConfig = {
    'stamen_terrain': {
      extension: 'png',
    },
    'stamen_terrain_background': {
      extension: 'png',
    },
    'stamen_terrain_labels': {
      extension: 'png',
    },
    'stamen_terrain_lines': {
      extension: 'png',
    },
    'stamen_toner_background': {
      extension: 'png',
    },
    'stamen_toner': {
      extension: 'png',
    },
    'stamen_toner_labels': {
      extension: 'png',
    },
    'stamen_toner_lines': {
      extension: 'png',
    },
    'stamen_toner_lite': {
      extension: 'png',
    },
    'stamen_watercolor': {
      extension: 'jpg',
    },
    'alidade_smooth': {
      extension: 'png',
    },
    'alidade_smooth_dark': {
      extension: 'png',
    },
    'alidade_satellite': {
      extension: 'png',
    },
    'outdoors': {
      extension: 'png',
    },
    'osm_bright': {
      extension: 'png',
    },
  };

  /**
   * @type {Object<string, {minZoom: number, maxZoom: number, retina: boolean}>}
   */
  const ProviderConfig = {
    'stamen_terrain': {
      minZoom: 0,
      maxZoom: 18,
      retina: true,
    },
    'stamen_toner': {
      minZoom: 0,
      maxZoom: 20,
      retina: true,
    },
    'stamen_watercolor': {
      minZoom: 1,
      maxZoom: 18,
      retina: false,
    },
  };

  /**
   * @typedef {Object} Options
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {string} layer Layer name. Valid values: `alidade_smooth`, `alidade_smooth_dark`, `outdoors`, `stamen_terrain`, `stamen_terrain_background`, `stamen_terrain_labels`, `stamen_terrain_lines`, `stamen_toner_background`, `stamen_toner`, `stamen_toner_labels`, `stamen_toner_lines`, `stamen_toner_lite`, `stamen_watercolor`, and `osm_bright`.
   * @property {number} [minZoom] Minimum zoom.
   * @property {number} [maxZoom] Maximum zoom.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction]
   * Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {number} [transition=250] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   * @property {string} [apiKey] Stadia Maps API key. Not required for localhost or most public web deployments. See https://docs.stadiamaps.com/authentication/ for details.
   * @property {boolean} [retina] Use retina tiles (if available; not available for Stamen Watercolor).
   */

  /**
   * @classdesc
   * Layer source for the Stadia Maps tile server.
   * @api
   */
  class StadiaMaps extends XYZ {
    /**
     * @param {Options} options StadiaMaps options.
     */
    constructor(options) {
      const i = options.layer.indexOf('-');
      const provider = i == -1 ? options.layer : options.layer.slice(0, i);
      const providerConfig = ProviderConfig[provider] || {
        'minZoom': 0,
        'maxZoom': 20,
        'retina': true,
      };

      const layerConfig = LayerConfig[options.layer];
      const query = options.apiKey ? '?api_key=' + options.apiKey : '';
      const retina = providerConfig.retina && options.retina ? '@2x' : '';

      const url =
        options.url !== undefined
          ? options.url
          : 'https://tiles.stadiamaps.com/tiles/' +
            options.layer +
            '/{z}/{x}/{y}' +
            retina +
            '.' +
            layerConfig.extension +
            query;

      const attributions = [STADIA_ATTRIBUTION, OMT_ATTRIBUTION, ATTRIBUTION];

      if (options.layer.startsWith('stamen_')) {
        attributions.splice(1, 0, STAMEN_ATTRIBUTION);
      }

      super({
        attributions: attributions,
        cacheSize: options.cacheSize,
        crossOrigin: 'anonymous',
        interpolate: options.interpolate,
        maxZoom:
          options.maxZoom !== undefined
            ? options.maxZoom
            : providerConfig.maxZoom,
        minZoom:
          options.minZoom !== undefined
            ? options.minZoom
            : providerConfig.minZoom,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileLoadFunction: options.tileLoadFunction,
        transition: options.transition,
        url: url,
        tilePixelRatio: retina ? 2 : 1,
        wrapX: options.wrapX,
        zDirection: options.zDirection,
      });
    }
  }

  /**
   * @module ol/source/TileArcGISRest
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {Object<string,*>} [params] ArcGIS Rest parameters. This field is optional. Service defaults will be
   * used for any fields not specified. `FORMAT` is `PNG32` by default. `F` is `IMAGE` by
   * default. `TRANSPARENT` is `true` by default.  `BBOX`, `SIZE`, `BBOXSR`,
   * and `IMAGESR` will be set dynamically. Set `LAYERS` to
   * override the default service layer visibility. See
   * https://developers.arcgis.com/rest/services-reference/export-map.htm
   * for further reference.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid. Base this on the resolutions,
   * tilesize and extent supported by the server.
   * If this is not defined, a default grid will be used: if there is a projection
   * extent, the grid will be based on that; if not, a grid based on a global
   * extent with origin at 0,0 will be used.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * The projection code must contain a numeric end portion separated by :
   * or the entire code must form a valid ArcGIS SpatialReference definition.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL.
   * The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {string} [url] ArcGIS Rest service URL for a Map Service or Image Service. The
   * url should include /MapServer or /ImageServer.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.  To disable the opacity
   * transition, pass `transition: 0`.
   * @property {Array<string>} [urls] ArcGIS Rest service urls. Use this instead of `url` when the ArcGIS
   * Service supports multiple urls for export requests.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data from ArcGIS Rest services. Map and Image
   * Services are supported.
   *
   * For cached ArcGIS services, better performance is available using the
   * {@link module:ol/source/XYZ~XYZ} data source.
   * @api
   */
  class TileArcGISRest extends TileImage {
    /**
     * @param {Options} [options] Tile ArcGIS Rest options.
     */
    constructor(options) {
      options = options ? options : {};

      super({
        attributions: options.attributions,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: options.projection,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileGrid: options.tileGrid,
        tileLoadFunction: options.tileLoadFunction,
        url: options.url,
        urls: options.urls,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {!Object}
       */
      this.params_ = Object.assign({}, options.params);

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.tmpExtent_ = createEmpty();

      this.setKey(this.getKeyForParams_());
    }

    /**
     * @private
     * @return {string} The key for the current params.
     */
    getKeyForParams_() {
      let i = 0;
      const res = [];
      for (const key in this.params_) {
        res[i++] = key + '-' + this.params_[key];
      }
      return res.join('/');
    }

    /**
     * Get the user-provided params, i.e. those passed to the constructor through
     * the "params" option, and possibly updated using the updateParams method.
     * @return {Object} Params.
     * @api
     */
    getParams() {
      return this.params_;
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../size.js").Size} tileSize Tile size.
     * @param {import("../extent.js").Extent} tileExtent Tile extent.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @param {Object} params Params.
     * @return {string|undefined} Request URL.
     * @private
     */
    getRequestUrl_(
      tileCoord,
      tileSize,
      tileExtent,
      pixelRatio,
      projection,
      params,
    ) {
      const urls = this.urls;
      if (!urls) {
        return undefined;
      }
      let url;
      if (urls.length == 1) {
        url = urls[0];
      } else {
        const index = modulo(hash(tileCoord), urls.length);
        url = urls[index];
      }

      return getRequestUrl(
        url,
        tileExtent,
        (
          this.tileGrid || this.getTileGridForProjection(projection)
        ).getResolution(tileCoord[0]),
        pixelRatio,
        projection,
        params,
      );
    }

    /**
     * Get the tile pixel ratio for this source.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Tile pixel ratio.
     * @override
     */
    getTilePixelRatio(pixelRatio) {
      return this.hidpi_ ? pixelRatio : 1;
    }

    /**
     * Set the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    setParams(params) {
      this.params_ = Object.assign({}, params);
      this.setKey(this.getKeyForParams_());
    }

    /**
     * Update the user-provided params.
     * @param {Object} params Params.
     * @api
     */
    updateParams(params) {
      Object.assign(this.params_, params);
      this.setKey(this.getKeyForParams_());
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord The tile coordinate
     * @param {number} pixelRatio The pixel ratio
     * @param {import("../proj/Projection.js").default} projection The projection
     * @return {string|undefined} The tile URL
     * @override
     */
    tileUrlFunction(tileCoord, pixelRatio, projection) {
      let tileGrid = this.getTileGrid();
      if (!tileGrid) {
        tileGrid = this.getTileGridForProjection(projection);
      }

      if (tileGrid.getResolutions().length <= tileCoord[0]) {
        return undefined;
      }

      if (pixelRatio != 1 && !this.hidpi_) {
        pixelRatio = 1;
      }

      const tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);
      let tileSize = toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize);

      if (pixelRatio != 1) {
        tileSize = scale$1(tileSize, pixelRatio, this.tmpSize);
      }

      // Apply default params and override with user specified values.
      const baseParams = {
        'F': 'image',
        'FORMAT': 'PNG32',
        'TRANSPARENT': true,
      };
      Object.assign(baseParams, this.params_);

      return this.getRequestUrl_(
        tileCoord,
        tileSize,
        tileExtent,
        pixelRatio,
        projection,
        baseParams,
      );
    }
  }

  /**
   * @module ol/source/TileDebug
   */


  /**
   * @typedef {Object} Options
   * @property {import("../proj.js").ProjectionLike} [projection='EPSG:3857'] Optional projection.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Set to `1` when debugging `VectorTile` sources with a default configuration.
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   * @property {import("./Tile.js").default} [source] Tile source.
   * This allows `projection`, `tileGrid`, `wrapX` and `zDirection` to be copied from another source.
   * If both `source` and individual options are specified the individual options will have precedence.
   * @property {string} [template='z:{z} x:{x} y:{y}'] Template for labeling the tiles.
   * Should include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.
   * @property {string} [color='grey'] CSS color to fill text and stroke grid lines of each tile.
   */

  /**
   * @classdesc
   * A pseudo tile source, which does not fetch tiles from a server, but renders
   * a grid outline for the tile grid/projection along with the coordinates for
   * each tile. See examples/canvas-tiles for an example.
   * @api
   */
  class TileDebug extends ImageTileSource {
    /**
     * @param {Options} [options] Debug tile options.
     */
    constructor(options) {
      /**
       * @type {Options}
       */
      options = options || {};
      const template = options.template || 'z:{z} x:{x} y:{y}';
      const source = options.source;
      const color = options.color || 'grey';

      super({
        transition: 0,
        wrapX:
          options.wrapX !== undefined
            ? options.wrapX
            : source !== undefined
              ? source.getWrapX()
              : undefined,
      });

      const setReady = () => {
        this.projection =
          options.projection !== undefined
            ? get$2(options.projection)
            : source !== undefined
              ? source.getProjection()
              : this.projection;
        this.tileGrid =
          options.tileGrid !== undefined
            ? options.tileGrid
            : source !== undefined
              ? source.getTileGrid()
              : this.tileGrid;
        this.zDirection =
          options.zDirection !== undefined
            ? options.zDirection
            : source !== undefined
              ? source.zDirection
              : this.zDirection;

        if (source instanceof DataTileSource) {
          this.transformMatrix = source.transformMatrix?.slice() || null;
        }

        const tileGrid = this.tileGrid;
        if (tileGrid) {
          this.setTileSizes(
            tileGrid
              .getResolutions()
              .map((r, i) =>
                toSize(tileGrid.getTileSize(i)).map((s) =>
                  Math.max(Math.floor(s), 1),
                ),
              ),
          );
        }

        this.setLoader((z, x, y, loaderOptions) => {
          const text = renderXYZTemplate(template, z, x, y, loaderOptions.maxY);
          const [width, height] = this.getTileSize(z);
          const context = createCanvasContext2D(width, height);

          context.strokeStyle = color;
          context.strokeRect(0.5, 0.5, width + 0.5, height + 0.5);

          context.fillStyle = color;
          context.strokeStyle = 'white';
          context.textAlign = 'center';
          context.textBaseline = 'middle';
          context.font = '24px sans-serif';
          context.lineWidth = 4;
          context.strokeText(text, width / 2, height / 2, width);
          context.fillText(text, width / 2, height / 2, width);
          // make the loader aysnc, so it behaves like other sources that fetch data from a remote server
          return Promise.resolve(context.canvas);
        });
        this.setState('ready');
      };

      if (source === undefined || source.getState() === 'ready') {
        setReady();
      } else {
        const handler = () => {
          if (source.getState() === 'ready') {
            source.removeEventListener(EventType.CHANGE, handler);
            setReady();
          }
        };
        source.addEventListener(EventType.CHANGE, handler);
      }
    }
  }

  /**
   * @module ol/source/TileWMS
   */


  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {Object<string,*>} params WMS request parameters.
   * At least a `LAYERS` param is required. `STYLES` is
   * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT`, `BBOX`
   * and `CRS` (`SRS` for WMS version < 1.3.0) will be set dynamically.
   * @property {number} [gutter=0]
   * The size in pixels of the gutter around image tiles to ignore. By setting
   * this property to a non-zero value, images will be requested that are wider
   * and taller than the tile size by a value of `2 x gutter`.
   * Using a non-zero value allows artifacts of rendering at tile edges to be
   * ignored. If you control the WMS service it is recommended to address
   * "artifacts at tile edges" issues by properly configuring the WMS service. For
   * example, MapServer has a `tile_map_edge_buffer` configuration parameter for
   * this. See https://mapserver.org/output/tile_mode.html.
   * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting
   * the image from the remote server.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {typeof import("../ImageTile.js").default} [tileClass] Class used to instantiate image tiles.
   * Default is {@link module:ol/ImageTile~ImageTile}.
   * @property {import("../tilegrid/TileGrid.js").default} [tileGrid] Tile grid. Base this on the resolutions,
   * tilesize and extent supported by the server.
   * If this is not defined, a default grid will be used: if there is a projection
   * extent, the grid will be based on that; if not, a grid based on a global
   * extent with origin at 0,0 will be used.
   * @property {import("./wms.js").ServerType} [serverType] The type of
   * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.
   * Only needed if `hidpi` is `true`.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {string} [url] WMS service URL.
   * @property {Array<string>} [urls] WMS service urls.
   * Use this instead of `url` when the WMS supports multiple urls for GetMap requests.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * When set to `false`, only one world
   * will be rendered. When `true`, tiles will be requested for one world only,
   * but they will be wrapped horizontally to render multiple worlds.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data from WMS servers.
   * @api
   */
  class TileWMS extends TileImage {
    /**
     * @param {Options} [options] Tile WMS options.
     */
    constructor(options) {
      options = options ? options : /** @type {Options} */ ({});

      const params = Object.assign({}, options.params);

      super({
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: options.projection,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileClass: options.tileClass,
        tileGrid: options.tileGrid,
        tileLoadFunction: options.tileLoadFunction,
        url: options.url,
        urls: options.urls,
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {number}
       */
      this.gutter_ = options.gutter !== undefined ? options.gutter : 0;

      /**
       * @private
       * @type {!Object}
       */
      this.params_ = params;

      /**
       * @private
       * @type {boolean}
       */
      this.v13_ = true;

      /**
       * @private
       * @type {import("./wms.js").ServerType}
       */
      this.serverType_ = options.serverType;

      /**
       * @private
       * @type {boolean}
       */
      this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.tmpExtent_ = createEmpty();

      this.updateV13_();
      this.setKey(this.getKeyForParams_());
    }

    /**
     * Return the GetFeatureInfo URL for the passed coordinate, resolution, and
     * projection. Return `undefined` if the GetFeatureInfo URL cannot be
     * constructed.
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} resolution Resolution.
     * @param {import("../proj.js").ProjectionLike} projection Projection.
     * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should
     *     be provided. If `QUERY_LAYERS` is not provided then the layers specified
     *     in the `LAYERS` parameter will be used. `VERSION` should not be
     *     specified here.
     * @return {string|undefined} GetFeatureInfo URL.
     * @api
     */
    getFeatureInfoUrl(coordinate, resolution, projection, params) {
      const projectionObj = get$2(projection);
      const sourceProjectionObj = this.getProjection() || projectionObj;

      let tileGrid = this.getTileGrid();
      if (!tileGrid) {
        tileGrid = this.getTileGridForProjection(sourceProjectionObj);
      }

      const sourceProjCoord = transform(
        coordinate,
        projectionObj,
        sourceProjectionObj,
      );
      const sourceResolution = calculateSourceResolution(
        sourceProjectionObj,
        projectionObj,
        coordinate,
        resolution,
      );

      const z = tileGrid.getZForResolution(sourceResolution, this.zDirection);
      const tileResolution = tileGrid.getResolution(z);
      const tileCoord = tileGrid.getTileCoordForCoordAndZ(sourceProjCoord, z);

      if (tileGrid.getResolutions().length <= tileCoord[0]) {
        return undefined;
      }

      let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);

      const gutter = this.gutter_;
      if (gutter !== 0) {
        tileExtent = buffer$1(tileExtent, tileResolution * gutter, tileExtent);
      }

      const baseParams = {
        'QUERY_LAYERS': this.params_['LAYERS'],
      };
      Object.assign(
        baseParams,
        getRequestParams(this.params_, 'GetFeatureInfo'),
        params,
      );

      const x = Math.floor((sourceProjCoord[0] - tileExtent[0]) / tileResolution);
      const y = Math.floor((tileExtent[3] - sourceProjCoord[1]) / tileResolution);

      baseParams[this.v13_ ? 'I' : 'X'] = x;
      baseParams[this.v13_ ? 'J' : 'Y'] = y;

      return this.getRequestUrl_(
        tileCoord,
        tileExtent,
        1,
        sourceProjectionObj || projectionObj,
        baseParams,
      );
    }

    /**
     * Return the GetLegendGraphic URL, optionally optimized for the passed
     * resolution and possibly including any passed specific parameters. Returns
     * `undefined` if the GetLegendGraphic URL cannot be constructed.
     *
     * @param {number} [resolution] Resolution. If set to undefined, `SCALE`
     *     will not be calculated and included in URL.
     * @param {Object} [params] GetLegendGraphic params. If `LAYER` is set, the
     *     request is generated for this wms layer, else it will try to use the
     *     configured wms layer. Default `FORMAT` is `image/png`.
     *     `VERSION` should not be specified here.
     * @return {string|undefined} GetLegendGraphic URL.
     * @api
     */
    getLegendUrl(resolution, params) {
      if (this.urls[0] === undefined) {
        return undefined;
      }

      const baseParams = {
        'SERVICE': 'WMS',
        'VERSION': DEFAULT_VERSION,
        'REQUEST': 'GetLegendGraphic',
        'FORMAT': 'image/png',
      };

      if (params === undefined || params['LAYER'] === undefined) {
        const layers = this.params_.LAYERS;
        const isSingleLayer = !Array.isArray(layers) || layers.length === 1;
        if (!isSingleLayer) {
          return undefined;
        }
        baseParams['LAYER'] = layers;
      }

      if (resolution !== undefined) {
        const mpu = this.getProjection()
          ? this.getProjection().getMetersPerUnit()
          : 1;
        const pixelSize = 0.00028;
        baseParams['SCALE'] = (resolution * mpu) / pixelSize;
      }

      Object.assign(baseParams, params);

      return appendParams(/** @type {string} */ (this.urls[0]), baseParams);
    }

    /**
     * @return {number} Gutter.
     * @override
     */
    getGutter() {
      return this.gutter_;
    }

    /**
     * Get the user-provided params, i.e. those passed to the constructor through
     * the "params" option, and possibly updated using the updateParams method.
     * @return {Object} Params.
     * @api
     */
    getParams() {
      return this.params_;
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../extent.js").Extent} tileExtent Tile extent.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @param {Object} params Params.
     * @return {string|undefined} Request URL.
     * @private
     */
    getRequestUrl_(tileCoord, tileExtent, pixelRatio, projection, params) {
      const urls = this.urls;
      if (!urls) {
        return undefined;
      }
      let url;
      if (urls.length == 1) {
        url = urls[0];
      } else {
        const index = modulo(hash(tileCoord), urls.length);
        url = urls[index];
      }

      return getImageSrc(
        tileExtent,
        (
          this.tileGrid || this.getTileGridForProjection(projection)
        ).getResolution(tileCoord[0]),
        pixelRatio,
        projection,
        url,
        params,
        this.serverType_,
      );
    }

    /**
     * Get the tile pixel ratio for this source.
     * @param {number} pixelRatio Pixel ratio.
     * @return {number} Tile pixel ratio.
     * @override
     */
    getTilePixelRatio(pixelRatio) {
      return !this.hidpi_ || this.serverType_ === undefined ? 1 : pixelRatio;
    }

    /**
     * @private
     * @return {string} The key for the current params.
     */
    getKeyForParams_() {
      let i = 0;
      const res = [];
      for (const key in this.params_) {
        res[i++] = key + '-' + this.params_[key];
      }
      return res.join('/');
    }

    /**
     * @param {Object} params New URL paremeters.
     * @private
     */
    setParams_(params) {
      this.params_ = params;
      this.updateV13_();
      this.setKey(this.getKeyForParams_());
    }

    /**
     * Set the URL parameters passed to the WMS source.
     * @param {Object} params New URL paremeters.
     * @api
     */
    setParams(params) {
      this.setParams_(Object.assign({}, params));
    }

    /**
     * Update the URL parameters. This method can be used to update a subset of the WMS
     * parameters. Call `setParams` to set all of the parameters.
     * @param {Object} params Updated URL parameters.
     * @api
     */
    updateParams(params) {
      this.setParams_(Object.assign(this.params_, params));
    }

    /**
     * @private
     */
    updateV13_() {
      const version = this.params_['VERSION'] || DEFAULT_VERSION;
      this.v13_ = compareVersions(version, '1.3') >= 0;
    }

    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord The tile coordinate
     * @param {number} pixelRatio The pixel ratio
     * @param {import("../proj/Projection.js").default} projection The projection
     * @return {string|undefined} The tile URL
     * @override
     */
    tileUrlFunction(tileCoord, pixelRatio, projection) {
      let tileGrid = this.getTileGrid();
      if (!tileGrid) {
        tileGrid = this.getTileGridForProjection(projection);
      }

      if (tileGrid.getResolutions().length <= tileCoord[0]) {
        return undefined;
      }

      if (pixelRatio != 1 && (!this.hidpi_ || this.serverType_ === undefined)) {
        pixelRatio = 1;
      }

      const tileResolution = tileGrid.getResolution(tileCoord[0]);
      let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);

      const gutter = this.gutter_;
      if (gutter !== 0) {
        tileExtent = buffer$1(tileExtent, tileResolution * gutter, tileExtent);
      }

      const baseParams = Object.assign(
        {},
        getRequestParams(this.params_, 'GetMap'),
      );

      return this.getRequestUrl_(
        tileCoord,
        tileExtent,
        pixelRatio,
        projection,
        baseParams,
      );
    }
  }

  /**
   * @module ol/source/UTFGrid
   */


  /**
   * @typedef {Object} UTFGridJSON
   * @property {Array<string>} grid The grid.
   * @property {Array<string>} keys The keys.
   * @property {Object<string, Object>} [data] Optional data.
   */

  class CustomTile extends Tile {
    /**
     * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
     * @param {import("../TileState.js").default} state State.
     * @param {string} src Image source URI.
     * @param {import("../extent.js").Extent} extent Extent of the tile.
     * @param {boolean} preemptive Load the tile when visible (before it's needed).
     * @param {boolean} jsonp Load the tile as a script.
     */
    constructor(tileCoord, state, src, extent, preemptive, jsonp) {
      super(tileCoord, state);

      /**
       * @private
       * @type {string}
       */
      this.src_ = src;

      /**
       * @private
       * @type {import("../extent.js").Extent}
       */
      this.extent_ = extent;

      /**
       * @private
       * @type {boolean}
       */
      this.preemptive_ = preemptive;

      /**
       * @private
       * @type {Array<string>}
       */
      this.grid_ = null;

      /**
       * @private
       * @type {Array<string>}
       */
      this.keys_ = null;

      /**
       * @private
       * @type {Object<string, Object>|undefined}
       */
      this.data_ = null;

      /**
       * @private
       * @type {boolean}
       */
      this.jsonp_ = jsonp;
    }

    /**
     * Get the image element for this tile.
     * @return {HTMLImageElement} Image.
     */
    getImage() {
      return null;
    }

    /**
     * Synchronously returns data at given coordinate (if available).
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @return {*} The data.
     */
    getData(coordinate) {
      if (!this.grid_ || !this.keys_) {
        return null;
      }
      const xRelative =
        (coordinate[0] - this.extent_[0]) / (this.extent_[2] - this.extent_[0]);
      const yRelative =
        (coordinate[1] - this.extent_[1]) / (this.extent_[3] - this.extent_[1]);

      const row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)];

      if (typeof row !== 'string') {
        return null;
      }

      let code = row.charCodeAt(Math.floor(xRelative * row.length));
      if (code >= 93) {
        code--;
      }
      if (code >= 35) {
        code--;
      }
      code -= 32;

      let data = null;
      if (code in this.keys_) {
        const id = this.keys_[code];
        if (this.data_ && id in this.data_) {
          data = this.data_[id];
        } else {
          data = id;
        }
      }
      return data;
    }

    /**
     * Calls the callback (synchronously by default) with the available data
     * for given coordinate (or `null` if not yet loaded).
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {function(*): void} callback Callback.
     * @param {boolean} [request] If `true` the callback is always async.
     *                               The tile data is requested if not yet loaded.
     */
    forDataAtCoordinate(coordinate, callback, request) {
      if (this.state == TileState.EMPTY && request === true) {
        this.state = TileState.IDLE;
        listenOnce(this, EventType.CHANGE, (e) => {
          callback(this.getData(coordinate));
        });
        this.loadInternal_();
      } else {
        if (request === true) {
          setTimeout(() => {
            callback(this.getData(coordinate));
          }, 0);
        } else {
          callback(this.getData(coordinate));
        }
      }
    }

    /**
     * Return the key to be used for all tiles in the source.
     * @return {string} The key for all tiles.
     * @override
     */
    getKey() {
      return this.src_;
    }

    /**
     * @private
     */
    handleError_() {
      this.state = TileState.ERROR;
      this.changed();
    }

    /**
     * @param {!UTFGridJSON} json UTFGrid data.
     * @private
     */
    handleLoad_(json) {
      this.grid_ = json['grid'];
      this.keys_ = json['keys'];
      this.data_ = json['data'];

      this.state = TileState.LOADED;
      this.changed();
    }

    /**
     * @private
     */
    loadInternal_() {
      if (this.state == TileState.IDLE) {
        this.state = TileState.LOADING;
        if (this.jsonp_) {
          jsonp(
            this.src_,
            this.handleLoad_.bind(this),
            this.handleError_.bind(this),
          );
        } else {
          const client = new XMLHttpRequest();
          client.addEventListener('load', this.onXHRLoad_.bind(this));
          client.addEventListener('error', this.onXHRError_.bind(this));
          client.open('GET', this.src_);
          client.send();
        }
      }
    }

    /**
     * @private
     * @param {Event} event The load event.
     */
    onXHRLoad_(event) {
      const client = /** @type {XMLHttpRequest} */ (event.target);
      // status will be 0 for file:// urls
      if (!client.status || (client.status >= 200 && client.status < 300)) {
        let response;
        try {
          response = /** @type {!UTFGridJSON} */ (
            JSON.parse(client.responseText)
          );
        } catch {
          this.handleError_();
          return;
        }
        this.handleLoad_(response);
      } else {
        this.handleError_();
      }
    }

    /**
     * @private
     * @param {Event} event The error event.
     */
    onXHRError_(event) {
      this.handleError_();
    }

    /**
     * @override
     */
    load() {
      if (this.preemptive_) {
        this.loadInternal_();
      } else {
        this.setState(TileState.EMPTY);
      }
    }
  }

  /**
   * @typedef {Object} Options
   * @property {boolean} [preemptive=true]
   * If `true` the UTFGrid source loads the tiles based on their "visibility".
   * This improves the speed of response, but increases traffic.
   * Note that if set to `false` (lazy loading), you need to pass `true` as
   * `request` to the `forDataAtCoordinateAndResolution` method otherwise no
   * data will ever be loaded.
   * @property {boolean} [jsonp=false] Use JSONP with callback to load the TileJSON.
   * Useful when the server does not support CORS..
   * @property {import("./TileJSON.js").Config} [tileJSON] TileJSON configuration for this source.
   * If not provided, `url` must be configured.
   * @property {string} [url] TileJSON endpoint that provides the configuration for this source.
   * Request will be made through JSONP. If not provided, `tileJSON` must be configured.
   * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for UTFGrid interaction data loaded from TileJSON format.
   * @api
   */
  class UTFGrid extends TileSource {
    /**
     * @param {Options} options Source options.
     */
    constructor(options) {
      super({
        projection: get$2('EPSG:3857'),
        state: 'loading',
        wrapX: options.wrapX !== undefined ? options.wrapX : true,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {boolean}
       */
      this.preemptive_ =
        options.preemptive !== undefined ? options.preemptive : true;

      /**
       * @private
       * @type {!import("../Tile.js").UrlFunction}
       */
      this.tileUrlFunction_ = nullTileUrlFunction;

      /**
       * @private
       * @type {string|undefined}
       */
      this.template_ = undefined;

      /**
       * @private
       * @type {boolean}
       */
      this.jsonp_ = options.jsonp || false;

      /**
       * @private
       * @type {LRUCache}
       */
      this.tileCache_ = new LRUCache(512);

      if (options.url) {
        if (this.jsonp_) {
          jsonp(
            options.url,
            this.handleTileJSONResponse.bind(this),
            this.handleTileJSONError.bind(this),
          );
        } else {
          const client = new XMLHttpRequest();
          client.addEventListener('load', this.onXHRLoad_.bind(this));
          client.addEventListener('error', this.onXHRError_.bind(this));
          client.open('GET', options.url);
          client.send();
        }
      } else if (options.tileJSON) {
        this.handleTileJSONResponse(options.tileJSON);
      } else {
        throw new Error('Either `url` or `tileJSON` options must be provided');
      }
    }

    /**
     * @private
     * @param {Event} event The load event.
     */
    onXHRLoad_(event) {
      const client = /** @type {XMLHttpRequest} */ (event.target);
      // status will be 0 for file:// urls
      if (!client.status || (client.status >= 200 && client.status < 300)) {
        let response;
        try {
          response = /** @type {import("./TileJSON.js").Config} */ (
            JSON.parse(client.responseText)
          );
        } catch {
          this.handleTileJSONError();
          return;
        }
        this.handleTileJSONResponse(response);
      } else {
        this.handleTileJSONError();
      }
    }

    /**
     * @private
     * @param {Event} event The error event.
     */
    onXHRError_(event) {
      this.handleTileJSONError();
    }

    /**
     * Return the template from TileJSON.
     * @return {string|undefined} The template from TileJSON.
     * @api
     */
    getTemplate() {
      return this.template_;
    }

    /**
     * Calls the callback (synchronously by default) with the available data
     * for given coordinate and resolution (or `null` if not yet loaded or
     * in case of an error).
     * @param {import("../coordinate.js").Coordinate} coordinate Coordinate.
     * @param {number} resolution Resolution.
     * @param {function(*): void} callback Callback.
     * @param {boolean} [request] If `true` the callback is always async.
     *                               The tile data is requested if not yet loaded.
     * @api
     */
    forDataAtCoordinateAndResolution(coordinate, resolution, callback, request) {
      if (this.tileGrid) {
        const z = this.tileGrid.getZForResolution(resolution, this.zDirection);
        const tileCoord = this.tileGrid.getTileCoordForCoordAndZ(coordinate, z);
        const tile = /** @type {!CustomTile} */ (
          this.getTile(
            tileCoord[0],
            tileCoord[1],
            tileCoord[2],
            1,
            this.getProjection(),
          )
        );
        if (tile.getState() == TileState.IDLE) {
          tile.load();
        }
        tile.forDataAtCoordinate(coordinate, callback, request);
      } else {
        if (request === true) {
          setTimeout(function () {
            callback(null);
          }, 0);
        } else {
          callback(null);
        }
      }
    }

    /**
     * @protected
     */
    handleTileJSONError() {
      this.setState('error');
    }

    /**
     * TODO: very similar to ol/source/TileJSON#handleTileJSONResponse
     * @protected
     * @param {import("./TileJSON.js").Config} tileJSON Tile JSON.
     */
    handleTileJSONResponse(tileJSON) {
      const epsg4326Projection = get$2('EPSG:4326');

      const sourceProjection = this.getProjection();
      let extent;
      if (tileJSON['bounds'] !== undefined) {
        const transform = getTransformFromProjections(
          epsg4326Projection,
          sourceProjection,
        );
        extent = applyTransform(tileJSON['bounds'], transform);
      }

      const gridExtent = extentFromProjection(sourceProjection);
      const minZoom = tileJSON['minzoom'] || 0;
      const maxZoom = tileJSON['maxzoom'] || 22;
      const tileGrid = createXYZ({
        extent: gridExtent,
        maxZoom: maxZoom,
        minZoom: minZoom,
      });
      this.tileGrid = tileGrid;

      this.template_ = tileJSON['template'];

      const grids = tileJSON['grids'];
      if (!grids) {
        this.setState('error');
        return;
      }

      this.tileUrlFunction_ = createFromTemplates(grids, tileGrid);

      if (tileJSON['attribution']) {
        const attributionExtent = extent !== undefined ? extent : gridExtent;
        this.setAttributions(function (frameState) {
          if (intersects$2(attributionExtent, frameState.extent)) {
            return [tileJSON['attribution']];
          }
          return null;
        });
      }

      this.setState('ready');
    }

    /**
     * @param {number} z Tile coordinate z.
     * @param {number} x Tile coordinate x.
     * @param {number} y Tile coordinate y.
     * @param {number} pixelRatio Pixel ratio.
     * @param {import("../proj/Projection.js").default} projection Projection.
     * @return {!CustomTile} Tile.
     * @override
     */
    getTile(z, x, y, pixelRatio, projection) {
      const tileCoord = [z, x, y];
      const urlTileCoord = this.getTileCoordForTileUrlFunction(
        tileCoord,
        projection,
      );
      const tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection);
      const tileKey = `${this.getKey()},${getKeyZXY(z, x, y)}`;
      if (this.tileCache_.containsKey(tileKey)) {
        return this.tileCache_.get(tileKey);
      }
      this.tileCache_.expireCache();
      const tile = new CustomTile(
        tileCoord,
        tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY,
        tileUrl !== undefined ? tileUrl : '',
        this.tileGrid.getTileCoordExtent(tileCoord),
        this.preemptive_,
        this.jsonp_,
      );
      this.tileCache_.set(tileKey, tile);
      return tile;
    }
  }

  /**
   * @module ol/source/WMTS
   */


  /**
   * Request encoding. One of 'KVP', 'REST'.
   * @typedef {'KVP' | 'REST'} RequestEncoding
   */

  /**
   * @typedef {Object} Options
   * @property {import("./Source.js").AttributionLike} [attributions] Attributions.
   * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
   * @property {number} [cacheSize] Deprecated.  Use the cacheSize option on the layer instead.
   * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images.  Note that
   * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.
   * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.
   * @property {boolean} [interpolate=true] Use interpolated values when resampling.  By default,
   * linear interpolation is used when resampling.  Set to false to use the nearest neighbor instead.
   * @property {import("../tilegrid/WMTS.js").default} tileGrid Tile grid.
   * @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
   * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).
   * Higher values can increase reprojection performance, but decrease precision.
   * @property {RequestEncoding} [requestEncoding='KVP'] Request encoding.
   * @property {string} layer Layer name as advertised in the WMTS capabilities.
   * @property {string} style Style name as advertised in the WMTS capabilities.
   * @property {typeof import("../ImageTile.js").default} [tileClass]  Class used to instantiate image tiles. Default is {@link module:ol/ImageTile~ImageTile}.
   * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.
   * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px
   * by 512px images (for retina/hidpi devices) then `tilePixelRatio`
   * should be set to `2`.
   * @property {string} [format='image/jpeg'] Image format. Only used when `requestEncoding` is `'KVP'`.
   * @property {string} [version='1.0.0'] WMTS version.
   * @property {string} matrixSet Matrix set.
   * @property {!Object} [dimensions] Additional "dimensions" for tile requests.
   * This is an object with properties named like the advertised WMTS dimensions.
   * @property {string} [url]  A URL for the service.
   * For the RESTful request encoding, this is a URL
   * template.  For KVP encoding, it is normal URL. A `{?-?}` template pattern,
   * for example `subdomain{a-f}.domain.com`, may be used instead of defining
   * each one separately in the `urls` option.
   * @property {import("../Tile.js").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is
   * ```js
   * function(imageTile, src) {
   *   imageTile.getImage().src = src;
   * };
   * ```
   * @property {Array<string>} [urls] An array of URLs.
   * Requests will be distributed among the URLs in this array.
   * @property {boolean} [wrapX=false] Whether to wrap the world horizontally.
   * @property {number} [transition] Duration of the opacity transition for rendering.
   * To disable the opacity transition, pass `transition: 0`.
   * @property {number|import("../array.js").NearestDirectionFunction} [zDirection=0]
   * Choose whether to use tiles with a higher or lower zoom level when between integer
   * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.
   */

  /**
   * @classdesc
   * Layer source for tile data from WMTS servers.
   * @api
   */
  class WMTS extends TileImage {
    /**
     * @param {Options} options WMTS options.
     */
    constructor(options) {
      // TODO: add support for TileMatrixLimits

      const requestEncoding =
        options.requestEncoding !== undefined ? options.requestEncoding : 'KVP';

      // FIXME: should we create a default tileGrid?
      // we could issue a getCapabilities xhr to retrieve missing configuration
      const tileGrid = options.tileGrid;

      let urls = options.urls;
      if (urls === undefined && options.url !== undefined) {
        urls = expandUrl(options.url);
      }

      super({
        attributions: options.attributions,
        attributionsCollapsible: options.attributionsCollapsible,
        cacheSize: options.cacheSize,
        crossOrigin: options.crossOrigin,
        interpolate: options.interpolate,
        projection: options.projection,
        reprojectionErrorThreshold: options.reprojectionErrorThreshold,
        tileClass: options.tileClass,
        tileGrid: tileGrid,
        tileLoadFunction: options.tileLoadFunction,
        tilePixelRatio: options.tilePixelRatio,
        urls: urls,
        wrapX: options.wrapX !== undefined ? options.wrapX : false,
        transition: options.transition,
        zDirection: options.zDirection,
      });

      /**
       * @private
       * @type {string}
       */
      this.version_ = options.version !== undefined ? options.version : '1.0.0';

      /**
       * @private
       * @type {string}
       */
      this.format_ = options.format !== undefined ? options.format : 'image/jpeg';

      /**
       * @private
       * @type {!Object}
       */
      this.dimensions_ =
        options.dimensions !== undefined ? options.dimensions : {};

      /**
       * @private
       * @type {string}
       */
      this.layer_ = options.layer;

      /**
       * @private
       * @type {string}
       */
      this.matrixSet_ = options.matrixSet;

      /**
       * @private
       * @type {string}
       */
      this.style_ = options.style;

      // FIXME: should we guess this requestEncoding from options.url(s)
      //        structure? that would mean KVP only if a template is not provided.

      /**
       * @private
       * @type {RequestEncoding}
       */
      this.requestEncoding_ = requestEncoding;

      this.setKey(this.getKeyForDimensions_());

      if (urls && urls.length > 0) {
        this.tileUrlFunction = createFromTileUrlFunctions(
          urls.map(this.createFromWMTSTemplate.bind(this)),
        );
      }
    }

    /**
     * Set the URLs to use for requests.
     * URLs may contain OGC conform URL Template Variables: {TileMatrix}, {TileRow}, {TileCol}.
     * @param {Array<string>} urls URLs.
     * @override
     */
    setUrls(urls) {
      this.urls = urls;
      const key = urls.join('\n');
      this.setTileUrlFunction(
        createFromTileUrlFunctions(
          urls.map(this.createFromWMTSTemplate.bind(this)),
        ),
        key,
      );
    }

    /**
     * Get the dimensions, i.e. those passed to the constructor through the
     * "dimensions" option, and possibly updated using the updateDimensions
     * method.
     * @return {!Object} Dimensions.
     * @api
     */
    getDimensions() {
      return this.dimensions_;
    }

    /**
     * Return the image format of the WMTS source.
     * @return {string} Format.
     * @api
     */
    getFormat() {
      return this.format_;
    }

    /**
     * Return the layer of the WMTS source.
     * @return {string} Layer.
     * @api
     */
    getLayer() {
      return this.layer_;
    }

    /**
     * Return the matrix set of the WMTS source.
     * @return {string} MatrixSet.
     * @api
     */
    getMatrixSet() {
      return this.matrixSet_;
    }

    /**
     * Return the request encoding, either "KVP" or "REST".
     * @return {RequestEncoding} Request encoding.
     * @api
     */
    getRequestEncoding() {
      return this.requestEncoding_;
    }

    /**
     * Return the style of the WMTS source.
     * @return {string} Style.
     * @api
     */
    getStyle() {
      return this.style_;
    }

    /**
     * Return the version of the WMTS source.
     * @return {string} Version.
     * @api
     */
    getVersion() {
      return this.version_;
    }

    /**
     * @private
     * @return {string} The key for the current dimensions.
     */
    getKeyForDimensions_() {
      const res = this.urls ? this.urls.slice(0) : [];
      for (const key in this.dimensions_) {
        res.push(key + '-' + this.dimensions_[key]);
      }
      return res.join('/');
    }

    /**
     * Update the dimensions.
     * @param {Object} dimensions Dimensions.
     * @api
     */
    updateDimensions(dimensions) {
      Object.assign(this.dimensions_, dimensions);
      this.setKey(this.getKeyForDimensions_());
    }

    /**
     * @param {string} template Template.
     * @return {import("../Tile.js").UrlFunction} Tile URL function.
     */
    createFromWMTSTemplate(template) {
      const requestEncoding = this.requestEncoding_;

      // context property names are lower case to allow for a case insensitive
      // replacement as some services use different naming conventions
      const context = {
        'layer': this.layer_,
        'style': this.style_,
        'tilematrixset': this.matrixSet_,
      };

      if (requestEncoding == 'KVP') {
        Object.assign(context, {
          'Service': 'WMTS',
          'Request': 'GetTile',
          'Version': this.version_,
          'Format': this.format_,
        });
      }

      // TODO: we may want to create our own appendParams function so that params
      // order conforms to wmts spec guidance, and so that we can avoid to escape
      // special template params

      template =
        requestEncoding == 'KVP'
          ? appendParams(template, context)
          : template.replace(/\{(\w+?)\}/g, function (m, p) {
              return p.toLowerCase() in context ? context[p.toLowerCase()] : m;
            });

      const tileGrid = /** @type {import("../tilegrid/WMTS.js").default} */ (
        this.tileGrid
      );
      const dimensions = this.dimensions_;

      return (
        /**
         * @param {import("../tilecoord.js").TileCoord} tileCoord Tile coordinate.
         * @param {number} pixelRatio Pixel ratio.
         * @param {import("../proj/Projection.js").default} projection Projection.
         * @return {string|undefined} Tile URL.
         */
        function (tileCoord, pixelRatio, projection) {
          if (!tileCoord) {
            return undefined;
          }
          const localContext = {
            'TileMatrix': tileGrid.getMatrixId(tileCoord[0]),
            'TileCol': tileCoord[1],
            'TileRow': tileCoord[2],
          };
          Object.assign(localContext, dimensions);
          let url = template;
          if (requestEncoding == 'KVP') {
            url = appendParams(url, localContext);
          } else {
            url = url.replace(/\{(\w+?)\}/g, function (m, p) {
              return encodeURIComponent(localContext[p]);
            });
          }
          return url;
        }
      );
    }
  }

  /**
   * @module ol/source
   */


  /**
   * Creates a sources function from a tile grid. This function can be used as value for the
   * `sources` property of the {@link module:ol/layer/Layer~Layer} subclasses that support it.
   * @param {import("./tilegrid/TileGrid.js").default} tileGrid Tile grid.
   * @param {function(import("./tilecoord.js").TileCoord): import("./source/Source.js").default} factory Source factory.
   * This function takes a {@link module:ol/tilecoord~TileCoord} as argument and is expected to return a
   * {@link module:ol/source/Source~Source}. **Note**: The returned sources should have a tile grid with
   * a limited set of resolutions, matching the resolution range of a single zoom level of the pyramid
   * `tileGrid` that `sourcesFromTileGrid` was called with.
   * @return {function(import("./extent.js").Extent, number): Array<import("./source/Source.js").default>} Sources function.
   * @api
   */
  function sourcesFromTileGrid(tileGrid, factory) {
    const sourceCache = new LRUCache(32);
    const tileGridExtent = tileGrid.getExtent();
    return function (extent, resolution) {
      sourceCache.expireCache();
      if (tileGridExtent) {
        extent = getIntersection(tileGridExtent, extent);
      }
      const z = tileGrid.getZForResolution(resolution);
      const wantedSources = [];
      tileGrid.forEachTileCoord(extent, z, (tileCoord) => {
        const key = tileCoord.toString();
        if (!sourceCache.containsKey(key)) {
          const source = factory(tileCoord);
          sourceCache.set(key, source);
        }
        wantedSources.push(sourceCache.get(key));
      });
      return wantedSources;
    };
  }

  var nsSource = {
    __proto__: null,
    BingMaps: BingMaps,
    CartoDB: CartoDB,
    Cluster: Cluster,
    DataTile: DataTileSource,
    GeoTIFF: GeoTIFFSource,
    Google: Google,
    IIIF: IIIF,
    Image: ImageSource,
    ImageArcGISRest: ImageArcGISRest,
    ImageCanvas: ImageCanvasSource,
    ImageMapGuide: ImageMapGuide,
    ImageStatic: Static,
    ImageTile: ImageTileSource,
    ImageWMS: ImageWMS,
    OGCMapTile: OGCMapTile,
    OGCVectorTile: OGCVectorTile,
    OSM: OSM,
    Raster: RasterSource,
    Source: Source,
    StadiaMaps: StadiaMaps,
    Tile: TileSource,
    TileArcGISRest: TileArcGISRest,
    TileDebug: TileDebug,
    TileImage: TileImage,
    TileJSON: TileJSON,
    TileWMS: TileWMS,
    UTFGrid: UTFGrid,
    UrlTile: UrlTile,
    Vector: VectorSource,
    VectorTile: VectorTile,
    WMTS: WMTS,
    XYZ: XYZ,
    Zoomify: Zoomify,
    createArcGISRestLoader: createLoader$2,
    createMapGuideLoader: createLoader$1,
    createStaticLoader: createLoader,
    createWMSLoader: createLoader$3,
    sourcesFromTileGrid: sourcesFromTileGrid
  };

  // Import (parts of) Openlayers 9 and reexport them in a ~nested namespace structure similar to Openlayers 4


  const nsInteraction = {};
  Object.assign(nsInteraction, interaction0);
  nsInteraction.Draw.createBox = createBox;

  const nsProj = {};
  Object.assign(nsProj, proj0, {
      proj4: proj_proj4
  });

  const nsStyle = {};
  Object.assign(nsStyle, style0, {
      expressions: style_expressions,
      IconAnchorUnits: {
          /**
           * This changed from a separate module to a simple typedef
           * @see https://github.com/openlayers/openlayers/blob/v6.15.1/src/ol/style/IconAnchorUnits.js
           * @see https://github.com/openlayers/openlayers/blob/v7.2.2/src/ol/style/Icon.js#L13
           */
          FRACTION: 'fraction',
          PIXELS: 'pixels'
      },
      IconOrigin: {
          /**
           * This changed from a separate module to a simple typedef
           * @see https://github.com/openlayers/openlayers/blob/v6.15.1/src/ol/style/IconOrigin.js
           * @see https://github.com/openlayers/openlayers/blob/v7.2.2/src/ol/style/Icon.js#L18
           */
          BOTTOM_LEFT: 'bottom-left',
          BOTTOM_RIGHT: 'bottom-right',
          TOP_LEFT: 'top-left',
          TOP_RIGHT: 'top-right'
      },
      TextPlacement: {
          /**
           * This changed from a separate module to a simple typedef
           * @see https://github.com/openlayers/openlayers/blob/v6.15.1/src/ol/style/TextPlacement.js
           * @see https://github.com/openlayers/openlayers/blob/v7.2.2/src/ol/style/Text.js#L8
           */
          POINT: 'point',
          LINE: 'line'
      }
  });
  Object.assign(nsStyle.Style, {
      createDefaultStyle: createDefaultStyle$1,
      createEditingStyle: createEditingStyle
  });


  const ol = {
      // top-level classes
      Collection: Collection,
      Disposable: Disposable,
      Feature: Feature,
      Geolocation: Geolocation,
      Graticule: Graticule,
      Image: ImageWrapper,
      ImageCanvas: ImageCanvas,
      ImageTile: ImageTile,
      Kinetic: Kinetic,
      Map: Map$1,
      MapBrowserEvent: MapBrowserEvent,
      MapBrowserEventHandler: MapBrowserEventHandler,
      MapEvent: MapEvent,
      Object: BaseObject,
      Observable: Observable,
      Overlay: Overlay,
      Tile: Tile,
      TileQueue: TileQueue,
      TileRange: TileRange,
      VectorRenderTile: VectorRenderTile,
      VectorTile: VectorTile$1,
      WebGLVectorTile: WebGLVectorTileLayer,
      View: View,
      // globals (from util)
      getUid: getUid,
      VERSION: VERSION,
      // sub-namespaces
      coordinate: nsCoordinate,
      control: nsControl,
      events: Object.assign({}, nsEvents, {
          Event: Object.assign({}, nsEvents_Event, {
              BaseEvent: BaseEvent,
              stopPropagation: stopPropagation,
              preventDefault: preventDefault
          }),
          condition: nsEvents_condition
      }),
      extent: nsExtent,
      format: {
          GeoJSON: GeoJSON,
          GML: GML,
          GML2: GML2,
          GML3: GML3,
          GML32: GML32,
          KML: KML,
          WFS: WFS,
          WKT: WKT,
          EsriJSON: EsriJSON,
          GPX: GPX,
          IGC: IGC,
          IIIFInfo: IIIFInfo,
          MVT: MVT,
          OWS: OWS,
          Polyline: Polyline,
          TopoJSON: TopoJSON,
          WKB: WKB,
          WMSCapabilities: WMSCapabilities,
          WMSGetFeatureInfo: WMSGetFeatureInfo,
          WMTSCapabilities: WMTSCapabilities,
          filter: nsFormat_filter
      },
      geom: Object.assign({}, nsGeom, {
          Polygon: geom_Polygon
      }),
      interaction: nsInteraction,
      layer: {
          ...nsLayer,
          WebGLVectorTile: WebGLVectorTileLayer,
          MapboxVector: MapboxVectorLayer,
      },
      proj: nsProj,
      source: nsSource,
      sphere: nsSphere,
      style: nsStyle,
      render: {
        toContext: toContext,
        toFeature: toFeature,
      },
      tilegrid: {
          WMTS: WMTSTileGrid
      },
      loadingstrategy: nsLoadingStrategy,
      util: {
          getRequestUrl: getRequestUrl$1,
          applyMapboxStyle: applyStyle
      }
  };
  // dirty solution?
  if (window.ol) {
      window.console.error('"ol" already exists');
  } else {
      window.ol = ol;
  }

  class RawDecoder extends BaseDecoder {
    decodeBlock(buffer) {
      return buffer;
    }
  }

  var raw = {
    __proto__: null,
    default: RawDecoder
  };

  const MIN_BITS = 9;
  const CLEAR_CODE = 256; // clear code
  const EOI_CODE = 257; // end of information
  const MAX_BYTELENGTH = 12;

  function getByte(array, position, length) {
    const d = position % 8;
    const a = Math.floor(position / 8);
    const de = 8 - d;
    const ef = (position + length) - ((a + 1) * 8);
    let fg = (8 * (a + 2)) - (position + length);
    const dg = ((a + 2) * 8) - position;
    fg = Math.max(0, fg);
    if (a >= array.length) {
      console.warn('ran off the end of the buffer before finding EOI_CODE (end on input code)');
      return EOI_CODE;
    }
    let chunk1 = array[a] & ((2 ** (8 - d)) - 1);
    chunk1 <<= (length - de);
    let chunks = chunk1;
    if (a + 1 < array.length) {
      let chunk2 = array[a + 1] >>> fg;
      chunk2 <<= Math.max(0, (length - dg));
      chunks += chunk2;
    }
    if (ef > 8 && a + 2 < array.length) {
      const hi = ((a + 3) * 8) - (position + length);
      const chunk3 = array[a + 2] >>> hi;
      chunks += chunk3;
    }
    return chunks;
  }

  function appendReversed(dest, source) {
    for (let i = source.length - 1; i >= 0; i--) {
      dest.push(source[i]);
    }
    return dest;
  }

  function decompress(input) {
    const dictionaryIndex = new Uint16Array(4093);
    const dictionaryChar = new Uint8Array(4093);
    for (let i = 0; i <= 257; i++) {
      dictionaryIndex[i] = 4096;
      dictionaryChar[i] = i;
    }
    let dictionaryLength = 258;
    let byteLength = MIN_BITS;
    let position = 0;

    function initDictionary() {
      dictionaryLength = 258;
      byteLength = MIN_BITS;
    }
    function getNext(array) {
      const byte = getByte(array, position, byteLength);
      position += byteLength;
      return byte;
    }
    function addToDictionary(i, c) {
      dictionaryChar[dictionaryLength] = c;
      dictionaryIndex[dictionaryLength] = i;
      dictionaryLength++;
      return dictionaryLength - 1;
    }
    function getDictionaryReversed(n) {
      const rev = [];
      for (let i = n; i !== 4096; i = dictionaryIndex[i]) {
        rev.push(dictionaryChar[i]);
      }
      return rev;
    }

    const result = [];
    initDictionary();
    const array = new Uint8Array(input);
    let code = getNext(array);
    let oldCode;
    while (code !== EOI_CODE) {
      if (code === CLEAR_CODE) {
        initDictionary();
        code = getNext(array);
        while (code === CLEAR_CODE) {
          code = getNext(array);
        }

        if (code === EOI_CODE) {
          break;
        } else if (code > CLEAR_CODE) {
          throw new Error(`corrupted code at scanline ${code}`);
        } else {
          const val = getDictionaryReversed(code);
          appendReversed(result, val);
          oldCode = code;
        }
      } else if (code < dictionaryLength) {
        const val = getDictionaryReversed(code);
        appendReversed(result, val);
        addToDictionary(oldCode, val[val.length - 1]);
        oldCode = code;
      } else {
        const oldVal = getDictionaryReversed(oldCode);
        if (!oldVal) {
          throw new Error(`Bogus entry. Not in dictionary, ${oldCode} / ${dictionaryLength}, position: ${position}`);
        }
        appendReversed(result, oldVal);
        result.push(oldVal[oldVal.length - 1]);
        addToDictionary(oldCode, oldVal[oldVal.length - 1]);
        oldCode = code;
      }

      if (dictionaryLength + 1 >= (2 ** byteLength)) {
        if (byteLength === MAX_BYTELENGTH) {
          oldCode = undefined;
        } else {
          byteLength++;
        }
      }
      code = getNext(array);
    }
    return new Uint8Array(result);
  }

  class LZWDecoder extends BaseDecoder {
    decodeBlock(buffer) {
      return decompress(buffer).buffer;
    }
  }

  var lzw = {
    __proto__: null,
    default: LZWDecoder
  };

  /* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
  /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  /*
     Copyright 2011 notmasteryet
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
         http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
  */

  // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
  //   (www.w3.org/Graphics/JPEG/itu-t81.pdf)
  // - The JFIF specification can be found in the JPEG File Interchange Format
  //   (www.w3.org/Graphics/JPEG/jfif3.pdf)
  // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
  //   in PostScript Level 2, Technical Note #5116
  //   (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)

  const dctZigZag = new Int32Array([
    0,
    1, 8,
    16, 9, 2,
    3, 10, 17, 24,
    32, 25, 18, 11, 4,
    5, 12, 19, 26, 33, 40,
    48, 41, 34, 27, 20, 13, 6,
    7, 14, 21, 28, 35, 42, 49, 56,
    57, 50, 43, 36, 29, 22, 15,
    23, 30, 37, 44, 51, 58,
    59, 52, 45, 38, 31,
    39, 46, 53, 60,
    61, 54, 47,
    55, 62,
    63,
  ]);

  const dctCos1 = 4017; // cos(pi/16)
  const dctSin1 = 799; // sin(pi/16)
  const dctCos3 = 3406; // cos(3*pi/16)
  const dctSin3 = 2276; // sin(3*pi/16)
  const dctCos6 = 1567; // cos(6*pi/16)
  const dctSin6 = 3784; // sin(6*pi/16)
  const dctSqrt2 = 5793; // sqrt(2)
  const dctSqrt1d2 = 2896;// sqrt(2) / 2

  function buildHuffmanTable(codeLengths, values) {
    let k = 0;
    const code = [];
    let length = 16;
    while (length > 0 && !codeLengths[length - 1]) {
      --length;
    }
    code.push({ children: [], index: 0 });

    let p = code[0];
    let q;
    for (let i = 0; i < length; i++) {
      for (let j = 0; j < codeLengths[i]; j++) {
        p = code.pop();
        p.children[p.index] = values[k];
        while (p.index > 0) {
          p = code.pop();
        }
        p.index++;
        code.push(p);
        while (code.length <= i) {
          code.push(q = { children: [], index: 0 });
          p.children[p.index] = q.children;
          p = q;
        }
        k++;
      }
      if (i + 1 < length) {
        // p here points to last code
        code.push(q = { children: [], index: 0 });
        p.children[p.index] = q.children;
        p = q;
      }
    }
    return code[0].children;
  }

  function decodeScan(data, initialOffset,
    frame, components, resetInterval,
    spectralStart, spectralEnd,
    successivePrev, successive) {
    const { mcusPerLine, progressive } = frame;

    const startOffset = initialOffset;
    let offset = initialOffset;
    let bitsData = 0;
    let bitsCount = 0;
    function readBit() {
      if (bitsCount > 0) {
        bitsCount--;
        return (bitsData >> bitsCount) & 1;
      }
      bitsData = data[offset++];
      if (bitsData === 0xFF) {
        const nextByte = data[offset++];
        if (nextByte) {
          throw new Error(`unexpected marker: ${((bitsData << 8) | nextByte).toString(16)}`);
        }
        // unstuff 0
      }
      bitsCount = 7;
      return bitsData >>> 7;
    }
    function decodeHuffman(tree) {
      let node = tree;
      let bit;
      while ((bit = readBit()) !== null) { // eslint-disable-line no-cond-assign
        node = node[bit];
        if (typeof node === 'number') {
          return node;
        }
        if (typeof node !== 'object') {
          throw new Error('invalid huffman sequence');
        }
      }
      return null;
    }
    function receive(initialLength) {
      let length = initialLength;
      let n = 0;
      while (length > 0) {
        const bit = readBit();
        if (bit === null) {
          return undefined;
        }
        n = (n << 1) | bit;
        --length;
      }
      return n;
    }
    function receiveAndExtend(length) {
      const n = receive(length);
      if (n >= 1 << (length - 1)) {
        return n;
      }
      return n + (-1 << length) + 1;
    }
    function decodeBaseline(component, zz) {
      const t = decodeHuffman(component.huffmanTableDC);
      const diff = t === 0 ? 0 : receiveAndExtend(t);
      component.pred += diff;
      zz[0] = component.pred;
      let k = 1;
      while (k < 64) {
        const rs = decodeHuffman(component.huffmanTableAC);
        const s = rs & 15;
        const r = rs >> 4;
        if (s === 0) {
          if (r < 15) {
            break;
          }
          k += 16;
        } else {
          k += r;
          const z = dctZigZag[k];
          zz[z] = receiveAndExtend(s);
          k++;
        }
      }
    }
    function decodeDCFirst(component, zz) {
      const t = decodeHuffman(component.huffmanTableDC);
      const diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);
      component.pred += diff;
      zz[0] = component.pred;
    }
    function decodeDCSuccessive(component, zz) {
      zz[0] |= readBit() << successive;
    }
    let eobrun = 0;
    function decodeACFirst(component, zz) {
      if (eobrun > 0) {
        eobrun--;
        return;
      }
      let k = spectralStart;
      const e = spectralEnd;
      while (k <= e) {
        const rs = decodeHuffman(component.huffmanTableAC);
        const s = rs & 15;
        const r = rs >> 4;
        if (s === 0) {
          if (r < 15) {
            eobrun = receive(r) + (1 << r) - 1;
            break;
          }
          k += 16;
        } else {
          k += r;
          const z = dctZigZag[k];
          zz[z] = receiveAndExtend(s) * (1 << successive);
          k++;
        }
      }
    }
    let successiveACState = 0;
    let successiveACNextValue;
    function decodeACSuccessive(component, zz) {
      let k = spectralStart;
      const e = spectralEnd;
      let r = 0;
      while (k <= e) {
        const z = dctZigZag[k];
        const direction = zz[z] < 0 ? -1 : 1;
        switch (successiveACState) {
          case 0: { // initial state
            const rs = decodeHuffman(component.huffmanTableAC);
            const s = rs & 15;
            r = rs >> 4;
            if (s === 0) {
              if (r < 15) {
                eobrun = receive(r) + (1 << r);
                successiveACState = 4;
              } else {
                r = 16;
                successiveACState = 1;
              }
            } else {
              if (s !== 1) {
                throw new Error('invalid ACn encoding');
              }
              successiveACNextValue = receiveAndExtend(s);
              successiveACState = r ? 2 : 3;
            }
            continue; // eslint-disable-line no-continue
          }
          case 1: // skipping r zero items
          case 2:
            if (zz[z]) {
              zz[z] += (readBit() << successive) * direction;
            } else {
              r--;
              if (r === 0) {
                successiveACState = successiveACState === 2 ? 3 : 0;
              }
            }
            break;
          case 3: // set value for a zero item
            if (zz[z]) {
              zz[z] += (readBit() << successive) * direction;
            } else {
              zz[z] = successiveACNextValue << successive;
              successiveACState = 0;
            }
            break;
          case 4: // eob
            if (zz[z]) {
              zz[z] += (readBit() << successive) * direction;
            }
            break;
        }
        k++;
      }
      if (successiveACState === 4) {
        eobrun--;
        if (eobrun === 0) {
          successiveACState = 0;
        }
      }
    }
    function decodeMcu(component, decodeFunction, mcu, row, col) {
      const mcuRow = (mcu / mcusPerLine) | 0;
      const mcuCol = mcu % mcusPerLine;
      const blockRow = (mcuRow * component.v) + row;
      const blockCol = (mcuCol * component.h) + col;
      decodeFunction(component, component.blocks[blockRow][blockCol]);
    }
    function decodeBlock(component, decodeFunction, mcu) {
      const blockRow = (mcu / component.blocksPerLine) | 0;
      const blockCol = mcu % component.blocksPerLine;
      decodeFunction(component, component.blocks[blockRow][blockCol]);
    }

    const componentsLength = components.length;
    let component;
    let i;
    let j;
    let k;
    let n;
    let decodeFn;
    if (progressive) {
      if (spectralStart === 0) {
        decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;
      } else {
        decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
      }
    } else {
      decodeFn = decodeBaseline;
    }

    let mcu = 0;
    let marker;
    let mcuExpected;
    if (componentsLength === 1) {
      mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
    } else {
      mcuExpected = mcusPerLine * frame.mcusPerColumn;
    }

    const usedResetInterval = resetInterval || mcuExpected;

    while (mcu < mcuExpected) {
      // reset interval stuff
      for (i = 0; i < componentsLength; i++) {
        components[i].pred = 0;
      }
      eobrun = 0;

      if (componentsLength === 1) {
        component = components[0];
        for (n = 0; n < usedResetInterval; n++) {
          decodeBlock(component, decodeFn, mcu);
          mcu++;
        }
      } else {
        for (n = 0; n < usedResetInterval; n++) {
          for (i = 0; i < componentsLength; i++) {
            component = components[i];
            const { h, v } = component;
            for (j = 0; j < v; j++) {
              for (k = 0; k < h; k++) {
                decodeMcu(component, decodeFn, mcu, j, k);
              }
            }
          }
          mcu++;

          // If we've reached our expected MCU's, stop decoding
          if (mcu === mcuExpected) {
            break;
          }
        }
      }

      // find marker
      bitsCount = 0;
      marker = (data[offset] << 8) | data[offset + 1];
      if (marker < 0xFF00) {
        throw new Error('marker was not found');
      }

      if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx
        offset += 2;
      } else {
        break;
      }
    }

    return offset - startOffset;
  }

  function buildComponentData(frame, component) {
    const lines = [];
    const { blocksPerLine, blocksPerColumn } = component;
    const samplesPerLine = blocksPerLine << 3;
    const R = new Int32Array(64);
    const r = new Uint8Array(64);

    // A port of poppler's IDCT method which in turn is taken from:
    //   Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
    //   "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
    //   IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
    //   988-991.
    function quantizeAndInverse(zz, dataOut, dataIn) {
      const qt = component.quantizationTable;
      let v0;
      let v1;
      let v2;
      let v3;
      let v4;
      let v5;
      let v6;
      let v7;
      let t;
      const p = dataIn;
      let i;

      // dequant
      for (i = 0; i < 64; i++) {
        p[i] = zz[i] * qt[i];
      }

      // inverse DCT on rows
      for (i = 0; i < 8; ++i) {
        const row = 8 * i;

        // check for all-zero AC coefficients
        if (p[1 + row] === 0 && p[2 + row] === 0 && p[3 + row] === 0
          && p[4 + row] === 0 && p[5 + row] === 0 && p[6 + row] === 0
          && p[7 + row] === 0) {
          t = ((dctSqrt2 * p[0 + row]) + 512) >> 10;
          p[0 + row] = t;
          p[1 + row] = t;
          p[2 + row] = t;
          p[3 + row] = t;
          p[4 + row] = t;
          p[5 + row] = t;
          p[6 + row] = t;
          p[7 + row] = t;
          continue; // eslint-disable-line no-continue
        }

        // stage 4
        v0 = ((dctSqrt2 * p[0 + row]) + 128) >> 8;
        v1 = ((dctSqrt2 * p[4 + row]) + 128) >> 8;
        v2 = p[2 + row];
        v3 = p[6 + row];
        v4 = ((dctSqrt1d2 * (p[1 + row] - p[7 + row])) + 128) >> 8;
        v7 = ((dctSqrt1d2 * (p[1 + row] + p[7 + row])) + 128) >> 8;
        v5 = p[3 + row] << 4;
        v6 = p[5 + row] << 4;

        // stage 3
        t = (v0 - v1 + 1) >> 1;
        v0 = (v0 + v1 + 1) >> 1;
        v1 = t;
        t = ((v2 * dctSin6) + (v3 * dctCos6) + 128) >> 8;
        v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 128) >> 8;
        v3 = t;
        t = (v4 - v6 + 1) >> 1;
        v4 = (v4 + v6 + 1) >> 1;
        v6 = t;
        t = (v7 + v5 + 1) >> 1;
        v5 = (v7 - v5 + 1) >> 1;
        v7 = t;

        // stage 2
        t = (v0 - v3 + 1) >> 1;
        v0 = (v0 + v3 + 1) >> 1;
        v3 = t;
        t = (v1 - v2 + 1) >> 1;
        v1 = (v1 + v2 + 1) >> 1;
        v2 = t;
        t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
        v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
        v7 = t;
        t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
        v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
        v6 = t;

        // stage 1
        p[0 + row] = v0 + v7;
        p[7 + row] = v0 - v7;
        p[1 + row] = v1 + v6;
        p[6 + row] = v1 - v6;
        p[2 + row] = v2 + v5;
        p[5 + row] = v2 - v5;
        p[3 + row] = v3 + v4;
        p[4 + row] = v3 - v4;
      }

      // inverse DCT on columns
      for (i = 0; i < 8; ++i) {
        const col = i;

        // check for all-zero AC coefficients
        if (p[(1 * 8) + col] === 0 && p[(2 * 8) + col] === 0 && p[(3 * 8) + col] === 0
          && p[(4 * 8) + col] === 0 && p[(5 * 8) + col] === 0 && p[(6 * 8) + col] === 0
          && p[(7 * 8) + col] === 0) {
          t = ((dctSqrt2 * dataIn[i + 0]) + 8192) >> 14;
          p[(0 * 8) + col] = t;
          p[(1 * 8) + col] = t;
          p[(2 * 8) + col] = t;
          p[(3 * 8) + col] = t;
          p[(4 * 8) + col] = t;
          p[(5 * 8) + col] = t;
          p[(6 * 8) + col] = t;
          p[(7 * 8) + col] = t;
          continue; // eslint-disable-line no-continue
        }

        // stage 4
        v0 = ((dctSqrt2 * p[(0 * 8) + col]) + 2048) >> 12;
        v1 = ((dctSqrt2 * p[(4 * 8) + col]) + 2048) >> 12;
        v2 = p[(2 * 8) + col];
        v3 = p[(6 * 8) + col];
        v4 = ((dctSqrt1d2 * (p[(1 * 8) + col] - p[(7 * 8) + col])) + 2048) >> 12;
        v7 = ((dctSqrt1d2 * (p[(1 * 8) + col] + p[(7 * 8) + col])) + 2048) >> 12;
        v5 = p[(3 * 8) + col];
        v6 = p[(5 * 8) + col];

        // stage 3
        t = (v0 - v1 + 1) >> 1;
        v0 = (v0 + v1 + 1) >> 1;
        v1 = t;
        t = ((v2 * dctSin6) + (v3 * dctCos6) + 2048) >> 12;
        v2 = ((v2 * dctCos6) - (v3 * dctSin6) + 2048) >> 12;
        v3 = t;
        t = (v4 - v6 + 1) >> 1;
        v4 = (v4 + v6 + 1) >> 1;
        v6 = t;
        t = (v7 + v5 + 1) >> 1;
        v5 = (v7 - v5 + 1) >> 1;
        v7 = t;

        // stage 2
        t = (v0 - v3 + 1) >> 1;
        v0 = (v0 + v3 + 1) >> 1;
        v3 = t;
        t = (v1 - v2 + 1) >> 1;
        v1 = (v1 + v2 + 1) >> 1;
        v2 = t;
        t = ((v4 * dctSin3) + (v7 * dctCos3) + 2048) >> 12;
        v4 = ((v4 * dctCos3) - (v7 * dctSin3) + 2048) >> 12;
        v7 = t;
        t = ((v5 * dctSin1) + (v6 * dctCos1) + 2048) >> 12;
        v5 = ((v5 * dctCos1) - (v6 * dctSin1) + 2048) >> 12;
        v6 = t;

        // stage 1
        p[(0 * 8) + col] = v0 + v7;
        p[(7 * 8) + col] = v0 - v7;
        p[(1 * 8) + col] = v1 + v6;
        p[(6 * 8) + col] = v1 - v6;
        p[(2 * 8) + col] = v2 + v5;
        p[(5 * 8) + col] = v2 - v5;
        p[(3 * 8) + col] = v3 + v4;
        p[(4 * 8) + col] = v3 - v4;
      }

      // convert to 8-bit integers
      for (i = 0; i < 64; ++i) {
        const sample = 128 + ((p[i] + 8) >> 4);
        if (sample < 0) {
          dataOut[i] = 0;
        } else if (sample > 0XFF) {
          dataOut[i] = 0xFF;
        } else {
          dataOut[i] = sample;
        }
      }
    }

    for (let blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
      const scanLine = blockRow << 3;
      for (let i = 0; i < 8; i++) {
        lines.push(new Uint8Array(samplesPerLine));
      }
      for (let blockCol = 0; blockCol < blocksPerLine; blockCol++) {
        quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);

        let offset = 0;
        const sample = blockCol << 3;
        for (let j = 0; j < 8; j++) {
          const line = lines[scanLine + j];
          for (let i = 0; i < 8; i++) {
            line[sample + i] = r[offset++];
          }
        }
      }
    }
    return lines;
  }

  class JpegStreamReader {
    constructor() {
      this.jfif = null;
      this.adobe = null;

      this.quantizationTables = [];
      this.huffmanTablesAC = [];
      this.huffmanTablesDC = [];
      this.resetFrames();
    }

    resetFrames() {
      this.frames = [];
    }

    parse(data) {
      let offset = 0;
      // const { length } = data;
      function readUint16() {
        const value = (data[offset] << 8) | data[offset + 1];
        offset += 2;
        return value;
      }
      function readDataBlock() {
        const length = readUint16();
        const array = data.subarray(offset, offset + length - 2);
        offset += array.length;
        return array;
      }
      function prepareComponents(frame) {
        let maxH = 0;
        let maxV = 0;
        let component;
        let componentId;
        for (componentId in frame.components) {
          if (frame.components.hasOwnProperty(componentId)) {
            component = frame.components[componentId];
            if (maxH < component.h) {
              maxH = component.h;
            }
            if (maxV < component.v) {
              maxV = component.v;
            }
          }
        }
        const mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
        const mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
        for (componentId in frame.components) {
          if (frame.components.hasOwnProperty(componentId)) {
            component = frame.components[componentId];
            const blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
            const blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
            const blocksPerLineForMcu = mcusPerLine * component.h;
            const blocksPerColumnForMcu = mcusPerColumn * component.v;
            const blocks = [];
            for (let i = 0; i < blocksPerColumnForMcu; i++) {
              const row = [];
              for (let j = 0; j < blocksPerLineForMcu; j++) {
                row.push(new Int32Array(64));
              }
              blocks.push(row);
            }
            component.blocksPerLine = blocksPerLine;
            component.blocksPerColumn = blocksPerColumn;
            component.blocks = blocks;
          }
        }
        frame.maxH = maxH;
        frame.maxV = maxV;
        frame.mcusPerLine = mcusPerLine;
        frame.mcusPerColumn = mcusPerColumn;
      }

      let fileMarker = readUint16();
      if (fileMarker !== 0xFFD8) { // SOI (Start of Image)
        throw new Error('SOI not found');
      }

      fileMarker = readUint16();
      while (fileMarker !== 0xFFD9) { // EOI (End of image)
        switch (fileMarker) {
          case 0xFF00: break;
          case 0xFFE0: // APP0 (Application Specific)
          case 0xFFE1: // APP1
          case 0xFFE2: // APP2
          case 0xFFE3: // APP3
          case 0xFFE4: // APP4
          case 0xFFE5: // APP5
          case 0xFFE6: // APP6
          case 0xFFE7: // APP7
          case 0xFFE8: // APP8
          case 0xFFE9: // APP9
          case 0xFFEA: // APP10
          case 0xFFEB: // APP11
          case 0xFFEC: // APP12
          case 0xFFED: // APP13
          case 0xFFEE: // APP14
          case 0xFFEF: // APP15
          case 0xFFFE: { // COM (Comment)
            const appData = readDataBlock();

            if (fileMarker === 0xFFE0) {
              if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49
                && appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\x00'
                this.jfif = {
                  version: { major: appData[5], minor: appData[6] },
                  densityUnits: appData[7],
                  xDensity: (appData[8] << 8) | appData[9],
                  yDensity: (appData[10] << 8) | appData[11],
                  thumbWidth: appData[12],
                  thumbHeight: appData[13],
                  thumbData: appData.subarray(14, 14 + (3 * appData[12] * appData[13])),
                };
              }
            }
            // TODO APP1 - Exif
            if (fileMarker === 0xFFEE) {
              if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F
                && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\x00'
                this.adobe = {
                  version: appData[6],
                  flags0: (appData[7] << 8) | appData[8],
                  flags1: (appData[9] << 8) | appData[10],
                  transformCode: appData[11],
                };
              }
            }
            break;
          }

          case 0xFFDB: { // DQT (Define Quantization Tables)
            const quantizationTablesLength = readUint16();
            const quantizationTablesEnd = quantizationTablesLength + offset - 2;
            while (offset < quantizationTablesEnd) {
              const quantizationTableSpec = data[offset++];
              const tableData = new Int32Array(64);
              if ((quantizationTableSpec >> 4) === 0) { // 8 bit values
                for (let j = 0; j < 64; j++) {
                  const z = dctZigZag[j];
                  tableData[z] = data[offset++];
                }
              } else if ((quantizationTableSpec >> 4) === 1) { // 16 bit
                for (let j = 0; j < 64; j++) {
                  const z = dctZigZag[j];
                  tableData[z] = readUint16();
                }
              } else {
                throw new Error('DQT: invalid table spec');
              }
              this.quantizationTables[quantizationTableSpec & 15] = tableData;
            }
            break;
          }

          case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
          case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
          case 0xFFC2: { // SOF2 (Start of Frame, Progressive DCT)
            readUint16(); // skip data length
            const frame = {
              extended: (fileMarker === 0xFFC1),
              progressive: (fileMarker === 0xFFC2),
              precision: data[offset++],
              scanLines: readUint16(),
              samplesPerLine: readUint16(),
              components: {},
              componentsOrder: [],
            };

            const componentsCount = data[offset++];
            let componentId;
            // let maxH = 0;
            // let maxV = 0;
            for (let i = 0; i < componentsCount; i++) {
              componentId = data[offset];
              const h = data[offset + 1] >> 4;
              const v = data[offset + 1] & 15;
              const qId = data[offset + 2];
              frame.componentsOrder.push(componentId);
              frame.components[componentId] = {
                h,
                v,
                quantizationIdx: qId,
              };
              offset += 3;
            }
            prepareComponents(frame);
            this.frames.push(frame);
            break;
          }

          case 0xFFC4: { // DHT (Define Huffman Tables)
            const huffmanLength = readUint16();
            for (let i = 2; i < huffmanLength;) {
              const huffmanTableSpec = data[offset++];
              const codeLengths = new Uint8Array(16);
              let codeLengthSum = 0;
              for (let j = 0; j < 16; j++, offset++) {
                codeLengths[j] = data[offset];
                codeLengthSum += codeLengths[j];
              }
              const huffmanValues = new Uint8Array(codeLengthSum);
              for (let j = 0; j < codeLengthSum; j++, offset++) {
                huffmanValues[j] = data[offset];
              }
              i += 17 + codeLengthSum;

              if ((huffmanTableSpec >> 4) === 0) {
                this.huffmanTablesDC[huffmanTableSpec & 15] = buildHuffmanTable(
                  codeLengths, huffmanValues,
                );
              } else {
                this.huffmanTablesAC[huffmanTableSpec & 15] = buildHuffmanTable(
                  codeLengths, huffmanValues,
                );
              }
            }
            break;
          }

          case 0xFFDD: // DRI (Define Restart Interval)
            readUint16(); // skip data length
            this.resetInterval = readUint16();
            break;

          case 0xFFDA: { // SOS (Start of Scan)
            readUint16(); // skip length
            const selectorsCount = data[offset++];
            const components = [];
            const frame = this.frames[0];
            for (let i = 0; i < selectorsCount; i++) {
              const component = frame.components[data[offset++]];
              const tableSpec = data[offset++];
              component.huffmanTableDC = this.huffmanTablesDC[tableSpec >> 4];
              component.huffmanTableAC = this.huffmanTablesAC[tableSpec & 15];
              components.push(component);
            }
            const spectralStart = data[offset++];
            const spectralEnd = data[offset++];
            const successiveApproximation = data[offset++];
            const processed = decodeScan(data, offset,
              frame, components, this.resetInterval,
              spectralStart, spectralEnd,
              successiveApproximation >> 4, successiveApproximation & 15);
            offset += processed;
            break;
          }

          case 0xFFFF: // Fill bytes
            if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.
              offset--;
            }
            break;

          default:
            if (data[offset - 3] === 0xFF
              && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
              // could be incorrect encoding -- last 0xFF byte of the previous
              // block was eaten by the encoder
              offset -= 3;
              break;
            }
            throw new Error(`unknown JPEG marker ${fileMarker.toString(16)}`);
        }
        fileMarker = readUint16();
      }
    }

    getResult() {
      const { frames } = this;
      if (this.frames.length === 0) {
        throw new Error('no frames were decoded');
      } else if (this.frames.length > 1) {
        console.warn('more than one frame is not supported');
      }

      // set each frame's components quantization table
      for (let i = 0; i < this.frames.length; i++) {
        const cp = this.frames[i].components;
        for (const j of Object.keys(cp)) {
          cp[j].quantizationTable = this.quantizationTables[cp[j].quantizationIdx];
          delete cp[j].quantizationIdx;
        }
      }

      const frame = frames[0];
      const { components, componentsOrder } = frame;
      const outComponents = [];
      const width = frame.samplesPerLine;
      const height = frame.scanLines;

      for (let i = 0; i < componentsOrder.length; i++) {
        const component = components[componentsOrder[i]];
        outComponents.push({
          lines: buildComponentData(frame, component),
          scaleX: component.h / frame.maxH,
          scaleY: component.v / frame.maxV,
        });
      }

      const out = new Uint8Array(width * height * outComponents.length);
      let oi = 0;
      for (let y = 0; y < height; ++y) {
        for (let x = 0; x < width; ++x) {
          for (let i = 0; i < outComponents.length; ++i) {
            const component = outComponents[i];
            out[oi] = component.lines[0 | y * component.scaleY][0 | x * component.scaleX];
            ++oi;
          }
        }
      }
      return out;
    }
  }

  class JpegDecoder extends BaseDecoder {
    constructor(fileDirectory) {
      super();
      this.reader = new JpegStreamReader();
      if (fileDirectory.JPEGTables) {
        this.reader.parse(fileDirectory.JPEGTables);
      }
    }

    decodeBlock(buffer) {
      this.reader.resetFrames();
      this.reader.parse(new Uint8Array(buffer));
      return this.reader.getResult().buffer;
    }
  }

  var jpeg = {
    __proto__: null,
    default: JpegDecoder
  };

  /*============================================================================*/


  function zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  /* The three kinds of block type */

  const MIN_MATCH$1    = 3;
  const MAX_MATCH$1    = 258;
  /* The minimum and maximum match lengths */

  // From deflate.h
  /* ===========================================================================
   * Internal compression state.
   */

  const LENGTH_CODES$1  = 29;
  /* number of length codes, not counting the special END_BLOCK code */

  const LITERALS$1      = 256;
  /* number of literal bytes 0..255 */

  const L_CODES$1       = LITERALS$1 + 1 + LENGTH_CODES$1;
  /* number of Literal or Length codes, including the END_BLOCK code */

  const D_CODES$1       = 30;
  /* eslint-enable comma-spacing,array-bracket-spacing */

  /* The lengths of the bit length codes are sent in order of decreasing
   * probability, to avoid transmitting the lengths for unused bit length codes.
   */

  /* ===========================================================================
   * Local data. These are initialized only once.
   */

  // We pre-fill arrays with 0 to avoid uninitialized gaps

  const DIST_CODE_LEN = 512; /* see definition of array dist_code below */

  // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  const static_ltree  = new Array((L_CODES$1 + 2) * 2);
  zero$1(static_ltree);
  /* The static literal tree. Since the bit lengths are imposed, there is no
   * need for the L_CODES extra codes used during heap construction. However
   * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
   * below).
   */

  const static_dtree  = new Array(D_CODES$1 * 2);
  zero$1(static_dtree);
  /* The static distance tree. (Actually a trivial tree since all codes use
   * 5 bits.)
   */

  const _dist_code    = new Array(DIST_CODE_LEN);
  zero$1(_dist_code);
  /* Distance codes. The first 256 values correspond to the distances
   * 3 .. 258, the last 256 values correspond to the top 8 bits of
   * the 15 bit distances.
   */

  const _length_code  = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);
  zero$1(_length_code);
  /* length code for each normalized match length (0 == MIN_MATCH) */

  const base_length   = new Array(LENGTH_CODES$1);
  zero$1(base_length);
  /* First normalized length for each code (0 = MIN_MATCH) */

  const base_dist     = new Array(D_CODES$1);
  zero$1(base_dist);

  // Note: adler32 takes 12% for level 0 and 2% for level 6.
  // It isn't worth it to make additional optimizations as in original.
  // Small size is preferable.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  const adler32 = (adler, buf, len, pos) => {
    let s1 = (adler & 0xffff) |0,
        s2 = ((adler >>> 16) & 0xffff) |0,
        n = 0;

    while (len !== 0) {
      // Set limit ~ twice less than 5552, to keep
      // s2 in 31-bits, because we force signed ints.
      // in other case %= will fail.
      n = len > 2000 ? 2000 : len;
      len -= n;

      do {
        s1 = (s1 + buf[pos++]) |0;
        s2 = (s2 + s1) |0;
      } while (--n);

      s1 %= 65521;
      s2 %= 65521;
    }

    return (s1 | (s2 << 16)) |0;
  };


  var adler32_1 = adler32;

  // Note: we can't get significant speed boost here.
  // So write code to minimize size - no pregenerated tables
  // and array tools dependencies.

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // Use ordinary array, since untyped makes no boost here
  const makeTable = () => {
    let c, table = [];

    for (var n = 0; n < 256; n++) {
      c = n;
      for (var k = 0; k < 8; k++) {
        c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
      }
      table[n] = c;
    }

    return table;
  };

  // Create table on load. Just 255 signed longs. Not a problem.
  const crcTable = new Uint32Array(makeTable());


  const crc32 = (crc, buf, len, pos) => {
    const t = crcTable;
    const end = pos + len;

    crc ^= -1;

    for (let i = pos; i < end; i++) {
      crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
    }

    return (crc ^ (-1)); // >>> 0;
  };


  var crc32_1 = crc32;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var messages = {
    2:      'need dictionary',     /* Z_NEED_DICT       2  */
    1:      'stream end',          /* Z_STREAM_END      1  */
    0:      '',                    /* Z_OK              0  */
    '-1':   'file error',          /* Z_ERRNO         (-1) */
    '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
    '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
    '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
    '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
    '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  var constants$2 = {

    /* Allowed flush values; see deflate() and inflate() below for details */
    Z_NO_FLUSH:         0,
    Z_FINISH:           4,
    Z_BLOCK:            5,
    Z_TREES:            6,

    /* Return codes for the compression/decompression functions. Negative values
    * are errors, positive values are used for special but normal events.
    */
    Z_OK:               0,
    Z_STREAM_END:       1,
    Z_NEED_DICT:        2,
    Z_STREAM_ERROR:    -2,
    Z_DATA_ERROR:      -3,
    Z_MEM_ERROR:       -4,
    Z_BUF_ERROR:       -5,
    /* The deflate compression method */
    Z_DEFLATED:               8
    //Z_NULL:                 null // Use -1 or null inline, depending on var type
  };

  const _has = (obj, key) => {
    return Object.prototype.hasOwnProperty.call(obj, key);
  };

  var assign = function (obj /*from1, from2, from3, ...*/) {
    const sources = Array.prototype.slice.call(arguments, 1);
    while (sources.length) {
      const source = sources.shift();
      if (!source) { continue; }

      if (typeof source !== 'object') {
        throw new TypeError(source + 'must be non-object');
      }

      for (const p in source) {
        if (_has(source, p)) {
          obj[p] = source[p];
        }
      }
    }

    return obj;
  };


  // Join array of chunks to single array.
  var flattenChunks = (chunks) => {
    // calculate data length
    let len = 0;

    for (let i = 0, l = chunks.length; i < l; i++) {
      len += chunks[i].length;
    }

    // join chunks
    const result = new Uint8Array(len);

    for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {
      let chunk = chunks[i];
      result.set(chunk, pos);
      pos += chunk.length;
    }

    return result;
  };

  var common = {
  	assign: assign,
  	flattenChunks: flattenChunks
  };

  // String encode/decode helpers


  // Quick check if we can use fast array to bin string conversion
  //
  // - apply(Array) can fail on Android 2.2
  // - apply(Uint8Array) can fail on iOS 5.1 Safari
  //
  let STR_APPLY_UIA_OK = true;

  try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }


  // Table with utf8 lengths (calculated by first byte of sequence)
  // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  // because max possible codepoint is 0x10ffff
  const _utf8len = new Uint8Array(256);
  for (let q = 0; q < 256; q++) {
    _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  }
  _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start


  // convert string to array (typed, when possible)
  var string2buf = (str) => {
    if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {
      return new TextEncoder().encode(str);
    }

    let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;

    // count binary size
    for (m_pos = 0; m_pos < str_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
    }

    // allocate buffer
    buf = new Uint8Array(buf_len);

    // convert
    for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
      c = str.charCodeAt(m_pos);
      if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
        c2 = str.charCodeAt(m_pos + 1);
        if ((c2 & 0xfc00) === 0xdc00) {
          c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
          m_pos++;
        }
      }
      if (c < 0x80) {
        /* one byte */
        buf[i++] = c;
      } else if (c < 0x800) {
        /* two bytes */
        buf[i++] = 0xC0 | (c >>> 6);
        buf[i++] = 0x80 | (c & 0x3f);
      } else if (c < 0x10000) {
        /* three bytes */
        buf[i++] = 0xE0 | (c >>> 12);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      } else {
        /* four bytes */
        buf[i++] = 0xf0 | (c >>> 18);
        buf[i++] = 0x80 | (c >>> 12 & 0x3f);
        buf[i++] = 0x80 | (c >>> 6 & 0x3f);
        buf[i++] = 0x80 | (c & 0x3f);
      }
    }

    return buf;
  };

  // Helper
  const buf2binstring = (buf, len) => {
    // On Chrome, the arguments in a function call that are allowed is `65534`.
    // If the length of the buffer is smaller than that, we can use this optimization,
    // otherwise we will take a slower path.
    if (len < 65534) {
      if (buf.subarray && STR_APPLY_UIA_OK) {
        return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));
      }
    }

    let result = '';
    for (let i = 0; i < len; i++) {
      result += String.fromCharCode(buf[i]);
    }
    return result;
  };


  // convert array to string
  var buf2string = (buf, max) => {
    const len = max || buf.length;

    if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {
      return new TextDecoder().decode(buf.subarray(0, max));
    }

    let i, out;

    // Reserve max possible length (2 words per char)
    // NB: by unknown reasons, Array is significantly faster for
    //     String.fromCharCode.apply than Uint16Array.
    const utf16buf = new Array(len * 2);

    for (out = 0, i = 0; i < len;) {
      let c = buf[i++];
      // quick process ascii
      if (c < 0x80) { utf16buf[out++] = c; continue; }

      let c_len = _utf8len[c];
      // skip 5 & 6 byte codes
      if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }

      // apply mask on first byte
      c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
      // join the rest
      while (c_len > 1 && i < len) {
        c = (c << 6) | (buf[i++] & 0x3f);
        c_len--;
      }

      // terminated by end of string?
      if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }

      if (c < 0x10000) {
        utf16buf[out++] = c;
      } else {
        c -= 0x10000;
        utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
        utf16buf[out++] = 0xdc00 | (c & 0x3ff);
      }
    }

    return buf2binstring(utf16buf, out);
  };


  // Calculate max possible position in utf8 buffer,
  // that will not break sequence. If that's not possible
  // - (very small limits) return max size as is.
  //
  // buf[] - utf8 bytes array
  // max   - length limit (mandatory);
  var utf8border = (buf, max) => {

    max = max || buf.length;
    if (max > buf.length) { max = buf.length; }

    // go back from last position, until start of sequence found
    let pos = max - 1;
    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }

    // Very small and broken sequence,
    // return max, because we should return something anyway.
    if (pos < 0) { return max; }

    // If we came to start of buffer - that means buffer is too small,
    // return max too.
    if (pos === 0) { return max; }

    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  };

  var strings = {
  	string2buf: string2buf,
  	buf2string: buf2string,
  	utf8border: utf8border
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function ZStream() {
    /* next input byte */
    this.input = null; // JS specific, because we have no pointers
    this.next_in = 0;
    /* number of bytes available at input */
    this.avail_in = 0;
    /* total number of input bytes read so far */
    this.total_in = 0;
    /* next output byte should be put there */
    this.output = null; // JS specific, because we have no pointers
    this.next_out = 0;
    /* remaining free space at output */
    this.avail_out = 0;
    /* total number of bytes output so far */
    this.total_out = 0;
    /* last error message, NULL if no error */
    this.msg = ''/*Z_NULL*/;
    /* not visible by applications */
    this.state = null;
    /* best guess about the data type: binary or text */
    this.data_type = 2/*Z_UNKNOWN*/;
    /* adler32 value of the uncompressed data */
    this.adler = 0;
  }

  var zstream = ZStream;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  // See state defs from inflate.js
  const BAD$1 = 16209;       /* got a data error -- remain here until reset */
  const TYPE$1 = 16191;      /* i: waiting for type bits, including last-flag bit */

  /*
     Decode literal, length, and distance codes and write out the resulting
     literal and match bytes until either not enough input or output is
     available, an end-of-block is encountered, or a data error is encountered.
     When large enough input and output buffers are supplied to inflate(), for
     example, a 16K input buffer and a 64K output buffer, more than 95% of the
     inflate execution time is spent in this routine.

     Entry assumptions:

          state.mode === LEN
          strm.avail_in >= 6
          strm.avail_out >= 258
          start >= strm.avail_out
          state.bits < 8

     On return, state.mode is one of:

          LEN -- ran out of enough output space or enough available input
          TYPE -- reached end of block code, inflate() to interpret next block
          BAD -- error in block data

     Notes:

      - The maximum input bits used by a length/distance pair is 15 bits for the
        length code, 5 bits for the length extra, 15 bits for the distance code,
        and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
        Therefore if strm.avail_in >= 6, then there is enough input to avoid
        checking for available input while decoding.

      - The maximum bytes that a single length/distance pair can output is 258
        bytes, which is the maximum length that can be coded.  inflate_fast()
        requires strm.avail_out >= 258 for each loop to avoid checking for
        output space.
   */
  var inffast = function inflate_fast(strm, start) {
    let _in;                    /* local strm.input */
    let last;                   /* have enough input while in < last */
    let _out;                   /* local strm.output */
    let beg;                    /* inflate()'s initial strm.output */
    let end;                    /* while out < end, enough space available */
  //#ifdef INFLATE_STRICT
    let dmax;                   /* maximum distance from zlib header */
  //#endif
    let wsize;                  /* window size or zero if not using window */
    let whave;                  /* valid bytes in the window */
    let wnext;                  /* window write index */
    // Use `s_window` instead `window`, avoid conflict with instrumentation tools
    let s_window;               /* allocated sliding window, if wsize != 0 */
    let hold;                   /* local strm.hold */
    let bits;                   /* local strm.bits */
    let lcode;                  /* local strm.lencode */
    let dcode;                  /* local strm.distcode */
    let lmask;                  /* mask for first level of length codes */
    let dmask;                  /* mask for first level of distance codes */
    let here;                   /* retrieved table entry */
    let op;                     /* code bits, operation, extra bits, or */
                                /*  window position, window bytes to copy */
    let len;                    /* match length, unused bytes */
    let dist;                   /* match distance */
    let from;                   /* where to copy match from */
    let from_source;


    let input, output; // JS specific, because we have no pointers

    /* copy state to local variables */
    const state = strm.state;
    //here = state.here;
    _in = strm.next_in;
    input = strm.input;
    last = _in + (strm.avail_in - 5);
    _out = strm.next_out;
    output = strm.output;
    beg = _out - (start - strm.avail_out);
    end = _out + (strm.avail_out - 257);
  //#ifdef INFLATE_STRICT
    dmax = state.dmax;
  //#endif
    wsize = state.wsize;
    whave = state.whave;
    wnext = state.wnext;
    s_window = state.window;
    hold = state.hold;
    bits = state.bits;
    lcode = state.lencode;
    dcode = state.distcode;
    lmask = (1 << state.lenbits) - 1;
    dmask = (1 << state.distbits) - 1;


    /* decode literals and length/distances until end-of-block or not enough
       input data or output space */

    top:
    do {
      if (bits < 15) {
        hold += input[_in++] << bits;
        bits += 8;
        hold += input[_in++] << bits;
        bits += 8;
      }

      here = lcode[hold & lmask];

      dolen:
      for (;;) { // Goto emulation
        op = here >>> 24/*here.bits*/;
        hold >>>= op;
        bits -= op;
        op = (here >>> 16) & 0xff/*here.op*/;
        if (op === 0) {                          /* literal */
          //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
          //        "inflate:         literal '%c'\n" :
          //        "inflate:         literal 0x%02x\n", here.val));
          output[_out++] = here & 0xffff/*here.val*/;
        }
        else if (op & 16) {                     /* length base */
          len = here & 0xffff/*here.val*/;
          op &= 15;                           /* number of extra bits */
          if (op) {
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
            }
            len += hold & ((1 << op) - 1);
            hold >>>= op;
            bits -= op;
          }
          //Tracevv((stderr, "inflate:         length %u\n", len));
          if (bits < 15) {
            hold += input[_in++] << bits;
            bits += 8;
            hold += input[_in++] << bits;
            bits += 8;
          }
          here = dcode[hold & dmask];

          dodist:
          for (;;) { // goto emulation
            op = here >>> 24/*here.bits*/;
            hold >>>= op;
            bits -= op;
            op = (here >>> 16) & 0xff/*here.op*/;

            if (op & 16) {                      /* distance base */
              dist = here & 0xffff/*here.val*/;
              op &= 15;                       /* number of extra bits */
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
                if (bits < op) {
                  hold += input[_in++] << bits;
                  bits += 8;
                }
              }
              dist += hold & ((1 << op) - 1);
  //#ifdef INFLATE_STRICT
              if (dist > dmax) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD$1;
                break top;
              }
  //#endif
              hold >>>= op;
              bits -= op;
              //Tracevv((stderr, "inflate:         distance %u\n", dist));
              op = _out - beg;                /* max distance in output */
              if (dist > op) {                /* see if copy from window */
                op = dist - op;               /* distance back in window */
                if (op > whave) {
                  if (state.sane) {
                    strm.msg = 'invalid distance too far back';
                    state.mode = BAD$1;
                    break top;
                  }

  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //                if (len <= op - whave) {
  //                  do {
  //                    output[_out++] = 0;
  //                  } while (--len);
  //                  continue top;
  //                }
  //                len -= op - whave;
  //                do {
  //                  output[_out++] = 0;
  //                } while (--op > whave);
  //                if (op === 0) {
  //                  from = _out - dist;
  //                  do {
  //                    output[_out++] = output[from++];
  //                  } while (--len);
  //                  continue top;
  //                }
  //#endif
                }
                from = 0; // window index
                from_source = s_window;
                if (wnext === 0) {           /* very common case */
                  from += wsize - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                else if (wnext < op) {      /* wrap around window */
                  from += wsize + wnext - op;
                  op -= wnext;
                  if (op < len) {         /* some from end of window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = 0;
                    if (wnext < len) {  /* some from start of window */
                      op = wnext;
                      len -= op;
                      do {
                        output[_out++] = s_window[from++];
                      } while (--op);
                      from = _out - dist;      /* rest from output */
                      from_source = output;
                    }
                  }
                }
                else {                      /* contiguous in window */
                  from += wnext - op;
                  if (op < len) {         /* some from window */
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;  /* rest from output */
                    from_source = output;
                  }
                }
                while (len > 2) {
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  output[_out++] = from_source[from++];
                  len -= 3;
                }
                if (len) {
                  output[_out++] = from_source[from++];
                  if (len > 1) {
                    output[_out++] = from_source[from++];
                  }
                }
              }
              else {
                from = _out - dist;          /* copy direct from output */
                do {                        /* minimum length is three */
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  output[_out++] = output[from++];
                  len -= 3;
                } while (len > 2);
                if (len) {
                  output[_out++] = output[from++];
                  if (len > 1) {
                    output[_out++] = output[from++];
                  }
                }
              }
            }
            else if ((op & 64) === 0) {          /* 2nd level distance code */
              here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
              continue dodist;
            }
            else {
              strm.msg = 'invalid distance code';
              state.mode = BAD$1;
              break top;
            }

            break; // need to emulate goto via "continue"
          }
        }
        else if ((op & 64) === 0) {              /* 2nd level length code */
          here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
          continue dolen;
        }
        else if (op & 32) {                     /* end-of-block */
          //Tracevv((stderr, "inflate:         end of block\n"));
          state.mode = TYPE$1;
          break top;
        }
        else {
          strm.msg = 'invalid literal/length code';
          state.mode = BAD$1;
          break top;
        }

        break; // need to emulate goto via "continue"
      }
    } while (_in < last && _out < end);

    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
    len = bits >> 3;
    _in -= len;
    bits -= len << 3;
    hold &= (1 << bits) - 1;

    /* update state and return */
    strm.next_in = _in;
    strm.next_out = _out;
    strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
    strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
    state.hold = hold;
    state.bits = bits;
    return;
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  const MAXBITS = 15;
  const ENOUGH_LENS$1 = 852;
  const ENOUGH_DISTS$1 = 592;
  //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

  const CODES$1 = 0;
  const LENS$1 = 1;
  const DISTS$1 = 2;

  const lbase = new Uint16Array([ /* Length codes 257..285 base */
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  ]);

  const lext = new Uint8Array([ /* Length codes 257..285 extra */
    16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
    19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  ]);

  const dbase = new Uint16Array([ /* Distance codes 0..29 base */
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    8193, 12289, 16385, 24577, 0, 0
  ]);

  const dext = new Uint8Array([ /* Distance codes 0..29 extra */
    16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
    23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
    28, 28, 29, 29, 64, 64
  ]);

  const inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>
  {
    const bits = opts.bits;
        //here = opts.here; /* table entry for duplication */

    let len = 0;               /* a code's length in bits */
    let sym = 0;               /* index of code symbols */
    let min = 0, max = 0;          /* minimum and maximum code lengths */
    let root = 0;              /* number of index bits for root table */
    let curr = 0;              /* number of index bits for current table */
    let drop = 0;              /* code bits to drop for sub-table */
    let left = 0;                   /* number of prefix codes available */
    let used = 0;              /* code entries in table used */
    let huff = 0;              /* Huffman code */
    let incr;              /* for incrementing code, index */
    let fill;              /* index for replicating entries */
    let low;               /* low bits for current root entry */
    let mask;              /* mask for low root bits */
    let next;             /* next available space in table */
    let base = null;     /* base value table to use */
  //  let shoextra;    /* extra bits table to use */
    let match;                  /* use base and extra for symbol >= match */
    const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
    const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
    let extra = null;

    let here_bits, here_op, here_val;

    /*
     Process a set of code lengths to create a canonical Huffman code.  The
     code lengths are lens[0..codes-1].  Each length corresponds to the
     symbols 0..codes-1.  The Huffman code is generated by first sorting the
     symbols by length from short to long, and retaining the symbol order
     for codes with equal lengths.  Then the code starts with all zero bits
     for the first code of the shortest length, and the codes are integer
     increments for the same length, and zeros are appended as the length
     increases.  For the deflate format, these bits are stored backwards
     from their more natural integer increment ordering, and so when the
     decoding tables are built in the large loop below, the integer codes
     are incremented backwards.

     This routine assumes, but does not check, that all of the entries in
     lens[] are in the range 0..MAXBITS.  The caller must assure this.
     1..MAXBITS is interpreted as that code length.  zero means that that
     symbol does not occur in this code.

     The codes are sorted by computing a count of codes for each length,
     creating from that a table of starting indices for each length in the
     sorted table, and then entering the symbols in order in the sorted
     table.  The sorted table is work[], with that space being provided by
     the caller.

     The length counts are used for other purposes as well, i.e. finding
     the minimum and maximum length codes, determining if there are any
     codes at all, checking for a valid set of lengths, and looking ahead
     at length counts to determine sub-table sizes when building the
     decoding tables.
     */

    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
    for (len = 0; len <= MAXBITS; len++) {
      count[len] = 0;
    }
    for (sym = 0; sym < codes; sym++) {
      count[lens[lens_index + sym]]++;
    }

    /* bound code lengths, force root to be within code lengths */
    root = bits;
    for (max = MAXBITS; max >= 1; max--) {
      if (count[max] !== 0) { break; }
    }
    if (root > max) {
      root = max;
    }
    if (max === 0) {                     /* no symbols to code at all */
      //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
      //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
      //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;


      //table.op[opts.table_index] = 64;
      //table.bits[opts.table_index] = 1;
      //table.val[opts.table_index++] = 0;
      table[table_index++] = (1 << 24) | (64 << 16) | 0;

      opts.bits = 1;
      return 0;     /* no symbols, but wait for decoding to report error */
    }
    for (min = 1; min < max; min++) {
      if (count[min] !== 0) { break; }
    }
    if (root < min) {
      root = min;
    }

    /* check for an over-subscribed or incomplete set of lengths */
    left = 1;
    for (len = 1; len <= MAXBITS; len++) {
      left <<= 1;
      left -= count[len];
      if (left < 0) {
        return -1;
      }        /* over-subscribed */
    }
    if (left > 0 && (type === CODES$1 || max !== 1)) {
      return -1;                      /* incomplete set */
    }

    /* generate offsets into symbol table for each length for sorting */
    offs[1] = 0;
    for (len = 1; len < MAXBITS; len++) {
      offs[len + 1] = offs[len] + count[len];
    }

    /* sort symbols by length, by symbol order within each length */
    for (sym = 0; sym < codes; sym++) {
      if (lens[lens_index + sym] !== 0) {
        work[offs[lens[lens_index + sym]]++] = sym;
      }
    }

    /*
     Create and fill in decoding tables.  In this loop, the table being
     filled is at next and has curr index bits.  The code being used is huff
     with length len.  That code is converted to an index by dropping drop
     bits off of the bottom.  For codes where len is less than drop + curr,
     those top drop + curr - len bits are incremented through all values to
     fill the table with replicated entries.

     root is the number of index bits for the root table.  When len exceeds
     root, sub-tables are created pointed to by the root entry with an index
     of the low root bits of huff.  This is saved in low to check for when a
     new sub-table should be started.  drop is zero when the root table is
     being filled, and drop is root when sub-tables are being filled.

     When a new sub-table is needed, it is necessary to look ahead in the
     code lengths to determine what size sub-table is needed.  The length
     counts are used for this, and so count[] is decremented as codes are
     entered in the tables.

     used keeps track of how many table entries have been allocated from the
     provided *table space.  It is checked for LENS and DIST tables against
     the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
     the initial root table size constants.  See the comments in inftrees.h
     for more information.

     sym increments through all symbols, and the loop terminates when
     all codes of length max, i.e. all codes, have been processed.  This
     routine permits incomplete codes, so another loop after this one fills
     in the rest of the decoding tables with invalid code markers.
     */

    /* set up for code type */
    // poor man optimization - use if-else instead of switch,
    // to avoid deopts in old v8
    if (type === CODES$1) {
      base = extra = work;    /* dummy value--not used */
      match = 20;

    } else if (type === LENS$1) {
      base = lbase;
      extra = lext;
      match = 257;

    } else {                    /* DISTS */
      base = dbase;
      extra = dext;
      match = 0;
    }

    /* initialize opts for loop */
    huff = 0;                   /* starting code */
    sym = 0;                    /* starting code symbol */
    len = min;                  /* starting code length */
    next = table_index;              /* current table to fill in */
    curr = root;                /* current table index bits */
    drop = 0;                   /* current bits to drop from code for index */
    low = -1;                   /* trigger new sub-table when len > root */
    used = 1 << root;          /* use root table entries */
    mask = used - 1;            /* mask for comparing low */

    /* check available table space */
    if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
      (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
      return 1;
    }

    /* process all codes and make table entries */
    for (;;) {
      /* create table entry */
      here_bits = len - drop;
      if (work[sym] + 1 < match) {
        here_op = 0;
        here_val = work[sym];
      }
      else if (work[sym] >= match) {
        here_op = extra[work[sym] - match];
        here_val = base[work[sym] - match];
      }
      else {
        here_op = 32 + 64;         /* end of block */
        here_val = 0;
      }

      /* replicate for those indices with low len bits equal to huff */
      incr = 1 << (len - drop);
      fill = 1 << curr;
      min = fill;                 /* save offset to next table */
      do {
        fill -= incr;
        table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
      } while (fill !== 0);

      /* backwards increment the len-bit code huff */
      incr = 1 << (len - 1);
      while (huff & incr) {
        incr >>= 1;
      }
      if (incr !== 0) {
        huff &= incr - 1;
        huff += incr;
      } else {
        huff = 0;
      }

      /* go to next symbol, update count, len */
      sym++;
      if (--count[len] === 0) {
        if (len === max) { break; }
        len = lens[lens_index + work[sym]];
      }

      /* create new sub-table if needed */
      if (len > root && (huff & mask) !== low) {
        /* if first time, transition to sub-tables */
        if (drop === 0) {
          drop = root;
        }

        /* increment past last table */
        next += min;            /* here min is 1 << curr */

        /* determine length of next table */
        curr = len - drop;
        left = 1 << curr;
        while (curr + drop < max) {
          left -= count[curr + drop];
          if (left <= 0) { break; }
          curr++;
          left <<= 1;
        }

        /* check for enough space */
        used += 1 << curr;
        if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
          (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
          return 1;
        }

        /* point entry in root table to sub-table */
        low = huff & mask;
        /*table.op[low] = curr;
        table.bits[low] = root;
        table.val[low] = next - opts.table_index;*/
        table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
      }
    }

    /* fill in remaining table entry if code is incomplete (guaranteed to have
     at most one remaining entry, since if the code is incomplete, the
     maximum code length that was allowed to get this far is one bit) */
    if (huff !== 0) {
      //table.op[next + huff] = 64;            /* invalid code marker */
      //table.bits[next + huff] = len - drop;
      //table.val[next + huff] = 0;
      table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
    }

    /* set return parameters */
    //opts.table_index += used;
    opts.bits = root;
    return 0;
  };


  var inftrees = inflate_table;

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.






  const CODES = 0;
  const LENS = 1;
  const DISTS = 2;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,
    Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,
    Z_DEFLATED
  } = constants$2;


  /* STATES ====================================================================*/
  /* ===========================================================================*/


  const    HEAD = 16180;       /* i: waiting for magic header */
  const    FLAGS = 16181;      /* i: waiting for method and flags (gzip) */
  const    TIME = 16182;       /* i: waiting for modification time (gzip) */
  const    OS = 16183;         /* i: waiting for extra flags and operating system (gzip) */
  const    EXLEN = 16184;      /* i: waiting for extra length (gzip) */
  const    EXTRA = 16185;      /* i: waiting for extra bytes (gzip) */
  const    NAME = 16186;       /* i: waiting for end of file name (gzip) */
  const    COMMENT = 16187;    /* i: waiting for end of comment (gzip) */
  const    HCRC = 16188;       /* i: waiting for header crc (gzip) */
  const    DICTID = 16189;    /* i: waiting for dictionary check value */
  const    DICT = 16190;      /* waiting for inflateSetDictionary() call */
  const        TYPE = 16191;      /* i: waiting for type bits, including last-flag bit */
  const        TYPEDO = 16192;    /* i: same, but skip check to exit inflate on new block */
  const        STORED = 16193;    /* i: waiting for stored size (length and complement) */
  const        COPY_ = 16194;     /* i/o: same as COPY below, but only first time in */
  const        COPY = 16195;      /* i/o: waiting for input or output to copy stored block */
  const        TABLE = 16196;     /* i: waiting for dynamic block table lengths */
  const        LENLENS = 16197;   /* i: waiting for code length code lengths */
  const        CODELENS = 16198;  /* i: waiting for length/lit and distance code lengths */
  const            LEN_ = 16199;      /* i: same as LEN below, but only first time in */
  const            LEN = 16200;       /* i: waiting for length/lit/eob code */
  const            LENEXT = 16201;    /* i: waiting for length extra bits */
  const            DIST = 16202;      /* i: waiting for distance code */
  const            DISTEXT = 16203;   /* i: waiting for distance extra bits */
  const            MATCH = 16204;     /* o: waiting for output space to copy string */
  const            LIT = 16205;       /* o: waiting for output space to write literal */
  const    CHECK = 16206;     /* i: waiting for 32-bit check value */
  const    LENGTH = 16207;    /* i: waiting for 32-bit length (gzip) */
  const    DONE = 16208;      /* finished check, done -- remain here until reset */
  const    BAD = 16209;       /* got a data error -- remain here until reset */
  const    MEM = 16210;       /* got an inflate() memory error -- remain here until reset */
  const    SYNC = 16211;      /* looking for synchronization bytes to restart inflate() */

  /* ===========================================================================*/



  const ENOUGH_LENS = 852;
  const ENOUGH_DISTS = 592;
  //const ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);

  const MAX_WBITS = 15;
  /* 32K LZ77 window */
  const DEF_WBITS = MAX_WBITS;


  const zswap32 = (q) => {

    return  (((q >>> 24) & 0xff) +
            ((q >>> 8) & 0xff00) +
            ((q & 0xff00) << 8) +
            ((q & 0xff) << 24));
  };


  function InflateState() {
    this.strm = null;           /* pointer back to this zlib stream */
    this.mode = 0;              /* current inflate mode */
    this.last = false;          /* true if processing last block */
    this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip,
                                   bit 2 true to validate check value */
    this.havedict = false;      /* true if dictionary provided */
    this.flags = 0;             /* gzip header method and flags (0 if zlib), or
                                   -1 if raw or no header yet */
    this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
    this.check = 0;             /* protected copy of check value */
    this.total = 0;             /* protected copy of output count */
    // TODO: may be {}
    this.head = null;           /* where to save gzip header information */

    /* sliding window */
    this.wbits = 0;             /* log base 2 of requested window size */
    this.wsize = 0;             /* window size or zero if not using window */
    this.whave = 0;             /* valid bytes in the window */
    this.wnext = 0;             /* window write index */
    this.window = null;         /* allocated sliding window, if needed */

    /* bit accumulator */
    this.hold = 0;              /* input bit accumulator */
    this.bits = 0;              /* number of bits in "in" */

    /* for string and stored block copying */
    this.length = 0;            /* literal or length of data to copy */
    this.offset = 0;            /* distance back to copy string from */

    /* for table and code decoding */
    this.extra = 0;             /* extra bits needed */

    /* fixed and dynamic code tables */
    this.lencode = null;          /* starting table for length/literal codes */
    this.distcode = null;         /* starting table for distance codes */
    this.lenbits = 0;           /* index bits for lencode */
    this.distbits = 0;          /* index bits for distcode */

    /* dynamic table building */
    this.ncode = 0;             /* number of code length code lengths */
    this.nlen = 0;              /* number of length code lengths */
    this.ndist = 0;             /* number of distance code lengths */
    this.have = 0;              /* number of code lengths in lens[] */
    this.next = null;              /* next available space in codes[] */

    this.lens = new Uint16Array(320); /* temporary storage for code lengths */
    this.work = new Uint16Array(288); /* work area for code table building */

    /*
     because we don't have pointers in js, we use lencode and distcode directly
     as buffers so we don't need codes
    */
    //this.codes = new Int32Array(ENOUGH);       /* space for code tables */
    this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
    this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
    this.sane = 0;                   /* if false, allow invalid distance too far */
    this.back = 0;                   /* bits back of last unprocessed length/lit */
    this.was = 0;                    /* initial length of match */
  }


  const inflateStateCheck = (strm) => {

    if (!strm) {
      return 1;
    }
    const state = strm.state;
    if (!state || state.strm !== strm ||
      state.mode < HEAD || state.mode > SYNC) {
      return 1;
    }
    return 0;
  };


  const inflateResetKeep = (strm) => {

    if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
    const state = strm.state;
    strm.total_in = strm.total_out = state.total = 0;
    strm.msg = ''; /*Z_NULL*/
    if (state.wrap) {       /* to support ill-conceived Java test suite */
      strm.adler = state.wrap & 1;
    }
    state.mode = HEAD;
    state.last = 0;
    state.havedict = 0;
    state.flags = -1;
    state.dmax = 32768;
    state.head = null/*Z_NULL*/;
    state.hold = 0;
    state.bits = 0;
    //state.lencode = state.distcode = state.next = state.codes;
    state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);
    state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);

    state.sane = 1;
    state.back = -1;
    //Tracev((stderr, "inflate: reset\n"));
    return Z_OK$1;
  };


  const inflateReset = (strm) => {

    if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
    const state = strm.state;
    state.wsize = 0;
    state.whave = 0;
    state.wnext = 0;
    return inflateResetKeep(strm);

  };


  const inflateReset2 = (strm, windowBits) => {
    let wrap;

    /* get the state */
    if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
    const state = strm.state;

    /* extract wrap request from windowBits parameter */
    if (windowBits < 0) {
      wrap = 0;
      windowBits = -windowBits;
    }
    else {
      wrap = (windowBits >> 4) + 5;
      if (windowBits < 48) {
        windowBits &= 15;
      }
    }

    /* set number of window bits, free window if different */
    if (windowBits && (windowBits < 8 || windowBits > 15)) {
      return Z_STREAM_ERROR$1;
    }
    if (state.window !== null && state.wbits !== windowBits) {
      state.window = null;
    }

    /* update state and reset the rest of it */
    state.wrap = wrap;
    state.wbits = windowBits;
    return inflateReset(strm);
  };


  const inflateInit2 = (strm, windowBits) => {

    if (!strm) { return Z_STREAM_ERROR$1; }
    //strm.msg = Z_NULL;                 /* in case we return an error */

    const state = new InflateState();

    //if (state === Z_NULL) return Z_MEM_ERROR;
    //Tracev((stderr, "inflate: allocated\n"));
    strm.state = state;
    state.strm = strm;
    state.window = null/*Z_NULL*/;
    state.mode = HEAD;     /* to pass state test in inflateReset2() */
    const ret = inflateReset2(strm, windowBits);
    if (ret !== Z_OK$1) {
      strm.state = null/*Z_NULL*/;
    }
    return ret;
  };


  const inflateInit = (strm) => {

    return inflateInit2(strm, DEF_WBITS);
  };


  /*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
   */
  let virgin = true;

  let lenfix, distfix; // We have no pointers in JS, so keep tables separate


  const fixedtables = (state) => {

    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
      lenfix = new Int32Array(512);
      distfix = new Int32Array(32);

      /* literal/length table */
      let sym = 0;
      while (sym < 144) { state.lens[sym++] = 8; }
      while (sym < 256) { state.lens[sym++] = 9; }
      while (sym < 280) { state.lens[sym++] = 7; }
      while (sym < 288) { state.lens[sym++] = 8; }

      inftrees(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

      /* distance table */
      sym = 0;
      while (sym < 32) { state.lens[sym++] = 5; }

      inftrees(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

      /* do this just once */
      virgin = false;
    }

    state.lencode = lenfix;
    state.lenbits = 9;
    state.distcode = distfix;
    state.distbits = 5;
  };


  /*
   Update the window with the last wsize (normally 32K) bytes written before
   returning.  If window does not exist yet, create it.  This is only called
   when a window is already in use, or when output has been written during this
   inflate call, but the end of the deflate stream has not been reached yet.
   It is also called to create a window for dictionary data when a dictionary
   is loaded.

   Providing output buffers larger than 32K to inflate() should provide a speed
   advantage, since only the last 32K of output is copied to the sliding window
   upon return from inflate(), and since all distances after the first 32K of
   output will fall in the output data, making match copies simpler and faster.
   The advantage may be dependent on the size of the processor's data caches.
   */
  const updatewindow = (strm, src, end, copy) => {

    let dist;
    const state = strm.state;

    /* if it hasn't been done already, allocate space for the window */
    if (state.window === null) {
      state.wsize = 1 << state.wbits;
      state.wnext = 0;
      state.whave = 0;

      state.window = new Uint8Array(state.wsize);
    }

    /* copy state->wsize or less output bytes into the circular window */
    if (copy >= state.wsize) {
      state.window.set(src.subarray(end - state.wsize, end), 0);
      state.wnext = 0;
      state.whave = state.wsize;
    }
    else {
      dist = state.wsize - state.wnext;
      if (dist > copy) {
        dist = copy;
      }
      //zmemcpy(state->window + state->wnext, end - copy, dist);
      state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);
      copy -= dist;
      if (copy) {
        //zmemcpy(state->window, end - copy, copy);
        state.window.set(src.subarray(end - copy, end), 0);
        state.wnext = copy;
        state.whave = state.wsize;
      }
      else {
        state.wnext += dist;
        if (state.wnext === state.wsize) { state.wnext = 0; }
        if (state.whave < state.wsize) { state.whave += dist; }
      }
    }
    return 0;
  };


  const inflate$2 = (strm, flush) => {

    let state;
    let input, output;          // input/output buffers
    let next;                   /* next input INDEX */
    let put;                    /* next output INDEX */
    let have, left;             /* available input and output */
    let hold;                   /* bit buffer */
    let bits;                   /* bits in bit buffer */
    let _in, _out;              /* save starting available input and output */
    let copy;                   /* number of stored or match bytes to copy */
    let from;                   /* where to copy match bytes from */
    let from_source;
    let here = 0;               /* current decoding table entry */
    let here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
    //let last;                   /* parent table entry */
    let last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
    let len;                    /* length to copy for repeats, bits to drop */
    let ret;                    /* return code */
    const hbuf = new Uint8Array(4);    /* buffer for gzip header crc calculation */
    let opts;

    let n; // temporary variable for NEED_BITS

    const order = /* permutation of code lengths */
      new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);


    if (inflateStateCheck(strm) || !strm.output ||
        (!strm.input && strm.avail_in !== 0)) {
      return Z_STREAM_ERROR$1;
    }

    state = strm.state;
    if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */


    //--- LOAD() ---
    put = strm.next_out;
    output = strm.output;
    left = strm.avail_out;
    next = strm.next_in;
    input = strm.input;
    have = strm.avail_in;
    hold = state.hold;
    bits = state.bits;
    //---

    _in = have;
    _out = left;
    ret = Z_OK$1;

    inf_leave: // goto emulation
    for (;;) {
      switch (state.mode) {
        case HEAD:
          if (state.wrap === 0) {
            state.mode = TYPEDO;
            break;
          }
          //=== NEEDBITS(16);
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
            if (state.wbits === 0) {
              state.wbits = 15;
            }
            state.check = 0/*crc32(0L, Z_NULL, 0)*/;
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//

            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            state.mode = FLAGS;
            break;
          }
          if (state.head) {
            state.head.done = false;
          }
          if (!(state.wrap & 1) ||   /* check if zlib header allowed */
            (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
            strm.msg = 'incorrect header check';
            state.mode = BAD;
            break;
          }
          if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
            strm.msg = 'unknown compression method';
            state.mode = BAD;
            break;
          }
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
          len = (hold & 0x0f)/*BITS(4)*/ + 8;
          if (state.wbits === 0) {
            state.wbits = len;
          }
          if (len > 15 || len > state.wbits) {
            strm.msg = 'invalid window size';
            state.mode = BAD;
            break;
          }

          // !!! pako patch. Force use `options.windowBits` if passed.
          // Required to always use max window size by default.
          state.dmax = 1 << state.wbits;
          //state.dmax = 1 << len;

          state.flags = 0;               /* indicate zlib header */
          //Tracev((stderr, "inflate:   zlib header ok\n"));
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = hold & 0x200 ? DICTID : TYPE;
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          break;
        case FLAGS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.flags = hold;
          if ((state.flags & 0xff) !== Z_DEFLATED) {
            strm.msg = 'unknown compression method';
            state.mode = BAD;
            break;
          }
          if (state.flags & 0xe000) {
            strm.msg = 'unknown header flags set';
            state.mode = BAD;
            break;
          }
          if (state.head) {
            state.head.text = ((hold >> 8) & 1);
          }
          if ((state.flags & 0x0200) && (state.wrap & 4)) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = TIME;
          /* falls through */
        case TIME:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.time = hold;
          }
          if ((state.flags & 0x0200) && (state.wrap & 4)) {
            //=== CRC4(state.check, hold)
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            hbuf[2] = (hold >>> 16) & 0xff;
            hbuf[3] = (hold >>> 24) & 0xff;
            state.check = crc32_1(state.check, hbuf, 4, 0);
            //===
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = OS;
          /* falls through */
        case OS:
          //=== NEEDBITS(16); */
          while (bits < 16) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if (state.head) {
            state.head.xflags = (hold & 0xff);
            state.head.os = (hold >> 8);
          }
          if ((state.flags & 0x0200) && (state.wrap & 4)) {
            //=== CRC2(state.check, hold);
            hbuf[0] = hold & 0xff;
            hbuf[1] = (hold >>> 8) & 0xff;
            state.check = crc32_1(state.check, hbuf, 2, 0);
            //===//
          }
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = EXLEN;
          /* falls through */
        case EXLEN:
          if (state.flags & 0x0400) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length = hold;
            if (state.head) {
              state.head.extra_len = hold;
            }
            if ((state.flags & 0x0200) && (state.wrap & 4)) {
              //=== CRC2(state.check, hold);
              hbuf[0] = hold & 0xff;
              hbuf[1] = (hold >>> 8) & 0xff;
              state.check = crc32_1(state.check, hbuf, 2, 0);
              //===//
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          else if (state.head) {
            state.head.extra = null/*Z_NULL*/;
          }
          state.mode = EXTRA;
          /* falls through */
        case EXTRA:
          if (state.flags & 0x0400) {
            copy = state.length;
            if (copy > have) { copy = have; }
            if (copy) {
              if (state.head) {
                len = state.head.extra_len - state.length;
                if (!state.head.extra) {
                  // Use untyped array for more convenient processing later
                  state.head.extra = new Uint8Array(state.head.extra_len);
                }
                state.head.extra.set(
                  input.subarray(
                    next,
                    // extra field is limited to 65536 bytes
                    // - no need for additional size check
                    next + copy
                  ),
                  /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
                  len
                );
                //zmemcpy(state.head.extra + len, next,
                //        len + copy > state.head.extra_max ?
                //        state.head.extra_max - len : copy);
              }
              if ((state.flags & 0x0200) && (state.wrap & 4)) {
                state.check = crc32_1(state.check, input, copy, next);
              }
              have -= copy;
              next += copy;
              state.length -= copy;
            }
            if (state.length) { break inf_leave; }
          }
          state.length = 0;
          state.mode = NAME;
          /* falls through */
        case NAME:
          if (state.flags & 0x0800) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              // TODO: 2 or 1 bytes?
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.name_max*/)) {
                state.head.name += String.fromCharCode(len);
              }
            } while (len && copy < have);

            if ((state.flags & 0x0200) && (state.wrap & 4)) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.name = null;
          }
          state.length = 0;
          state.mode = COMMENT;
          /* falls through */
        case COMMENT:
          if (state.flags & 0x1000) {
            if (have === 0) { break inf_leave; }
            copy = 0;
            do {
              len = input[next + copy++];
              /* use constant limit because in js we should not preallocate memory */
              if (state.head && len &&
                  (state.length < 65536 /*state.head.comm_max*/)) {
                state.head.comment += String.fromCharCode(len);
              }
            } while (len && copy < have);
            if ((state.flags & 0x0200) && (state.wrap & 4)) {
              state.check = crc32_1(state.check, input, copy, next);
            }
            have -= copy;
            next += copy;
            if (len) { break inf_leave; }
          }
          else if (state.head) {
            state.head.comment = null;
          }
          state.mode = HCRC;
          /* falls through */
        case HCRC:
          if (state.flags & 0x0200) {
            //=== NEEDBITS(16); */
            while (bits < 16) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {
              strm.msg = 'header crc mismatch';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
          }
          if (state.head) {
            state.head.hcrc = ((state.flags >> 9) & 1);
            state.head.done = true;
          }
          strm.adler = state.check = 0;
          state.mode = TYPE;
          break;
        case DICTID:
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          strm.adler = state.check = zswap32(hold);
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = DICT;
          /* falls through */
        case DICT:
          if (state.havedict === 0) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            return Z_NEED_DICT$1;
          }
          strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
          state.mode = TYPE;
          /* falls through */
        case TYPE:
          if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case TYPEDO:
          if (state.last) {
            //--- BYTEBITS() ---//
            hold >>>= bits & 7;
            bits -= bits & 7;
            //---//
            state.mode = CHECK;
            break;
          }
          //=== NEEDBITS(3); */
          while (bits < 3) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.last = (hold & 0x01)/*BITS(1)*/;
          //--- DROPBITS(1) ---//
          hold >>>= 1;
          bits -= 1;
          //---//

          switch ((hold & 0x03)/*BITS(2)*/) {
            case 0:                             /* stored block */
              //Tracev((stderr, "inflate:     stored block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = STORED;
              break;
            case 1:                             /* fixed block */
              fixedtables(state);
              //Tracev((stderr, "inflate:     fixed codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = LEN_;             /* decode codes */
              if (flush === Z_TREES) {
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
                break inf_leave;
              }
              break;
            case 2:                             /* dynamic block */
              //Tracev((stderr, "inflate:     dynamic codes block%s\n",
              //        state.last ? " (last)" : ""));
              state.mode = TABLE;
              break;
            case 3:
              strm.msg = 'invalid block type';
              state.mode = BAD;
          }
          //--- DROPBITS(2) ---//
          hold >>>= 2;
          bits -= 2;
          //---//
          break;
        case STORED:
          //--- BYTEBITS() ---// /* go to byte boundary */
          hold >>>= bits & 7;
          bits -= bits & 7;
          //---//
          //=== NEEDBITS(32); */
          while (bits < 32) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
            strm.msg = 'invalid stored block lengths';
            state.mode = BAD;
            break;
          }
          state.length = hold & 0xffff;
          //Tracev((stderr, "inflate:       stored length %u\n",
          //        state.length));
          //=== INITBITS();
          hold = 0;
          bits = 0;
          //===//
          state.mode = COPY_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case COPY_:
          state.mode = COPY;
          /* falls through */
        case COPY:
          copy = state.length;
          if (copy) {
            if (copy > have) { copy = have; }
            if (copy > left) { copy = left; }
            if (copy === 0) { break inf_leave; }
            //--- zmemcpy(put, next, copy); ---
            output.set(input.subarray(next, next + copy), put);
            //---//
            have -= copy;
            next += copy;
            left -= copy;
            put += copy;
            state.length -= copy;
            break;
          }
          //Tracev((stderr, "inflate:       stored end\n"));
          state.mode = TYPE;
          break;
        case TABLE:
          //=== NEEDBITS(14); */
          while (bits < 14) {
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
          }
          //===//
          state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
          //--- DROPBITS(5) ---//
          hold >>>= 5;
          bits -= 5;
          //---//
          state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
          //--- DROPBITS(4) ---//
          hold >>>= 4;
          bits -= 4;
          //---//
  //#ifndef PKZIP_BUG_WORKAROUND
          if (state.nlen > 286 || state.ndist > 30) {
            strm.msg = 'too many length or distance symbols';
            state.mode = BAD;
            break;
          }
  //#endif
          //Tracev((stderr, "inflate:       table sizes ok\n"));
          state.have = 0;
          state.mode = LENLENS;
          /* falls through */
        case LENLENS:
          while (state.have < state.ncode) {
            //=== NEEDBITS(3);
            while (bits < 3) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
            //--- DROPBITS(3) ---//
            hold >>>= 3;
            bits -= 3;
            //---//
          }
          while (state.have < 19) {
            state.lens[order[state.have++]] = 0;
          }
          // We have separate tables & no pointers. 2 commented lines below not needed.
          //state.next = state.codes;
          //state.lencode = state.next;
          // Switch to use dynamic table
          state.lencode = state.lendyn;
          state.lenbits = 7;

          opts = { bits: state.lenbits };
          ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
          state.lenbits = opts.bits;

          if (ret) {
            strm.msg = 'invalid code lengths set';
            state.mode = BAD;
            break;
          }
          //Tracev((stderr, "inflate:       code lengths ok\n"));
          state.have = 0;
          state.mode = CODELENS;
          /* falls through */
        case CODELENS:
          while (state.have < state.nlen + state.ndist) {
            for (;;) {
              here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            if (here_val < 16) {
              //--- DROPBITS(here.bits) ---//
              hold >>>= here_bits;
              bits -= here_bits;
              //---//
              state.lens[state.have++] = here_val;
            }
            else {
              if (here_val === 16) {
                //=== NEEDBITS(here.bits + 2);
                n = here_bits + 2;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                if (state.have === 0) {
                  strm.msg = 'invalid bit length repeat';
                  state.mode = BAD;
                  break;
                }
                len = state.lens[state.have - 1];
                copy = 3 + (hold & 0x03);//BITS(2);
                //--- DROPBITS(2) ---//
                hold >>>= 2;
                bits -= 2;
                //---//
              }
              else if (here_val === 17) {
                //=== NEEDBITS(here.bits + 3);
                n = here_bits + 3;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 3 + (hold & 0x07);//BITS(3);
                //--- DROPBITS(3) ---//
                hold >>>= 3;
                bits -= 3;
                //---//
              }
              else {
                //=== NEEDBITS(here.bits + 7);
                n = here_bits + 7;
                while (bits < n) {
                  if (have === 0) { break inf_leave; }
                  have--;
                  hold += input[next++] << bits;
                  bits += 8;
                }
                //===//
                //--- DROPBITS(here.bits) ---//
                hold >>>= here_bits;
                bits -= here_bits;
                //---//
                len = 0;
                copy = 11 + (hold & 0x7f);//BITS(7);
                //--- DROPBITS(7) ---//
                hold >>>= 7;
                bits -= 7;
                //---//
              }
              if (state.have + copy > state.nlen + state.ndist) {
                strm.msg = 'invalid bit length repeat';
                state.mode = BAD;
                break;
              }
              while (copy--) {
                state.lens[state.have++] = len;
              }
            }
          }

          /* handle error breaks in while */
          if (state.mode === BAD) { break; }

          /* check for end-of-block code (better have one) */
          if (state.lens[256] === 0) {
            strm.msg = 'invalid code -- missing end-of-block';
            state.mode = BAD;
            break;
          }

          /* build code tables -- note: do not change the lenbits or distbits
             values here (9 and 6) without reading the comments in inftrees.h
             concerning the ENOUGH constants, which depend on those values */
          state.lenbits = 9;

          opts = { bits: state.lenbits };
          ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.lenbits = opts.bits;
          // state.lencode = state.next;

          if (ret) {
            strm.msg = 'invalid literal/lengths set';
            state.mode = BAD;
            break;
          }

          state.distbits = 6;
          //state.distcode.copy(state.codes);
          // Switch to use dynamic table
          state.distcode = state.distdyn;
          opts = { bits: state.distbits };
          ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
          // We have separate tables & no pointers. 2 commented lines below not needed.
          // state.next_index = opts.table_index;
          state.distbits = opts.bits;
          // state.distcode = state.next;

          if (ret) {
            strm.msg = 'invalid distances set';
            state.mode = BAD;
            break;
          }
          //Tracev((stderr, 'inflate:       codes ok\n'));
          state.mode = LEN_;
          if (flush === Z_TREES) { break inf_leave; }
          /* falls through */
        case LEN_:
          state.mode = LEN;
          /* falls through */
        case LEN:
          if (have >= 6 && left >= 258) {
            //--- RESTORE() ---
            strm.next_out = put;
            strm.avail_out = left;
            strm.next_in = next;
            strm.avail_in = have;
            state.hold = hold;
            state.bits = bits;
            //---
            inffast(strm, _out);
            //--- LOAD() ---
            put = strm.next_out;
            output = strm.output;
            left = strm.avail_out;
            next = strm.next_in;
            input = strm.input;
            have = strm.avail_in;
            hold = state.hold;
            bits = state.bits;
            //---

            if (state.mode === TYPE) {
              state.back = -1;
            }
            break;
          }
          state.back = 0;
          for (;;) {
            here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if (here_bits <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if (here_op && (here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.lencode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          state.length = here_val;
          if (here_op === 0) {
            //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
            //        "inflate:         literal '%c'\n" :
            //        "inflate:         literal 0x%02x\n", here.val));
            state.mode = LIT;
            break;
          }
          if (here_op & 32) {
            //Tracevv((stderr, "inflate:         end of block\n"));
            state.back = -1;
            state.mode = TYPE;
            break;
          }
          if (here_op & 64) {
            strm.msg = 'invalid literal/length code';
            state.mode = BAD;
            break;
          }
          state.extra = here_op & 15;
          state.mode = LENEXT;
          /* falls through */
        case LENEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
          //Tracevv((stderr, "inflate:         length %u\n", state.length));
          state.was = state.length;
          state.mode = DIST;
          /* falls through */
        case DIST:
          for (;;) {
            here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
            here_bits = here >>> 24;
            here_op = (here >>> 16) & 0xff;
            here_val = here & 0xffff;

            if ((here_bits) <= bits) { break; }
            //--- PULLBYTE() ---//
            if (have === 0) { break inf_leave; }
            have--;
            hold += input[next++] << bits;
            bits += 8;
            //---//
          }
          if ((here_op & 0xf0) === 0) {
            last_bits = here_bits;
            last_op = here_op;
            last_val = here_val;
            for (;;) {
              here = state.distcode[last_val +
                      ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
              here_bits = here >>> 24;
              here_op = (here >>> 16) & 0xff;
              here_val = here & 0xffff;

              if ((last_bits + here_bits) <= bits) { break; }
              //--- PULLBYTE() ---//
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
              //---//
            }
            //--- DROPBITS(last.bits) ---//
            hold >>>= last_bits;
            bits -= last_bits;
            //---//
            state.back += last_bits;
          }
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.back += here_bits;
          if (here_op & 64) {
            strm.msg = 'invalid distance code';
            state.mode = BAD;
            break;
          }
          state.offset = here_val;
          state.extra = (here_op) & 15;
          state.mode = DISTEXT;
          /* falls through */
        case DISTEXT:
          if (state.extra) {
            //=== NEEDBITS(state.extra);
            n = state.extra;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
            //--- DROPBITS(state.extra) ---//
            hold >>>= state.extra;
            bits -= state.extra;
            //---//
            state.back += state.extra;
          }
  //#ifdef INFLATE_STRICT
          if (state.offset > state.dmax) {
            strm.msg = 'invalid distance too far back';
            state.mode = BAD;
            break;
          }
  //#endif
          //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
          state.mode = MATCH;
          /* falls through */
        case MATCH:
          if (left === 0) { break inf_leave; }
          copy = _out - left;
          if (state.offset > copy) {         /* copy from window */
            copy = state.offset - copy;
            if (copy > state.whave) {
              if (state.sane) {
                strm.msg = 'invalid distance too far back';
                state.mode = BAD;
                break;
              }
  // (!) This block is disabled in zlib defaults,
  // don't enable it for binary compatibility
  //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  //          Trace((stderr, "inflate.c too far\n"));
  //          copy -= state.whave;
  //          if (copy > state.length) { copy = state.length; }
  //          if (copy > left) { copy = left; }
  //          left -= copy;
  //          state.length -= copy;
  //          do {
  //            output[put++] = 0;
  //          } while (--copy);
  //          if (state.length === 0) { state.mode = LEN; }
  //          break;
  //#endif
            }
            if (copy > state.wnext) {
              copy -= state.wnext;
              from = state.wsize - copy;
            }
            else {
              from = state.wnext - copy;
            }
            if (copy > state.length) { copy = state.length; }
            from_source = state.window;
          }
          else {                              /* copy from output */
            from_source = output;
            from = put - state.offset;
            copy = state.length;
          }
          if (copy > left) { copy = left; }
          left -= copy;
          state.length -= copy;
          do {
            output[put++] = from_source[from++];
          } while (--copy);
          if (state.length === 0) { state.mode = LEN; }
          break;
        case LIT:
          if (left === 0) { break inf_leave; }
          output[put++] = state.length;
          left--;
          state.mode = LEN;
          break;
        case CHECK:
          if (state.wrap) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              // Use '|' instead of '+' to make sure that result is signed
              hold |= input[next++] << bits;
              bits += 8;
            }
            //===//
            _out -= left;
            strm.total_out += _out;
            state.total += _out;
            if ((state.wrap & 4) && _out) {
              strm.adler = state.check =
                  /*UPDATE_CHECK(state.check, put - _out, _out);*/
                  (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));

            }
            _out = left;
            // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
            if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {
              strm.msg = 'incorrect data check';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   check matches trailer\n"));
          }
          state.mode = LENGTH;
          /* falls through */
        case LENGTH:
          if (state.wrap && state.flags) {
            //=== NEEDBITS(32);
            while (bits < 32) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {
              strm.msg = 'incorrect length check';
              state.mode = BAD;
              break;
            }
            //=== INITBITS();
            hold = 0;
            bits = 0;
            //===//
            //Tracev((stderr, "inflate:   length matches trailer\n"));
          }
          state.mode = DONE;
          /* falls through */
        case DONE:
          ret = Z_STREAM_END$1;
          break inf_leave;
        case BAD:
          ret = Z_DATA_ERROR$1;
          break inf_leave;
        case MEM:
          return Z_MEM_ERROR$1;
        case SYNC:
          /* falls through */
        default:
          return Z_STREAM_ERROR$1;
      }
    }

    // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */

    //--- RESTORE() ---
    strm.next_out = put;
    strm.avail_out = left;
    strm.next_in = next;
    strm.avail_in = have;
    state.hold = hold;
    state.bits = bits;
    //---

    if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                        (state.mode < CHECK || flush !== Z_FINISH$1))) {
      if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
    }
    _in -= strm.avail_in;
    _out -= strm.avail_out;
    strm.total_in += _in;
    strm.total_out += _out;
    state.total += _out;
    if ((state.wrap & 4) && _out) {
      strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/
        (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));
    }
    strm.data_type = state.bits + (state.last ? 64 : 0) +
                      (state.mode === TYPE ? 128 : 0) +
                      (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
    if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {
      ret = Z_BUF_ERROR;
    }
    return ret;
  };


  const inflateEnd = (strm) => {

    if (inflateStateCheck(strm)) {
      return Z_STREAM_ERROR$1;
    }

    let state = strm.state;
    if (state.window) {
      state.window = null;
    }
    strm.state = null;
    return Z_OK$1;
  };


  const inflateGetHeader = (strm, head) => {

    /* check state */
    if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
    const state = strm.state;
    if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }

    /* save header structure */
    state.head = head;
    head.done = false;
    return Z_OK$1;
  };


  const inflateSetDictionary = (strm, dictionary) => {
    const dictLength = dictionary.length;

    let state;
    let dictid;
    let ret;

    /* check state */
    if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }
    state = strm.state;

    if (state.wrap !== 0 && state.mode !== DICT) {
      return Z_STREAM_ERROR$1;
    }

    /* check for correct dictionary identifier */
    if (state.mode === DICT) {
      dictid = 1; /* adler32(0, null, 0)*/
      /* dictid = adler32(dictid, dictionary, dictLength); */
      dictid = adler32_1(dictid, dictionary, dictLength, 0);
      if (dictid !== state.check) {
        return Z_DATA_ERROR$1;
      }
    }
    /* copy dictionary to window using updatewindow(), which will amend the
     existing dictionary if appropriate */
    ret = updatewindow(strm, dictionary, dictLength, dictLength);
    if (ret) {
      state.mode = MEM;
      return Z_MEM_ERROR$1;
    }
    state.havedict = 1;
    // Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK$1;
  };


  var inflateReset_1 = inflateReset;
  var inflateReset2_1 = inflateReset2;
  var inflateResetKeep_1 = inflateResetKeep;
  var inflateInit_1 = inflateInit;
  var inflateInit2_1 = inflateInit2;
  var inflate_2$1 = inflate$2;
  var inflateEnd_1 = inflateEnd;
  var inflateGetHeader_1 = inflateGetHeader;
  var inflateSetDictionary_1 = inflateSetDictionary;
  var inflateInfo = 'pako inflate (from Nodeca project)';

  /* Not implemented
  module.exports.inflateCodesUsed = inflateCodesUsed;
  module.exports.inflateCopy = inflateCopy;
  module.exports.inflateGetDictionary = inflateGetDictionary;
  module.exports.inflateMark = inflateMark;
  module.exports.inflatePrime = inflatePrime;
  module.exports.inflateSync = inflateSync;
  module.exports.inflateSyncPoint = inflateSyncPoint;
  module.exports.inflateUndermine = inflateUndermine;
  module.exports.inflateValidate = inflateValidate;
  */

  var inflate_1$2 = {
  	inflateReset: inflateReset_1,
  	inflateReset2: inflateReset2_1,
  	inflateResetKeep: inflateResetKeep_1,
  	inflateInit: inflateInit_1,
  	inflateInit2: inflateInit2_1,
  	inflate: inflate_2$1,
  	inflateEnd: inflateEnd_1,
  	inflateGetHeader: inflateGetHeader_1,
  	inflateSetDictionary: inflateSetDictionary_1,
  	inflateInfo: inflateInfo
  };

  // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  //
  // This software is provided 'as-is', without any express or implied
  // warranty. In no event will the authors be held liable for any damages
  // arising from the use of this software.
  //
  // Permission is granted to anyone to use this software for any purpose,
  // including commercial applications, and to alter it and redistribute it
  // freely, subject to the following restrictions:
  //
  // 1. The origin of this software must not be misrepresented; you must not
  //   claim that you wrote the original software. If you use this software
  //   in a product, an acknowledgment in the product documentation would be
  //   appreciated but is not required.
  // 2. Altered source versions must be plainly marked as such, and must not be
  //   misrepresented as being the original software.
  // 3. This notice may not be removed or altered from any source distribution.

  function GZheader() {
    /* true if compressed data believed to be text */
    this.text       = 0;
    /* modification time */
    this.time       = 0;
    /* extra flags (not used when writing a gzip file) */
    this.xflags     = 0;
    /* operating system */
    this.os         = 0;
    /* pointer to extra field or Z_NULL if none */
    this.extra      = null;
    /* extra field length (valid if extra != Z_NULL) */
    this.extra_len  = 0; // Actually, we don't need it in JS,
                         // but leave for few code modifications

    //
    // Setup limits is not necessary because in js we should not preallocate memory
    // for inflate use constant limit in 65536 bytes
    //

    /* space at extra (only when reading header) */
    // this.extra_max  = 0;
    /* pointer to zero-terminated file name or Z_NULL */
    this.name       = '';
    /* space at name (only when reading header) */
    // this.name_max   = 0;
    /* pointer to zero-terminated comment or Z_NULL */
    this.comment    = '';
    /* space at comment (only when reading header) */
    // this.comm_max   = 0;
    /* true if there was or will be a header crc */
    this.hcrc       = 0;
    /* true when done reading gzip header (not used when writing a gzip file) */
    this.done       = false;
  }

  var gzheader = GZheader;

  const toString = Object.prototype.toString;

  /* Public constants ==========================================================*/
  /* ===========================================================================*/

  const {
    Z_NO_FLUSH, Z_FINISH,
    Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR
  } = constants$2;

  /* ===========================================================================*/


  /**
   * class Inflate
   *
   * Generic JS-style wrapper for zlib calls. If you don't need
   * streaming behaviour - use more simple functions: [[inflate]]
   * and [[inflateRaw]].
   **/

  /* internal
   * inflate.chunks -> Array
   *
   * Chunks of output data, if [[Inflate#onData]] not overridden.
   **/

  /**
   * Inflate.result -> Uint8Array|String
   *
   * Uncompressed result, generated by default [[Inflate#onData]]
   * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
   * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
   **/

  /**
   * Inflate.err -> Number
   *
   * Error code after inflate finished. 0 (Z_OK) on success.
   * Should be checked if broken data possible.
   **/

  /**
   * Inflate.msg -> String
   *
   * Error message, if [[Inflate.err]] != 0
   **/


  /**
   * new Inflate(options)
   * - options (Object): zlib inflate options.
   *
   * Creates new inflator instance with specified params. Throws exception
   * on bad params. Supported options:
   *
   * - `windowBits`
   * - `dictionary`
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information on these.
   *
   * Additional options, for internal needs:
   *
   * - `chunkSize` - size of generated data chunks (16K by default)
   * - `raw` (Boolean) - do raw inflate
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   * By default, when no options set, autodetect deflate/gzip data format via
   * wrapper header.
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako')
   * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])
   * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);
   *
   * const inflate = new pako.Inflate({ level: 3});
   *
   * inflate.push(chunk1, false);
   * inflate.push(chunk2, true);  // true -> last chunk
   *
   * if (inflate.err) { throw new Error(inflate.err); }
   *
   * console.log(inflate.result);
   * ```
   **/
  function Inflate$1(options) {
    this.options = common.assign({
      chunkSize: 1024 * 64,
      windowBits: 15,
      to: ''
    }, options || {});

    const opt = this.options;

    // Force window size for `raw` data, if not set directly,
    // because we have no header for autodetect.
    if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
      opt.windowBits = -opt.windowBits;
      if (opt.windowBits === 0) { opt.windowBits = -15; }
    }

    // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
    if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
        !(options && options.windowBits)) {
      opt.windowBits += 32;
    }

    // Gzip header has no info about windows size, we can do autodetect only
    // for deflate. So, if window size not set, force it to max when gzip possible
    if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
      // bit 3 (16) -> gzipped data
      // bit 4 (32) -> autodetect gzip/deflate
      if ((opt.windowBits & 15) === 0) {
        opt.windowBits |= 15;
      }
    }

    this.err    = 0;      // error code, if happens (0 = Z_OK)
    this.msg    = '';     // error message
    this.ended  = false;  // used to avoid multiple onEnd() calls
    this.chunks = [];     // chunks of compressed data

    this.strm   = new zstream();
    this.strm.avail_out = 0;

    let status  = inflate_1$2.inflateInit2(
      this.strm,
      opt.windowBits
    );

    if (status !== Z_OK) {
      throw new Error(messages[status]);
    }

    this.header = new gzheader();

    inflate_1$2.inflateGetHeader(this.strm, this.header);

    // Setup dictionary
    if (opt.dictionary) {
      // Convert data if needed
      if (typeof opt.dictionary === 'string') {
        opt.dictionary = strings.string2buf(opt.dictionary);
      } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
        opt.dictionary = new Uint8Array(opt.dictionary);
      }
      if (opt.raw) { //In raw mode we need to set the dictionary early
        status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);
        if (status !== Z_OK) {
          throw new Error(messages[status]);
        }
      }
    }
  }

  /**
   * Inflate#push(data[, flush_mode]) -> Boolean
   * - data (Uint8Array|ArrayBuffer): input data
   * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE
   *   flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,
   *   `true` means Z_FINISH.
   *
   * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
   * new output chunks. Returns `true` on success. If end of stream detected,
   * [[Inflate#onEnd]] will be called.
   *
   * `flush_mode` is not needed for normal operation, because end of stream
   * detected automatically. You may try to use it for advanced things, but
   * this functionality was not tested.
   *
   * On fail call [[Inflate#onEnd]] with error code and return false.
   *
   * ##### Example
   *
   * ```javascript
   * push(chunk, false); // push one of data chunks
   * ...
   * push(chunk, true);  // push last chunk
   * ```
   **/
  Inflate$1.prototype.push = function (data, flush_mode) {
    const strm = this.strm;
    const chunkSize = this.options.chunkSize;
    const dictionary = this.options.dictionary;
    let status, _flush_mode, last_avail_out;

    if (this.ended) return false;

    if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;
    else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;

    // Convert data if needed
    if (toString.call(data) === '[object ArrayBuffer]') {
      strm.input = new Uint8Array(data);
    } else {
      strm.input = data;
    }

    strm.next_in = 0;
    strm.avail_in = strm.input.length;

    for (;;) {
      if (strm.avail_out === 0) {
        strm.output = new Uint8Array(chunkSize);
        strm.next_out = 0;
        strm.avail_out = chunkSize;
      }

      status = inflate_1$2.inflate(strm, _flush_mode);

      if (status === Z_NEED_DICT && dictionary) {
        status = inflate_1$2.inflateSetDictionary(strm, dictionary);

        if (status === Z_OK) {
          status = inflate_1$2.inflate(strm, _flush_mode);
        } else if (status === Z_DATA_ERROR) {
          // Replace code with more verbose
          status = Z_NEED_DICT;
        }
      }

      // Skip snyc markers if more data follows and not raw mode
      while (strm.avail_in > 0 &&
             status === Z_STREAM_END &&
             strm.state.wrap > 0 &&
             data[strm.next_in] !== 0)
      {
        inflate_1$2.inflateReset(strm);
        status = inflate_1$2.inflate(strm, _flush_mode);
      }

      switch (status) {
        case Z_STREAM_ERROR:
        case Z_DATA_ERROR:
        case Z_NEED_DICT:
        case Z_MEM_ERROR:
          this.onEnd(status);
          this.ended = true;
          return false;
      }

      // Remember real `avail_out` value, because we may patch out buffer content
      // to align utf8 strings boundaries.
      last_avail_out = strm.avail_out;

      if (strm.next_out) {
        if (strm.avail_out === 0 || status === Z_STREAM_END) {

          if (this.options.to === 'string') {

            let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);

            let tail = strm.next_out - next_out_utf8;
            let utf8str = strings.buf2string(strm.output, next_out_utf8);

            // move tail & realign counters
            strm.next_out = tail;
            strm.avail_out = chunkSize - tail;
            if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);

            this.onData(utf8str);

          } else {
            this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));
          }
        }
      }

      // Must repeat iteration if out buffer is full
      if (status === Z_OK && last_avail_out === 0) continue;

      // Finalize if end of stream reached.
      if (status === Z_STREAM_END) {
        status = inflate_1$2.inflateEnd(this.strm);
        this.onEnd(status);
        this.ended = true;
        return true;
      }

      if (strm.avail_in === 0) break;
    }

    return true;
  };


  /**
   * Inflate#onData(chunk) -> Void
   * - chunk (Uint8Array|String): output data. When string output requested,
   *   each chunk will be string.
   *
   * By default, stores data blocks in `chunks[]` property and glue
   * those in `onEnd`. Override this handler, if you need another behaviour.
   **/
  Inflate$1.prototype.onData = function (chunk) {
    this.chunks.push(chunk);
  };


  /**
   * Inflate#onEnd(status) -> Void
   * - status (Number): inflate status. 0 (Z_OK) on success,
   *   other if not.
   *
   * Called either after you tell inflate that the input stream is
   * complete (Z_FINISH). By default - join collected chunks,
   * free memory and fill `results` / `err` properties.
   **/
  Inflate$1.prototype.onEnd = function (status) {
    // On success - join
    if (status === Z_OK) {
      if (this.options.to === 'string') {
        this.result = this.chunks.join('');
      } else {
        this.result = common.flattenChunks(this.chunks);
      }
    }
    this.chunks = [];
    this.err = status;
    this.msg = this.strm.msg;
  };


  /**
   * inflate(data[, options]) -> Uint8Array|String
   * - data (Uint8Array|ArrayBuffer): input data to decompress.
   * - options (Object): zlib inflate options.
   *
   * Decompress `data` with inflate/ungzip and `options`. Autodetect
   * format via wrapper header by default. That's why we don't provide
   * separate `ungzip` method.
   *
   * Supported options are:
   *
   * - windowBits
   *
   * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
   * for more information.
   *
   * Sugar (options):
   *
   * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
   *   negative windowBits implicitly.
   * - `to` (String) - if equal to 'string', then result will be converted
   *   from utf8 to utf16 (javascript) string. When string output requested,
   *   chunk length can differ from `chunkSize`, depending on content.
   *
   *
   * ##### Example:
   *
   * ```javascript
   * const pako = require('pako');
   * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));
   * let output;
   *
   * try {
   *   output = pako.inflate(input);
   * } catch (err) {
   *   console.log(err);
   * }
   * ```
   **/
  function inflate$1(input, options) {
    const inflator = new Inflate$1(options);

    inflator.push(input);

    // That will never happens, if you don't cheat with options :)
    if (inflator.err) throw inflator.msg || messages[inflator.err];

    return inflator.result;
  }
  var inflate_2 = inflate$1;

  var inflate_1$1 = {
  	inflate: inflate_2};

  const { inflate} = inflate_1$1;
  var inflate_1 = inflate;

  class DeflateDecoder extends BaseDecoder {
    decodeBlock(buffer) {
      return inflate_1(new Uint8Array(buffer)).buffer;
    }
  }

  var deflate = {
    __proto__: null,
    default: DeflateDecoder
  };

  class PackbitsDecoder extends BaseDecoder {
    decodeBlock(buffer) {
      const dataView = new DataView(buffer);
      const out = [];

      for (let i = 0; i < buffer.byteLength; ++i) {
        let header = dataView.getInt8(i);
        if (header < 0) {
          const next = dataView.getUint8(i + 1);
          header = -header;
          for (let j = 0; j <= header; ++j) {
            out.push(next);
          }
          i += 1;
        } else {
          for (let j = 0; j <= header; ++j) {
            out.push(dataView.getUint8(i + j + 1));
          }
          i += header + 1;
        }
      }
      return new Uint8Array(out).buffer;
    }
  }

  var packbits = {
    __proto__: null,
    default: PackbitsDecoder
  };

  var LercDecode = {exports: {}};

  /* jshint forin: false, bitwise: false */

  var hasRequiredLercDecode;

  function requireLercDecode () {
  	if (hasRequiredLercDecode) return LercDecode.exports;
  	hasRequiredLercDecode = 1;
  	(function (module) {
  		/*
  		Copyright 2015-2021 Esri

  		Licensed under the Apache License, Version 2.0 (the "License");
  		you may not use this file except in compliance with the License.
  		You may obtain a copy of the License at

  		http://www.apache.org/licenses/LICENSE-2.0

  		Unless required by applicable law or agreed to in writing, software
  		distributed under the License is distributed on an "AS IS" BASIS,
  		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  		See the License for the specific language governing permissions and
  		limitations under the License.

  		A copy of the license and additional notices are located with the
  		source distribution at:

  		http://github.com/Esri/lerc/

  		Contributors:  Johannes Schmid, (LERC v1)
  		               Chayanika Khatua, (LERC v1)
  		               Wenxue Ju (LERC v1, v2.x)
  		*/

  		/* Copyright 2015-2021 Esri. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 @preserve */

  		/**
  		 * a module for decoding LERC blobs
  		 * @module Lerc
  		 */
  		(function() {
  		  //this decoder supports all lerc versions, each version has its own class (LercDecode and Lerc2Decode). 
  		  //the exported module handles format variation autoamtically.

  		  //the original LercDecode for Version 1
  		  var LercDecode = (function() {

  		    // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  		    // the class was chosen to be future proof.

  		    var CntZImage = {};

  		    CntZImage.defaultNoDataValue = -34027999387901484e22; // smallest Float32 value

  		    /**
  		     * Decode a LERC byte stream and return an object containing the pixel data and some required and optional
  		     * information about it, such as the image's width and height.
  		     *
  		     * @param {ArrayBuffer} input The LERC input byte stream
  		     * @param {object} [options] Decoding options, containing any of the following properties:
  		     * @config {number} [inputOffset = 0]
  		     *        Skip the first inputOffset bytes of the input byte stream. A valid LERC file is expected at that position.
  		     * @config {Uint8Array} [encodedMask = null]
  		     *        If specified, the decoder will not read mask information from the input and use the specified encoded
  		     *        mask data instead. Mask header/data must not be present in the LERC byte stream in this case.
  		     * @config {number} [noDataValue = LercCode.defaultNoDataValue]
  		     *        Pixel value to use for masked pixels.
  		     * @config {ArrayBufferView|Array} [pixelType = Float32Array]
  		     *        The desired type of the pixelData array in the return value. Note that it is the caller's responsibility to
  		     *        provide an appropriate noDataValue if the default pixelType is overridden.
  		     * @config {boolean} [returnMask = false]
  		     *        If true, the return value will contain a maskData property of type Uint8Array which has one element per
  		     *        pixel, the value of which is 1 or 0 depending on whether that pixel's data is present or masked. If the
  		     *        input LERC data does not contain a mask, maskData will not be returned.
  		     * @config {boolean} [returnEncodedMask = false]
  		     *        If true, the return value will contain a encodedMaskData property, which can be passed into encode() as
  		     *        encodedMask.
  		     * @config {boolean} [returnFileInfo = false]
  		     *        If true, the return value will have a fileInfo property that contains metadata obtained from the
  		     *        LERC headers and the decoding process.
  		     * @config {boolean} [computeUsedBitDepths = false]
  		     *        If true, the fileInfo property in the return value will contain the set of all block bit depths
  		     *        encountered during decoding. Will only have an effect if returnFileInfo option is true.
  		     * @returns {{width, height, pixelData, minValue, maxValue, noDataValue, maskData, encodedMaskData, fileInfo}}
  		     */
  		    CntZImage.decode = function(input, options) {
  		      options = options || {};

  		      var skipMask = options.encodedMaskData || (options.encodedMaskData === null);
  		      var parsedData = parse(input, options.inputOffset || 0, skipMask);

  		      var noDataValue = (options.noDataValue !== null) ? options.noDataValue : CntZImage.defaultNoDataValue;

  		      var uncompressedData = uncompressPixelValues(parsedData, options.pixelType || Float32Array,
  		        options.encodedMaskData, noDataValue, options.returnMask);

  		      var result = {
  		        width: parsedData.width,
  		        height: parsedData.height,
  		        pixelData: uncompressedData.resultPixels,
  		        minValue: uncompressedData.minValue,
  		        maxValue: parsedData.pixels.maxValue,
  		        noDataValue: noDataValue
  		      };

  		      if (uncompressedData.resultMask) {
  		        result.maskData = uncompressedData.resultMask;
  		      }

  		      if (options.returnEncodedMask && parsedData.mask) {
  		        result.encodedMaskData = parsedData.mask.bitset ? parsedData.mask.bitset : null;
  		      }

  		      if (options.returnFileInfo) {
  		        result.fileInfo = formatFileInfo(parsedData);
  		        if (options.computeUsedBitDepths) {
  		          result.fileInfo.bitDepths = computeUsedBitDepths(parsedData);
  		        }
  		      }

  		      return result;
  		    };

  		    var uncompressPixelValues = function(data, TypedArrayClass, maskBitset, noDataValue, storeDecodedMask) {
  		      var blockIdx = 0;
  		      var numX = data.pixels.numBlocksX;
  		      var numY = data.pixels.numBlocksY;
  		      var blockWidth = Math.floor(data.width / numX);
  		      var blockHeight = Math.floor(data.height / numY);
  		      var scale = 2 * data.maxZError;
  		      var minValue = Number.MAX_VALUE, currentValue;
  		      maskBitset = maskBitset || ((data.mask) ? data.mask.bitset : null);

  		      var resultPixels, resultMask;
  		      resultPixels = new TypedArrayClass(data.width * data.height);
  		      if (storeDecodedMask && maskBitset) {
  		        resultMask = new Uint8Array(data.width * data.height);
  		      }
  		      var blockDataBuffer = new Float32Array(blockWidth * blockHeight);

  		      var xx, yy;
  		      for (var y = 0; y <= numY; y++) {
  		        var thisBlockHeight = (y !== numY) ? blockHeight : (data.height % numY);
  		        if (thisBlockHeight === 0) {
  		          continue;
  		        }
  		        for (var x = 0; x <= numX; x++) {
  		          var thisBlockWidth = (x !== numX) ? blockWidth : (data.width % numX);
  		          if (thisBlockWidth === 0) {
  		            continue;
  		          }

  		          var outPtr = y * data.width * blockHeight + x * blockWidth;
  		          var outStride = data.width - thisBlockWidth;

  		          var block = data.pixels.blocks[blockIdx];

  		          var blockData, blockPtr, constValue;
  		          if (block.encoding < 2) {
  		            // block is either uncompressed or bit-stuffed (encodings 0 and 1)
  		            if (block.encoding === 0) {
  		              // block is uncompressed
  		              blockData = block.rawData;
  		            } else {
  		              // block is bit-stuffed
  		              unstuff(block.stuffedData, block.bitsPerPixel, block.numValidPixels, block.offset, scale, blockDataBuffer, data.pixels.maxValue);
  		              blockData = blockDataBuffer;
  		            }
  		            blockPtr = 0;
  		          }
  		          else if (block.encoding === 2) {
  		            // block is all 0
  		            constValue = 0;
  		          }
  		          else {
  		            // block has constant value (encoding === 3)
  		            constValue = block.offset;
  		          }

  		          var maskByte;
  		          if (maskBitset) {
  		            for (yy = 0; yy < thisBlockHeight; yy++) {
  		              if (outPtr & 7) {
  		                //
  		                maskByte = maskBitset[outPtr >> 3];
  		                maskByte <<= outPtr & 7;
  		              }
  		              for (xx = 0; xx < thisBlockWidth; xx++) {
  		                if (!(outPtr & 7)) {
  		                  // read next byte from mask
  		                  maskByte = maskBitset[outPtr >> 3];
  		                }
  		                if (maskByte & 128) {
  		                  // pixel data present
  		                  if (resultMask) {
  		                    resultMask[outPtr] = 1;
  		                  }
  		                  currentValue = (block.encoding < 2) ? blockData[blockPtr++] : constValue;
  		                  minValue = minValue > currentValue ? currentValue : minValue;
  		                  resultPixels[outPtr++] = currentValue;
  		                } else {
  		                  // pixel data not present
  		                  if (resultMask) {
  		                    resultMask[outPtr] = 0;
  		                  }
  		                  resultPixels[outPtr++] = noDataValue;
  		                }
  		                maskByte <<= 1;
  		              }
  		              outPtr += outStride;
  		            }
  		          } else {
  		            // mask not present, simply copy block over
  		            if (block.encoding < 2) {
  		              // duplicating this code block for performance reasons
  		              // blockData case:
  		              for (yy = 0; yy < thisBlockHeight; yy++) {
  		                for (xx = 0; xx < thisBlockWidth; xx++) {
  		                  currentValue = blockData[blockPtr++];
  		                  minValue = minValue > currentValue ? currentValue : minValue;
  		                  resultPixels[outPtr++] = currentValue;
  		                }
  		                outPtr += outStride;
  		              }
  		            }
  		            else {
  		              // constValue case:
  		              minValue = minValue > constValue ? constValue : minValue;
  		              for (yy = 0; yy < thisBlockHeight; yy++) {
  		                for (xx = 0; xx < thisBlockWidth; xx++) {
  		                  resultPixels[outPtr++] = constValue;
  		                }
  		                outPtr += outStride;
  		              }
  		            }
  		          }
  		          if ((block.encoding === 1) && (blockPtr !== block.numValidPixels)) {
  		            throw "Block and Mask do not match";
  		          }
  		          blockIdx++;
  		        }
  		      }

  		      return {
  		        resultPixels: resultPixels,
  		        resultMask: resultMask,
  		        minValue: minValue
  		      };
  		    };

  		    var formatFileInfo = function(data) {
  		      return {
  		        "fileIdentifierString": data.fileIdentifierString,
  		        "fileVersion": data.fileVersion,
  		        "imageType": data.imageType,
  		        "height": data.height,
  		        "width": data.width,
  		        "maxZError": data.maxZError,
  		        "eofOffset": data.eofOffset,
  		        "mask": data.mask ? {
  		          "numBlocksX": data.mask.numBlocksX,
  		          "numBlocksY": data.mask.numBlocksY,
  		          "numBytes": data.mask.numBytes,
  		          "maxValue": data.mask.maxValue
  		        } : null,
  		        "pixels": {
  		          "numBlocksX": data.pixels.numBlocksX,
  		          "numBlocksY": data.pixels.numBlocksY,
  		          "numBytes": data.pixels.numBytes,
  		          "maxValue": data.pixels.maxValue,
  		          "noDataValue": data.noDataValue
  		        }
  		      };
  		    };

  		    var computeUsedBitDepths = function(data) {
  		      var numBlocks = data.pixels.numBlocksX * data.pixels.numBlocksY;
  		      var bitDepths = {};
  		      for (var i = 0; i < numBlocks; i++) {
  		        var block = data.pixels.blocks[i];
  		        if (block.encoding === 0) {
  		          bitDepths.float32 = true;
  		        } else if (block.encoding === 1) {
  		          bitDepths[block.bitsPerPixel] = true;
  		        } else {
  		          bitDepths[0] = true;
  		        }
  		      }

  		      return Object.keys(bitDepths);
  		    };

  		    var parse = function(input, fp, skipMask) {
  		      var data = {};

  		      // File header
  		      var fileIdView = new Uint8Array(input, fp, 10);
  		      data.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  		      if (data.fileIdentifierString.trim() !== "CntZImage") {
  		        throw "Unexpected file identifier string: " + data.fileIdentifierString;
  		      }
  		      fp += 10;
  		      var view = new DataView(input, fp, 24);
  		      data.fileVersion = view.getInt32(0, true);
  		      data.imageType = view.getInt32(4, true);
  		      data.height = view.getUint32(8, true);
  		      data.width = view.getUint32(12, true);
  		      data.maxZError = view.getFloat64(16, true);
  		      fp += 24;

  		      // Mask Header
  		      if (!skipMask) {
  		        view = new DataView(input, fp, 16);
  		        data.mask = {};
  		        data.mask.numBlocksY = view.getUint32(0, true);
  		        data.mask.numBlocksX = view.getUint32(4, true);
  		        data.mask.numBytes = view.getUint32(8, true);
  		        data.mask.maxValue = view.getFloat32(12, true);
  		        fp += 16;

  		        // Mask Data
  		        if (data.mask.numBytes > 0) {
  		          var bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  		          view = new DataView(input, fp, data.mask.numBytes);
  		          var cnt = view.getInt16(0, true);
  		          var ip = 2, op = 0;
  		          do {
  		            if (cnt > 0) {
  		              while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  		            } else {
  		              var val = view.getUint8(ip++);
  		              cnt = -cnt;
  		              while (cnt--) { bitset[op++] = val; }
  		            }
  		            cnt = view.getInt16(ip, true);
  		            ip += 2;
  		          } while (ip < data.mask.numBytes);
  		          if ((cnt !== -32768) || (op < bitset.length)) {
  		            throw "Unexpected end of mask RLE encoding";
  		          }
  		          data.mask.bitset = bitset;
  		          fp += data.mask.numBytes;
  		        }
  		        else if ((data.mask.numBytes | data.mask.numBlocksY | data.mask.maxValue) === 0) {  // Special case, all nodata
  		          data.mask.bitset = new Uint8Array(Math.ceil(data.width * data.height / 8));
  		        }
  		      }

  		      // Pixel Header
  		      view = new DataView(input, fp, 16);
  		      data.pixels = {};
  		      data.pixels.numBlocksY = view.getUint32(0, true);
  		      data.pixels.numBlocksX = view.getUint32(4, true);
  		      data.pixels.numBytes = view.getUint32(8, true);
  		      data.pixels.maxValue = view.getFloat32(12, true);
  		      fp += 16;

  		      var numBlocksX = data.pixels.numBlocksX;
  		      var numBlocksY = data.pixels.numBlocksY;
  		      // the number of blocks specified in the header does not take into account the blocks at the end of
  		      // each row/column with a special width/height that make the image complete in case the width is not
  		      // evenly divisible by the number of blocks.
  		      var actualNumBlocksX = numBlocksX + ((data.width % numBlocksX) > 0 ? 1 : 0);
  		      var actualNumBlocksY = numBlocksY + ((data.height % numBlocksY) > 0 ? 1 : 0);
  		      data.pixels.blocks = new Array(actualNumBlocksX * actualNumBlocksY);
  		      var blockI = 0;
  		      for (var blockY = 0; blockY < actualNumBlocksY; blockY++) {
  		        for (var blockX = 0; blockX < actualNumBlocksX; blockX++) {

  		          // Block
  		          var size = 0;
  		          var bytesLeft = input.byteLength - fp;
  		          view = new DataView(input, fp, Math.min(10, bytesLeft));
  		          var block = {};
  		          data.pixels.blocks[blockI++] = block;
  		          var headerByte = view.getUint8(0); size++;
  		          block.encoding = headerByte & 63;
  		          if (block.encoding > 3) {
  		            throw "Invalid block encoding (" + block.encoding + ")";
  		          }
  		          if (block.encoding === 2) {
  		            fp++;
  		            continue;
  		          }
  		          if ((headerByte !== 0) && (headerByte !== 2)) {
  		            headerByte >>= 6;
  		            block.offsetType = headerByte;
  		            if (headerByte === 2) {
  		              block.offset = view.getInt8(1); size++;
  		            } else if (headerByte === 1) {
  		              block.offset = view.getInt16(1, true); size += 2;
  		            } else if (headerByte === 0) {
  		              block.offset = view.getFloat32(1, true); size += 4;
  		            } else {
  		              throw "Invalid block offset type";
  		            }

  		            if (block.encoding === 1) {
  		              headerByte = view.getUint8(size); size++;
  		              block.bitsPerPixel = headerByte & 63;
  		              headerByte >>= 6;
  		              block.numValidPixelsType = headerByte;
  		              if (headerByte === 2) {
  		                block.numValidPixels = view.getUint8(size); size++;
  		              } else if (headerByte === 1) {
  		                block.numValidPixels = view.getUint16(size, true); size += 2;
  		              } else if (headerByte === 0) {
  		                block.numValidPixels = view.getUint32(size, true); size += 4;
  		              } else {
  		                throw "Invalid valid pixel count type";
  		              }
  		            }
  		          }
  		          fp += size;

  		          if (block.encoding === 3) {
  		            continue;
  		          }

  		          var arrayBuf, store8;
  		          if (block.encoding === 0) {
  		            var numPixels = (data.pixels.numBytes - 1) / 4;
  		            if (numPixels !== Math.floor(numPixels)) {
  		              throw "uncompressed block has invalid length";
  		            }
  		            arrayBuf = new ArrayBuffer(numPixels * 4);
  		            store8 = new Uint8Array(arrayBuf);
  		            store8.set(new Uint8Array(input, fp, numPixels * 4));
  		            var rawData = new Float32Array(arrayBuf);
  		            block.rawData = rawData;
  		            fp += numPixels * 4;
  		          } else if (block.encoding === 1) {
  		            var dataBytes = Math.ceil(block.numValidPixels * block.bitsPerPixel / 8);
  		            var dataWords = Math.ceil(dataBytes / 4);
  		            arrayBuf = new ArrayBuffer(dataWords * 4);
  		            store8 = new Uint8Array(arrayBuf);
  		            store8.set(new Uint8Array(input, fp, dataBytes));
  		            block.stuffedData = new Uint32Array(arrayBuf);
  		            fp += dataBytes;
  		          }
  		        }
  		      }
  		      data.eofOffset = fp;
  		      return data;
  		    };

  		    var unstuff = function(src, bitsPerPixel, numPixels, offset, scale, dest, maxValue) {
  		      var bitMask = (1 << bitsPerPixel) - 1;
  		      var i = 0, o;
  		      var bitsLeft = 0;
  		      var n, buffer;
  		      var nmax = Math.ceil((maxValue - offset) / scale);
  		      // get rid of trailing bytes that are already part of next block
  		      var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  		      src[src.length - 1] <<= 8 * numInvalidTailBytes;

  		      for (o = 0; o < numPixels; o++) {
  		        if (bitsLeft === 0) {
  		          buffer = src[i++];
  		          bitsLeft = 32;
  		        }
  		        if (bitsLeft >= bitsPerPixel) {
  		          n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  		          bitsLeft -= bitsPerPixel;
  		        } else {
  		          var missingBits = (bitsPerPixel - bitsLeft);
  		          n = ((buffer & bitMask) << missingBits) & bitMask;
  		          buffer = src[i++];
  		          bitsLeft = 32 - missingBits;
  		          n += (buffer >>> bitsLeft);
  		        }
  		        //pixel values may exceed max due to quantization
  		        dest[o] = n < nmax ? offset + n * scale : maxValue;
  		      }
  		      return dest;
  		    };

  		    return CntZImage;
  		  })();

  		  //version 2. Supports 2.1, 2.2, 2.3
  		  var Lerc2Decode = (function() {
  		    // Note: currently, this module only has an implementation for decoding LERC data, not encoding. The name of
  		    // the class was chosen to be future proof, following LercDecode.

  		    /*****************************************
  		    * private static class bitsutffer used by Lerc2Decode
  		    *******************************************/
  		    var BitStuffer = {
  		      //methods ending with 2 are for the new byte order used by Lerc2.3 and above.
  		      //originalUnstuff is used to unpack Huffman code table. code is duplicated to unstuffx for performance reasons.
  		      unstuff: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o;
  		        var bitsLeft = 0;
  		        var n, buffer, missingBits, nmax;

  		        // get rid of trailing bytes that are already part of next block
  		        var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  		        src[src.length - 1] <<= 8 * numInvalidTailBytes;
  		        if (lutArr) {
  		          for (o = 0; o < numPixels; o++) {
  		            if (bitsLeft === 0) {
  		              buffer = src[i++];
  		              bitsLeft = 32;
  		            }
  		            if (bitsLeft >= bitsPerPixel) {
  		              n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  		              bitsLeft -= bitsPerPixel;
  		            }
  		            else {
  		              missingBits = (bitsPerPixel - bitsLeft);
  		              n = ((buffer & bitMask) << missingBits) & bitMask;
  		              buffer = src[i++];
  		              bitsLeft = 32 - missingBits;
  		              n += (buffer >>> bitsLeft);
  		            }
  		            dest[o] = lutArr[n];//offset + lutArr[n] * scale;
  		          }
  		        }
  		        else {
  		          nmax = Math.ceil((maxValue - offset) / scale);
  		          for (o = 0; o < numPixels; o++) {
  		            if (bitsLeft === 0) {
  		              buffer = src[i++];
  		              bitsLeft = 32;
  		            }
  		            if (bitsLeft >= bitsPerPixel) {
  		              n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  		              bitsLeft -= bitsPerPixel;
  		            }
  		            else {
  		              missingBits = (bitsPerPixel - bitsLeft);
  		              n = ((buffer & bitMask) << missingBits) & bitMask;
  		              buffer = src[i++];
  		              bitsLeft = 32 - missingBits;
  		              n += (buffer >>> bitsLeft);
  		            }
  		            //pixel values may exceed max due to quantization
  		            dest[o] = n < nmax ? offset + n * scale : maxValue;
  		          }
  		        }
  		      },

  		      unstuffLUT: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0;
  		        var buffer;
  		        var dest = [];

  		        // get rid of trailing bytes that are already part of next block
  		        var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  		        src[src.length - 1] <<= 8 * numInvalidTailBytes;

  		        var nmax = Math.ceil((maxValue - offset) / scale);
  		        for (o = 0; o < numPixels; o++) {
  		          if (bitsLeft === 0) {
  		            buffer = src[i++];
  		            bitsLeft = 32;
  		          }
  		          if (bitsLeft >= bitsPerPixel) {
  		            n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  		            bitsLeft -= bitsPerPixel;
  		          } else {
  		            missingBits = (bitsPerPixel - bitsLeft);
  		            n = ((buffer & bitMask) << missingBits) & bitMask;
  		            buffer = src[i++];
  		            bitsLeft = 32 - missingBits;
  		            n += (buffer >>> bitsLeft);
  		          }
  		          //dest.push(n);
  		          dest[o] = n < nmax ? offset + n * scale : maxValue;
  		        }
  		        dest.unshift(offset);//1st one
  		        return dest;
  		      },

  		      unstuff2: function(src, dest, bitsPerPixel, numPixels, lutArr, offset, scale, maxValue) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o;
  		        var bitsLeft = 0, bitPos = 0;
  		        var n, buffer, missingBits;
  		        if (lutArr) {
  		          for (o = 0; o < numPixels; o++) {
  		            if (bitsLeft === 0) {
  		              buffer = src[i++];
  		              bitsLeft = 32;
  		              bitPos = 0;
  		            }
  		            if (bitsLeft >= bitsPerPixel) {
  		              n = ((buffer >>> bitPos) & bitMask);
  		              bitsLeft -= bitsPerPixel;
  		              bitPos += bitsPerPixel;
  		            } else {
  		              missingBits = (bitsPerPixel - bitsLeft);
  		              n = (buffer >>> bitPos) & bitMask;
  		              buffer = src[i++];
  		              bitsLeft = 32 - missingBits;
  		              n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  		              bitPos = missingBits;
  		            }
  		            dest[o] = lutArr[n];
  		          }
  		        }
  		        else {
  		          var nmax = Math.ceil((maxValue - offset) / scale);
  		          for (o = 0; o < numPixels; o++) {
  		            if (bitsLeft === 0) {
  		              buffer = src[i++];
  		              bitsLeft = 32;
  		              bitPos = 0;
  		            }
  		            if (bitsLeft >= bitsPerPixel) {
  		              //no unsigned left shift
  		              n = ((buffer >>> bitPos) & bitMask);
  		              bitsLeft -= bitsPerPixel;
  		              bitPos += bitsPerPixel;
  		            } else {
  		              missingBits = (bitsPerPixel - bitsLeft);
  		              n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  		              buffer = src[i++];
  		              bitsLeft = 32 - missingBits;
  		              n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  		              bitPos = missingBits;
  		            }
  		            //pixel values may exceed max due to quantization
  		            dest[o] = n < nmax ? offset + n * scale : maxValue;
  		          }
  		        }
  		        return dest;
  		      },

  		      unstuffLUT2: function(src, bitsPerPixel, numPixels, offset, scale, maxValue) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o = 0, missingBits = 0, bitsLeft = 0, n = 0, bitPos = 0;
  		        var buffer;
  		        var dest = [];
  		        var nmax = Math.ceil((maxValue - offset) / scale);
  		        for (o = 0; o < numPixels; o++) {
  		          if (bitsLeft === 0) {
  		            buffer = src[i++];
  		            bitsLeft = 32;
  		            bitPos = 0;
  		          }
  		          if (bitsLeft >= bitsPerPixel) {
  		            //no unsigned left shift
  		            n = ((buffer >>> bitPos) & bitMask);
  		            bitsLeft -= bitsPerPixel;
  		            bitPos += bitsPerPixel;
  		          } else {
  		            missingBits = (bitsPerPixel - bitsLeft);
  		            n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  		            buffer = src[i++];
  		            bitsLeft = 32 - missingBits;
  		            n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  		            bitPos = missingBits;
  		          }
  		          //dest.push(n);
  		          dest[o] = n < nmax ? offset + n * scale : maxValue;
  		        }
  		        dest.unshift(offset);
  		        return dest;
  		      },

  		      originalUnstuff: function(src, dest, bitsPerPixel, numPixels) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o;
  		        var bitsLeft = 0;
  		        var n, buffer, missingBits;

  		        // get rid of trailing bytes that are already part of next block
  		        var numInvalidTailBytes = src.length * 4 - Math.ceil(bitsPerPixel * numPixels / 8);
  		        src[src.length - 1] <<= 8 * numInvalidTailBytes;

  		        for (o = 0; o < numPixels; o++) {
  		          if (bitsLeft === 0) {
  		            buffer = src[i++];
  		            bitsLeft = 32;
  		          }
  		          if (bitsLeft >= bitsPerPixel) {
  		            n = (buffer >>> (bitsLeft - bitsPerPixel)) & bitMask;
  		            bitsLeft -= bitsPerPixel;
  		          }
  		          else {
  		            missingBits = (bitsPerPixel - bitsLeft);
  		            n = ((buffer & bitMask) << missingBits) & bitMask;
  		            buffer = src[i++];
  		            bitsLeft = 32 - missingBits;
  		            n += (buffer >>> bitsLeft);
  		          }
  		          dest[o] = n;
  		        }
  		        return dest;
  		      },

  		      originalUnstuff2: function(src, dest, bitsPerPixel, numPixels) {
  		        var bitMask = (1 << bitsPerPixel) - 1;
  		        var i = 0, o;
  		        var bitsLeft = 0, bitPos = 0;
  		        var n, buffer, missingBits;
  		        //micro-optimizations
  		        for (o = 0; o < numPixels; o++) {
  		          if (bitsLeft === 0) {
  		            buffer = src[i++];
  		            bitsLeft = 32;
  		            bitPos = 0;
  		          }
  		          if (bitsLeft >= bitsPerPixel) {
  		            //no unsigned left shift
  		            n = ((buffer >>> bitPos) & bitMask);
  		            bitsLeft -= bitsPerPixel;
  		            bitPos += bitsPerPixel;
  		          } else {
  		            missingBits = (bitsPerPixel - bitsLeft);
  		            n = (buffer >>> bitPos) & bitMask;//((buffer & bitMask) << missingBits) & bitMask;
  		            buffer = src[i++];
  		            bitsLeft = 32 - missingBits;
  		            n |= (buffer & ((1 << missingBits) - 1)) << (bitsPerPixel - missingBits);
  		            bitPos = missingBits;
  		          }
  		          dest[o] = n;
  		        }
  		        return dest;
  		      }
  		    };

  		    /*****************************************
  		    *private static class used by Lerc2Decode
  		    ******************************************/
  		    var Lerc2Helpers = {
  		      HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, treat it like constant
  		      computeChecksumFletcher32: function(input) {

  		        var sum1 = 0xffff, sum2 = 0xffff;
  		        var len = input.length;
  		        var words = Math.floor(len / 2);
  		        var i = 0;
  		        while (words) {
  		          var tlen = (words >= 359) ? 359 : words;
  		          words -= tlen;
  		          do {
  		            sum1 += (input[i++] << 8);
  		            sum2 += sum1 += input[i++];
  		          } while (--tlen);

  		          sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  		          sum2 = (sum2 & 0xffff) + (sum2 >>> 16);
  		        }

  		        // add the straggler byte if it exists
  		        if (len & 1) {
  		          sum2 += sum1 += (input[i] << 8);
  		        }
  		        // second reduction step to reduce sums to 16 bits
  		        sum1 = (sum1 & 0xffff) + (sum1 >>> 16);
  		        sum2 = (sum2 & 0xffff) + (sum2 >>> 16);

  		        return (sum2 << 16 | sum1) >>> 0;
  		      },

  		      readHeaderInfo: function(input, data) {
  		        var ptr = data.ptr;
  		        var fileIdView = new Uint8Array(input, ptr, 6);
  		        var headerInfo = {};
  		        headerInfo.fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  		        if (headerInfo.fileIdentifierString.lastIndexOf("Lerc2", 0) !== 0) {
  		          throw "Unexpected file identifier string (expect Lerc2 ): " + headerInfo.fileIdentifierString;
  		        }
  		        ptr += 6;
  		        var view = new DataView(input, ptr, 8);
  		        var fileVersion = view.getInt32(0, true);
  		        headerInfo.fileVersion = fileVersion;
  		        ptr += 4;
  		        if (fileVersion >= 3) {
  		          headerInfo.checksum = view.getUint32(4, true); //nrows
  		          ptr += 4;
  		        }

  		        //keys start from here
  		        view = new DataView(input, ptr, 12);
  		        headerInfo.height = view.getUint32(0, true); //nrows
  		        headerInfo.width = view.getUint32(4, true); //ncols
  		        ptr += 8;
  		        if (fileVersion >= 4) {
  		          headerInfo.numDims = view.getUint32(8, true);
  		          ptr += 4;
  		        }
  		        else {
  		          headerInfo.numDims = 1;
  		        }

  		        view = new DataView(input, ptr, 40);
  		        headerInfo.numValidPixel = view.getUint32(0, true);
  		        headerInfo.microBlockSize = view.getInt32(4, true);
  		        headerInfo.blobSize = view.getInt32(8, true);
  		        headerInfo.imageType = view.getInt32(12, true);

  		        headerInfo.maxZError = view.getFloat64(16, true);
  		        headerInfo.zMin = view.getFloat64(24, true);
  		        headerInfo.zMax = view.getFloat64(32, true);
  		        ptr += 40;
  		        data.headerInfo = headerInfo;
  		        data.ptr = ptr;

  		        var checksum, keyLength;
  		        if (fileVersion >= 3) {
  		          keyLength = fileVersion >= 4 ? 52 : 48;
  		          checksum = this.computeChecksumFletcher32(new Uint8Array(input, ptr - keyLength, headerInfo.blobSize - 14));
  		          if (checksum !== headerInfo.checksum) {
  		            throw "Checksum failed.";
  		          }
  		        }
  		        return true;
  		      },

  		      checkMinMaxRanges: function(input, data) {
  		        var headerInfo = data.headerInfo;
  		        var OutPixelTypeArray = this.getDataTypeArray(headerInfo.imageType);
  		        var rangeBytes = headerInfo.numDims * this.getDataTypeSize(headerInfo.imageType);
  		        var minValues = this.readSubArray(input, data.ptr, OutPixelTypeArray, rangeBytes);
  		        var maxValues = this.readSubArray(input, data.ptr + rangeBytes, OutPixelTypeArray, rangeBytes);
  		        data.ptr += (2 * rangeBytes);
  		        var i, equal = true;
  		        for (i = 0; i < headerInfo.numDims; i++) {
  		          if (minValues[i] !== maxValues[i]) {
  		            equal = false;
  		            break;
  		          }
  		        }
  		        headerInfo.minValues = minValues;
  		        headerInfo.maxValues = maxValues;
  		        return equal;
  		      },

  		      readSubArray: function(input, ptr, OutPixelTypeArray, numBytes) {
  		        var rawData;
  		        if (OutPixelTypeArray === Uint8Array) {
  		          rawData = new Uint8Array(input, ptr, numBytes);
  		        }
  		        else {
  		          var arrayBuf = new ArrayBuffer(numBytes);
  		          var store8 = new Uint8Array(arrayBuf);
  		          store8.set(new Uint8Array(input, ptr, numBytes));
  		          rawData = new OutPixelTypeArray(arrayBuf);
  		        }
  		        return rawData;
  		      },

  		      readMask: function(input, data) {
  		        var ptr = data.ptr;
  		        var headerInfo = data.headerInfo;
  		        var numPixels = headerInfo.width * headerInfo.height;
  		        var numValidPixel = headerInfo.numValidPixel;

  		        var view = new DataView(input, ptr, 4);
  		        var mask = {};
  		        mask.numBytes = view.getUint32(0, true);
  		        ptr += 4;

  		        // Mask Data
  		        if ((0 === numValidPixel || numPixels === numValidPixel) && 0 !== mask.numBytes) {
  		          throw ("invalid mask");
  		        }
  		        var bitset, resultMask;
  		        if (numValidPixel === 0) {
  		          bitset = new Uint8Array(Math.ceil(numPixels / 8));
  		          mask.bitset = bitset;
  		          resultMask = new Uint8Array(numPixels);
  		          data.pixels.resultMask = resultMask;
  		          ptr += mask.numBytes;
  		        }// ????? else if (data.mask.numBytes > 0 && data.mask.numBytes< data.numValidPixel) {
  		        else if (mask.numBytes > 0) {
  		          bitset = new Uint8Array(Math.ceil(numPixels / 8));
  		          view = new DataView(input, ptr, mask.numBytes);
  		          var cnt = view.getInt16(0, true);
  		          var ip = 2, op = 0, val = 0;
  		          do {
  		            if (cnt > 0) {
  		              while (cnt--) { bitset[op++] = view.getUint8(ip++); }
  		            } else {
  		              val = view.getUint8(ip++);
  		              cnt = -cnt;
  		              while (cnt--) { bitset[op++] = val; }
  		            }
  		            cnt = view.getInt16(ip, true);
  		            ip += 2;
  		          } while (ip < mask.numBytes);
  		          if ((cnt !== -32768) || (op < bitset.length)) {
  		            throw "Unexpected end of mask RLE encoding";
  		          }

  		          resultMask = new Uint8Array(numPixels);
  		          var mb = 0, k = 0;

  		          for (k = 0; k < numPixels; k++) {
  		            if (k & 7) {
  		              mb = bitset[k >> 3];
  		              mb <<= k & 7;
  		            }
  		            else {
  		              mb = bitset[k >> 3];
  		            }
  		            if (mb & 128) {
  		              resultMask[k] = 1;
  		            }
  		          }
  		          data.pixels.resultMask = resultMask;

  		          mask.bitset = bitset;
  		          ptr += mask.numBytes;
  		        }
  		        data.ptr = ptr;
  		        data.mask = mask;
  		        return true;
  		      },

  		      readDataOneSweep: function(input, data, OutPixelTypeArray, useBSQForOutputDim) {
  		        var ptr = data.ptr;
  		        var headerInfo = data.headerInfo;
  		        var numDims = headerInfo.numDims;
  		        var numPixels = headerInfo.width * headerInfo.height;
  		        var imageType = headerInfo.imageType;
  		        var numBytes = headerInfo.numValidPixel * Lerc2Helpers.getDataTypeSize(imageType) * numDims;
  		        //data.pixels.numBytes = numBytes;
  		        var rawData;
  		        var mask = data.pixels.resultMask;
  		        if (OutPixelTypeArray === Uint8Array) {
  		          rawData = new Uint8Array(input, ptr, numBytes);
  		        }
  		        else {
  		          var arrayBuf = new ArrayBuffer(numBytes);
  		          var store8 = new Uint8Array(arrayBuf);
  		          store8.set(new Uint8Array(input, ptr, numBytes));
  		          rawData = new OutPixelTypeArray(arrayBuf);
  		        }
  		        if (rawData.length === numPixels * numDims) {
  		          if (useBSQForOutputDim) {
  		            data.pixels.resultPixels = Lerc2Helpers.swapDimensionOrder(rawData, numPixels, numDims, OutPixelTypeArray, true);
  		          }
  		          else {
  		            data.pixels.resultPixels = rawData;
  		          }
  		        }
  		        else  //mask
  		        {
  		          data.pixels.resultPixels = new OutPixelTypeArray(numPixels * numDims);
  		          var z = 0, k = 0, i = 0, nStart = 0;
  		          if (numDims > 1) {
  		            if (useBSQForOutputDim) {
  		              for (k = 0; k < numPixels; k++) {
  		                if (mask[k]) {
  		                  nStart = k;
  		                  for (i = 0; i < numDims; i++, nStart+=numPixels) {
  		                    data.pixels.resultPixels[nStart] = rawData[z++];
  		                  }
  		                }
  		              }
  		            }
  		            else {
  		              for (k = 0; k < numPixels; k++) {
  		                if (mask[k]) {
  		                  nStart = k * numDims;
  		                  for (i = 0; i < numDims; i++) {
  		                    data.pixels.resultPixels[nStart + i] = rawData[z++];
  		                  }
  		                }
  		              }
  		            }
  		          }
  		          else {
  		            for (k = 0; k < numPixels; k++) {
  		              if (mask[k]) {
  		                data.pixels.resultPixels[k] = rawData[z++];
  		              }
  		            }
  		          }
  		        }
  		        ptr += numBytes;
  		        data.ptr = ptr;       //return data;
  		        return true;
  		      },

  		      readHuffmanTree: function(input, data) {
  		        var BITS_MAX = this.HUFFMAN_LUT_BITS_MAX; //8 is slow for the large test image
  		        //var size_max = 1 << BITS_MAX;
  		        /* ************************
  		        * reading code table
  		        *************************/
  		        var view = new DataView(input, data.ptr, 16);
  		        data.ptr += 16;
  		        var version = view.getInt32(0, true);
  		        if (version < 2) {
  		          throw "unsupported Huffman version";
  		        }
  		        var size = view.getInt32(4, true);
  		        var i0 = view.getInt32(8, true);
  		        var i1 = view.getInt32(12, true);
  		        if (i0 >= i1) {
  		          return false;
  		        }
  		        var blockDataBuffer = new Uint32Array(i1 - i0);
  		        Lerc2Helpers.decodeBits(input, data, blockDataBuffer);
  		        var codeTable = []; //size
  		        var i, j, k, len;

  		        for (i = i0; i < i1; i++) {
  		          j = i - (i < size ? 0 : size);//wrap around
  		          codeTable[j] = { first: blockDataBuffer[i - i0], second: null };
  		        }

  		        var dataBytes = input.byteLength - data.ptr;
  		        var dataWords = Math.ceil(dataBytes / 4);
  		        var arrayBuf = new ArrayBuffer(dataWords * 4);
  		        var store8 = new Uint8Array(arrayBuf);
  		        store8.set(new Uint8Array(input, data.ptr, dataBytes));
  		        var stuffedData = new Uint32Array(arrayBuf); //must start from x*4
  		        var bitPos = 0, word, srcPtr = 0;
  		        word = stuffedData[0];
  		        for (i = i0; i < i1; i++) {
  		          j = i - (i < size ? 0 : size);//wrap around
  		          len = codeTable[j].first;
  		          if (len > 0) {
  		            codeTable[j].second = (word << bitPos) >>> (32 - len);

  		            if (32 - bitPos >= len) {
  		              bitPos += len;
  		              if (bitPos === 32) {
  		                bitPos = 0;
  		                srcPtr++;
  		                word = stuffedData[srcPtr];
  		              }
  		            }
  		            else {
  		              bitPos += len - 32;
  		              srcPtr++;
  		              word = stuffedData[srcPtr];
  		              codeTable[j].second |= word >>> (32 - bitPos);
  		            }
  		          }
  		        }

  		        //finished reading code table

  		        /* ************************
  		        * building lut
  		        *************************/
  		        var numBitsLUT = 0, numBitsLUTQick = 0;
  		        var tree = new TreeNode();
  		        for (i = 0; i < codeTable.length; i++) {
  		          if (codeTable[i] !== undefined) {
  		            numBitsLUT = Math.max(numBitsLUT, codeTable[i].first);
  		          }
  		        }
  		        if (numBitsLUT >= BITS_MAX) {
  		          numBitsLUTQick = BITS_MAX;
  		        }
  		        else {
  		          numBitsLUTQick = numBitsLUT;
  		        }
  		        // for debugging purpose
  		        // if (numBitsLUT >= 30) {
  		        //   console.log("WARning, large NUM LUT BITS IS " + numBitsLUT);
  		        // }
  		        var decodeLut = [], entry, code, numEntries, jj, currentBit, node;
  		        for (i = i0; i < i1; i++) {
  		          j = i - (i < size ? 0 : size);//wrap around
  		          len = codeTable[j].first;
  		          if (len > 0) {
  		            entry = [len, j];
  		            if (len <= numBitsLUTQick) {
  		              code = codeTable[j].second << (numBitsLUTQick - len);
  		              numEntries = 1 << (numBitsLUTQick - len);
  		              for (k = 0; k < numEntries; k++) {
  		                decodeLut[code | k] = entry;
  		              }
  		            }
  		            else {
  		              //build tree
  		              code = codeTable[j].second;
  		              node = tree;
  		              for (jj = len - 1; jj >= 0; jj--) {
  		                currentBit = code >>> jj & 1; //no left shift as length could be 30,31
  		                if (currentBit) {
  		                  if (!node.right) {
  		                    node.right = new TreeNode();
  		                  }
  		                  node = node.right;
  		                }
  		                else {
  		                  if (!node.left) {
  		                    node.left = new TreeNode();
  		                  }
  		                  node = node.left;
  		                }
  		                if (jj === 0 && !node.val) {
  		                  node.val = entry[1];
  		                }
  		              }
  		            }
  		          }
  		        }
  		        return {
  		          decodeLut: decodeLut,
  		          numBitsLUTQick: numBitsLUTQick,
  		          numBitsLUT: numBitsLUT,
  		          tree: tree,
  		          stuffedData: stuffedData,
  		          srcPtr: srcPtr,
  		          bitPos: bitPos
  		        };
  		      },

  		      readHuffman: function(input, data, OutPixelTypeArray, useBSQForOutputDim) {
  		        var headerInfo = data.headerInfo;
  		        var numDims = headerInfo.numDims;
  		        var height = data.headerInfo.height;
  		        var width = data.headerInfo.width;
  		        var numPixels = width * height;
  		        //var size_max = 1 << BITS_MAX;
  		        /* ************************
  		        * reading huffman structure info
  		        *************************/
  		        var huffmanInfo = this.readHuffmanTree(input, data);
  		        var decodeLut = huffmanInfo.decodeLut;
  		        var tree = huffmanInfo.tree;
  		        //stuffedData includes huffman headers
  		        var stuffedData = huffmanInfo.stuffedData;
  		        var srcPtr = huffmanInfo.srcPtr;
  		        var bitPos = huffmanInfo.bitPos;
  		        var numBitsLUTQick = huffmanInfo.numBitsLUTQick;
  		        var numBitsLUT = huffmanInfo.numBitsLUT;
  		        var offset = data.headerInfo.imageType === 0 ? 128 : 0;
  		        /*************************
  		        *  decode
  		        ***************************/
  		        var node, val, delta, mask = data.pixels.resultMask, valTmp, valTmpQuick, currentBit;
  		        var i, j, k, ii;
  		        var prevVal = 0;
  		        if (bitPos > 0) {
  		          srcPtr++;
  		          bitPos = 0;
  		        }
  		        var word = stuffedData[srcPtr];
  		        var deltaEncode = data.encodeMode === 1;
  		        var resultPixelsAllDim = new OutPixelTypeArray(numPixels * numDims);
  		        var resultPixels = resultPixelsAllDim;
  		        var iDim;
  		        // TODO: reevaluate the need to keep inlined decoding code as IE support is phasing out
  		        if (numDims < 2 || deltaEncode) {
  		          for (iDim = 0; iDim < numDims; iDim++) {
  		            if (numDims > 1) {
  		              //get the mem block of current dimension
  		              resultPixels = new OutPixelTypeArray(resultPixelsAllDim.buffer, numPixels * iDim, numPixels);
  		              prevVal = 0;
  		            }
  		            if (data.headerInfo.numValidPixel === width * height) { //all valid
  		              for (k = 0, i = 0; i < height; i++) {
  		                for (j = 0; j < width; j++, k++) {
  		                  val = 0;
  		                  valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  		                  valTmpQuick = valTmp;// >>> deltaBits;
  		                  if (32 - bitPos < numBitsLUTQick) {
  		                    valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  		                    valTmpQuick = valTmp;// >>> deltaBits;
  		                  }
  		                  if (decodeLut[valTmpQuick])    // if there, move the correct number of bits and done
  		                  {
  		                    val = decodeLut[valTmpQuick][1];
  		                    bitPos += decodeLut[valTmpQuick][0];
  		                  }
  		                  else {
  		                    valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  		                    valTmpQuick = valTmp;// >>> deltaBits;
  		                    if (32 - bitPos < numBitsLUT) {
  		                      valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  		                      valTmpQuick = valTmp;// >>> deltaBits;
  		                    }
  		                    node = tree;
  		                    for (ii = 0; ii < numBitsLUT; ii++) {
  		                      currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  		                      node = currentBit ? node.right : node.left;
  		                      if (!(node.left || node.right)) {
  		                        val = node.val;
  		                        bitPos = bitPos + ii + 1;
  		                        break;
  		                      }
  		                    }
  		                  }
  		    
  		                  if (bitPos >= 32) {
  		                    bitPos -= 32;
  		                    srcPtr++;
  		                    word = stuffedData[srcPtr];
  		                  }
  		    
  		                  delta = val - offset;
  		                  if (deltaEncode) {
  		                    if (j > 0) {
  		                      delta += prevVal;    // use overflow
  		                    }
  		                    else if (i > 0) {
  		                      delta += resultPixels[k - width];
  		                    }
  		                    else {
  		                      delta += prevVal;
  		                    }
  		                    delta &= 0xFF; //overflow
  		                    resultPixels[k] = delta;//overflow
  		                    prevVal = delta;
  		                  }
  		                  else {
  		                    resultPixels[k] = delta;
  		                  }
  		                }
  		              }
  		            }
  		            else { //not all valid, use mask
  		              for (k = 0, i = 0; i < height; i++) {
  		                for (j = 0; j < width; j++, k++) {
  		                  if (mask[k]) {
  		                    val = 0;
  		                    valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  		                    valTmpQuick = valTmp;// >>> deltaBits;
  		                    if (32 - bitPos < numBitsLUTQick) {
  		                      valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  		                      valTmpQuick = valTmp;// >>> deltaBits;
  		                    }
  		                    if (decodeLut[valTmpQuick])    // if there, move the correct number of bits and done
  		                    {
  		                      val = decodeLut[valTmpQuick][1];
  		                      bitPos += decodeLut[valTmpQuick][0];
  		                    }
  		                    else {
  		                      valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  		                      valTmpQuick = valTmp;// >>> deltaBits;
  		                      if (32 - bitPos < numBitsLUT) {
  		                        valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  		                        valTmpQuick = valTmp;// >>> deltaBits;
  		                      }
  		                      node = tree;
  		                      for (ii = 0; ii < numBitsLUT; ii++) {
  		                        currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  		                        node = currentBit ? node.right : node.left;
  		                        if (!(node.left || node.right)) {
  		                          val = node.val;
  		                          bitPos = bitPos + ii + 1;
  		                          break;
  		                        }
  		                      }
  		                    }
  		    
  		                    if (bitPos >= 32) {
  		                      bitPos -= 32;
  		                      srcPtr++;
  		                      word = stuffedData[srcPtr];
  		                    }
  		    
  		                    delta = val - offset;
  		                    if (deltaEncode) {
  		                      if (j > 0 && mask[k - 1]) {
  		                        delta += prevVal;    // use overflow
  		                      }
  		                      else if (i > 0 && mask[k - width]) {
  		                        delta += resultPixels[k - width];
  		                      }
  		                      else {
  		                        delta += prevVal;
  		                      }
  		    
  		                      delta &= 0xFF; //overflow
  		                      resultPixels[k] = delta;//overflow
  		                      prevVal = delta;
  		                    }
  		                    else {
  		                      resultPixels[k] = delta;
  		                    }
  		                  }
  		                }
  		              }
  		            }
  		          }
  		        }
  		        else {
  		          for (k = 0, i = 0; i < height; i++) {
  		            for (j = 0; j < width; j++) {
  		              k = i * width + j;
  		              if (!mask || mask[k]) {
  		                for (iDim = 0; iDim < numDims; iDim++, k+=numPixels) {
  		                  val = 0;
  		                  valTmp = (word << bitPos) >>> (32 - numBitsLUTQick);
  		                  valTmpQuick = valTmp;
  		                  if (32 - bitPos < numBitsLUTQick) {
  		                    valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUTQick));
  		                    valTmpQuick = valTmp;
  		                  }
  		                  if (decodeLut[valTmpQuick])
  		                  {
  		                    val = decodeLut[valTmpQuick][1];
  		                    bitPos += decodeLut[valTmpQuick][0];
  		                  }
  		                  else {
  		                    valTmp = (word << bitPos) >>> (32 - numBitsLUT);
  		                    valTmpQuick = valTmp;
  		                    if (32 - bitPos < numBitsLUT) {
  		                      valTmp |= ((stuffedData[srcPtr + 1]) >>> (64 - bitPos - numBitsLUT));
  		                      valTmpQuick = valTmp;
  		                    }
  		                    node = tree;
  		                    for (ii = 0; ii < numBitsLUT; ii++) {
  		                      currentBit = valTmp >>> (numBitsLUT - ii - 1) & 1;
  		                      node = currentBit ? node.right : node.left;
  		                      if (!(node.left || node.right)) {
  		                        val = node.val;
  		                        bitPos = bitPos + ii + 1;
  		                        break;
  		                      }
  		                    }
  		                  }

  		                  if (bitPos >= 32) {
  		                    bitPos -= 32;
  		                    srcPtr++;
  		                    word = stuffedData[srcPtr];
  		                  }

  		                  delta = val - offset;
  		                  resultPixels[k] = delta;
  		                }
  		              }
  		            }
  		          }
  		        }
  		        data.ptr = data.ptr + (srcPtr + 1) * 4 + (bitPos > 0 ? 4 : 0);
  		        data.pixels.resultPixels = resultPixelsAllDim;
  		        //swap for BIP layout
  		        if (numDims > 1 && !useBSQForOutputDim) {
  		          data.pixels.resultPixels = Lerc2Helpers.swapDimensionOrder(resultPixelsAllDim, numPixels, numDims, OutPixelTypeArray);
  		        }
  		      },

  		      decodeBits: function(input, data, blockDataBuffer, offset, iDim) {
  		        {
  		          //bitstuff encoding is 3
  		          var headerInfo = data.headerInfo;
  		          var fileVersion = headerInfo.fileVersion;
  		          //var block = {};
  		          var blockPtr = 0;
  		          var viewByteLength = ((input.byteLength - data.ptr) >= 5) ? 5 : (input.byteLength - data.ptr);
  		          var view = new DataView(input, data.ptr, viewByteLength);
  		          var headerByte = view.getUint8(0);
  		          blockPtr++;
  		          var bits67 = headerByte >> 6;
  		          var n = (bits67 === 0) ? 4 : 3 - bits67;
  		          var doLut = (headerByte & 32) > 0 ? true : false;//5th bit
  		          var numBits = headerByte & 31;
  		          var numElements = 0;
  		          if (n === 1) {
  		            numElements = view.getUint8(blockPtr); blockPtr++;
  		          } else if (n === 2) {
  		            numElements = view.getUint16(blockPtr, true); blockPtr += 2;
  		          } else if (n === 4) {
  		            numElements = view.getUint32(blockPtr, true); blockPtr += 4;
  		          } else {
  		            throw "Invalid valid pixel count type";
  		          }
  		          //fix: huffman codes are bit stuffed, but not bound by data's max value, so need to use originalUnstuff
  		          //offset = offset || 0;
  		          var scale = 2 * headerInfo.maxZError;
  		          var stuffedData, arrayBuf, store8, dataBytes, dataWords;
  		          var lutArr, lutData, lutBytes, bitsPerPixel;
  		          var zMax = headerInfo.numDims > 1 ? headerInfo.maxValues[iDim] : headerInfo.zMax;
  		          if (doLut) {
  		            data.counter.lut++;
  		            lutBytes = view.getUint8(blockPtr);
  		            blockPtr++;
  		            dataBytes = Math.ceil((lutBytes - 1) * numBits / 8);
  		            dataWords = Math.ceil(dataBytes / 4);
  		            arrayBuf = new ArrayBuffer(dataWords * 4);
  		            store8 = new Uint8Array(arrayBuf);

  		            data.ptr += blockPtr;
  		            store8.set(new Uint8Array(input, data.ptr, dataBytes));

  		            lutData = new Uint32Array(arrayBuf);
  		            data.ptr += dataBytes;

  		            bitsPerPixel = 0;
  		            while ((lutBytes - 1) >>> bitsPerPixel) {
  		              bitsPerPixel++;
  		            }
  		            dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  		            dataWords = Math.ceil(dataBytes / 4);
  		            arrayBuf = new ArrayBuffer(dataWords * 4);
  		            store8 = new Uint8Array(arrayBuf);
  		            store8.set(new Uint8Array(input, data.ptr, dataBytes));
  		            stuffedData = new Uint32Array(arrayBuf);
  		            data.ptr += dataBytes;
  		            if (fileVersion >= 3) {
  		              lutArr = BitStuffer.unstuffLUT2(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  		            }
  		            else {
  		              lutArr = BitStuffer.unstuffLUT(lutData, numBits, lutBytes - 1, offset, scale, zMax);
  		            }
  		            //lutArr.unshift(0);
  		            if (fileVersion >= 3) {
  		              //BitStuffer.unstuff2(block, blockDataBuffer, headerInfo.zMax);
  		              BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  		            }
  		            else {
  		              BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, lutArr);
  		            }
  		          }
  		          else {
  		            //console.debug("bitstuffer");
  		            data.counter.bitstuffer++;
  		            bitsPerPixel = numBits;
  		            data.ptr += blockPtr;
  		            if (bitsPerPixel > 0) {
  		              dataBytes = Math.ceil(numElements * bitsPerPixel / 8);
  		              dataWords = Math.ceil(dataBytes / 4);
  		              arrayBuf = new ArrayBuffer(dataWords * 4);
  		              store8 = new Uint8Array(arrayBuf);
  		              store8.set(new Uint8Array(input, data.ptr, dataBytes));
  		              stuffedData = new Uint32Array(arrayBuf);
  		              data.ptr += dataBytes;
  		              if (fileVersion >= 3) {
  		                if (offset == null) {
  		                  BitStuffer.originalUnstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  		                }
  		                else {
  		                  BitStuffer.unstuff2(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  		                }
  		              }
  		              else {
  		                if (offset == null) {
  		                  BitStuffer.originalUnstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements);
  		                }
  		                else {
  		                  BitStuffer.unstuff(stuffedData, blockDataBuffer, bitsPerPixel, numElements, false, offset, scale, zMax);
  		                }
  		              }
  		            }
  		          }
  		        }

  		      },

  		      readTiles: function(input, data, OutPixelTypeArray, useBSQForOutputDim) {
  		        var headerInfo = data.headerInfo;
  		        var width = headerInfo.width;
  		        var height = headerInfo.height;
  		        var numPixels = width * height;
  		        var microBlockSize = headerInfo.microBlockSize;
  		        var imageType = headerInfo.imageType;
  		        var dataTypeSize = Lerc2Helpers.getDataTypeSize(imageType);
  		        var numBlocksX = Math.ceil(width / microBlockSize);
  		        var numBlocksY = Math.ceil(height / microBlockSize);
  		        data.pixels.numBlocksY = numBlocksY;
  		        data.pixels.numBlocksX = numBlocksX;
  		        data.pixels.ptr = 0;
  		        var row = 0, col = 0, blockY = 0, blockX = 0, thisBlockHeight = 0, thisBlockWidth = 0, bytesLeft = 0, headerByte = 0, bits67 = 0, testCode = 0, outPtr = 0, outStride = 0, numBytes = 0, bytesleft = 0, z = 0, blockPtr = 0;
  		        var view, block, arrayBuf, store8, rawData;
  		        var blockEncoding;
  		        var blockDataBuffer = new OutPixelTypeArray(microBlockSize * microBlockSize);
  		        var lastBlockHeight = (height % microBlockSize) || microBlockSize;
  		        var lastBlockWidth = (width % microBlockSize) || microBlockSize;
  		        var offsetType, offset;
  		        var numDims = headerInfo.numDims, iDim;
  		        var mask = data.pixels.resultMask;
  		        var resultPixels = data.pixels.resultPixels;
  		        var fileVersion = headerInfo.fileVersion;
  		        var fileVersionCheckNum = fileVersion >= 5 ? 14 : 15;
  		        var isDiffEncoding;
  		        var zMax = headerInfo.zMax;
  		        //var resultPixelsAllDim = resultPixels;
  		        var resultPixelsPrevDim;
  		        for (blockY = 0; blockY < numBlocksY; blockY++) {
  		          thisBlockHeight = (blockY !== numBlocksY - 1) ? microBlockSize : lastBlockHeight;
  		          for (blockX = 0; blockX < numBlocksX; blockX++) {
  		            //console.debug("y" + blockY + " x" + blockX);
  		            thisBlockWidth = (blockX !== numBlocksX - 1) ? microBlockSize : lastBlockWidth;

  		            outPtr = blockY * width * microBlockSize + blockX * microBlockSize;
  		            outStride = width - thisBlockWidth;

  		            for (iDim = 0; iDim < numDims; iDim++) {
  		              if (numDims > 1) {
  		                resultPixelsPrevDim = resultPixels;
  		                outPtr = blockY * width * microBlockSize + blockX * microBlockSize;
  		                resultPixels = new OutPixelTypeArray(data.pixels.resultPixels.buffer, numPixels * iDim * dataTypeSize, numPixels);
  		                zMax = headerInfo.maxValues[iDim];
  		              } else {
  		                resultPixelsPrevDim = null;
  		              }
  		              bytesLeft = input.byteLength - data.ptr;
  		              view = new DataView(input, data.ptr, Math.min(10, bytesLeft));
  		              block = {};
  		              blockPtr = 0;
  		              headerByte = view.getUint8(0);
  		              blockPtr++;
  		              isDiffEncoding = headerInfo.fileVersion >= 5 ? headerByte & 4 : 0;
  		              bits67 = (headerByte >> 6) & 0xFF;
  		              testCode = (headerByte >> 2) & fileVersionCheckNum;    // use bits 2345 for integrity check
  		              if (testCode !== (((blockX * microBlockSize) >> 3) & fileVersionCheckNum)) {
  		                throw "integrity issue";
  		              }

  		              if (isDiffEncoding && iDim === 0) {
  		                throw "integrity issue";
  		              }

  		              blockEncoding = headerByte & 3;
  		              if (blockEncoding > 3) {
  		                data.ptr += blockPtr;
  		                throw "Invalid block encoding (" + blockEncoding + ")";
  		              }
  		              else if (blockEncoding === 2) { //constant 0
  		                if (isDiffEncoding) {
  		                  if (mask) {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        if (mask[outPtr]) {
  		                          resultPixels[outPtr] = resultPixelsPrevDim[outPtr];
  		                        }
  		                        outPtr++;
  		                      }
  		                    }
  		                  }
  		                  else {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        resultPixels[outPtr] = resultPixelsPrevDim[outPtr];
  		                        outPtr++;
  		                      }
  		                    }
  		                  }
  		                }
  		                data.counter.constant++;
  		                data.ptr += blockPtr;
  		                continue;
  		              }
  		              else if (blockEncoding === 0) {  //uncompressed
  		                if (isDiffEncoding) {
  		                  // doesn't make sense, should not happen
  		                  throw "integrity issue";
  		                }
  		                data.counter.uncompressed++;
  		                data.ptr += blockPtr;
  		                numBytes = thisBlockHeight * thisBlockWidth * dataTypeSize;
  		                bytesleft = input.byteLength - data.ptr;
  		                numBytes = numBytes < bytesleft ? numBytes : bytesleft;
  		                //bit alignment
  		                arrayBuf = new ArrayBuffer((numBytes % dataTypeSize) === 0 ? numBytes : (numBytes + dataTypeSize - numBytes % dataTypeSize));
  		                store8 = new Uint8Array(arrayBuf);
  		                store8.set(new Uint8Array(input, data.ptr, numBytes));
  		                rawData = new OutPixelTypeArray(arrayBuf);
  		                z = 0;
  		                if (mask) {
  		                  for (row = 0; row < thisBlockHeight; row++) {
  		                    for (col = 0; col < thisBlockWidth; col++) {
  		                      if (mask[outPtr]) {
  		                        resultPixels[outPtr] = rawData[z++];
  		                      }
  		                      outPtr++;
  		                    }
  		                    outPtr += outStride;
  		                  }
  		                }
  		                else {//all valid
  		                  for (row = 0; row < thisBlockHeight; row++) {
  		                    for (col = 0; col < thisBlockWidth; col++) {
  		                      resultPixels[outPtr++] = rawData[z++];
  		                    }
  		                    outPtr += outStride;
  		                  }
  		                }
  		                data.ptr += z * dataTypeSize;
  		              }
  		              else { //1 or 3
  		                offsetType = Lerc2Helpers.getDataTypeUsed((isDiffEncoding && imageType < 6) ? 4 : imageType, bits67);
  		                offset = Lerc2Helpers.getOnePixel(block, blockPtr, offsetType, view);
  		                blockPtr += Lerc2Helpers.getDataTypeSize(offsetType);
  		                if (blockEncoding === 3) //constant offset value
  		                {
  		                  data.ptr += blockPtr;
  		                  data.counter.constantoffset++;
  		                  //you can delete the following resultMask case in favor of performance because val is constant and users use nodata mask, otherwise nodatavalue post processing handles it too.
  		                  //while the above statement is true, we're not doing it as we want to keep invalid pixel value at 0 rather than arbitrary values
  		                  if (mask) {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        if (mask[outPtr]) {
  		                          resultPixels[outPtr] = isDiffEncoding ? Math.min(zMax, resultPixelsPrevDim[outPtr] + offset) : offset;
  		                        }
  		                        outPtr++;
  		                      }
  		                      outPtr += outStride;
  		                    }
  		                  }
  		                  else {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        resultPixels[outPtr] = isDiffEncoding ? Math.min(zMax, resultPixelsPrevDim[outPtr] + offset) : offset;
  		                        outPtr++;
  		                      }
  		                      outPtr += outStride;
  		                    }
  		                  }
  		                }
  		                else { //bitstuff encoding is 3
  		                  data.ptr += blockPtr;
  		                  //heavy lifting
  		                  Lerc2Helpers.decodeBits(input, data, blockDataBuffer, offset, iDim);
  		                  blockPtr = 0;
  		                  // duplicate code to favor performance, diff encoding is for multidimension only
  		                  if (isDiffEncoding) {
  		                    if (mask) {
  		                      for (row = 0; row < thisBlockHeight; row++) {
  		                        for (col = 0; col < thisBlockWidth; col++) {
  		                          if (mask[outPtr]) {
  		                            resultPixels[outPtr] = blockDataBuffer[blockPtr++] + resultPixelsPrevDim[outPtr];
  		                          }
  		                          outPtr++;
  		                        }
  		                        outPtr += outStride;
  		                      }
  		                    }
  		                    else {
  		                      for (row = 0; row < thisBlockHeight; row++) {
  		                        for (col = 0; col < thisBlockWidth; col++) {
  		                          resultPixels[outPtr] = blockDataBuffer[blockPtr++] + resultPixelsPrevDim[outPtr];
  		                          outPtr++;
  		                        }
  		                        outPtr += outStride;
  		                      }
  		                    }
  		                  }
  		                  else if (mask) {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        if (mask[outPtr]) {
  		                          resultPixels[outPtr] = blockDataBuffer[blockPtr++];
  		                        }
  		                        outPtr++;
  		                      }
  		                      outPtr += outStride;
  		                    }
  		                  }
  		                  else {
  		                    for (row = 0; row < thisBlockHeight; row++) {
  		                      for (col = 0; col < thisBlockWidth; col++) {
  		                        resultPixels[outPtr++] = blockDataBuffer[blockPtr++];
  		                      }
  		                      outPtr += outStride;
  		                    }
  		                  }
  		                }
  		              }
  		            }
  		          }
  		        }
  		        //swap for BIP: it's always easier for clients to handle BSQ so we keep existing logic and introduce a swap here to minimze changes
  		        if (numDims > 1 && !useBSQForOutputDim) {
  		          data.pixels.resultPixels = Lerc2Helpers.swapDimensionOrder(data.pixels.resultPixels, numPixels, numDims, OutPixelTypeArray);
  		        }
  		      },

  		      /*****************
  		      *  private methods (helper methods)
  		      *****************/

  		      formatFileInfo: function(data) {
  		        return {
  		          "fileIdentifierString": data.headerInfo.fileIdentifierString,
  		          "fileVersion": data.headerInfo.fileVersion,
  		          "imageType": data.headerInfo.imageType,
  		          "height": data.headerInfo.height,
  		          "width": data.headerInfo.width,
  		          "numValidPixel": data.headerInfo.numValidPixel,
  		          "microBlockSize": data.headerInfo.microBlockSize,
  		          "blobSize": data.headerInfo.blobSize,
  		          "maxZError": data.headerInfo.maxZError,
  		          "pixelType": Lerc2Helpers.getPixelType(data.headerInfo.imageType),
  		          "eofOffset": data.eofOffset,
  		          "mask": data.mask ? {
  		            "numBytes": data.mask.numBytes
  		          } : null,
  		          "pixels": {
  		            "numBlocksX": data.pixels.numBlocksX,
  		            "numBlocksY": data.pixels.numBlocksY,
  		            //"numBytes": data.pixels.numBytes,
  		            "maxValue": data.headerInfo.zMax,
  		            "minValue": data.headerInfo.zMin,
  		            "noDataValue": data.noDataValue
  		          }
  		        };
  		      },

  		      constructConstantSurface: function(data, useBSQForOutputDim) {
  		        var val = data.headerInfo.zMax;
  		        var valMin = data.headerInfo.zMin;
  		        var maxValues = data.headerInfo.maxValues;
  		        var numDims = data.headerInfo.numDims;
  		        var numPixels = data.headerInfo.height * data.headerInfo.width;
  		        var i = 0, k = 0, nStart = 0;
  		        var mask = data.pixels.resultMask;
  		        var resultPixels = data.pixels.resultPixels;
  		        if (mask) {
  		          if (numDims > 1) {
  		            if (useBSQForOutputDim) {
  		              for (i = 0; i < numDims; i++) {
  		                nStart = i * numPixels;
  		                val = maxValues[i];
  		                for (k = 0; k < numPixels; k++) {
  		                  if (mask[k]) {
  		                    resultPixels[nStart + k] = val;
  		                  }
  		                }
  		              }  
  		            }
  		            else {
  		              for (k = 0; k < numPixels; k++) {
  		                if (mask[k]) {
  		                  nStart = k * numDims;
  		                  for (i = 0; i < numDims; i++) {
  		                    resultPixels[nStart + numDims] = maxValues[i];
  		                  }
  		                }
  		              }
  		            }
  		          }
  		          else {
  		            for (k = 0; k < numPixels; k++) {
  		              if (mask[k]) {
  		                resultPixels[k] = val;
  		              }
  		            }
  		          }
  		        }
  		        else {
  		          if (numDims > 1 && valMin !== val) {
  		            if (useBSQForOutputDim) {
  		              for (i = 0; i < numDims; i++) {
  		                nStart = i * numPixels;
  		                val = maxValues[i];
  		                for (k = 0; k < numPixels; k++) {
  		                  resultPixels[nStart + k] = val;
  		                }
  		              }
  		            }
  		            else {
  		              for (k = 0; k < numPixels; k++) {
  		                nStart = k * numDims;
  		                for (i = 0; i < numDims; i++) {
  		                  resultPixels[nStart + i] = maxValues[i];
  		                }
  		              }
  		            }
  		          }
  		          else {
  		            for (k = 0; k < numPixels * numDims; k++) {
  		              resultPixels[k] = val;
  		            }
  		          }
  		        }
  		        return;
  		      },

  		      getDataTypeArray: function(t) {
  		        var tp;
  		        switch (t) {
  		          case 0: //char
  		            tp = Int8Array;
  		            break;
  		          case 1: //byte
  		            tp = Uint8Array;
  		            break;
  		          case 2: //short
  		            tp = Int16Array;
  		            break;
  		          case 3: //ushort
  		            tp = Uint16Array;
  		            break;
  		          case 4:
  		            tp = Int32Array;
  		            break;
  		          case 5:
  		            tp = Uint32Array;
  		            break;
  		          case 6:
  		            tp = Float32Array;
  		            break;
  		          case 7:
  		            tp = Float64Array;
  		            break;
  		          default:
  		            tp = Float32Array;
  		        }
  		        return tp;
  		      },

  		      getPixelType: function(t) {
  		        var tp;
  		        switch (t) {
  		          case 0: //char
  		            tp = "S8";
  		            break;
  		          case 1: //byte
  		            tp = "U8";
  		            break;
  		          case 2: //short
  		            tp = "S16";
  		            break;
  		          case 3: //ushort
  		            tp = "U16";
  		            break;
  		          case 4:
  		            tp = "S32";
  		            break;
  		          case 5:
  		            tp = "U32";
  		            break;
  		          case 6:
  		            tp = "F32";
  		            break;
  		          case 7:
  		            tp = "F64";
  		            break;
  		          default:
  		            tp = "F32";
  		        }
  		        return tp;
  		      },

  		      isValidPixelValue: function(t, val) {
  		        if (val == null) {
  		          return false;
  		        }
  		        var isValid;
  		        switch (t) {
  		          case 0: //char
  		            isValid = val >= -128 && val <= 127;
  		            break;
  		          case 1: //byte  (unsigned char)
  		            isValid = val >= 0 && val <= 255;
  		            break;
  		          case 2: //short
  		            isValid = val >= -32768 && val <= 32767;
  		            break;
  		          case 3: //ushort
  		            isValid = val >= 0 && val <= 65536;
  		            break;
  		          case 4: //int 32
  		            isValid = val >= -2147483648 && val <= 2147483647;
  		            break;
  		          case 5: //uinit 32
  		            isValid = val >= 0 && val <= 4294967296;
  		            break;
  		          case 6:
  		            isValid = val >= -34027999387901484e22 && val <= 3.4027999387901484e+38;
  		            break;
  		          case 7:
  		            isValid = val >= -17976931348623157e292 && val <= 1.7976931348623157e+308;
  		            break;
  		          default:
  		            isValid = false;
  		        }
  		        return isValid;
  		      },

  		      getDataTypeSize: function(t) {
  		        var s = 0;
  		        switch (t) {
  		          case 0: //ubyte
  		          case 1: //byte
  		            s = 1;
  		            break;
  		          case 2: //short
  		          case 3: //ushort
  		            s = 2;
  		            break;
  		          case 4:
  		          case 5:
  		          case 6:
  		            s = 4;
  		            break;
  		          case 7:
  		            s = 8;
  		            break;
  		          default:
  		            s = t;
  		        }
  		        return s;
  		      },

  		      getDataTypeUsed: function(dt, tc) {
  		        var t = dt;
  		        switch (dt) {
  		          case 2: //short
  		          case 4: //long
  		            t = dt - tc;
  		            break;
  		          case 3: //ushort
  		          case 5: //ulong
  		            t = dt - 2 * tc;
  		            break;
  		          case 6: //float
  		            if (0 === tc) {
  		              t = dt;
  		            }
  		            else if (1 === tc) {
  		              t = 2;
  		            }
  		            else {
  		              t = 1;//byte
  		            }
  		            break;
  		          case 7: //double
  		            if (0 === tc) {
  		              t = dt;
  		            }
  		            else {
  		              t = dt - 2 * tc + 1;
  		            }
  		            break;
  		          default:
  		            t = dt;
  		            break;
  		        }
  		        return t;
  		      },

  		      getOnePixel: function(block, blockPtr, offsetType, view) {
  		        var temp = 0;
  		        switch (offsetType) {
  		          case 0: //char
  		            temp = view.getInt8(blockPtr);
  		            break;
  		          case 1: //byte
  		            temp = view.getUint8(blockPtr);
  		            break;
  		          case 2:
  		            temp = view.getInt16(blockPtr, true);
  		            break;
  		          case 3:
  		            temp = view.getUint16(blockPtr, true);
  		            break;
  		          case 4:
  		            temp = view.getInt32(blockPtr, true);
  		            break;
  		          case 5:
  		            temp = view.getUInt32(blockPtr, true);
  		            break;
  		          case 6:
  		            temp = view.getFloat32(blockPtr, true);
  		            break;
  		          case 7:
  		            temp = view.getFloat64(blockPtr, true);
  		            break;
  		          default:
  		            throw ("the decoder does not understand this pixel type");
  		        }
  		        return temp;
  		      },

  		      swapDimensionOrder: function(pixels, numPixels, numDims, OutPixelTypeArray, inputIsBIP) {
  		        var i = 0, j = 0, iDim = 0, temp = 0, swap = pixels;
  		        if (numDims > 1) {
  		          swap = new OutPixelTypeArray(numPixels * numDims);
  		          if (inputIsBIP) {
  		            for (i=0; i<numPixels; i++) {
  		              temp = i;
  		              for (iDim=0; iDim < numDims; iDim++, temp += numPixels) {
  		                swap[temp] = pixels[j++];
  		              }
  		            }  
  		          }
  		          else {
  		            for (i=0; i<numPixels; i++) {
  		              temp = i;
  		              for (iDim=0; iDim < numDims; iDim++, temp += numPixels) {
  		                swap[j++] = pixels[temp];
  		              }
  		            }
  		          }
  		        }
  		        return swap;
  		      }
  		    };

  		    /***************************************************
  		    *private class for a tree node. Huffman code is in Lerc2Helpers
  		    ****************************************************/
  		    var TreeNode = function(val, left, right) {
  		      this.val = val;
  		      this.left = left;
  		      this.right = right;
  		    };

  		    var Lerc2Decode = {
  		      /*
  		      * ********removed options compared to LERC1. We can bring some of them back if needed.
  		       * removed pixel type. LERC2 is typed and doesn't require user to give pixel type
  		       * changed encodedMaskData to maskData. LERC2 's js version make it faster to use maskData directly.
  		       * removed returnMask. mask is used by LERC2 internally and is cost free. In case of user input mask, it's returned as well and has neglible cost.
  		       * removed nodatavalue. Because LERC2 pixels are typed, nodatavalue will sacrify a useful value for many types (8bit, 16bit) etc,
  		       *       user has to be knowledgable enough about raster and their data to avoid usability issues. so nodata value is simply removed now.
  		       *       We can add it back later if their's a clear requirement.
  		       * removed encodedMask. This option was not implemented in LercDecode. It can be done after decoding (less efficient)
  		       * removed computeUsedBitDepths.
  		       *
  		       *
  		       * response changes compared to LERC1
  		       * 1. encodedMaskData is not available
  		       * 2. noDataValue is optional (returns only if user's noDataValue is with in the valid data type range)
  		       * 3. maskData is always available
  		      */
  		      /*****************
  		      *  public properties
  		      ******************/
  		      //HUFFMAN_LUT_BITS_MAX: 12, //use 2^12 lut, not configurable

  		      /*****************
  		      *  public methods
  		      *****************/

  		      /**
  		       * Decode a LERC2 byte stream and return an object containing the pixel data and optional metadata.
  		       *
  		       * @param {ArrayBuffer} input The LERC input byte stream
  		       * @param {object} [options] options Decoding options
  		       * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid LERC file is expected at that position
  		       * @param {boolean} [options.returnFileInfo] If true, the return value will have a fileInfo property that contains metadata obtained from the LERC headers and the decoding process
  		       * @param {boolean} [options.returnPixelInterleavedDims]  If true, returned dimensions are pixel-interleaved, a.k.a [p1_dim0, p1_dim1, p1_dimn, p2_dim0...], default is [p1_dim0, p2_dim0, ..., p1_dim1, p2_dim1...]
  		       */
  		      decode: function(/*byte array*/ input, /*object*/ options) {
  		        //currently there's a bug in the sparse array, so please do not set to false
  		        options = options || {};
  		        var noDataValue = options.noDataValue;

  		        //initialize
  		        var i = 0, data = {};
  		        data.ptr = options.inputOffset || 0;
  		        data.pixels = {};

  		        // File header
  		        if (!Lerc2Helpers.readHeaderInfo(input, data)) {
  		          return;
  		        }

  		        var headerInfo = data.headerInfo;
  		        var fileVersion = headerInfo.fileVersion;
  		        var OutPixelTypeArray = Lerc2Helpers.getDataTypeArray(headerInfo.imageType);

  		        // version check
  		        if (fileVersion > 5) {
  		          throw "unsupported lerc version 2." + fileVersion;
  		        }

  		        // Mask Header
  		        Lerc2Helpers.readMask(input, data);
  		        if (headerInfo.numValidPixel !== headerInfo.width * headerInfo.height && !data.pixels.resultMask) {
  		          data.pixels.resultMask = options.maskData;
  		        }

  		        var numPixels = headerInfo.width * headerInfo.height;
  		        data.pixels.resultPixels = new OutPixelTypeArray(numPixels * headerInfo.numDims);

  		        data.counter = {
  		          onesweep: 0,
  		          uncompressed: 0,
  		          lut: 0,
  		          bitstuffer: 0,
  		          constant: 0,
  		          constantoffset: 0
  		        };
  		        var useBSQForOutputDim = !options.returnPixelInterleavedDims;
  		        if (headerInfo.numValidPixel !== 0) {
  		          //not tested
  		          if (headerInfo.zMax === headerInfo.zMin) //constant surface
  		          {
  		            Lerc2Helpers.constructConstantSurface(data, useBSQForOutputDim);
  		          }
  		          else if (fileVersion >= 4 && Lerc2Helpers.checkMinMaxRanges(input, data)) {
  		            Lerc2Helpers.constructConstantSurface(data, useBSQForOutputDim);
  		          }
  		          else {
  		            var view = new DataView(input, data.ptr, 2);
  		            var bReadDataOneSweep = view.getUint8(0);
  		            data.ptr++;
  		            if (bReadDataOneSweep) {
  		              //console.debug("OneSweep");
  		              Lerc2Helpers.readDataOneSweep(input, data, OutPixelTypeArray, useBSQForOutputDim);
  		            }
  		            else {
  		              //lerc2.1: //bitstuffing + lut
  		              //lerc2.2: //bitstuffing + lut + huffman
  		              //lerc2.3: new bitstuffer
  		              if (fileVersion > 1 && headerInfo.imageType <= 1 && Math.abs(headerInfo.maxZError - 0.5) < 0.00001) {
  		                //this is 2.x plus 8 bit (unsigned and signed) data, possiblity of Huffman
  		                var flagHuffman = view.getUint8(1);
  		                data.ptr++;
  		                data.encodeMode = flagHuffman;
  		                if (flagHuffman > 2 || (fileVersion < 4 && flagHuffman > 1)) {
  		                  throw "Invalid Huffman flag " + flagHuffman;
  		                }
  		                if (flagHuffman) {//1 - delta Huffman, 2 - Huffman
  		                  //console.log("Huffman");
  		                  Lerc2Helpers.readHuffman(input, data, OutPixelTypeArray, useBSQForOutputDim);
  		                }
  		                else {
  		                  //console.log("Tiles");
  		                  Lerc2Helpers.readTiles(input, data, OutPixelTypeArray, useBSQForOutputDim);
  		                }
  		              }
  		              else { //lerc2.x non-8 bit data
  		                //console.log("Tiles");
  		                Lerc2Helpers.readTiles(input, data, OutPixelTypeArray, useBSQForOutputDim);
  		              }
  		            }
  		          }
  		        }

  		        data.eofOffset = data.ptr;
  		        var diff;
  		        if (options.inputOffset) {
  		          diff = data.headerInfo.blobSize + options.inputOffset - data.ptr;
  		          if (Math.abs(diff) >= 1) {
  		            //console.debug("incorrect eof: dataptr " + data.ptr + " offset " + options.inputOffset + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  		            data.eofOffset = options.inputOffset + data.headerInfo.blobSize;
  		          }
  		        }
  		        else {
  		          diff = data.headerInfo.blobSize - data.ptr;
  		          if (Math.abs(diff) >= 1) {
  		            //console.debug("incorrect first band eof: dataptr " + data.ptr + " blobsize " + data.headerInfo.blobSize + " diff: " + diff);
  		            data.eofOffset = data.headerInfo.blobSize;
  		          }
  		        }

  		        var result = {
  		          width: headerInfo.width,
  		          height: headerInfo.height,
  		          pixelData: data.pixels.resultPixels,
  		          minValue: headerInfo.zMin,
  		          maxValue: headerInfo.zMax,
  		          validPixelCount: headerInfo.numValidPixel,
  		          dimCount: headerInfo.numDims,
  		          dimStats: {
  		            minValues: headerInfo.minValues,
  		            maxValues: headerInfo.maxValues
  		          },
  		          maskData: data.pixels.resultMask
  		          //noDataValue: noDataValue
  		        };

  		        //we should remove this if there's no existing client
  		        //optional noDataValue processing, it's user's responsiblity
  		        if (data.pixels.resultMask && Lerc2Helpers.isValidPixelValue(headerInfo.imageType, noDataValue)) {
  		          var mask = data.pixels.resultMask;
  		          for (i = 0; i < numPixels; i++) {
  		            if (!mask[i]) {
  		              result.pixelData[i] = noDataValue;
  		            }
  		          }
  		          result.noDataValue = noDataValue;
  		        }
  		        data.noDataValue = noDataValue;
  		        if (options.returnFileInfo) {
  		          result.fileInfo = Lerc2Helpers.formatFileInfo(data);
  		        }
  		        return result;
  		      },

  		      getBandCount: function(/*byte array*/ input) {
  		        var count = 0;
  		        var i = 0;
  		        var temp = {};
  		        temp.ptr = 0;
  		        temp.pixels = {};
  		        while (i < input.byteLength - 58) {
  		          Lerc2Helpers.readHeaderInfo(input, temp);
  		          i += temp.headerInfo.blobSize;
  		          count++;
  		          temp.ptr = i;
  		        }
  		        return count;
  		      }
  		    };

  		    return Lerc2Decode;
  		  })();

  		  var isPlatformLittleEndian = (function() {
  		    var a = new ArrayBuffer(4);
  		    var b = new Uint8Array(a);
  		    var c = new Uint32Array(a);
  		    c[0] = 1;
  		    return b[0] === 1;
  		  })();

  		  var Lerc = {
  		    /************wrapper**********************************************/
  		    /**
  		     * A wrapper for decoding both LERC1 and LERC2 byte streams capable of handling multiband pixel blocks for various pixel types.
  		     *
  		     * @alias module:Lerc
  		     * @param {ArrayBuffer} input The LERC input byte stream
  		     * @param {object} [options] The decoding options below are optional.
  		     * @param {number} [options.inputOffset] The number of bytes to skip in the input byte stream. A valid Lerc file is expected at that position.
  		     * @param {string} [options.pixelType] (LERC1 only) Default value is F32. Valid pixel types for input are U8/S8/S16/U16/S32/U32/F32.
  		     * @param {number} [options.noDataValue] (LERC1 only). It is recommended to use the returned mask instead of setting this value.
  		     * @param {boolean} [options.returnPixelInterleavedDims] (nDim LERC2 only) If true, returned dimensions are pixel-interleaved, a.k.a [p1_dim0, p1_dim1, p1_dimn, p2_dim0...], default is [p1_dim0, p2_dim0, ..., p1_dim1, p2_dim1...]
  		     * @returns {{width, height, pixels, pixelType, mask, statistics}}
  		       * @property {number} width Width of decoded image.
  		       * @property {number} height Height of decoded image.
  		       * @property {array} pixels [band1, band2, …] Each band is a typed array of width*height.
  		       * @property {string} pixelType The type of pixels represented in the output.
  		       * @property {mask} mask Typed array with a size of width*height, or null if all pixels are valid.
  		       * @property {array} statistics [statistics_band1, statistics_band2, …] Each element is a statistics object representing min and max values
  		    **/
  		    decode: function(encodedData, options) {
  		      if (!isPlatformLittleEndian) {
  		        throw "Big endian system is not supported.";
  		      }
  		      options = options || {};
  		      var inputOffset = options.inputOffset || 0;
  		      var fileIdView = new Uint8Array(encodedData, inputOffset, 10);
  		      var fileIdentifierString = String.fromCharCode.apply(null, fileIdView);
  		      var lerc, majorVersion;
  		      if (fileIdentifierString.trim() === "CntZImage") {
  		        lerc = LercDecode;
  		        majorVersion = 1;
  		      }
  		      else if (fileIdentifierString.substring(0, 5) === "Lerc2") {
  		        lerc = Lerc2Decode;
  		        majorVersion = 2;
  		      }
  		      else {
  		        throw "Unexpected file identifier string: " + fileIdentifierString;
  		      }

  		      var iPlane = 0, eof = encodedData.byteLength - 10, encodedMaskData, bandMasks = [], bandMask, maskData;
  		      var decodedPixelBlock = {
  		        width: 0,
  		        height: 0,
  		        pixels: [],
  		        pixelType: options.pixelType,
  		        mask: null,
  		        statistics: []
  		      };
  		      var uniqueBandMaskCount = 0;

  		      while (inputOffset < eof) {
  		        var result = lerc.decode(encodedData, {
  		          inputOffset: inputOffset,//for both lerc1 and lerc2
  		          encodedMaskData: encodedMaskData,//lerc1 only
  		          maskData: maskData,//lerc2 only
  		          returnMask: iPlane === 0 ? true : false,//lerc1 only
  		          returnEncodedMask: iPlane === 0 ? true : false,//lerc1 only
  		          returnFileInfo: true,//for both lerc1 and lerc2
  		          returnPixelInterleavedDims: options.returnPixelInterleavedDims,//for ndim lerc2 only
  		          pixelType: options.pixelType || null,//lerc1 only
  		          noDataValue: options.noDataValue || null//lerc1 only
  		        });

  		        inputOffset = result.fileInfo.eofOffset;
  		        maskData = result.maskData;//lerc2
  		        if (iPlane === 0) {
  		          encodedMaskData = result.encodedMaskData;//lerc1
  		          decodedPixelBlock.width = result.width;
  		          decodedPixelBlock.height = result.height;
  		          decodedPixelBlock.dimCount = result.dimCount || 1;
  		          //decodedPixelBlock.dimStats = decodedPixelBlock.dimStats;
  		          decodedPixelBlock.pixelType = result.pixelType || result.fileInfo.pixelType;
  		          decodedPixelBlock.mask = maskData;
  		        }
  		        if (majorVersion > 1) {
  		          if (maskData) {
  		            bandMasks.push(maskData);
  		          }
  		          if (result.fileInfo.mask && result.fileInfo.mask.numBytes > 0) {
  		            uniqueBandMaskCount++;
  		          }
  		        }

  		        iPlane++;
  		        decodedPixelBlock.pixels.push(result.pixelData);
  		        decodedPixelBlock.statistics.push({
  		          minValue: result.minValue,
  		          maxValue: result.maxValue,
  		          noDataValue: result.noDataValue,
  		          dimStats: result.dimStats
  		        });
  		      }
  		      var i, j, numPixels;
  		      if (majorVersion > 1 && uniqueBandMaskCount > 1) {
  		        numPixels = decodedPixelBlock.width * decodedPixelBlock.height;
  		        decodedPixelBlock.bandMasks = bandMasks;
  		        maskData = new Uint8Array(numPixels);
  		        maskData.set(bandMasks[0]);
  		        for (i = 1; i < bandMasks.length; i++) {
  		          bandMask = bandMasks[i];
  		          for (j = 0; j < numPixels; j++) {
  		            maskData[j] = maskData[j] & bandMask[j];
  		          }
  		        }
  		        decodedPixelBlock.maskData = maskData;
  		      }

  		      return decodedPixelBlock;
  		    }
  		  };

  		  if (module.exports) {/* jshint ignore:line */
  		    //commonJS module 1.0/1.1/1.1.1 systems, such as nodeJS
  		    //http://wiki.commonjs.org/wiki/Modules
  		    module.exports = Lerc;/* jshint ignore:line */
  		  }
  		  else {
  		    //assign to this, most likely window
  		    this.Lerc = Lerc;
  		  }

  		})(); 
  	} (LercDecode));
  	return LercDecode.exports;
  }

  var LercDecodeExports = requireLercDecode();
  var Lerc = /*@__PURE__*/getDefaultExportFromCjs(LercDecodeExports);

  let init;
  let instance;
  let heap;
  const IMPORT_OBJECT = {
    env: {
      emscripten_notify_memory_growth: function (index) {
        heap = new Uint8Array(instance.exports.memory.buffer);
      }
    }
  };
  /**
   * ZSTD (Zstandard) decoder.
   */
  class ZSTDDecoder {
    init() {
      if (init) return init;
      if (typeof fetch !== 'undefined') {
        // Web.
        init = fetch('data:application/wasm;base64,' + wasm).then(response => response.arrayBuffer()).then(arrayBuffer => WebAssembly.instantiate(arrayBuffer, IMPORT_OBJECT)).then(this._init);
      } else {
        // Node.js.
        init = WebAssembly.instantiate(Buffer.from(wasm, 'base64'), IMPORT_OBJECT).then(this._init);
      }
      return init;
    }
    _init(result) {
      instance = result.instance;
      IMPORT_OBJECT.env.emscripten_notify_memory_growth(0); // initialize heap.
    }

    decode(array, uncompressedSize = 0) {
      if (!instance) throw new Error(`ZSTDDecoder: Await .init() before decoding.`);
      // Write compressed data into WASM memory.
      const compressedSize = array.byteLength;
      const compressedPtr = instance.exports.malloc(compressedSize);
      heap.set(array, compressedPtr);
      // Decompress into WASM memory.
      uncompressedSize = uncompressedSize || Number(instance.exports.ZSTD_findDecompressedSize(compressedPtr, compressedSize));
      const uncompressedPtr = instance.exports.malloc(uncompressedSize);
      const actualSize = instance.exports.ZSTD_decompress(uncompressedPtr, uncompressedSize, compressedPtr, compressedSize);
      // Read decompressed data and free WASM memory.
      const dec = heap.slice(uncompressedPtr, uncompressedPtr + actualSize);
      instance.exports.free(compressedPtr);
      instance.exports.free(uncompressedPtr);
      return dec;
    }
  }
  /**
   * BSD License
   *
   * For Zstandard software
   *
   * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without modification,
   * are permitted provided that the following conditions are met:
   *
   *  * Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   *
   *  * Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the documentation
   *    and/or other materials provided with the distribution.
   *
   *  * Neither the name Facebook nor the names of its contributors may be used to
   *    endorse or promote products derived from this software without specific
   *    prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
   * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */
  // wasm:begin
  const wasm = ' ';

  const zstd = new ZSTDDecoder();

  class LercDecoder extends BaseDecoder {
    constructor(fileDirectory) {
      super();

      this.planarConfiguration = typeof fileDirectory.PlanarConfiguration !== 'undefined' ? fileDirectory.PlanarConfiguration : 1;
      this.samplesPerPixel = typeof fileDirectory.SamplesPerPixel !== 'undefined' ? fileDirectory.SamplesPerPixel : 1;

      this.addCompression = fileDirectory.LercParameters[LercParameters.AddCompression];
    }

    decodeBlock(buffer) {
      switch (this.addCompression) {
        case LercAddCompression.None:
          break;
        case LercAddCompression.Deflate:
          buffer = inflate_1(new Uint8Array(buffer)).buffer; // eslint-disable-line no-param-reassign, prefer-destructuring
          break;
        case LercAddCompression.Zstandard:
          buffer = zstd.decode(new Uint8Array(buffer)).buffer; // eslint-disable-line no-param-reassign, prefer-destructuring
          break;
        default:
          throw new Error(`Unsupported LERC additional compression method identifier: ${this.addCompression}`);
      }

      const lercResult = Lerc.decode(buffer, { returnPixelInterleavedDims: this.planarConfiguration === 1 });
      const lercData = lercResult.pixels[0];
      return lercData.buffer;
    }
  }

  var lerc = {
    __proto__: null,
    default: LercDecoder,
    zstd: zstd
  };

  /**
   * class WebImageDecoder
   *
   * This decoder uses the browsers image decoding facilities to read image
   * formats like WebP when supported.
   */
  class WebImageDecoder extends BaseDecoder {
    constructor() {
      super();
      if (typeof createImageBitmap === 'undefined') {
        throw new Error('Cannot decode WebImage as `createImageBitmap` is not available');
      } else if (typeof document === 'undefined' && typeof OffscreenCanvas === 'undefined') {
        throw new Error('Cannot decode WebImage as neither `document` nor `OffscreenCanvas` is not available');
      }
    }

    async decode(fileDirectory, buffer) {
      const blob = new Blob([buffer]);
      const imageBitmap = await createImageBitmap(blob);

      let canvas;
      if (typeof document !== 'undefined') {
        canvas = document.createElement('canvas');
        canvas.width = imageBitmap.width;
        canvas.height = imageBitmap.height;
      } else {
        canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
      }

      const ctx = canvas.getContext('2d');
      ctx.drawImage(imageBitmap, 0, 0);

      // TODO: check how many samples per pixel we have, and return RGB/RGBA accordingly
      // it seems like GDAL always encodes via RGBA which does not require a translation

      return ctx.getImageData(0, 0, imageBitmap.width, imageBitmap.height).data.buffer;
    }
  }

  var webimage = {
    __proto__: null,
    default: WebImageDecoder
  };

  /**
   * Copyright 2020 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */

  var Worker$1 = typeof Worker !== 'undefined' ? Worker : undefined;

  function create() {
            const source = "function A(A,e,t,i,r,I,g){try{var n=A[I](g),a=n.value}catch(A){return void t(A)}n.done?e(a):Promise.resolve(a).then(i,r)}function e(e){return function(){var t=this,i=arguments;return new Promise((function(r,I){var g=e.apply(t,i);function n(e){A(g,r,I,n,a,\"next\",e)}function a(e){A(g,r,I,n,a,\"throw\",e)}n(void 0)}))}}function t(A){return t=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(A){return typeof A}:function(A){return A&&\"function\"==typeof Symbol&&A.constructor===Symbol&&A!==Symbol.prototype?\"symbol\":typeof A},t(A)}var i={exports:{}};!function(A){var e=function(A){var e,i=Object.prototype,r=i.hasOwnProperty,I=\"function\"==typeof Symbol?Symbol:{},g=I.iterator||\"@@iterator\",n=I.asyncIterator||\"@@asyncIterator\",a=I.toStringTag||\"@@toStringTag\";function o(A,e,t){return Object.defineProperty(A,e,{value:t,enumerable:!0,configurable:!0,writable:!0}),A[e]}try{o({},\"\")}catch(A){o=function(A,e,t){return A[e]=t}}function B(A,e,t,i){var r=e&&e.prototype instanceof h?e:h,I=Object.create(r.prototype),g=new S(i||[]);return I._invoke=function(A,e,t){var i=Q;return function(r,I){if(i===s)throw new Error(\"Generator is already running\");if(i===f){if(\"throw\"===r)throw I;return R()}for(t.method=r,t.arg=I;;){var g=t.delegate;if(g){var n=m(g,t);if(n){if(n===c)continue;return n}}if(\"next\"===t.method)t.sent=t._sent=t.arg;else if(\"throw\"===t.method){if(i===Q)throw i=f,t.arg;t.dispatchException(t.arg)}else\"return\"===t.method&&t.abrupt(\"return\",t.arg);i=s;var a=C(A,e,t);if(\"normal\"===a.type){if(i=t.done?f:E,a.arg===c)continue;return{value:a.arg,done:t.done}}\"throw\"===a.type&&(i=f,t.method=\"throw\",t.arg=a.arg)}}}(A,t,g),I}function C(A,e,t){try{return{type:\"normal\",arg:A.call(e,t)}}catch(A){return{type:\"throw\",arg:A}}}A.wrap=B;var Q=\"suspendedStart\",E=\"suspendedYield\",s=\"executing\",f=\"completed\",c={};function h(){}function l(){}function u(){}var w={};o(w,g,(function(){return this}));var d=Object.getPrototypeOf,D=d&&d(d(v([])));D&&D!==i&&r.call(D,g)&&(w=D);var y=u.prototype=h.prototype=Object.create(w);function k(A){[\"next\",\"throw\",\"return\"].forEach((function(e){o(A,e,(function(A){return this._invoke(e,A)}))}))}function p(A,e){function i(I,g,n,a){var o=C(A[I],A,g);if(\"throw\"!==o.type){var B=o.arg,Q=B.value;return Q&&\"object\"===t(Q)&&r.call(Q,\"__await\")?e.resolve(Q.__await).then((function(A){i(\"next\",A,n,a)}),(function(A){i(\"throw\",A,n,a)})):e.resolve(Q).then((function(A){B.value=A,n(B)}),(function(A){return i(\"throw\",A,n,a)}))}a(o.arg)}var I;this._invoke=function(A,t){function r(){return new e((function(e,r){i(A,t,e,r)}))}return I=I?I.then(r,r):r()}}function m(A,t){var i=A.iterator[t.method];if(i===e){if(t.delegate=null,\"throw\"===t.method){if(A.iterator.return&&(t.method=\"return\",t.arg=e,m(A,t),\"throw\"===t.method))return c;t.method=\"throw\",t.arg=new TypeError(\"The iterator does not provide a 'throw' method\")}return c}var r=C(i,A.iterator,t.arg);if(\"throw\"===r.type)return t.method=\"throw\",t.arg=r.arg,t.delegate=null,c;var I=r.arg;return I?I.done?(t[A.resultName]=I.value,t.next=A.nextLoc,\"return\"!==t.method&&(t.method=\"next\",t.arg=e),t.delegate=null,c):I:(t.method=\"throw\",t.arg=new TypeError(\"iterator result is not an object\"),t.delegate=null,c)}function G(A){var e={tryLoc:A[0]};1 in A&&(e.catchLoc=A[1]),2 in A&&(e.finallyLoc=A[2],e.afterLoc=A[3]),this.tryEntries.push(e)}function F(A){var e=A.completion||{};e.type=\"normal\",delete e.arg,A.completion=e}function S(A){this.tryEntries=[{tryLoc:\"root\"}],A.forEach(G,this),this.reset(!0)}function v(A){if(A){var t=A[g];if(t)return t.call(A);if(\"function\"==typeof A.next)return A;if(!isNaN(A.length)){var i=-1,I=function t(){for(;++i<A.length;)if(r.call(A,i))return t.value=A[i],t.done=!1,t;return t.value=e,t.done=!0,t};return I.next=I}}return{next:R}}function R(){return{value:e,done:!0}}return l.prototype=u,o(y,\"constructor\",u),o(u,\"constructor\",l),l.displayName=o(u,a,\"GeneratorFunction\"),A.isGeneratorFunction=function(A){var e=\"function\"==typeof A&&A.constructor;return!!e&&(e===l||\"GeneratorFunction\"===(e.displayName||e.name))},A.mark=function(A){return Object.setPrototypeOf?Object.setPrototypeOf(A,u):(A.__proto__=u,o(A,a,\"GeneratorFunction\")),A.prototype=Object.create(y),A},A.awrap=function(A){return{__await:A}},k(p.prototype),o(p.prototype,n,(function(){return this})),A.AsyncIterator=p,A.async=function(e,t,i,r,I){void 0===I&&(I=Promise);var g=new p(B(e,t,i,r),I);return A.isGeneratorFunction(t)?g:g.next().then((function(A){return A.done?A.value:g.next()}))},k(y),o(y,a,\"Generator\"),o(y,g,(function(){return this})),o(y,\"toString\",(function(){return\"[object Generator]\"})),A.keys=function(A){var e=[];for(var t in A)e.push(t);return e.reverse(),function t(){for(;e.length;){var i=e.pop();if(i in A)return t.value=i,t.done=!1,t}return t.done=!0,t}},A.values=v,S.prototype={constructor:S,reset:function(A){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method=\"next\",this.arg=e,this.tryEntries.forEach(F),!A)for(var t in this)\"t\"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=e)},stop:function(){this.done=!0;var A=this.tryEntries[0].completion;if(\"throw\"===A.type)throw A.arg;return this.rval},dispatchException:function(A){if(this.done)throw A;var t=this;function i(i,r){return n.type=\"throw\",n.arg=A,t.next=i,r&&(t.method=\"next\",t.arg=e),!!r}for(var I=this.tryEntries.length-1;I>=0;--I){var g=this.tryEntries[I],n=g.completion;if(\"root\"===g.tryLoc)return i(\"end\");if(g.tryLoc<=this.prev){var a=r.call(g,\"catchLoc\"),o=r.call(g,\"finallyLoc\");if(a&&o){if(this.prev<g.catchLoc)return i(g.catchLoc,!0);if(this.prev<g.finallyLoc)return i(g.finallyLoc)}else if(a){if(this.prev<g.catchLoc)return i(g.catchLoc,!0)}else{if(!o)throw new Error(\"try statement without catch or finally\");if(this.prev<g.finallyLoc)return i(g.finallyLoc)}}}},abrupt:function(A,e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc<=this.prev&&r.call(i,\"finallyLoc\")&&this.prev<i.finallyLoc){var I=i;break}}I&&(\"break\"===A||\"continue\"===A)&&I.tryLoc<=e&&e<=I.finallyLoc&&(I=null);var g=I?I.completion:{};return g.type=A,g.arg=e,I?(this.method=\"next\",this.next=I.finallyLoc,c):this.complete(g)},complete:function(A,e){if(\"throw\"===A.type)throw A.arg;return\"break\"===A.type||\"continue\"===A.type?this.next=A.arg:\"return\"===A.type?(this.rval=this.arg=A.arg,this.method=\"return\",this.next=\"end\"):\"normal\"===A.type&&e&&(this.next=e),c},finish:function(A){for(var e=this.tryEntries.length-1;e>=0;--e){var t=this.tryEntries[e];if(t.finallyLoc===A)return this.complete(t.completion,t.afterLoc),F(t),c}},catch:function(A){for(var e=this.tryEntries.length-1;e>=0;--e){var t=this.tryEntries[e];if(t.tryLoc===A){var i=t.completion;if(\"throw\"===i.type){var r=i.arg;F(t)}return r}}throw new Error(\"illegal catch attempt\")},delegateYield:function(A,t,i){return this.delegate={iterator:v(A),resultName:t,nextLoc:i},\"next\"===this.method&&(this.arg=e),c}},A}(A.exports);try{regeneratorRuntime=e}catch(A){\"object\"===(\"undefined\"==typeof globalThis?\"undefined\":t(globalThis))?globalThis.regeneratorRuntime=e:Function(\"r\",\"regeneratorRuntime = r\")(e)}}(i);var r=i.exports,I=new Map;function g(A,e){Array.isArray(A)||(A=[A]),A.forEach((function(A){return I.set(A,e)}))}function n(A){return a.apply(this,arguments)}function a(){return(a=e(r.mark((function A(e){var t,i;return r.wrap((function(A){for(;;)switch(A.prev=A.next){case 0:if(t=I.get(e.Compression)){A.next=3;break}throw new Error(\"Unknown compression method identifier: \".concat(e.Compression));case 3:return A.next=5,t();case 5:return i=A.sent,A.abrupt(\"return\",new i(e));case 7:case\"end\":return A.stop()}}),A)})))).apply(this,arguments)}g([void 0,1],(function(){return Promise.resolve().then((function(){return y})).then((function(A){return A.default}))})),g(5,(function(){return Promise.resolve().then((function(){return F})).then((function(A){return A.default}))})),g(6,(function(){throw new Error(\"old style JPEG compression is not supported.\")})),g(7,(function(){return Promise.resolve().then((function(){return N})).then((function(A){return A.default}))})),g([8,32946],(function(){return Promise.resolve().then((function(){return OA})).then((function(A){return A.default}))})),g(32773,(function(){return Promise.resolve().then((function(){return _A})).then((function(A){return A.default}))})),g(34887,(function(){return Promise.resolve().then((function(){return le})).then(function(){var A=e(r.mark((function A(e){return r.wrap((function(A){for(;;)switch(A.prev=A.next){case 0:return A.next=2,e.zstd.init();case 2:return A.abrupt(\"return\",e);case 3:case\"end\":return A.stop()}}),A)})));return function(e){return A.apply(this,arguments)}}()).then((function(A){return A.default}))})),g(50001,(function(){return Promise.resolve().then((function(){return de})).then((function(A){return A.default}))}));var o=globalThis;function B(A,e){if(!(A instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function C(A,e){for(var t=0;t<e.length;t++){var i=e[t];i.enumerable=i.enumerable||!1,i.configurable=!0,\"value\"in i&&(i.writable=!0),Object.defineProperty(A,i.key,i)}}function Q(A,e,t){return e&&C(A.prototype,e),t&&C(A,t),A}function E(A,e){return E=Object.setPrototypeOf||function(A,e){return A.__proto__=e,A},E(A,e)}function s(A,e){if(\"function\"!=typeof e&&null!==e)throw new TypeError(\"Super expression must either be null or a function\");A.prototype=Object.create(e&&e.prototype,{constructor:{value:A,writable:!0,configurable:!0}}),e&&E(A,e)}function f(A,e){if(e&&(\"object\"===t(e)||\"function\"==typeof e))return e;if(void 0!==e)throw new TypeError(\"Derived constructors may only return object or undefined\");return function(A){if(void 0===A)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return A}(A)}function c(A){return c=Object.setPrototypeOf?Object.getPrototypeOf:function(A){return A.__proto__||Object.getPrototypeOf(A)},c(A)}function h(A,e){var t=A.length-e,i=0;do{for(var r=e;r>0;r--)A[i+e]+=A[i],i++;t-=e}while(t>0)}function l(A,e,t){for(var i=0,r=A.length,I=r/t;r>e;){for(var g=e;g>0;--g)A[i+e]+=A[i],++i;r-=e}for(var n=A.slice(),a=0;a<I;++a)for(var o=0;o<t;++o)A[t*a+o]=n[(t-o-1)*I+a]}function u(A,e,t,i,r,I){if(!e||1===e)return A;for(var g=0;g<r.length;++g){if(r[g]%8!=0)throw new Error(\"When decoding with predictor, only multiple of 8 bits are supported.\");if(r[g]!==r[0])throw new Error(\"When decoding with predictor, all samples must have the same size.\")}for(var n=r[0]/8,a=2===I?1:r.length,o=0;o<i&&!(o*a*t*n>=A.byteLength);++o){var B=void 0;if(2===e){switch(r[0]){case 8:B=new Uint8Array(A,o*a*t*n,a*t*n);break;case 16:B=new Uint16Array(A,o*a*t*n,a*t*n/2);break;case 32:B=new Uint32Array(A,o*a*t*n,a*t*n/4);break;default:throw new Error(\"Predictor 2 not allowed with \".concat(r[0],\" bits per sample.\"))}h(B,a)}else 3===e&&l(B=new Uint8Array(A,o*a*t*n,a*t*n),a,n)}return A}o.addEventListener(\"message\",function(){var A=e(r.mark((function A(e){var t,i,I,g,a,B;return r.wrap((function(A){for(;;)switch(A.prev=A.next){case 0:return t=e.data,i=t.id,I=t.fileDirectory,g=t.buffer,A.next=3,n(I);case 3:return a=A.sent,A.next=6,a.decode(I,g);case 6:B=A.sent,o.postMessage({decoded:B,id:i},[B]);case 8:case\"end\":return A.stop()}}),A)})));return function(e){return A.apply(this,arguments)}}());var w=function(){function A(){B(this,A)}var t;return Q(A,[{key:\"decode\",value:(t=e(r.mark((function A(e,t){var i,I,g,n,a;return r.wrap((function(A){for(;;)switch(A.prev=A.next){case 0:return A.next=2,this.decodeBlock(t);case 2:if(i=A.sent,1===(I=e.Predictor||1)){A.next=9;break}return g=!e.StripOffsets,n=g?e.TileWidth:e.ImageWidth,a=g?e.TileLength:e.RowsPerStrip||e.ImageLength,A.abrupt(\"return\",u(i,I,n,a,e.BitsPerSample,e.PlanarConfiguration));case 9:return A.abrupt(\"return\",i);case 10:case\"end\":return A.stop()}}),A,this)}))),function(A,e){return t.apply(this,arguments)})}]),A}();function d(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var D=function(A){s(t,w);var e=d(t);function t(){return B(this,t),e.apply(this,arguments)}return Q(t,[{key:\"decodeBlock\",value:function(A){return A}}]),t}(),y=Object.freeze({__proto__:null,default:D});function k(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}function p(A,e){for(var t=e.length-1;t>=0;t--)A.push(e[t]);return A}function m(A){for(var e=new Uint16Array(4093),t=new Uint8Array(4093),i=0;i<=257;i++)e[i]=4096,t[i]=i;var r=258,I=9,g=0;function n(){r=258,I=9}function a(A){var e=function(A,e,t){var i=e%8,r=Math.floor(e/8),I=8-i,g=e+t-8*(r+1),n=8*(r+2)-(e+t),a=8*(r+2)-e;if(n=Math.max(0,n),r>=A.length)return console.warn(\"ran off the end of the buffer before finding EOI_CODE (end on input code)\"),257;var o=A[r]&Math.pow(2,8-i)-1,B=o<<=t-I;if(r+1<A.length){var C=A[r+1]>>>n;B+=C<<=Math.max(0,t-a)}if(g>8&&r+2<A.length){var Q=8*(r+3)-(e+t);B+=A[r+2]>>>Q}return B}(A,g,I);return g+=I,e}function o(A,i){return t[r]=i,e[r]=A,++r-1}function B(A){for(var i=[],r=A;4096!==r;r=e[r])i.push(t[r]);return i}var C=[];n();for(var Q,E=new Uint8Array(A),s=a(E);257!==s;){if(256===s){for(n(),s=a(E);256===s;)s=a(E);if(257===s)break;if(s>256)throw new Error(\"corrupted code at scanline \".concat(s));p(C,B(s)),Q=s}else if(s<r){var f=B(s);p(C,f),o(Q,f[f.length-1]),Q=s}else{var c=B(Q);if(!c)throw new Error(\"Bogus entry. Not in dictionary, \".concat(Q,\" / \").concat(r,\", position: \").concat(g));p(C,c),C.push(c[c.length-1]),o(Q,c[c.length-1]),Q=s}r+1>=Math.pow(2,I)&&(12===I?Q=void 0:I++),s=a(E)}return new Uint8Array(C)}var G=function(A){s(t,w);var e=k(t);function t(){return B(this,t),e.apply(this,arguments)}return Q(t,[{key:\"decodeBlock\",value:function(A){return m(A).buffer}}]),t}(),F=Object.freeze({__proto__:null,default:G});function S(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var v=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]);function R(A,e){for(var t=0,i=[],r=16;r>0&&!A[r-1];)--r;i.push({children:[],index:0});for(var I,g=i[0],n=0;n<r;n++){for(var a=0;a<A[n];a++){for((g=i.pop()).children[g.index]=e[t];g.index>0;)g=i.pop();for(g.index++,i.push(g);i.length<=n;)i.push(I={children:[],index:0}),g.children[g.index]=I.children,g=I;t++}n+1<r&&(i.push(I={children:[],index:0}),g.children[g.index]=I.children,g=I)}return i[0].children}function U(A,e,i,r,I,g,n,a,o){var B=i.mcusPerLine,C=i.progressive,Q=e,E=e,s=0,f=0;function c(){if(f>0)return f--,s>>f&1;if(255===(s=A[E++])){var e=A[E++];if(e)throw new Error(\"unexpected marker: \".concat((s<<8|e).toString(16)))}return f=7,s>>>7}function h(A){for(var e,i=A;null!==(e=c());){if(\"number\"==typeof(i=i[e]))return i;if(\"object\"!==t(i))throw new Error(\"invalid huffman sequence\")}return null}function l(A){for(var e=A,t=0;e>0;){var i=c();if(null===i)return;t=t<<1|i,--e}return t}function u(A){var e=l(A);return e>=1<<A-1?e:e+(-1<<A)+1}var w=0;var d,D=0;function y(A,e,t,i,r){var I=t%B,g=(t/B|0)*A.v+i,n=I*A.h+r;e(A,A.blocks[g][n])}function k(A,e,t){var i=t/A.blocksPerLine|0,r=t%A.blocksPerLine;e(A,A.blocks[i][r])}var p,m,G,F,S,R,U=r.length;R=C?0===g?0===a?function(A,e){var t=h(A.huffmanTableDC),i=0===t?0:u(t)<<o;A.pred+=i,e[0]=A.pred}:function(A,e){e[0]|=c()<<o}:0===a?function(A,e){if(w>0)w--;else for(var t=g,i=n;t<=i;){var r=h(A.huffmanTableAC),I=15&r,a=r>>4;if(0===I){if(a<15){w=l(a)+(1<<a)-1;break}t+=16}else e[v[t+=a]]=u(I)*(1<<o),t++}}:function(A,e){for(var t=g,i=n,r=0;t<=i;){var I=v[t],a=e[I]<0?-1:1;switch(D){case 0:var B=h(A.huffmanTableAC),C=15&B;if(r=B>>4,0===C)r<15?(w=l(r)+(1<<r),D=4):(r=16,D=1);else{if(1!==C)throw new Error(\"invalid ACn encoding\");d=u(C),D=r?2:3}continue;case 1:case 2:e[I]?e[I]+=(c()<<o)*a:0==--r&&(D=2===D?3:0);break;case 3:e[I]?e[I]+=(c()<<o)*a:(e[I]=d<<o,D=0);break;case 4:e[I]&&(e[I]+=(c()<<o)*a)}t++}4===D&&0==--w&&(D=0)}:function(A,e){var t=h(A.huffmanTableDC),i=0===t?0:u(t);A.pred+=i,e[0]=A.pred;for(var r=1;r<64;){var I=h(A.huffmanTableAC),g=15&I,n=I>>4;if(0===g){if(n<15)break;r+=16}else e[v[r+=n]]=u(g),r++}};var L,b,M=0;b=1===U?r[0].blocksPerLine*r[0].blocksPerColumn:B*i.mcusPerColumn;for(var N=I||b;M<b;){for(m=0;m<U;m++)r[m].pred=0;if(w=0,1===U)for(p=r[0],S=0;S<N;S++)k(p,R,M),M++;else for(S=0;S<N;S++){for(m=0;m<U;m++){var x=p=r[m],J=x.h,q=x.v;for(G=0;G<q;G++)for(F=0;F<J;F++)y(p,R,M,G,F)}if(++M===b)break}if(f=0,(L=A[E]<<8|A[E+1])<65280)throw new Error(\"marker was not found\");if(!(L>=65488&&L<=65495))break;E+=2}return E-Q}function L(A,e){var t=[],i=e.blocksPerLine,r=e.blocksPerColumn,I=i<<3,g=new Int32Array(64),n=new Uint8Array(64);function a(A,t,i){var r,I,g,n,a,o,B,C,Q,E,s=e.quantizationTable,f=i;for(E=0;E<64;E++)f[E]=A[E]*s[E];for(E=0;E<8;++E){var c=8*E;0!==f[1+c]||0!==f[2+c]||0!==f[3+c]||0!==f[4+c]||0!==f[5+c]||0!==f[6+c]||0!==f[7+c]?(r=5793*f[0+c]+128>>8,I=5793*f[4+c]+128>>8,g=f[2+c],n=f[6+c],a=2896*(f[1+c]-f[7+c])+128>>8,C=2896*(f[1+c]+f[7+c])+128>>8,o=f[3+c]<<4,Q=r-I+1>>1,r=r+I+1>>1,I=Q,Q=3784*g+1567*n+128>>8,g=1567*g-3784*n+128>>8,n=Q,Q=a-(B=f[5+c]<<4)+1>>1,a=a+B+1>>1,B=Q,Q=C+o+1>>1,o=C-o+1>>1,C=Q,Q=r-n+1>>1,r=r+n+1>>1,n=Q,Q=I-g+1>>1,I=I+g+1>>1,g=Q,Q=2276*a+3406*C+2048>>12,a=3406*a-2276*C+2048>>12,C=Q,Q=799*o+4017*B+2048>>12,o=4017*o-799*B+2048>>12,B=Q,f[0+c]=r+C,f[7+c]=r-C,f[1+c]=I+B,f[6+c]=I-B,f[2+c]=g+o,f[5+c]=g-o,f[3+c]=n+a,f[4+c]=n-a):(Q=5793*f[0+c]+512>>10,f[0+c]=Q,f[1+c]=Q,f[2+c]=Q,f[3+c]=Q,f[4+c]=Q,f[5+c]=Q,f[6+c]=Q,f[7+c]=Q)}for(E=0;E<8;++E){var h=E;0!==f[8+h]||0!==f[16+h]||0!==f[24+h]||0!==f[32+h]||0!==f[40+h]||0!==f[48+h]||0!==f[56+h]?(r=5793*f[0+h]+2048>>12,I=5793*f[32+h]+2048>>12,g=f[16+h],n=f[48+h],a=2896*(f[8+h]-f[56+h])+2048>>12,C=2896*(f[8+h]+f[56+h])+2048>>12,o=f[24+h],Q=r-I+1>>1,r=r+I+1>>1,I=Q,Q=3784*g+1567*n+2048>>12,g=1567*g-3784*n+2048>>12,n=Q,Q=a-(B=f[40+h])+1>>1,a=a+B+1>>1,B=Q,Q=C+o+1>>1,o=C-o+1>>1,C=Q,Q=r-n+1>>1,r=r+n+1>>1,n=Q,Q=I-g+1>>1,I=I+g+1>>1,g=Q,Q=2276*a+3406*C+2048>>12,a=3406*a-2276*C+2048>>12,C=Q,Q=799*o+4017*B+2048>>12,o=4017*o-799*B+2048>>12,B=Q,f[0+h]=r+C,f[56+h]=r-C,f[8+h]=I+B,f[48+h]=I-B,f[16+h]=g+o,f[40+h]=g-o,f[24+h]=n+a,f[32+h]=n-a):(Q=5793*i[E+0]+8192>>14,f[0+h]=Q,f[8+h]=Q,f[16+h]=Q,f[24+h]=Q,f[32+h]=Q,f[40+h]=Q,f[48+h]=Q,f[56+h]=Q)}for(E=0;E<64;++E){var l=128+(f[E]+8>>4);t[E]=l<0?0:l>255?255:l}}for(var o=0;o<r;o++){for(var B=o<<3,C=0;C<8;C++)t.push(new Uint8Array(I));for(var Q=0;Q<i;Q++){a(e.blocks[o][Q],n,g);for(var E=0,s=Q<<3,f=0;f<8;f++)for(var c=t[B+f],h=0;h<8;h++)c[s+h]=n[E++]}}return t}var b=function(){function A(){B(this,A),this.jfif=null,this.adobe=null,this.quantizationTables=[],this.huffmanTablesAC=[],this.huffmanTablesDC=[],this.resetFrames()}return Q(A,[{key:\"resetFrames\",value:function(){this.frames=[]}},{key:\"parse\",value:function(A){var e=0;function t(){var t=A[e]<<8|A[e+1];return e+=2,t}function i(A){var e,t,i=0,r=0;for(t in A.components)A.components.hasOwnProperty(t)&&(i<(e=A.components[t]).h&&(i=e.h),r<e.v&&(r=e.v));var I=Math.ceil(A.samplesPerLine/8/i),g=Math.ceil(A.scanLines/8/r);for(t in A.components)if(A.components.hasOwnProperty(t)){e=A.components[t];for(var n=Math.ceil(Math.ceil(A.samplesPerLine/8)*e.h/i),a=Math.ceil(Math.ceil(A.scanLines/8)*e.v/r),o=I*e.h,B=g*e.v,C=[],Q=0;Q<B;Q++){for(var E=[],s=0;s<o;s++)E.push(new Int32Array(64));C.push(E)}e.blocksPerLine=n,e.blocksPerColumn=a,e.blocks=C}A.maxH=i,A.maxV=r,A.mcusPerLine=I,A.mcusPerColumn=g}var r,I,g=t();if(65496!==g)throw new Error(\"SOI not found\");for(g=t();65497!==g;){switch(g){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var n=(r=void 0,I=void 0,r=t(),I=A.subarray(e,e+r-2),e+=I.length,I);65504===g&&74===n[0]&&70===n[1]&&73===n[2]&&70===n[3]&&0===n[4]&&(this.jfif={version:{major:n[5],minor:n[6]},densityUnits:n[7],xDensity:n[8]<<8|n[9],yDensity:n[10]<<8|n[11],thumbWidth:n[12],thumbHeight:n[13],thumbData:n.subarray(14,14+3*n[12]*n[13])}),65518===g&&65===n[0]&&100===n[1]&&111===n[2]&&98===n[3]&&101===n[4]&&0===n[5]&&(this.adobe={version:n[6],flags0:n[7]<<8|n[8],flags1:n[9]<<8|n[10],transformCode:n[11]});break;case 65499:for(var a=t()+e-2;e<a;){var o=A[e++],B=new Int32Array(64);if(o>>4==0)for(var C=0;C<64;C++){B[v[C]]=A[e++]}else{if(o>>4!=1)throw new Error(\"DQT: invalid table spec\");for(var Q=0;Q<64;Q++){B[v[Q]]=t()}}this.quantizationTables[15&o]=B}break;case 65472:case 65473:case 65474:t();for(var E={extended:65473===g,progressive:65474===g,precision:A[e++],scanLines:t(),samplesPerLine:t(),components:{},componentsOrder:[]},s=A[e++],f=void 0,c=0;c<s;c++){f=A[e];var h=A[e+1]>>4,l=15&A[e+1],u=A[e+2];E.componentsOrder.push(f),E.components[f]={h:h,v:l,quantizationIdx:u},e+=3}i(E),this.frames.push(E);break;case 65476:for(var w=t(),d=2;d<w;){for(var D=A[e++],y=new Uint8Array(16),k=0,p=0;p<16;p++,e++)y[p]=A[e],k+=y[p];for(var m=new Uint8Array(k),G=0;G<k;G++,e++)m[G]=A[e];d+=17+k,D>>4==0?this.huffmanTablesDC[15&D]=R(y,m):this.huffmanTablesAC[15&D]=R(y,m)}break;case 65501:t(),this.resetInterval=t();break;case 65498:t();for(var F=A[e++],S=[],L=this.frames[0],b=0;b<F;b++){var M=L.components[A[e++]],N=A[e++];M.huffmanTableDC=this.huffmanTablesDC[N>>4],M.huffmanTableAC=this.huffmanTablesAC[15&N],S.push(M)}var x=A[e++],J=A[e++],q=A[e++],Y=U(A,e,L,S,this.resetInterval,x,J,q>>4,15&q);e+=Y;break;case 65535:255!==A[e]&&e--;break;default:if(255===A[e-3]&&A[e-2]>=192&&A[e-2]<=254){e-=3;break}throw new Error(\"unknown JPEG marker \".concat(g.toString(16)))}g=t()}}},{key:\"getResult\",value:function(){var A=this.frames;if(0===this.frames.length)throw new Error(\"no frames were decoded\");this.frames.length>1&&console.warn(\"more than one frame is not supported\");for(var e=0;e<this.frames.length;e++)for(var t=this.frames[e].components,i=0,r=Object.keys(t);i<r.length;i++){var I=r[i];t[I].quantizationTable=this.quantizationTables[t[I].quantizationIdx],delete t[I].quantizationIdx}for(var g=A[0],n=g.components,a=g.componentsOrder,o=[],B=g.samplesPerLine,C=g.scanLines,Q=0;Q<a.length;Q++){var E=n[a[Q]];o.push({lines:L(0,E),scaleX:E.h/g.maxH,scaleY:E.v/g.maxV})}for(var s=new Uint8Array(B*C*o.length),f=0,c=0;c<C;++c)for(var h=0;h<B;++h)for(var l=0;l<o.length;++l){var u=o[l];s[f]=u.lines[0|c*u.scaleY][0|h*u.scaleX],++f}return s}}]),A}(),M=function(A){s(t,w);var e=S(t);function t(A){var i;return B(this,t),(i=e.call(this)).reader=new b,A.JPEGTables&&i.reader.parse(A.JPEGTables),i}return Q(t,[{key:\"decodeBlock\",value:function(A){return this.reader.resetFrames(),this.reader.parse(new Uint8Array(A)),this.reader.getResult().buffer}}]),t}(),N=Object.freeze({__proto__:null,default:M});function x(A){for(var e=A.length;--e>=0;)A[e]=0}x(new Array(576)),x(new Array(60)),x(new Array(512)),x(new Array(256)),x(new Array(29)),x(new Array(30));var J=function(A,e,t,i){for(var r=65535&A|0,I=A>>>16&65535|0,g=0;0!==t;){t-=g=t>2e3?2e3:t;do{I=I+(r=r+e[i++]|0)|0}while(--g);r%=65521,I%=65521}return r|I<<16|0},q=new Uint32Array(function(){for(var A,e=[],t=0;t<256;t++){A=t;for(var i=0;i<8;i++)A=1&A?3988292384^A>>>1:A>>>1;e[t]=A}return e}()),Y=function(A,e,t,i){var r=q,I=i+t;A^=-1;for(var g=i;g<I;g++)A=A>>>8^r[255&(A^e[g])];return-1^A},K={2:\"need dictionary\",1:\"stream end\",0:\"\",\"-1\":\"file error\",\"-2\":\"stream error\",\"-3\":\"data error\",\"-4\":\"insufficient memory\",\"-5\":\"buffer error\",\"-6\":\"incompatible version\"},H={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},O=function(A,e){return Object.prototype.hasOwnProperty.call(A,e)},P=function(A){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if(\"object\"!==t(i))throw new TypeError(i+\"must be non-object\");for(var r in i)O(i,r)&&(A[r]=i[r])}}return A},T=function(A){for(var e=0,t=0,i=A.length;t<i;t++)e+=A[t].length;for(var r=new Uint8Array(e),I=0,g=0,n=A.length;I<n;I++){var a=A[I];r.set(a,g),g+=a.length}return r},V=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(A){V=!1}for(var _=new Uint8Array(256),X=0;X<256;X++)_[X]=X>=252?6:X>=248?5:X>=240?4:X>=224?3:X>=192?2:1;_[254]=_[254]=1;var Z=function(A){if(\"function\"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(A);var e,t,i,r,I,g=A.length,n=0;for(r=0;r<g;r++)55296==(64512&(t=A.charCodeAt(r)))&&r+1<g&&56320==(64512&(i=A.charCodeAt(r+1)))&&(t=65536+(t-55296<<10)+(i-56320),r++),n+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(n),I=0,r=0;I<n;r++)55296==(64512&(t=A.charCodeAt(r)))&&r+1<g&&56320==(64512&(i=A.charCodeAt(r+1)))&&(t=65536+(t-55296<<10)+(i-56320),r++),t<128?e[I++]=t:t<2048?(e[I++]=192|t>>>6,e[I++]=128|63&t):t<65536?(e[I++]=224|t>>>12,e[I++]=128|t>>>6&63,e[I++]=128|63&t):(e[I++]=240|t>>>18,e[I++]=128|t>>>12&63,e[I++]=128|t>>>6&63,e[I++]=128|63&t);return e},j=function(A,e){var t,i,r=e||A.length;if(\"function\"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(A.subarray(0,e));var I=new Array(2*r);for(i=0,t=0;t<r;){var g=A[t++];if(g<128)I[i++]=g;else{var n=_[g];if(n>4)I[i++]=65533,t+=n-1;else{for(g&=2===n?31:3===n?15:7;n>1&&t<r;)g=g<<6|63&A[t++],n--;n>1?I[i++]=65533:g<65536?I[i++]=g:(g-=65536,I[i++]=55296|g>>10&1023,I[i++]=56320|1023&g)}}}return function(A,e){if(e<65534&&A.subarray&&V)return String.fromCharCode.apply(null,A.length===e?A:A.subarray(0,e));for(var t=\"\",i=0;i<e;i++)t+=String.fromCharCode(A[i]);return t}(I,i)},W=function(A,e){(e=e||A.length)>A.length&&(e=A.length);for(var t=e-1;t>=0&&128==(192&A[t]);)t--;return t<0||0===t?e:t+_[A[t]]>e?t:e};var z=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg=\"\",this.state=null,this.data_type=2,this.adler=0},$=function(A,e){var t,i,r,I,g,n,a,o,B,C,Q,E,s,f,c,h,l,u,w,d,D,y,k,p,m=A.state;t=A.next_in,k=A.input,i=t+(A.avail_in-5),r=A.next_out,p=A.output,I=r-(e-A.avail_out),g=r+(A.avail_out-257),n=m.dmax,a=m.wsize,o=m.whave,B=m.wnext,C=m.window,Q=m.hold,E=m.bits,s=m.lencode,f=m.distcode,c=(1<<m.lenbits)-1,h=(1<<m.distbits)-1;A:do{E<15&&(Q+=k[t++]<<E,E+=8,Q+=k[t++]<<E,E+=8),l=s[Q&c];e:for(;;){if(Q>>>=u=l>>>24,E-=u,0===(u=l>>>16&255))p[r++]=65535&l;else{if(!(16&u)){if(0==(64&u)){l=s[(65535&l)+(Q&(1<<u)-1)];continue e}if(32&u){m.mode=12;break A}A.msg=\"invalid literal/length code\",m.mode=30;break A}w=65535&l,(u&=15)&&(E<u&&(Q+=k[t++]<<E,E+=8),w+=Q&(1<<u)-1,Q>>>=u,E-=u),E<15&&(Q+=k[t++]<<E,E+=8,Q+=k[t++]<<E,E+=8),l=f[Q&h];t:for(;;){if(Q>>>=u=l>>>24,E-=u,!(16&(u=l>>>16&255))){if(0==(64&u)){l=f[(65535&l)+(Q&(1<<u)-1)];continue t}A.msg=\"invalid distance code\",m.mode=30;break A}if(d=65535&l,E<(u&=15)&&(Q+=k[t++]<<E,(E+=8)<u&&(Q+=k[t++]<<E,E+=8)),(d+=Q&(1<<u)-1)>n){A.msg=\"invalid distance too far back\",m.mode=30;break A}if(Q>>>=u,E-=u,d>(u=r-I)){if((u=d-u)>o&&m.sane){A.msg=\"invalid distance too far back\",m.mode=30;break A}if(D=0,y=C,0===B){if(D+=a-u,u<w){w-=u;do{p[r++]=C[D++]}while(--u);D=r-d,y=p}}else if(B<u){if(D+=a+B-u,(u-=B)<w){w-=u;do{p[r++]=C[D++]}while(--u);if(D=0,B<w){w-=u=B;do{p[r++]=C[D++]}while(--u);D=r-d,y=p}}}else if(D+=B-u,u<w){w-=u;do{p[r++]=C[D++]}while(--u);D=r-d,y=p}for(;w>2;)p[r++]=y[D++],p[r++]=y[D++],p[r++]=y[D++],w-=3;w&&(p[r++]=y[D++],w>1&&(p[r++]=y[D++]))}else{D=r-d;do{p[r++]=p[D++],p[r++]=p[D++],p[r++]=p[D++],w-=3}while(w>2);w&&(p[r++]=p[D++],w>1&&(p[r++]=p[D++]))}break}}break}}while(t<i&&r<g);t-=w=E>>3,Q&=(1<<(E-=w<<3))-1,A.next_in=t,A.next_out=r,A.avail_in=t<i?i-t+5:5-(t-i),A.avail_out=r<g?g-r+257:257-(r-g),m.hold=Q,m.bits=E},AA=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),eA=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),tA=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),iA=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),rA=function(A,e,t,i,r,I,g,n){var a,o,B,C,Q,E,s,f,c,h=n.bits,l=0,u=0,w=0,d=0,D=0,y=0,k=0,p=0,m=0,G=0,F=null,S=0,v=new Uint16Array(16),R=new Uint16Array(16),U=null,L=0;for(l=0;l<=15;l++)v[l]=0;for(u=0;u<i;u++)v[e[t+u]]++;for(D=h,d=15;d>=1&&0===v[d];d--);if(D>d&&(D=d),0===d)return r[I++]=20971520,r[I++]=20971520,n.bits=1,0;for(w=1;w<d&&0===v[w];w++);for(D<w&&(D=w),p=1,l=1;l<=15;l++)if(p<<=1,(p-=v[l])<0)return-1;if(p>0&&(0===A||1!==d))return-1;for(R[1]=0,l=1;l<15;l++)R[l+1]=R[l]+v[l];for(u=0;u<i;u++)0!==e[t+u]&&(g[R[e[t+u]]++]=u);if(0===A?(F=U=g,E=19):1===A?(F=AA,S-=257,U=eA,L-=257,E=256):(F=tA,U=iA,E=-1),G=0,u=0,l=w,Q=I,y=D,k=0,B=-1,C=(m=1<<D)-1,1===A&&m>852||2===A&&m>592)return 1;for(;;){s=l-k,g[u]<E?(f=0,c=g[u]):g[u]>E?(f=U[L+g[u]],c=F[S+g[u]]):(f=96,c=0),a=1<<l-k,w=o=1<<y;do{r[Q+(G>>k)+(o-=a)]=s<<24|f<<16|c|0}while(0!==o);for(a=1<<l-1;G&a;)a>>=1;if(0!==a?(G&=a-1,G+=a):G=0,u++,0==--v[l]){if(l===d)break;l=e[t+g[u]]}if(l>D&&(G&C)!==B){for(0===k&&(k=D),Q+=w,p=1<<(y=l-k);y+k<d&&!((p-=v[y+k])<=0);)y++,p<<=1;if(m+=1<<y,1===A&&m>852||2===A&&m>592)return 1;r[B=G&C]=D<<24|y<<16|Q-I|0}}return 0!==G&&(r[Q+G]=l-k<<24|64<<16|0),n.bits=D,0},IA=H.Z_FINISH,gA=H.Z_BLOCK,nA=H.Z_TREES,aA=H.Z_OK,oA=H.Z_STREAM_END,BA=H.Z_NEED_DICT,CA=H.Z_STREAM_ERROR,QA=H.Z_DATA_ERROR,EA=H.Z_MEM_ERROR,sA=H.Z_BUF_ERROR,fA=H.Z_DEFLATED,cA=function(A){return(A>>>24&255)+(A>>>8&65280)+((65280&A)<<8)+((255&A)<<24)};function hA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var lA,uA,wA=function(A){if(!A||!A.state)return CA;var e=A.state;return A.total_in=A.total_out=e.total=0,A.msg=\"\",e.wrap&&(A.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,aA},dA=function(A){if(!A||!A.state)return CA;var e=A.state;return e.wsize=0,e.whave=0,e.wnext=0,wA(A)},DA=function(A,e){var t;if(!A||!A.state)return CA;var i=A.state;return e<0?(t=0,e=-e):(t=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?CA:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=t,i.wbits=e,dA(A))},yA=function(A,e){if(!A)return CA;var t=new hA;A.state=t,t.window=null;var i=DA(A,e);return i!==aA&&(A.state=null),i},kA=!0,pA=function(A){if(kA){lA=new Int32Array(512),uA=new Int32Array(32);for(var e=0;e<144;)A.lens[e++]=8;for(;e<256;)A.lens[e++]=9;for(;e<280;)A.lens[e++]=7;for(;e<288;)A.lens[e++]=8;for(rA(1,A.lens,0,288,lA,0,A.work,{bits:9}),e=0;e<32;)A.lens[e++]=5;rA(2,A.lens,0,32,uA,0,A.work,{bits:5}),kA=!1}A.lencode=lA,A.lenbits=9,A.distcode=uA,A.distbits=5},mA=function(A,e,t,i){var r,I=A.state;return null===I.window&&(I.wsize=1<<I.wbits,I.wnext=0,I.whave=0,I.window=new Uint8Array(I.wsize)),i>=I.wsize?(I.window.set(e.subarray(t-I.wsize,t),0),I.wnext=0,I.whave=I.wsize):((r=I.wsize-I.wnext)>i&&(r=i),I.window.set(e.subarray(t-i,t-i+r),I.wnext),(i-=r)?(I.window.set(e.subarray(t-i,t),0),I.wnext=i,I.whave=I.wsize):(I.wnext+=r,I.wnext===I.wsize&&(I.wnext=0),I.whave<I.wsize&&(I.whave+=r))),0},GA={inflateReset:dA,inflateReset2:DA,inflateResetKeep:wA,inflateInit:function(A){return yA(A,15)},inflateInit2:yA,inflate:function(A,e){var t,i,r,I,g,n,a,o,B,C,Q,E,s,f,c,h,l,u,w,d,D,y,k,p,m=0,G=new Uint8Array(4),F=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!A||!A.state||!A.output||!A.input&&0!==A.avail_in)return CA;12===(t=A.state).mode&&(t.mode=13),g=A.next_out,r=A.output,a=A.avail_out,I=A.next_in,i=A.input,n=A.avail_in,o=t.hold,B=t.bits,C=n,Q=a,y=aA;A:for(;;)switch(t.mode){case 1:if(0===t.wrap){t.mode=13;break}for(;B<16;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(2&t.wrap&&35615===o){t.check=0,G[0]=255&o,G[1]=o>>>8&255,t.check=Y(t.check,G,2,0),o=0,B=0,t.mode=2;break}if(t.flags=0,t.head&&(t.head.done=!1),!(1&t.wrap)||(((255&o)<<8)+(o>>8))%31){A.msg=\"incorrect header check\",t.mode=30;break}if((15&o)!==fA){A.msg=\"unknown compression method\",t.mode=30;break}if(B-=4,D=8+(15&(o>>>=4)),0===t.wbits)t.wbits=D;else if(D>t.wbits){A.msg=\"invalid window size\",t.mode=30;break}t.dmax=1<<t.wbits,A.adler=t.check=1,t.mode=512&o?10:12,o=0,B=0;break;case 2:for(;B<16;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(t.flags=o,(255&t.flags)!==fA){A.msg=\"unknown compression method\",t.mode=30;break}if(57344&t.flags){A.msg=\"unknown header flags set\",t.mode=30;break}t.head&&(t.head.text=o>>8&1),512&t.flags&&(G[0]=255&o,G[1]=o>>>8&255,t.check=Y(t.check,G,2,0)),o=0,B=0,t.mode=3;case 3:for(;B<32;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.head&&(t.head.time=o),512&t.flags&&(G[0]=255&o,G[1]=o>>>8&255,G[2]=o>>>16&255,G[3]=o>>>24&255,t.check=Y(t.check,G,4,0)),o=0,B=0,t.mode=4;case 4:for(;B<16;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.head&&(t.head.xflags=255&o,t.head.os=o>>8),512&t.flags&&(G[0]=255&o,G[1]=o>>>8&255,t.check=Y(t.check,G,2,0)),o=0,B=0,t.mode=5;case 5:if(1024&t.flags){for(;B<16;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.length=o,t.head&&(t.head.extra_len=o),512&t.flags&&(G[0]=255&o,G[1]=o>>>8&255,t.check=Y(t.check,G,2,0)),o=0,B=0}else t.head&&(t.head.extra=null);t.mode=6;case 6:if(1024&t.flags&&((E=t.length)>n&&(E=n),E&&(t.head&&(D=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(i.subarray(I,I+E),D)),512&t.flags&&(t.check=Y(t.check,i,E,I)),n-=E,I+=E,t.length-=E),t.length))break A;t.length=0,t.mode=7;case 7:if(2048&t.flags){if(0===n)break A;E=0;do{D=i[I+E++],t.head&&D&&t.length<65536&&(t.head.name+=String.fromCharCode(D))}while(D&&E<n);if(512&t.flags&&(t.check=Y(t.check,i,E,I)),n-=E,I+=E,D)break A}else t.head&&(t.head.name=null);t.length=0,t.mode=8;case 8:if(4096&t.flags){if(0===n)break A;E=0;do{D=i[I+E++],t.head&&D&&t.length<65536&&(t.head.comment+=String.fromCharCode(D))}while(D&&E<n);if(512&t.flags&&(t.check=Y(t.check,i,E,I)),n-=E,I+=E,D)break A}else t.head&&(t.head.comment=null);t.mode=9;case 9:if(512&t.flags){for(;B<16;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(o!==(65535&t.check)){A.msg=\"header crc mismatch\",t.mode=30;break}o=0,B=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),A.adler=t.check=0,t.mode=12;break;case 10:for(;B<32;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}A.adler=t.check=cA(o),o=0,B=0,t.mode=11;case 11:if(0===t.havedict)return A.next_out=g,A.avail_out=a,A.next_in=I,A.avail_in=n,t.hold=o,t.bits=B,BA;A.adler=t.check=1,t.mode=12;case 12:if(e===gA||e===nA)break A;case 13:if(t.last){o>>>=7&B,B-=7&B,t.mode=27;break}for(;B<3;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}switch(t.last=1&o,B-=1,3&(o>>>=1)){case 0:t.mode=14;break;case 1:if(pA(t),t.mode=20,e===nA){o>>>=2,B-=2;break A}break;case 2:t.mode=17;break;case 3:A.msg=\"invalid block type\",t.mode=30}o>>>=2,B-=2;break;case 14:for(o>>>=7&B,B-=7&B;B<32;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if((65535&o)!=(o>>>16^65535)){A.msg=\"invalid stored block lengths\",t.mode=30;break}if(t.length=65535&o,o=0,B=0,t.mode=15,e===nA)break A;case 15:t.mode=16;case 16:if(E=t.length){if(E>n&&(E=n),E>a&&(E=a),0===E)break A;r.set(i.subarray(I,I+E),g),n-=E,I+=E,a-=E,g+=E,t.length-=E;break}t.mode=12;break;case 17:for(;B<14;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(t.nlen=257+(31&o),o>>>=5,B-=5,t.ndist=1+(31&o),o>>>=5,B-=5,t.ncode=4+(15&o),o>>>=4,B-=4,t.nlen>286||t.ndist>30){A.msg=\"too many length or distance symbols\",t.mode=30;break}t.have=0,t.mode=18;case 18:for(;t.have<t.ncode;){for(;B<3;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.lens[F[t.have++]]=7&o,o>>>=3,B-=3}for(;t.have<19;)t.lens[F[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},y=rA(0,t.lens,0,19,t.lencode,0,t.work,k),t.lenbits=k.bits,y){A.msg=\"invalid code lengths set\",t.mode=30;break}t.have=0,t.mode=19;case 19:for(;t.have<t.nlen+t.ndist;){for(;h=(m=t.lencode[o&(1<<t.lenbits)-1])>>>16&255,l=65535&m,!((c=m>>>24)<=B);){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(l<16)o>>>=c,B-=c,t.lens[t.have++]=l;else{if(16===l){for(p=c+2;B<p;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(o>>>=c,B-=c,0===t.have){A.msg=\"invalid bit length repeat\",t.mode=30;break}D=t.lens[t.have-1],E=3+(3&o),o>>>=2,B-=2}else if(17===l){for(p=c+3;B<p;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}B-=c,D=0,E=3+(7&(o>>>=c)),o>>>=3,B-=3}else{for(p=c+7;B<p;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}B-=c,D=0,E=11+(127&(o>>>=c)),o>>>=7,B-=7}if(t.have+E>t.nlen+t.ndist){A.msg=\"invalid bit length repeat\",t.mode=30;break}for(;E--;)t.lens[t.have++]=D}}if(30===t.mode)break;if(0===t.lens[256]){A.msg=\"invalid code -- missing end-of-block\",t.mode=30;break}if(t.lenbits=9,k={bits:t.lenbits},y=rA(1,t.lens,0,t.nlen,t.lencode,0,t.work,k),t.lenbits=k.bits,y){A.msg=\"invalid literal/lengths set\",t.mode=30;break}if(t.distbits=6,t.distcode=t.distdyn,k={bits:t.distbits},y=rA(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,k),t.distbits=k.bits,y){A.msg=\"invalid distances set\",t.mode=30;break}if(t.mode=20,e===nA)break A;case 20:t.mode=21;case 21:if(n>=6&&a>=258){A.next_out=g,A.avail_out=a,A.next_in=I,A.avail_in=n,t.hold=o,t.bits=B,$(A,Q),g=A.next_out,r=A.output,a=A.avail_out,I=A.next_in,i=A.input,n=A.avail_in,o=t.hold,B=t.bits,12===t.mode&&(t.back=-1);break}for(t.back=0;h=(m=t.lencode[o&(1<<t.lenbits)-1])>>>16&255,l=65535&m,!((c=m>>>24)<=B);){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(h&&0==(240&h)){for(u=c,w=h,d=l;h=(m=t.lencode[d+((o&(1<<u+w)-1)>>u)])>>>16&255,l=65535&m,!(u+(c=m>>>24)<=B);){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}o>>>=u,B-=u,t.back+=u}if(o>>>=c,B-=c,t.back+=c,t.length=l,0===h){t.mode=26;break}if(32&h){t.back=-1,t.mode=12;break}if(64&h){A.msg=\"invalid literal/length code\",t.mode=30;break}t.extra=15&h,t.mode=22;case 22:if(t.extra){for(p=t.extra;B<p;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.length+=o&(1<<t.extra)-1,o>>>=t.extra,B-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=23;case 23:for(;h=(m=t.distcode[o&(1<<t.distbits)-1])>>>16&255,l=65535&m,!((c=m>>>24)<=B);){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(0==(240&h)){for(u=c,w=h,d=l;h=(m=t.distcode[d+((o&(1<<u+w)-1)>>u)])>>>16&255,l=65535&m,!(u+(c=m>>>24)<=B);){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}o>>>=u,B-=u,t.back+=u}if(o>>>=c,B-=c,t.back+=c,64&h){A.msg=\"invalid distance code\",t.mode=30;break}t.offset=l,t.extra=15&h,t.mode=24;case 24:if(t.extra){for(p=t.extra;B<p;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}t.offset+=o&(1<<t.extra)-1,o>>>=t.extra,B-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){A.msg=\"invalid distance too far back\",t.mode=30;break}t.mode=25;case 25:if(0===a)break A;if(E=Q-a,t.offset>E){if((E=t.offset-E)>t.whave&&t.sane){A.msg=\"invalid distance too far back\",t.mode=30;break}E>t.wnext?(E-=t.wnext,s=t.wsize-E):s=t.wnext-E,E>t.length&&(E=t.length),f=t.window}else f=r,s=g-t.offset,E=t.length;E>a&&(E=a),a-=E,t.length-=E;do{r[g++]=f[s++]}while(--E);0===t.length&&(t.mode=21);break;case 26:if(0===a)break A;r[g++]=t.length,a--,t.mode=21;break;case 27:if(t.wrap){for(;B<32;){if(0===n)break A;n--,o|=i[I++]<<B,B+=8}if(Q-=a,A.total_out+=Q,t.total+=Q,Q&&(A.adler=t.check=t.flags?Y(t.check,r,Q,g-Q):J(t.check,r,Q,g-Q)),Q=a,(t.flags?o:cA(o))!==t.check){A.msg=\"incorrect data check\",t.mode=30;break}o=0,B=0}t.mode=28;case 28:if(t.wrap&&t.flags){for(;B<32;){if(0===n)break A;n--,o+=i[I++]<<B,B+=8}if(o!==(4294967295&t.total)){A.msg=\"incorrect length check\",t.mode=30;break}o=0,B=0}t.mode=29;case 29:y=oA;break A;case 30:y=QA;break A;case 31:return EA;default:return CA}return A.next_out=g,A.avail_out=a,A.next_in=I,A.avail_in=n,t.hold=o,t.bits=B,(t.wsize||Q!==A.avail_out&&t.mode<30&&(t.mode<27||e!==IA))&&mA(A,A.output,A.next_out,Q-A.avail_out),C-=A.avail_in,Q-=A.avail_out,A.total_in+=C,A.total_out+=Q,t.total+=Q,t.wrap&&Q&&(A.adler=t.check=t.flags?Y(t.check,r,Q,A.next_out-Q):J(t.check,r,Q,A.next_out-Q)),A.data_type=t.bits+(t.last?64:0)+(12===t.mode?128:0)+(20===t.mode||15===t.mode?256:0),(0===C&&0===Q||e===IA)&&y===aA&&(y=sA),y},inflateEnd:function(A){if(!A||!A.state)return CA;var e=A.state;return e.window&&(e.window=null),A.state=null,aA},inflateGetHeader:function(A,e){if(!A||!A.state)return CA;var t=A.state;return 0==(2&t.wrap)?CA:(t.head=e,e.done=!1,aA)},inflateSetDictionary:function(A,e){var t,i=e.length;return A&&A.state?0!==(t=A.state).wrap&&11!==t.mode?CA:11===t.mode&&J(1,e,i,0)!==t.check?QA:mA(A,e,i,i)?(t.mode=31,EA):(t.havedict=1,aA):CA},inflateInfo:\"pako inflate (from Nodeca project)\"};var FA=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name=\"\",this.comment=\"\",this.hcrc=0,this.done=!1},SA=Object.prototype.toString,vA=H.Z_NO_FLUSH,RA=H.Z_FINISH,UA=H.Z_OK,LA=H.Z_STREAM_END,bA=H.Z_NEED_DICT,MA=H.Z_STREAM_ERROR,NA=H.Z_DATA_ERROR,xA=H.Z_MEM_ERROR;function JA(A){this.options=P({chunkSize:65536,windowBits:15,to:\"\"},A||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||A&&A.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg=\"\",this.ended=!1,this.chunks=[],this.strm=new z,this.strm.avail_out=0;var t=GA.inflateInit2(this.strm,e.windowBits);if(t!==UA)throw new Error(K[t]);if(this.header=new FA,GA.inflateGetHeader(this.strm,this.header),e.dictionary&&(\"string\"==typeof e.dictionary?e.dictionary=Z(e.dictionary):\"[object ArrayBuffer]\"===SA.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=GA.inflateSetDictionary(this.strm,e.dictionary))!==UA))throw new Error(K[t])}function qA(A,e){var t=new JA(e);if(t.push(A),t.err)throw t.msg||K[t.err];return t.result}JA.prototype.push=function(A,e){var t,i,r,I=this.strm,g=this.options.chunkSize,n=this.options.dictionary;if(this.ended)return!1;for(i=e===~~e?e:!0===e?RA:vA,\"[object ArrayBuffer]\"===SA.call(A)?I.input=new Uint8Array(A):I.input=A,I.next_in=0,I.avail_in=I.input.length;;){for(0===I.avail_out&&(I.output=new Uint8Array(g),I.next_out=0,I.avail_out=g),(t=GA.inflate(I,i))===bA&&n&&((t=GA.inflateSetDictionary(I,n))===UA?t=GA.inflate(I,i):t===NA&&(t=bA));I.avail_in>0&&t===LA&&I.state.wrap>0&&0!==A[I.next_in];)GA.inflateReset(I),t=GA.inflate(I,i);switch(t){case MA:case NA:case bA:case xA:return this.onEnd(t),this.ended=!0,!1}if(r=I.avail_out,I.next_out&&(0===I.avail_out||t===LA))if(\"string\"===this.options.to){var a=W(I.output,I.next_out),o=I.next_out-a,B=j(I.output,a);I.next_out=o,I.avail_out=g-o,o&&I.output.set(I.output.subarray(a,a+o),0),this.onData(B)}else this.onData(I.output.length===I.next_out?I.output:I.output.subarray(0,I.next_out));if(t!==UA||0!==r){if(t===LA)return t=GA.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(0===I.avail_in)break}}return!0},JA.prototype.onData=function(A){this.chunks.push(A)},JA.prototype.onEnd=function(A){A===UA&&(\"string\"===this.options.to?this.result=this.chunks.join(\"\"):this.result=T(this.chunks)),this.chunks=[],this.err=A,this.msg=this.strm.msg};var YA={Inflate:JA,inflate:qA,inflateRaw:function(A,e){return(e=e||{}).raw=!0,qA(A,e)},ungzip:qA,constants:H}.inflate;function KA(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var HA=function(A){s(t,w);var e=KA(t);function t(){return B(this,t),e.apply(this,arguments)}return Q(t,[{key:\"decodeBlock\",value:function(A){return YA(new Uint8Array(A)).buffer}}]),t}(),OA=Object.freeze({__proto__:null,default:HA});function PA(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var TA,VA=function(A){s(t,w);var e=PA(t);function t(){return B(this,t),e.apply(this,arguments)}return Q(t,[{key:\"decodeBlock\",value:function(A){for(var e=new DataView(A),t=[],i=0;i<A.byteLength;++i){var r=e.getInt8(i);if(r<0){var I=e.getUint8(i+1);r=-r;for(var g=0;g<=r;++g)t.push(I);i+=1}else{for(var n=0;n<=r;++n)t.push(e.getUint8(i+n+1));i+=r+1}}return new Uint8Array(t).buffer}}]),t}(),_A=Object.freeze({__proto__:null,default:VA}),XA={exports:{}};TA=XA,\n/* Copyright 2015-2021 Esri. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 @preserve */\nfunction(){var A,e,t,i,r,I,g,n,a,o,B,C,Q,E,s,f,c=(A={defaultNoDataValue:-34027999387901484e22,decode:function(I,g){var n=(g=g||{}).encodedMaskData||null===g.encodedMaskData,a=r(I,g.inputOffset||0,n),o=null!==g.noDataValue?g.noDataValue:A.defaultNoDataValue,B=e(a,g.pixelType||Float32Array,g.encodedMaskData,o,g.returnMask),C={width:a.width,height:a.height,pixelData:B.resultPixels,minValue:B.minValue,maxValue:a.pixels.maxValue,noDataValue:o};return B.resultMask&&(C.maskData=B.resultMask),g.returnEncodedMask&&a.mask&&(C.encodedMaskData=a.mask.bitset?a.mask.bitset:null),g.returnFileInfo&&(C.fileInfo=t(a),g.computeUsedBitDepths&&(C.fileInfo.bitDepths=i(a))),C}},e=function(A,e,t,i,r){var g,n,a,o=0,B=A.pixels.numBlocksX,C=A.pixels.numBlocksY,Q=Math.floor(A.width/B),E=Math.floor(A.height/C),s=2*A.maxZError,f=Number.MAX_VALUE;t=t||(A.mask?A.mask.bitset:null),n=new e(A.width*A.height),r&&t&&(a=new Uint8Array(A.width*A.height));for(var c,h,l=new Float32Array(Q*E),u=0;u<=C;u++){var w=u!==C?E:A.height%C;if(0!==w)for(var d=0;d<=B;d++){var D=d!==B?Q:A.width%B;if(0!==D){var y,k,p,m,G=u*A.width*E+d*Q,F=A.width-D,S=A.pixels.blocks[o];if(S.encoding<2?(0===S.encoding?y=S.rawData:(I(S.stuffedData,S.bitsPerPixel,S.numValidPixels,S.offset,s,l,A.pixels.maxValue),y=l),k=0):p=2===S.encoding?0:S.offset,t)for(h=0;h<w;h++){for(7&G&&(m=t[G>>3],m<<=7&G),c=0;c<D;c++)7&G||(m=t[G>>3]),128&m?(a&&(a[G]=1),f=f>(g=S.encoding<2?y[k++]:p)?g:f,n[G++]=g):(a&&(a[G]=0),n[G++]=i),m<<=1;G+=F}else if(S.encoding<2)for(h=0;h<w;h++){for(c=0;c<D;c++)f=f>(g=y[k++])?g:f,n[G++]=g;G+=F}else for(f=f>p?p:f,h=0;h<w;h++){for(c=0;c<D;c++)n[G++]=p;G+=F}if(1===S.encoding&&k!==S.numValidPixels)throw\"Block and Mask do not match\";o++}}}return{resultPixels:n,resultMask:a,minValue:f}},t=function(A){return{fileIdentifierString:A.fileIdentifierString,fileVersion:A.fileVersion,imageType:A.imageType,height:A.height,width:A.width,maxZError:A.maxZError,eofOffset:A.eofOffset,mask:A.mask?{numBlocksX:A.mask.numBlocksX,numBlocksY:A.mask.numBlocksY,numBytes:A.mask.numBytes,maxValue:A.mask.maxValue}:null,pixels:{numBlocksX:A.pixels.numBlocksX,numBlocksY:A.pixels.numBlocksY,numBytes:A.pixels.numBytes,maxValue:A.pixels.maxValue,noDataValue:A.noDataValue}}},i=function(A){for(var e=A.pixels.numBlocksX*A.pixels.numBlocksY,t={},i=0;i<e;i++){var r=A.pixels.blocks[i];0===r.encoding?t.float32=!0:1===r.encoding?t[r.bitsPerPixel]=!0:t[0]=!0}return Object.keys(t)},r=function(A,e,t){var i={},r=new Uint8Array(A,e,10);if(i.fileIdentifierString=String.fromCharCode.apply(null,r),\"CntZImage\"!==i.fileIdentifierString.trim())throw\"Unexpected file identifier string: \"+i.fileIdentifierString;e+=10;var I=new DataView(A,e,24);if(i.fileVersion=I.getInt32(0,!0),i.imageType=I.getInt32(4,!0),i.height=I.getUint32(8,!0),i.width=I.getUint32(12,!0),i.maxZError=I.getFloat64(16,!0),e+=24,!t)if(I=new DataView(A,e,16),i.mask={},i.mask.numBlocksY=I.getUint32(0,!0),i.mask.numBlocksX=I.getUint32(4,!0),i.mask.numBytes=I.getUint32(8,!0),i.mask.maxValue=I.getFloat32(12,!0),e+=16,i.mask.numBytes>0){var g=new Uint8Array(Math.ceil(i.width*i.height/8)),n=(I=new DataView(A,e,i.mask.numBytes)).getInt16(0,!0),a=2,o=0;do{if(n>0)for(;n--;)g[o++]=I.getUint8(a++);else{var B=I.getUint8(a++);for(n=-n;n--;)g[o++]=B}n=I.getInt16(a,!0),a+=2}while(a<i.mask.numBytes);if(-32768!==n||o<g.length)throw\"Unexpected end of mask RLE encoding\";i.mask.bitset=g,e+=i.mask.numBytes}else 0==(i.mask.numBytes|i.mask.numBlocksY|i.mask.maxValue)&&(i.mask.bitset=new Uint8Array(Math.ceil(i.width*i.height/8)));I=new DataView(A,e,16),i.pixels={},i.pixels.numBlocksY=I.getUint32(0,!0),i.pixels.numBlocksX=I.getUint32(4,!0),i.pixels.numBytes=I.getUint32(8,!0),i.pixels.maxValue=I.getFloat32(12,!0),e+=16;var C=i.pixels.numBlocksX,Q=i.pixels.numBlocksY,E=C+(i.width%C>0?1:0),s=Q+(i.height%Q>0?1:0);i.pixels.blocks=new Array(E*s);for(var f=0,c=0;c<s;c++)for(var h=0;h<E;h++){var l=0,u=A.byteLength-e;I=new DataView(A,e,Math.min(10,u));var w={};i.pixels.blocks[f++]=w;var d=I.getUint8(0);if(l++,w.encoding=63&d,w.encoding>3)throw\"Invalid block encoding (\"+w.encoding+\")\";if(2!==w.encoding){if(0!==d&&2!==d){if(d>>=6,w.offsetType=d,2===d)w.offset=I.getInt8(1),l++;else if(1===d)w.offset=I.getInt16(1,!0),l+=2;else{if(0!==d)throw\"Invalid block offset type\";w.offset=I.getFloat32(1,!0),l+=4}if(1===w.encoding)if(d=I.getUint8(l),l++,w.bitsPerPixel=63&d,d>>=6,w.numValidPixelsType=d,2===d)w.numValidPixels=I.getUint8(l),l++;else if(1===d)w.numValidPixels=I.getUint16(l,!0),l+=2;else{if(0!==d)throw\"Invalid valid pixel count type\";w.numValidPixels=I.getUint32(l,!0),l+=4}}var D;if(e+=l,3!==w.encoding)if(0===w.encoding){var y=(i.pixels.numBytes-1)/4;if(y!==Math.floor(y))throw\"uncompressed block has invalid length\";D=new ArrayBuffer(4*y),new Uint8Array(D).set(new Uint8Array(A,e,4*y));var k=new Float32Array(D);w.rawData=k,e+=4*y}else if(1===w.encoding){var p=Math.ceil(w.numValidPixels*w.bitsPerPixel/8),m=Math.ceil(p/4);D=new ArrayBuffer(4*m),new Uint8Array(D).set(new Uint8Array(A,e,p)),w.stuffedData=new Uint32Array(D),e+=p}}else e++}return i.eofOffset=e,i},I=function(A,e,t,i,r,I,g){var n,a,o,B=(1<<e)-1,C=0,Q=0,E=Math.ceil((g-i)/r),s=4*A.length-Math.ceil(e*t/8);for(A[A.length-1]<<=8*s,n=0;n<t;n++){if(0===Q&&(o=A[C++],Q=32),Q>=e)a=o>>>Q-e&B,Q-=e;else{var f=e-Q;a=(o&B)<<f&B,a+=(o=A[C++])>>>(Q=32-f)}I[n]=a<E?i+a*r:g}return I},A),h=(g=function(A,e,t,i,r,I,g,n){var a,o,B,C,Q,E=(1<<t)-1,s=0,f=0,c=4*A.length-Math.ceil(t*i/8);if(A[A.length-1]<<=8*c,r)for(a=0;a<i;a++)0===f&&(B=A[s++],f=32),f>=t?(o=B>>>f-t&E,f-=t):(o=(B&E)<<(C=t-f)&E,o+=(B=A[s++])>>>(f=32-C)),e[a]=r[o];else for(Q=Math.ceil((n-I)/g),a=0;a<i;a++)0===f&&(B=A[s++],f=32),f>=t?(o=B>>>f-t&E,f-=t):(o=(B&E)<<(C=t-f)&E,o+=(B=A[s++])>>>(f=32-C)),e[a]=o<Q?I+o*g:n},n=function(A,e,t,i,r,I){var g,n=(1<<e)-1,a=0,o=0,B=0,C=0,Q=0,E=[],s=4*A.length-Math.ceil(e*t/8);A[A.length-1]<<=8*s;var f=Math.ceil((I-i)/r);for(o=0;o<t;o++)0===C&&(g=A[a++],C=32),C>=e?(Q=g>>>C-e&n,C-=e):(Q=(g&n)<<(B=e-C)&n,Q+=(g=A[a++])>>>(C=32-B)),E[o]=Q<f?i+Q*r:I;return E.unshift(i),E},a=function(A,e,t,i,r,I,g,n){var a,o,B,C,Q=(1<<t)-1,E=0,s=0,f=0;if(r)for(a=0;a<i;a++)0===s&&(B=A[E++],s=32,f=0),s>=t?(o=B>>>f&Q,s-=t,f+=t):(o=B>>>f&Q,s=32-(C=t-s),o|=((B=A[E++])&(1<<C)-1)<<t-C,f=C),e[a]=r[o];else{var c=Math.ceil((n-I)/g);for(a=0;a<i;a++)0===s&&(B=A[E++],s=32,f=0),s>=t?(o=B>>>f&Q,s-=t,f+=t):(o=B>>>f&Q,s=32-(C=t-s),o|=((B=A[E++])&(1<<C)-1)<<t-C,f=C),e[a]=o<c?I+o*g:n}return e},o=function(A,e,t,i,r,I){var g,n=(1<<e)-1,a=0,o=0,B=0,C=0,Q=0,E=0,s=[],f=Math.ceil((I-i)/r);for(o=0;o<t;o++)0===C&&(g=A[a++],C=32,E=0),C>=e?(Q=g>>>E&n,C-=e,E+=e):(Q=g>>>E&n,C=32-(B=e-C),Q|=((g=A[a++])&(1<<B)-1)<<e-B,E=B),s[o]=Q<f?i+Q*r:I;return s.unshift(i),s},B=function(A,e,t,i){var r,I,g,n,a=(1<<t)-1,o=0,B=0,C=4*A.length-Math.ceil(t*i/8);for(A[A.length-1]<<=8*C,r=0;r<i;r++)0===B&&(g=A[o++],B=32),B>=t?(I=g>>>B-t&a,B-=t):(I=(g&a)<<(n=t-B)&a,I+=(g=A[o++])>>>(B=32-n)),e[r]=I;return e},C=function(A,e,t,i){var r,I,g,n,a=(1<<t)-1,o=0,B=0,C=0;for(r=0;r<i;r++)0===B&&(g=A[o++],B=32,C=0),B>=t?(I=g>>>C&a,B-=t,C+=t):(I=g>>>C&a,B=32-(n=t-B),I|=((g=A[o++])&(1<<n)-1)<<t-n,C=n),e[r]=I;return e},Q={HUFFMAN_LUT_BITS_MAX:12,computeChecksumFletcher32:function(A){for(var e=65535,t=65535,i=A.length,r=Math.floor(i/2),I=0;r;){var g=r>=359?359:r;r-=g;do{e+=A[I++]<<8,t+=e+=A[I++]}while(--g);e=(65535&e)+(e>>>16),t=(65535&t)+(t>>>16)}return 1&i&&(t+=e+=A[I]<<8),((t=(65535&t)+(t>>>16))<<16|(e=(65535&e)+(e>>>16)))>>>0},readHeaderInfo:function(A,e){var t=e.ptr,i=new Uint8Array(A,t,6),r={};if(r.fileIdentifierString=String.fromCharCode.apply(null,i),0!==r.fileIdentifierString.lastIndexOf(\"Lerc2\",0))throw\"Unexpected file identifier string (expect Lerc2 ): \"+r.fileIdentifierString;t+=6;var I,g=new DataView(A,t,8),n=g.getInt32(0,!0);if(r.fileVersion=n,t+=4,n>=3&&(r.checksum=g.getUint32(4,!0),t+=4),g=new DataView(A,t,12),r.height=g.getUint32(0,!0),r.width=g.getUint32(4,!0),t+=8,n>=4?(r.numDims=g.getUint32(8,!0),t+=4):r.numDims=1,g=new DataView(A,t,40),r.numValidPixel=g.getUint32(0,!0),r.microBlockSize=g.getInt32(4,!0),r.blobSize=g.getInt32(8,!0),r.imageType=g.getInt32(12,!0),r.maxZError=g.getFloat64(16,!0),r.zMin=g.getFloat64(24,!0),r.zMax=g.getFloat64(32,!0),t+=40,e.headerInfo=r,e.ptr=t,n>=3&&(I=n>=4?52:48,this.computeChecksumFletcher32(new Uint8Array(A,t-I,r.blobSize-14))!==r.checksum))throw\"Checksum failed.\";return!0},checkMinMaxRanges:function(A,e){var t=e.headerInfo,i=this.getDataTypeArray(t.imageType),r=t.numDims*this.getDataTypeSize(t.imageType),I=this.readSubArray(A,e.ptr,i,r),g=this.readSubArray(A,e.ptr+r,i,r);e.ptr+=2*r;var n,a=!0;for(n=0;n<t.numDims;n++)if(I[n]!==g[n]){a=!1;break}return t.minValues=I,t.maxValues=g,a},readSubArray:function(A,e,t,i){var r;if(t===Uint8Array)r=new Uint8Array(A,e,i);else{var I=new ArrayBuffer(i);new Uint8Array(I).set(new Uint8Array(A,e,i)),r=new t(I)}return r},readMask:function(A,e){var t,i,r=e.ptr,I=e.headerInfo,g=I.width*I.height,n=I.numValidPixel,a=new DataView(A,r,4),o={};if(o.numBytes=a.getUint32(0,!0),r+=4,(0===n||g===n)&&0!==o.numBytes)throw\"invalid mask\";if(0===n)t=new Uint8Array(Math.ceil(g/8)),o.bitset=t,i=new Uint8Array(g),e.pixels.resultMask=i,r+=o.numBytes;else if(o.numBytes>0){t=new Uint8Array(Math.ceil(g/8));var B=(a=new DataView(A,r,o.numBytes)).getInt16(0,!0),C=2,Q=0,E=0;do{if(B>0)for(;B--;)t[Q++]=a.getUint8(C++);else for(E=a.getUint8(C++),B=-B;B--;)t[Q++]=E;B=a.getInt16(C,!0),C+=2}while(C<o.numBytes);if(-32768!==B||Q<t.length)throw\"Unexpected end of mask RLE encoding\";i=new Uint8Array(g);var s=0,f=0;for(f=0;f<g;f++)7&f?(s=t[f>>3],s<<=7&f):s=t[f>>3],128&s&&(i[f]=1);e.pixels.resultMask=i,o.bitset=t,r+=o.numBytes}return e.ptr=r,e.mask=o,!0},readDataOneSweep:function(A,e,t,i){var r,I=e.ptr,g=e.headerInfo,n=g.numDims,a=g.width*g.height,o=g.imageType,B=g.numValidPixel*Q.getDataTypeSize(o)*n,C=e.pixels.resultMask;if(t===Uint8Array)r=new Uint8Array(A,I,B);else{var E=new ArrayBuffer(B);new Uint8Array(E).set(new Uint8Array(A,I,B)),r=new t(E)}if(r.length===a*n)e.pixels.resultPixels=i?Q.swapDimensionOrder(r,a,n,t,!0):r;else{e.pixels.resultPixels=new t(a*n);var s=0,f=0,c=0,h=0;if(n>1){if(i){for(f=0;f<a;f++)if(C[f])for(h=f,c=0;c<n;c++,h+=a)e.pixels.resultPixels[h]=r[s++]}else for(f=0;f<a;f++)if(C[f])for(h=f*n,c=0;c<n;c++)e.pixels.resultPixels[h+c]=r[s++]}else for(f=0;f<a;f++)C[f]&&(e.pixels.resultPixels[f]=r[s++])}return I+=B,e.ptr=I,!0},readHuffmanTree:function(A,e){var t=this.HUFFMAN_LUT_BITS_MAX,i=new DataView(A,e.ptr,16);if(e.ptr+=16,i.getInt32(0,!0)<2)throw\"unsupported Huffman version\";var r=i.getInt32(4,!0),I=i.getInt32(8,!0),g=i.getInt32(12,!0);if(I>=g)return!1;var n=new Uint32Array(g-I);Q.decodeBits(A,e,n);var a,o,B,C,s=[];for(a=I;a<g;a++)s[o=a-(a<r?0:r)]={first:n[a-I],second:null};var f=A.byteLength-e.ptr,c=Math.ceil(f/4),h=new ArrayBuffer(4*c);new Uint8Array(h).set(new Uint8Array(A,e.ptr,f));var l,u=new Uint32Array(h),w=0,d=0;for(l=u[0],a=I;a<g;a++)(C=s[o=a-(a<r?0:r)].first)>0&&(s[o].second=l<<w>>>32-C,32-w>=C?32===(w+=C)&&(w=0,l=u[++d]):(w+=C-32,l=u[++d],s[o].second|=l>>>32-w));var D=0,y=0,k=new E;for(a=0;a<s.length;a++)void 0!==s[a]&&(D=Math.max(D,s[a].first));y=D>=t?t:D;var p,m,G,F,S,v=[];for(a=I;a<g;a++)if((C=s[o=a-(a<r?0:r)].first)>0)if(p=[C,o],C<=y)for(m=s[o].second<<y-C,G=1<<y-C,B=0;B<G;B++)v[m|B]=p;else for(m=s[o].second,S=k,F=C-1;F>=0;F--)m>>>F&1?(S.right||(S.right=new E),S=S.right):(S.left||(S.left=new E),S=S.left),0!==F||S.val||(S.val=p[1]);return{decodeLut:v,numBitsLUTQick:y,numBitsLUT:D,tree:k,stuffedData:u,srcPtr:d,bitPos:w}},readHuffman:function(A,e,t,i){var r,I,g,n,a,o,B,C,E,s=e.headerInfo.numDims,f=e.headerInfo.height,c=e.headerInfo.width,h=c*f,l=this.readHuffmanTree(A,e),u=l.decodeLut,w=l.tree,d=l.stuffedData,D=l.srcPtr,y=l.bitPos,k=l.numBitsLUTQick,p=l.numBitsLUT,m=0===e.headerInfo.imageType?128:0,G=e.pixels.resultMask,F=0;y>0&&(D++,y=0);var S,v=d[D],R=1===e.encodeMode,U=new t(h*s),L=U;if(s<2||R){for(S=0;S<s;S++)if(s>1&&(L=new t(U.buffer,h*S,h),F=0),e.headerInfo.numValidPixel===c*f)for(C=0,o=0;o<f;o++)for(B=0;B<c;B++,C++){if(I=0,a=n=v<<y>>>32-k,32-y<k&&(a=n|=d[D+1]>>>64-y-k),u[a])I=u[a][1],y+=u[a][0];else for(a=n=v<<y>>>32-p,32-y<p&&(a=n|=d[D+1]>>>64-y-p),r=w,E=0;E<p;E++)if(!(r=n>>>p-E-1&1?r.right:r.left).left&&!r.right){I=r.val,y=y+E+1;break}y>=32&&(y-=32,v=d[++D]),g=I-m,R?(g+=B>0?F:o>0?L[C-c]:F,g&=255,L[C]=g,F=g):L[C]=g}else for(C=0,o=0;o<f;o++)for(B=0;B<c;B++,C++)if(G[C]){if(I=0,a=n=v<<y>>>32-k,32-y<k&&(a=n|=d[D+1]>>>64-y-k),u[a])I=u[a][1],y+=u[a][0];else for(a=n=v<<y>>>32-p,32-y<p&&(a=n|=d[D+1]>>>64-y-p),r=w,E=0;E<p;E++)if(!(r=n>>>p-E-1&1?r.right:r.left).left&&!r.right){I=r.val,y=y+E+1;break}y>=32&&(y-=32,v=d[++D]),g=I-m,R?(B>0&&G[C-1]?g+=F:o>0&&G[C-c]?g+=L[C-c]:g+=F,g&=255,L[C]=g,F=g):L[C]=g}}else for(C=0,o=0;o<f;o++)for(B=0;B<c;B++)if(C=o*c+B,!G||G[C])for(S=0;S<s;S++,C+=h){if(I=0,a=n=v<<y>>>32-k,32-y<k&&(a=n|=d[D+1]>>>64-y-k),u[a])I=u[a][1],y+=u[a][0];else for(a=n=v<<y>>>32-p,32-y<p&&(a=n|=d[D+1]>>>64-y-p),r=w,E=0;E<p;E++)if(!(r=n>>>p-E-1&1?r.right:r.left).left&&!r.right){I=r.val,y=y+E+1;break}y>=32&&(y-=32,v=d[++D]),g=I-m,L[C]=g}e.ptr=e.ptr+4*(D+1)+(y>0?4:0),e.pixels.resultPixels=U,s>1&&!i&&(e.pixels.resultPixels=Q.swapDimensionOrder(U,h,s,t))},decodeBits:function(A,e,t,i,r){var I=e.headerInfo,Q=I.fileVersion,E=0,s=A.byteLength-e.ptr>=5?5:A.byteLength-e.ptr,f=new DataView(A,e.ptr,s),c=f.getUint8(0);E++;var h=c>>6,l=0===h?4:3-h,u=(32&c)>0,w=31&c,d=0;if(1===l)d=f.getUint8(E),E++;else if(2===l)d=f.getUint16(E,!0),E+=2;else{if(4!==l)throw\"Invalid valid pixel count type\";d=f.getUint32(E,!0),E+=4}var D,y,k,p,m,G,F,S,v,R=2*I.maxZError,U=I.numDims>1?I.maxValues[r]:I.zMax;if(u){for(e.counter.lut++,S=f.getUint8(E),E++,p=Math.ceil((S-1)*w/8),m=Math.ceil(p/4),y=new ArrayBuffer(4*m),k=new Uint8Array(y),e.ptr+=E,k.set(new Uint8Array(A,e.ptr,p)),F=new Uint32Array(y),e.ptr+=p,v=0;S-1>>>v;)v++;p=Math.ceil(d*v/8),m=Math.ceil(p/4),y=new ArrayBuffer(4*m),(k=new Uint8Array(y)).set(new Uint8Array(A,e.ptr,p)),D=new Uint32Array(y),e.ptr+=p,G=Q>=3?o(F,w,S-1,i,R,U):n(F,w,S-1,i,R,U),Q>=3?a(D,t,v,d,G):g(D,t,v,d,G)}else e.counter.bitstuffer++,v=w,e.ptr+=E,v>0&&(p=Math.ceil(d*v/8),m=Math.ceil(p/4),y=new ArrayBuffer(4*m),(k=new Uint8Array(y)).set(new Uint8Array(A,e.ptr,p)),D=new Uint32Array(y),e.ptr+=p,Q>=3?null==i?C(D,t,v,d):a(D,t,v,d,!1,i,R,U):null==i?B(D,t,v,d):g(D,t,v,d,!1,i,R,U))},readTiles:function(A,e,t,i){var r=e.headerInfo,I=r.width,g=r.height,n=I*g,a=r.microBlockSize,o=r.imageType,B=Q.getDataTypeSize(o),C=Math.ceil(I/a),E=Math.ceil(g/a);e.pixels.numBlocksY=E,e.pixels.numBlocksX=C,e.pixels.ptr=0;var s,f,c,h,l,u,w,d,D,y,k=0,p=0,m=0,G=0,F=0,S=0,v=0,R=0,U=0,L=0,b=0,M=0,N=0,x=0,J=0,q=new t(a*a),Y=g%a||a,K=I%a||a,H=r.numDims,O=e.pixels.resultMask,P=e.pixels.resultPixels,T=r.fileVersion>=5?14:15,V=r.zMax;for(m=0;m<E;m++)for(F=m!==E-1?a:Y,G=0;G<C;G++)for(L=m*I*a+G*a,b=I-(S=G!==C-1?a:K),d=0;d<H;d++){if(H>1?(y=P,L=m*I*a+G*a,P=new t(e.pixels.resultPixels.buffer,n*d*B,n),V=r.maxValues[d]):y=null,v=A.byteLength-e.ptr,f={},J=0,R=(s=new DataView(A,e.ptr,Math.min(10,v))).getUint8(0),J++,D=r.fileVersion>=5?4&R:0,U=R>>6&255,(R>>2&T)!=(G*a>>3&T))throw\"integrity issue\";if(D&&0===d)throw\"integrity issue\";if((l=3&R)>3)throw e.ptr+=J,\"Invalid block encoding (\"+l+\")\";if(2!==l)if(0===l){if(D)throw\"integrity issue\";if(e.counter.uncompressed++,e.ptr+=J,M=(M=F*S*B)<(N=A.byteLength-e.ptr)?M:N,c=new ArrayBuffer(M%B==0?M:M+B-M%B),new Uint8Array(c).set(new Uint8Array(A,e.ptr,M)),h=new t(c),x=0,O)for(k=0;k<F;k++){for(p=0;p<S;p++)O[L]&&(P[L]=h[x++]),L++;L+=b}else for(k=0;k<F;k++){for(p=0;p<S;p++)P[L++]=h[x++];L+=b}e.ptr+=x*B}else if(u=Q.getDataTypeUsed(D&&o<6?4:o,U),w=Q.getOnePixel(f,J,u,s),J+=Q.getDataTypeSize(u),3===l)if(e.ptr+=J,e.counter.constantoffset++,O)for(k=0;k<F;k++){for(p=0;p<S;p++)O[L]&&(P[L]=D?Math.min(V,y[L]+w):w),L++;L+=b}else for(k=0;k<F;k++){for(p=0;p<S;p++)P[L]=D?Math.min(V,y[L]+w):w,L++;L+=b}else if(e.ptr+=J,Q.decodeBits(A,e,q,w,d),J=0,D)if(O)for(k=0;k<F;k++){for(p=0;p<S;p++)O[L]&&(P[L]=q[J++]+y[L]),L++;L+=b}else for(k=0;k<F;k++){for(p=0;p<S;p++)P[L]=q[J++]+y[L],L++;L+=b}else if(O)for(k=0;k<F;k++){for(p=0;p<S;p++)O[L]&&(P[L]=q[J++]),L++;L+=b}else for(k=0;k<F;k++){for(p=0;p<S;p++)P[L++]=q[J++];L+=b}else{if(D)if(O)for(k=0;k<F;k++)for(p=0;p<S;p++)O[L]&&(P[L]=y[L]),L++;else for(k=0;k<F;k++)for(p=0;p<S;p++)P[L]=y[L],L++;e.counter.constant++,e.ptr+=J}}H>1&&!i&&(e.pixels.resultPixels=Q.swapDimensionOrder(e.pixels.resultPixels,n,H,t))},formatFileInfo:function(A){return{fileIdentifierString:A.headerInfo.fileIdentifierString,fileVersion:A.headerInfo.fileVersion,imageType:A.headerInfo.imageType,height:A.headerInfo.height,width:A.headerInfo.width,numValidPixel:A.headerInfo.numValidPixel,microBlockSize:A.headerInfo.microBlockSize,blobSize:A.headerInfo.blobSize,maxZError:A.headerInfo.maxZError,pixelType:Q.getPixelType(A.headerInfo.imageType),eofOffset:A.eofOffset,mask:A.mask?{numBytes:A.mask.numBytes}:null,pixels:{numBlocksX:A.pixels.numBlocksX,numBlocksY:A.pixels.numBlocksY,maxValue:A.headerInfo.zMax,minValue:A.headerInfo.zMin,noDataValue:A.noDataValue}}},constructConstantSurface:function(A,e){var t=A.headerInfo.zMax,i=A.headerInfo.zMin,r=A.headerInfo.maxValues,I=A.headerInfo.numDims,g=A.headerInfo.height*A.headerInfo.width,n=0,a=0,o=0,B=A.pixels.resultMask,C=A.pixels.resultPixels;if(B)if(I>1){if(e)for(n=0;n<I;n++)for(o=n*g,t=r[n],a=0;a<g;a++)B[a]&&(C[o+a]=t);else for(a=0;a<g;a++)if(B[a])for(o=a*I,n=0;n<I;n++)C[o+I]=r[n]}else for(a=0;a<g;a++)B[a]&&(C[a]=t);else if(I>1&&i!==t)if(e)for(n=0;n<I;n++)for(o=n*g,t=r[n],a=0;a<g;a++)C[o+a]=t;else for(a=0;a<g;a++)for(o=a*I,n=0;n<I;n++)C[o+n]=r[n];else for(a=0;a<g*I;a++)C[a]=t},getDataTypeArray:function(A){var e;switch(A){case 0:e=Int8Array;break;case 1:e=Uint8Array;break;case 2:e=Int16Array;break;case 3:e=Uint16Array;break;case 4:e=Int32Array;break;case 5:e=Uint32Array;break;case 6:default:e=Float32Array;break;case 7:e=Float64Array}return e},getPixelType:function(A){var e;switch(A){case 0:e=\"S8\";break;case 1:e=\"U8\";break;case 2:e=\"S16\";break;case 3:e=\"U16\";break;case 4:e=\"S32\";break;case 5:e=\"U32\";break;case 6:default:e=\"F32\";break;case 7:e=\"F64\"}return e},isValidPixelValue:function(A,e){if(null==e)return!1;var t;switch(A){case 0:t=e>=-128&&e<=127;break;case 1:t=e>=0&&e<=255;break;case 2:t=e>=-32768&&e<=32767;break;case 3:t=e>=0&&e<=65536;break;case 4:t=e>=-2147483648&&e<=2147483647;break;case 5:t=e>=0&&e<=4294967296;break;case 6:t=e>=-34027999387901484e22&&e<=34027999387901484e22;break;case 7:t=e>=-17976931348623157e292&&e<=17976931348623157e292;break;default:t=!1}return t},getDataTypeSize:function(A){var e=0;switch(A){case 0:case 1:e=1;break;case 2:case 3:e=2;break;case 4:case 5:case 6:e=4;break;case 7:e=8;break;default:e=A}return e},getDataTypeUsed:function(A,e){var t=A;switch(A){case 2:case 4:t=A-e;break;case 3:case 5:t=A-2*e;break;case 6:t=0===e?A:1===e?2:1;break;case 7:t=0===e?A:A-2*e+1;break;default:t=A}return t},getOnePixel:function(A,e,t,i){var r=0;switch(t){case 0:r=i.getInt8(e);break;case 1:r=i.getUint8(e);break;case 2:r=i.getInt16(e,!0);break;case 3:r=i.getUint16(e,!0);break;case 4:r=i.getInt32(e,!0);break;case 5:r=i.getUInt32(e,!0);break;case 6:r=i.getFloat32(e,!0);break;case 7:r=i.getFloat64(e,!0);break;default:throw\"the decoder does not understand this pixel type\"}return r},swapDimensionOrder:function(A,e,t,i,r){var I=0,g=0,n=0,a=0,o=A;if(t>1)if(o=new i(e*t),r)for(I=0;I<e;I++)for(a=I,n=0;n<t;n++,a+=e)o[a]=A[g++];else for(I=0;I<e;I++)for(a=I,n=0;n<t;n++,a+=e)o[g++]=A[a];return o}},E=function(A,e,t){this.val=A,this.left=e,this.right=t},{decode:function(A,e){var t=(e=e||{}).noDataValue,i=0,r={};r.ptr=e.inputOffset||0,r.pixels={},Q.readHeaderInfo(A,r);var I=r.headerInfo,g=I.fileVersion,n=Q.getDataTypeArray(I.imageType);if(g>5)throw\"unsupported lerc version 2.\"+g;Q.readMask(A,r),I.numValidPixel===I.width*I.height||r.pixels.resultMask||(r.pixels.resultMask=e.maskData);var a=I.width*I.height;r.pixels.resultPixels=new n(a*I.numDims),r.counter={onesweep:0,uncompressed:0,lut:0,bitstuffer:0,constant:0,constantoffset:0};var o,B=!e.returnPixelInterleavedDims;if(0!==I.numValidPixel)if(I.zMax===I.zMin)Q.constructConstantSurface(r,B);else if(g>=4&&Q.checkMinMaxRanges(A,r))Q.constructConstantSurface(r,B);else{var C=new DataView(A,r.ptr,2),E=C.getUint8(0);if(r.ptr++,E)Q.readDataOneSweep(A,r,n,B);else if(g>1&&I.imageType<=1&&Math.abs(I.maxZError-.5)<1e-5){var s=C.getUint8(1);if(r.ptr++,r.encodeMode=s,s>2||g<4&&s>1)throw\"Invalid Huffman flag \"+s;s?Q.readHuffman(A,r,n,B):Q.readTiles(A,r,n,B)}else Q.readTiles(A,r,n,B)}r.eofOffset=r.ptr,e.inputOffset?(o=r.headerInfo.blobSize+e.inputOffset-r.ptr,Math.abs(o)>=1&&(r.eofOffset=e.inputOffset+r.headerInfo.blobSize)):(o=r.headerInfo.blobSize-r.ptr,Math.abs(o)>=1&&(r.eofOffset=r.headerInfo.blobSize));var f={width:I.width,height:I.height,pixelData:r.pixels.resultPixels,minValue:I.zMin,maxValue:I.zMax,validPixelCount:I.numValidPixel,dimCount:I.numDims,dimStats:{minValues:I.minValues,maxValues:I.maxValues},maskData:r.pixels.resultMask};if(r.pixels.resultMask&&Q.isValidPixelValue(I.imageType,t)){var c=r.pixels.resultMask;for(i=0;i<a;i++)c[i]||(f.pixelData[i]=t);f.noDataValue=t}return r.noDataValue=t,e.returnFileInfo&&(f.fileInfo=Q.formatFileInfo(r)),f},getBandCount:function(A){for(var e=0,t=0,i={ptr:0,pixels:{}};t<A.byteLength-58;)Q.readHeaderInfo(A,i),t+=i.headerInfo.blobSize,e++,i.ptr=t;return e}}),l=(s=new ArrayBuffer(4),f=new Uint8Array(s),new Uint32Array(s)[0]=1,1===f[0]),u={decode:function(A,e){if(!l)throw\"Big endian system is not supported.\";var t,i,r=(e=e||{}).inputOffset||0,I=new Uint8Array(A,r,10),g=String.fromCharCode.apply(null,I);if(\"CntZImage\"===g.trim())t=c,i=1;else{if(\"Lerc2\"!==g.substring(0,5))throw\"Unexpected file identifier string: \"+g;t=h,i=2}for(var n,a,o,B,C,Q,E=0,s=A.byteLength-10,f=[],u={width:0,height:0,pixels:[],pixelType:e.pixelType,mask:null,statistics:[]},w=0;r<s;){var d=t.decode(A,{inputOffset:r,encodedMaskData:n,maskData:o,returnMask:0===E,returnEncodedMask:0===E,returnFileInfo:!0,returnPixelInterleavedDims:e.returnPixelInterleavedDims,pixelType:e.pixelType||null,noDataValue:e.noDataValue||null});r=d.fileInfo.eofOffset,o=d.maskData,0===E&&(n=d.encodedMaskData,u.width=d.width,u.height=d.height,u.dimCount=d.dimCount||1,u.pixelType=d.pixelType||d.fileInfo.pixelType,u.mask=o),i>1&&(o&&f.push(o),d.fileInfo.mask&&d.fileInfo.mask.numBytes>0&&w++),E++,u.pixels.push(d.pixelData),u.statistics.push({minValue:d.minValue,maxValue:d.maxValue,noDataValue:d.noDataValue,dimStats:d.dimStats})}if(i>1&&w>1){for(Q=u.width*u.height,u.bandMasks=f,(o=new Uint8Array(Q)).set(f[0]),B=1;B<f.length;B++)for(a=f[B],C=0;C<Q;C++)o[C]=o[C]&a[C];u.maskData=o}return u}};TA.exports?TA.exports=u:this.Lerc=u}();var ZA,jA,WA,zA=XA.exports,$A={env:{emscripten_notify_memory_growth:function(A){WA=new Uint8Array(jA.exports.memory.buffer)}}},Ae=function(){function A(){B(this,A)}return Q(A,[{key:\"init\",value:function(){return ZA||(ZA=\"undefined\"!=typeof fetch?fetch(\"data:application/wasm;base64,\"+ee).then((function(A){return A.arrayBuffer()})).then((function(A){return WebAssembly.instantiate(A,$A)})).then(this._init):WebAssembly.instantiate(Buffer.from(ee,\"base64\"),$A).then(this._init))}},{key:\"_init\",value:function(A){jA=A.instance,$A.env.emscripten_notify_memory_growth(0)}},{key:\"decode\",value:function(A){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!jA)throw new Error(\"ZSTDDecoder: Await .init() before decoding.\");var t=A.byteLength,i=jA.exports.malloc(t);WA.set(A,i),e=e||Number(jA.exports.ZSTD_findDecompressedSize(i,t));var r=jA.exports.malloc(e),I=jA.exports.ZSTD_decompress(r,e,i,t),g=WA.slice(r,r+I);return jA.exports.free(i),jA.exports.free(r),g}}]),A}(),ee=\" \",te={315:\"Artist\",258:\"BitsPerSample\",265:\"CellLength\",264:\"CellWidth\",320:\"ColorMap\",259:\"Compression\",33432:\"Copyright\",306:\"DateTime\",338:\"ExtraSamples\",266:\"FillOrder\",289:\"FreeByteCounts\",288:\"FreeOffsets\",291:\"GrayResponseCurve\",290:\"GrayResponseUnit\",316:\"HostComputer\",270:\"ImageDescription\",257:\"ImageLength\",256:\"ImageWidth\",271:\"Make\",281:\"MaxSampleValue\",280:\"MinSampleValue\",272:\"Model\",254:\"NewSubfileType\",274:\"Orientation\",262:\"PhotometricInterpretation\",284:\"PlanarConfiguration\",296:\"ResolutionUnit\",278:\"RowsPerStrip\",277:\"SamplesPerPixel\",305:\"Software\",279:\"StripByteCounts\",273:\"StripOffsets\",255:\"SubfileType\",263:\"Threshholding\",282:\"XResolution\",283:\"YResolution\",326:\"BadFaxLines\",327:\"CleanFaxData\",343:\"ClipPath\",328:\"ConsecutiveBadFaxLines\",433:\"Decode\",434:\"DefaultImageColor\",269:\"DocumentName\",336:\"DotRange\",321:\"HalftoneHints\",346:\"Indexed\",347:\"JPEGTables\",285:\"PageName\",297:\"PageNumber\",317:\"Predictor\",319:\"PrimaryChromaticities\",532:\"ReferenceBlackWhite\",339:\"SampleFormat\",340:\"SMinSampleValue\",341:\"SMaxSampleValue\",559:\"StripRowCounts\",330:\"SubIFDs\",292:\"T4Options\",293:\"T6Options\",325:\"TileByteCounts\",323:\"TileLength\",324:\"TileOffsets\",322:\"TileWidth\",301:\"TransferFunction\",318:\"WhitePoint\",344:\"XClipPathUnits\",286:\"XPosition\",529:\"YCbCrCoefficients\",531:\"YCbCrPositioning\",530:\"YCbCrSubSampling\",345:\"YClipPathUnits\",287:\"YPosition\",37378:\"ApertureValue\",40961:\"ColorSpace\",36868:\"DateTimeDigitized\",36867:\"DateTimeOriginal\",34665:\"Exif IFD\",36864:\"ExifVersion\",33434:\"ExposureTime\",41728:\"FileSource\",37385:\"Flash\",40960:\"FlashpixVersion\",33437:\"FNumber\",42016:\"ImageUniqueID\",37384:\"LightSource\",37500:\"MakerNote\",37377:\"ShutterSpeedValue\",37510:\"UserComment\",33723:\"IPTC\",34675:\"ICC Profile\",700:\"XMP\",42112:\"GDAL_METADATA\",42113:\"GDAL_NODATA\",34377:\"Photoshop\",33550:\"ModelPixelScale\",33922:\"ModelTiepoint\",34264:\"ModelTransformation\",34735:\"GeoKeyDirectory\",34736:\"GeoDoubleParams\",34737:\"GeoAsciiParams\",50674:\"LercParameters\"},ie={};for(var re in te)te.hasOwnProperty(re)&&(ie[te[re]]=parseInt(re,10));ie.BitsPerSample,ie.ExtraSamples,ie.SampleFormat,ie.StripByteCounts,ie.StripOffsets,ie.StripRowCounts,ie.TileByteCounts,ie.TileOffsets,ie.SubIFDs;var Ie={1:\"BYTE\",2:\"ASCII\",3:\"SHORT\",4:\"LONG\",5:\"RATIONAL\",6:\"SBYTE\",7:\"UNDEFINED\",8:\"SSHORT\",9:\"SLONG\",10:\"SRATIONAL\",11:\"FLOAT\",12:\"DOUBLE\",13:\"IFD\",16:\"LONG8\",17:\"SLONG8\",18:\"IFD8\"},ge={};for(var ne in Ie)Ie.hasOwnProperty(ne)&&(ge[Ie[ne]]=parseInt(ne,10));var ae=1,oe=0,Be=1,Ce=2,Qe={1024:\"GTModelTypeGeoKey\",1025:\"GTRasterTypeGeoKey\",1026:\"GTCitationGeoKey\",2048:\"GeographicTypeGeoKey\",2049:\"GeogCitationGeoKey\",2050:\"GeogGeodeticDatumGeoKey\",2051:\"GeogPrimeMeridianGeoKey\",2052:\"GeogLinearUnitsGeoKey\",2053:\"GeogLinearUnitSizeGeoKey\",2054:\"GeogAngularUnitsGeoKey\",2055:\"GeogAngularUnitSizeGeoKey\",2056:\"GeogEllipsoidGeoKey\",2057:\"GeogSemiMajorAxisGeoKey\",2058:\"GeogSemiMinorAxisGeoKey\",2059:\"GeogInvFlatteningGeoKey\",2060:\"GeogAzimuthUnitsGeoKey\",2061:\"GeogPrimeMeridianLongGeoKey\",2062:\"GeogTOWGS84GeoKey\",3072:\"ProjectedCSTypeGeoKey\",3073:\"PCSCitationGeoKey\",3074:\"ProjectionGeoKey\",3075:\"ProjCoordTransGeoKey\",3076:\"ProjLinearUnitsGeoKey\",3077:\"ProjLinearUnitSizeGeoKey\",3078:\"ProjStdParallel1GeoKey\",3079:\"ProjStdParallel2GeoKey\",3080:\"ProjNatOriginLongGeoKey\",3081:\"ProjNatOriginLatGeoKey\",3082:\"ProjFalseEastingGeoKey\",3083:\"ProjFalseNorthingGeoKey\",3084:\"ProjFalseOriginLongGeoKey\",3085:\"ProjFalseOriginLatGeoKey\",3086:\"ProjFalseOriginEastingGeoKey\",3087:\"ProjFalseOriginNorthingGeoKey\",3088:\"ProjCenterLongGeoKey\",3089:\"ProjCenterLatGeoKey\",3090:\"ProjCenterEastingGeoKey\",3091:\"ProjCenterNorthingGeoKey\",3092:\"ProjScaleAtNatOriginGeoKey\",3093:\"ProjScaleAtCenterGeoKey\",3094:\"ProjAzimuthAngleGeoKey\",3095:\"ProjStraightVertPoleLongGeoKey\",3096:\"ProjRectifiedGridAngleGeoKey\",4096:\"VerticalCSTypeGeoKey\",4097:\"VerticalCitationGeoKey\",4098:\"VerticalDatumGeoKey\",4099:\"VerticalUnitsGeoKey\"},Ee={};for(var se in Qe)Qe.hasOwnProperty(se)&&(Ee[Qe[se]]=parseInt(se,10));function fe(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var ce=new Ae,he=function(A){s(t,w);var e=fe(t);function t(A){var i;return B(this,t),(i=e.call(this)).planarConfiguration=void 0!==A.PlanarConfiguration?A.PlanarConfiguration:1,i.samplesPerPixel=void 0!==A.SamplesPerPixel?A.SamplesPerPixel:1,i.addCompression=A.LercParameters[ae],i}return Q(t,[{key:\"decodeBlock\",value:function(A){switch(this.addCompression){case oe:break;case Be:A=YA(new Uint8Array(A)).buffer;break;case Ce:A=ce.decode(new Uint8Array(A)).buffer;break;default:throw new Error(\"Unsupported LERC additional compression method identifier: \".concat(this.addCompression))}return zA.decode(A,{returnPixelInterleavedDims:1===this.planarConfiguration}).pixels[0].buffer}}]),t}(),le=Object.freeze({__proto__:null,zstd:ce,default:he});function ue(A){var e=function(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(A){return!1}}();return function(){var t,i=c(A);if(e){var r=c(this).constructor;t=Reflect.construct(i,arguments,r)}else t=i.apply(this,arguments);return f(this,t)}}var we=function(A){s(I,w);var t,i=ue(I);function I(){var A;if(B(this,I),A=i.call(this),\"undefined\"==typeof createImageBitmap)throw new Error(\"Cannot decode WebImage as `createImageBitmap` is not available\");if(\"undefined\"==typeof document&&\"undefined\"==typeof OffscreenCanvas)throw new Error(\"Cannot decode WebImage as neither `document` nor `OffscreenCanvas` is not available\");return A}return Q(I,[{key:\"decode\",value:(t=e(r.mark((function A(e,t){var i,I,g,n;return r.wrap((function(A){for(;;)switch(A.prev=A.next){case 0:return i=new Blob([t]),A.next=3,createImageBitmap(i);case 3:return I=A.sent,\"undefined\"!=typeof document?((g=document.createElement(\"canvas\")).width=I.width,g.height=I.height):g=new OffscreenCanvas(I.width,I.height),(n=g.getContext(\"2d\")).drawImage(I,0,0),A.abrupt(\"return\",n.getImageData(0,0,I.width,I.height).data.buffer);case 8:case\"end\":return A.stop()}}),A)}))),function(A,e){return t.apply(this,arguments)})}]),I}(),de=Object.freeze({__proto__:null,default:we});";
            return new Worker$1(typeof Buffer !== 'undefined' 
              ? 'data:application/javascript;base64,' + Buffer.from(source, 'binary').toString('base64')
              : URL.createObjectURL(new Blob([source], {type: 'application/javascript'})));
          }

  var decoder = {
    __proto__: null,
    create: create
  };

  return ol;

})();
